File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.707: download - view: text, annotated - select for diffs
Fri Sep 27 12:57:49 2013 UTC (10 years, 7 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Bubblesheet grading - mismatch tables:
Improve display improvement in rev. 1.658: also correctly display _multiple_ blanks to allow proper comparison of mismatching grading data

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.707 2013/09/27 12:57:49 bisitz 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 %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  334: 	my ($toprow,$bottomrow);
  335: 	foreach my $foil (@$order) {
  336: 	    if ($grading{$foil} == 1) {
  337: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  338: 	    } else {
  339: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  340: 	    }
  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  342: 	}
  343: 	return '<blockquote><table border="1">'.
  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  346: 	    $bottomrow.'</tr></table></blockquote>';
  347:     } elsif ($response eq 'match') {
  348: 	my %answer=&Apache::lonnet::str2hash($answer);
  349: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  350: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  351: 	my ($toprow,$middlerow,$bottomrow);
  352: 	foreach my $foil (@$order) {
  353: 	    my $item=shift(@items);
  354: 	    if ($grading{$foil} == 1) {
  355: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  356: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  357: 	    } else {
  358: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  359: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  360: 	    }
  361: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  362: 	}
  363: 	return '<blockquote><table border="1">'.
  364: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  366: 	    $middlerow.'</tr>'.
  367: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  368: 	    $bottomrow.'</tr></table></blockquote>';
  369:     } elsif ($response eq 'radiobutton') {
  370: 	my %answer=&Apache::lonnet::str2hash($answer);
  371: 	my ($toprow,$bottomrow);
  372: 	my $correct = 
  373: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  374: 	foreach my $foil (@$order) {
  375: 	    if (exists($answer{$foil})) {
  376: 		if ($foil eq $correct) {
  377: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  378: 		} else {
  379: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  380: 		}
  381: 	    } else {
  382: 		$toprow.='<td>'.&mt('false').'</td>';
  383: 	    }
  384: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  385: 	}
  386: 	return '<blockquote><table border="1">'.
  387: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  388: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  389: 	    $bottomrow.'</tr></table></blockquote>';
  390:     } elsif ($response eq 'essay') {
  391: 	if (! exists ($env{'form.'.$symb})) {
  392: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  393: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  394: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  395: 
  396: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  397: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  398: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  399: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  400: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  401: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  402: 	}
  403: 	$answer =~ s-\n-<br />-g;
  404: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  405:     } elsif ( $response eq 'organic') {
  406: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  407: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  408: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  409: 	return $result;
  410:     } elsif ( $response eq 'Task') {
  411: 	if ( $answer eq 'SUBMITTED') {
  412: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  413: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  414: 	    return $result;
  415: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  416: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  417: 			       keys(%{$record}));
  418: 	    return join('<br />',($version,@matches));
  419: 			       
  420: 			       
  421: 	} else {
  422: 	    my $result =
  423: 		'<p>'
  424: 		.&mt('Overall result: [_1]',
  425: 		     $record->{$version."resource.$respid.$partid.status"})
  426: 		.'</p>';
  427: 	    
  428: 	    $result .= '<ul>';
  429: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  430: 			     keys(%{$record}));
  431: 	    foreach my $grade (sort(@grade)) {
  432: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  433: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  434: 				     $dim, $record->{$grade}).
  435: 			  '</li>';
  436: 	    }
  437: 	    $result.='</ul>';
  438: 	    return $result;
  439: 	}
  440:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  441: 	$answer = 
  442: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  443: 							      $answer);
  444:     }
  445:     return $answer;
  446: }
  447: 
  448: #-- A couple of common js functions
  449: sub commonJSfunctions {
  450:     my $request = shift;
  451:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  452:     function radioSelection(radioButton) {
  453: 	var selection=null;
  454: 	if (radioButton.length > 1) {
  455: 	    for (var i=0; i<radioButton.length; i++) {
  456: 		if (radioButton[i].checked) {
  457: 		    return radioButton[i].value;
  458: 		}
  459: 	    }
  460: 	} else {
  461: 	    if (radioButton.checked) return radioButton.value;
  462: 	}
  463: 	return selection;
  464:     }
  465: 
  466:     function pullDownSelection(selectOne) {
  467: 	var selection="";
  468: 	if (selectOne.length > 1) {
  469: 	    for (var i=0; i<selectOne.length; i++) {
  470: 		if (selectOne[i].selected) {
  471: 		    return selectOne[i].value;
  472: 		}
  473: 	    }
  474: 	} else {
  475:             // only one value it must be the selected one
  476: 	    return selectOne.value;
  477: 	}
  478:     }
  479: COMMONJSFUNCTIONS
  480: }
  481: 
  482: #--- Dumps the class list with usernames,list of sections,
  483: #--- section, ids and fullnames for each user.
  484: sub getclasslist {
  485:     my ($getsec,$filterlist,$getgroup) = @_;
  486:     my @getsec;
  487:     my @getgroup;
  488:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  489:     if (!ref($getsec)) {
  490: 	if ($getsec ne '' && $getsec ne 'all') {
  491: 	    @getsec=($getsec);
  492: 	}
  493:     } else {
  494: 	@getsec=@{$getsec};
  495:     }
  496:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  497:     if (!ref($getgroup)) {
  498: 	if ($getgroup ne '' && $getgroup ne 'all') {
  499: 	    @getgroup=($getgroup);
  500: 	}
  501:     } else {
  502: 	@getgroup=@{$getgroup};
  503:     }
  504:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  505: 
  506:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  507:     # Bail out if we were unable to get the classlist
  508:     return if (! defined($classlist));
  509:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  510:     #
  511:     my %sections;
  512:     my %fullnames;
  513:     foreach my $student (keys(%$classlist)) {
  514:         my $end      = 
  515:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  516:         my $start    = 
  517:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  518:         my $id       = 
  519:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  520:         my $section  = 
  521:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  522:         my $fullname = 
  523:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  524:         my $status   = 
  525:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  526:         my $group   = 
  527:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  528: 	# filter students according to status selected
  529: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  530: 	    if (!($stu_status =~ $status)) {
  531: 		delete($classlist->{$student});
  532: 		next;
  533: 	    }
  534: 	}
  535: 	# filter students according to groups selected
  536: 	my @stu_groups = split(/,/,$group);
  537: 	if (@getgroup) {
  538: 	    my $exclude = 1;
  539: 	    foreach my $grp (@getgroup) {
  540: 	        foreach my $stu_group (@stu_groups) {
  541: 	            if ($stu_group eq $grp) {
  542: 	                $exclude = 0;
  543:     	            } 
  544: 	        }
  545:     	        if (($grp eq 'none') && !$group) {
  546:         	        $exclude = 0;
  547:         	}
  548: 	    }
  549: 	    if ($exclude) {
  550: 	        delete($classlist->{$student});
  551: 	    }
  552: 	}
  553: 	$section = ($section ne '' ? $section : 'none');
  554: 	if (&canview($section)) {
  555: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  556: 		$sections{$section}++;
  557: 		if ($classlist->{$student}) {
  558: 		    $fullnames{$student}=$fullname;
  559: 		}
  560: 	    } else {
  561: 		delete($classlist->{$student});
  562: 	    }
  563: 	} else {
  564: 	    delete($classlist->{$student});
  565: 	}
  566:     }
  567:     my %seen = ();
  568:     my @sections = sort(keys(%sections));
  569:     return ($classlist,\@sections,\%fullnames);
  570: }
  571: 
  572: sub canmodify {
  573:     my ($sec)=@_;
  574:     if ($perm{'mgr'}) {
  575: 	if (!defined($perm{'mgr_section'})) {
  576: 	    # can modify whole class
  577: 	    return 1;
  578: 	} else {
  579: 	    if ($sec eq $perm{'mgr_section'}) {
  580: 		#can modify the requested section
  581: 		return 1;
  582: 	    } else {
  583: 		# can't modify the request section
  584: 		return 0;
  585: 	    }
  586: 	}
  587:     }
  588:     #can't modify
  589:     return 0;
  590: }
  591: 
  592: sub canview {
  593:     my ($sec)=@_;
  594:     if ($perm{'vgr'}) {
  595: 	if (!defined($perm{'vgr_section'})) {
  596: 	    # can modify whole class
  597: 	    return 1;
  598: 	} else {
  599: 	    if ($sec eq $perm{'vgr_section'}) {
  600: 		#can modify the requested section
  601: 		return 1;
  602: 	    } else {
  603: 		# can't modify the request section
  604: 		return 0;
  605: 	    }
  606: 	}
  607:     }
  608:     #can't modify
  609:     return 0;
  610: }
  611: 
  612: #--- Retrieve the grade status of a student for all the parts
  613: sub student_gradeStatus {
  614:     my ($symb,$udom,$uname,$partlist) = @_;
  615:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  616:     my %partstatus = ();
  617:     foreach (@$partlist) {
  618: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  619: 	$status              = 'nothing' if ($status eq '');
  620: 	$partstatus{$_}      = $status;
  621: 	my $subkey           = "resource.$_.submitted_by";
  622: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  623:     }
  624:     return %partstatus;
  625: }
  626: 
  627: # hidden form and javascript that calls the form
  628: # Use by verifyscript and viewgrades
  629: # Shows a student's view of problem and submission
  630: sub jscriptNform {
  631:     my ($symb) = @_;
  632:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  633:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  634: 	'    function viewOneStudent(user,domain) {'."\n".
  635: 	'	document.onestudent.student.value = user;'."\n".
  636: 	'	document.onestudent.userdom.value = domain;'."\n".
  637: 	'	document.onestudent.submit();'."\n".
  638: 	'    }'."\n".
  639: 	"\n");
  640:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  641: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  642: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  643: 	'<input type="hidden" name="command" value="submission" />'."\n".
  644: 	'<input type="hidden" name="student" value="" />'."\n".
  645: 	'<input type="hidden" name="userdom" value="" />'."\n".
  646: 	'</form>'."\n";
  647:     return $jscript;
  648: }
  649: 
  650: 
  651: 
  652: # Given the score (as a number [0-1] and the weight) what is the final
  653: # point value? This function will round to the nearest tenth, third,
  654: # or quarter if one of those is within the tolerance of .00001.
  655: sub compute_points {
  656:     my ($score, $weight) = @_;
  657:     
  658:     my $tolerance = .00001;
  659:     my $points = $score * $weight;
  660: 
  661:     # Check for nearness to 1/x.
  662:     my $check_for_nearness = sub {
  663:         my ($factor) = @_;
  664:         my $num = ($points * $factor) + $tolerance;
  665:         my $floored_num = floor($num);
  666:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  667:             return $floored_num / $factor;
  668:         }
  669:         return $points;
  670:     };
  671: 
  672:     $points = $check_for_nearness->(10);
  673:     $points = $check_for_nearness->(3);
  674:     $points = $check_for_nearness->(4);
  675:     
  676:     return $points;
  677: }
  678: 
  679: #------------------ End of general use routines --------------------
  680: 
  681: #
  682: # Find most similar essay
  683: #
  684: 
  685: sub most_similar {
  686:     my ($uname,$udom,$symb,$uessay)=@_;
  687: 
  688:     unless ($symb) { return ''; }
  689: 
  690:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  691: 
  692: # ignore spaces and punctuation
  693: 
  694:     $uessay=~s/\W+/ /gs;
  695: 
  696: # ignore empty submissions (occuring when only files are sent)
  697: 
  698:     unless ($uessay=~/\w+/s) { return ''; }
  699: 
  700: # these will be returned. Do not care if not at least 50 percent similar
  701:     my $limit=0.6;
  702:     my $sname='';
  703:     my $sdom='';
  704:     my $scrsid='';
  705:     my $sessay='';
  706: # go through all essays ...
  707:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  708: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  709: # ... except the same student
  710:         next if (($tname eq $uname) && ($tdom eq $udom));
  711: 	my $tessay=$old_essays{$symb}{$tkey};
  712: 	$tessay=~s/\W+/ /gs;
  713: # String similarity gives up if not even limit
  714: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  715: # Found one
  716: 	if ($tsimilar>$limit) {
  717: 	    $limit=$tsimilar;
  718: 	    $sname=$tname;
  719: 	    $sdom=$tdom;
  720: 	    $scrsid=$tcrsid;
  721: 	    $sessay=$old_essays{$symb}{$tkey};
  722: 	}
  723:     }
  724:     if ($limit>0.6) {
  725:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  726:     } else {
  727:        return ('','','','',0);
  728:     }
  729: }
  730: 
  731: #-------------------------------------------------------------------
  732: 
  733: #------------------------------------ Receipt Verification Routines
  734: #
  735: 
  736: sub initialverifyreceipt {
  737:    my ($request,$symb) = @_;
  738:    &commonJSfunctions($request);
  739:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  740:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  741:         '-<input type="text" name="receipt" size="4" />'.
  742:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  743:         '<input type="hidden" name="command" value="verify" />'.
  744:         "</form>\n";
  745: }
  746: 
  747: #--- Check whether a receipt number is valid.---
  748: sub verifyreceipt {
  749:     my ($request,$symb)  = @_;
  750: 
  751:     my $courseid = $env{'request.course.id'};
  752:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  753: 	$env{'form.receipt'};
  754:     $receipt     =~ s/[^\-\d]//g;
  755: 
  756:     my $title.=
  757: 	'<h3><span class="LC_info">'.
  758: 	&mt('Verifying Receipt Number [_1]',$receipt).
  759: 	'</span></h3>'."\n";
  760: 
  761:     my ($string,$contents,$matches) = ('','',0);
  762:     my (undef,undef,$fullname) = &getclasslist('all','0');
  763:     
  764:     my $receiptparts=0;
  765:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  766: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  767:     my $parts=['0'];
  768:     if ($receiptparts) {
  769:         my $res_error; 
  770:         ($parts)=&response_type($symb,\$res_error);
  771:         if ($res_error) {
  772:             return &navmap_errormsg();
  773:         } 
  774:     }
  775:     
  776:     my $header = 
  777: 	&Apache::loncommon::start_data_table().
  778: 	&Apache::loncommon::start_data_table_header_row().
  779: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  780: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  781: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  782:     if ($receiptparts) {
  783: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  784:     }
  785:     $header.=
  786: 	&Apache::loncommon::end_data_table_header_row();
  787: 
  788:     foreach (sort 
  789: 	     {
  790: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  791: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  792: 		 }
  793: 		 return $a cmp $b;
  794: 	     } (keys(%$fullname))) {
  795: 	my ($uname,$udom)=split(/\:/);
  796: 	foreach my $part (@$parts) {
  797: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  798: 		$contents.=
  799: 		    &Apache::loncommon::start_data_table_row().
  800: 		    '<td>&nbsp;'."\n".
  801: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  802: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  803: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  804: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  805: 		if ($receiptparts) {
  806: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  807: 		}
  808: 		$contents.= 
  809: 		    &Apache::loncommon::end_data_table_row()."\n";
  810: 		
  811: 		$matches++;
  812: 	    }
  813: 	}
  814:     }
  815:     if ($matches == 0) {
  816:         $string = $title
  817:                  .'<p class="LC_warning">'
  818:                  .&mt('No match found for the above receipt number.')
  819:                  .'</p>';
  820:     } else {
  821: 	$string = &jscriptNform($symb).$title.
  822: 	    '<p>'.
  823: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  824: 	    '</p>'.
  825: 	    $header.
  826: 	    $contents.
  827: 	    &Apache::loncommon::end_data_table()."\n";
  828:     }
  829:     return $string;
  830: }
  831: 
  832: #--- This is called by a number of programs.
  833: #--- Called from the Grading Menu - View/Grade an individual student
  834: #--- Also called directly when one clicks on the subm button 
  835: #    on the problem page.
  836: sub listStudents {
  837:     my ($request,$symb,$submitonly) = @_;
  838: 
  839:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  840:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  841:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  842:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  843:     unless ($submitonly) {
  844:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  845:     }
  846: 
  847:     my $result='';
  848:     my $res_error;
  849:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  850: 
  851:     my %lt = &Apache::lonlocal::texthash (
  852: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  853: 		'single'   => 'Please select the student before clicking on the Next button.',
  854: 	     );
  855:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  856:     function checkSelect(checkBox) {
  857: 	var ctr=0;
  858: 	var sense="";
  859: 	if (checkBox.length > 1) {
  860: 	    for (var i=0; i<checkBox.length; i++) {
  861: 		if (checkBox[i].checked) {
  862: 		    ctr++;
  863: 		}
  864: 	    }
  865: 	    sense = '$lt{'multiple'}';
  866: 	} else {
  867: 	    if (checkBox.checked) {
  868: 		ctr = 1;
  869: 	    }
  870: 	    sense = '$lt{'single'}';
  871: 	}
  872: 	if (ctr == 0) {
  873: 	    alert(sense);
  874: 	    return false;
  875: 	}
  876: 	document.gradesub.submit();
  877:     }
  878: 
  879:     function reLoadList(formname) {
  880: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  881: 	formname.command.value = 'submission';
  882: 	formname.submit();
  883:     }
  884: LISTJAVASCRIPT
  885: 
  886:     &commonJSfunctions($request);
  887:     $request->print($result);
  888: 
  889:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  890: 	"\n";
  891: 	
  892:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  893:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  894:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  895:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  896:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  897:                   .&Apache::lonhtmlcommon::row_closure();
  898:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  899:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  900:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  901:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  902:                   .&Apache::lonhtmlcommon::row_closure();
  903: 
  904:     my $submission_options;
  905:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  906:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  907:     $env{'form.Status'} = $saveStatus;
  908:     $submission_options.=
  909:         '<span class="LC_nobreak">'.
  910:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  911:         &mt('last submission').' </label></span>'."\n".
  912:         '<span class="LC_nobreak">'.
  913:         '<label><input type="radio" name="lastSub" value="last" /> '.
  914:         &mt('last submission with details').' </label></span>'."\n".
  915:         '<span class="LC_nobreak">'.
  916:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  917:         &mt('all submissions').'</label></span>'."\n".
  918:         '<span class="LC_nobreak">'.
  919:         '<label><input type="radio" name="lastSub" value="all" /> '.
  920:         &mt('all submissions with details').'</label></span>';
  921:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
  922:                   .$submission_options
  923:                   .&Apache::lonhtmlcommon::row_closure();
  924: 
  925:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  926:                   .'<select name="increment">'
  927:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  928:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  929:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  930:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  931:                   .'</select>'
  932:                   .&Apache::lonhtmlcommon::row_closure();
  933: 
  934:     $gradeTable .= 
  935:         &build_section_inputs().
  936: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  937: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  938: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  939: 
  940:     if (exists($env{'form.Status'})) {
  941: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  942:     } else {
  943:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  944:                       .&Apache::lonhtmlcommon::StatusOptions(
  945:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  946:                       .&Apache::lonhtmlcommon::row_closure();
  947:     }
  948: 
  949:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  950:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  951:                   .&Apache::lonhtmlcommon::row_closure(1)
  952:                   .&Apache::lonhtmlcommon::end_pick_box();
  953: 
  954:     $gradeTable .= '<p>'
  955:                   .&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"
  956:                   .'<input type="hidden" name="command" value="processGroup" />'
  957:                   .'</p>';
  958: 
  959: # checkall buttons
  960:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  961:     $gradeTable.='<input type="button" '."\n".
  962:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  963:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  964:     $gradeTable.=&check_buttons();
  965:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  966:     $gradeTable.= &Apache::loncommon::start_data_table().
  967: 	&Apache::loncommon::start_data_table_header_row();
  968:     my $loop = 0;
  969:     while ($loop < 2) {
  970: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  971: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  972: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  973: 	    foreach my $part (sort(@$partlist)) {
  974: 		my $display_part=
  975: 		    &get_display_part((split(/_/,$part))[0],$symb);
  976: 		$gradeTable.=
  977: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  978: 	    }
  979: 	} elsif ($submitonly eq 'queued') {
  980: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  981: 	}
  982: 	$loop++;
  983: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  984:     }
  985:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  986: 
  987:     my $ctr = 0;
  988:     foreach my $student (sort 
  989: 			 {
  990: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  991: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  992: 			     }
  993: 			     return $a cmp $b;
  994: 			 }
  995: 			 (keys(%$fullname))) {
  996: 	my ($uname,$udom) = split(/:/,$student);
  997: 
  998: 	my %status = ();
  999: 
 1000: 	if ($submitonly eq 'queued') {
 1001: 	    my %queue_status = 
 1002: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1003: 							$udom,$uname);
 1004: 	    next if (!defined($queue_status{'gradingqueue'}));
 1005: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1006: 	}
 1007: 
 1008: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1009: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1010: 	    my $submitted = 0;
 1011: 	    my $graded = 0;
 1012: 	    my $incorrect = 0;
 1013: 	    foreach (keys(%status)) {
 1014: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1015: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1016: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1017: 		
 1018: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1019: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1020: 		    $submitted = 0;
 1021: 		    my ($part)=split(/\./,$partid);
 1022: 		    $gradeTable.='<input type="hidden" name="'.
 1023: 			$student.':'.$part.':submitted_by" value="'.
 1024: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1025: 		}
 1026: 	    }
 1027: 	    
 1028: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1029: 				     $submitonly eq 'incorrect' ||
 1030: 				     $submitonly eq 'graded'));
 1031: 	    next if (!$graded && ($submitonly eq 'graded'));
 1032: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1033: 	}
 1034: 
 1035: 	$ctr++;
 1036: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1037:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1038: 	if ( $perm{'vgr'} eq 'F' ) {
 1039: 	    if ($ctr%2 ==1) {
 1040: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1041: 	    }
 1042: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1043:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1044:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1045: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1046: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1047: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1048: 
 1049: 	    if ($submitonly ne 'all') {
 1050: 		foreach (sort(keys(%status))) {
 1051: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1052: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1053: 		}
 1054: 	    }
 1055: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1056: 	    if ($ctr%2 ==0) {
 1057: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1058: 	    }
 1059: 	}
 1060:     }
 1061:     if ($ctr%2 ==1) {
 1062: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1063: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1064: 		foreach (@$partlist) {
 1065: 		    $gradeTable.='<td>&nbsp;</td>';
 1066: 		}
 1067: 	    } elsif ($submitonly eq 'queued') {
 1068: 		$gradeTable.='<td>&nbsp;</td>';
 1069: 	    }
 1070: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1071:     }
 1072: 
 1073:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1074:         '<input type="button" '.
 1075:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1076:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1077:     if ($ctr == 0) {
 1078: 	my $num_students=(scalar(keys(%$fullname)));
 1079: 	if ($num_students eq 0) {
 1080: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1081: 	} else {
 1082: 	    my $submissions='submissions';
 1083: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1084: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1085: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1086: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1087: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1088: 		    $num_students).
 1089: 		'</span><br />';
 1090: 	}
 1091:     } elsif ($ctr == 1) {
 1092: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1093:     }
 1094:     $request->print($gradeTable);
 1095:     return '';
 1096: }
 1097: 
 1098: #---- Called from the listStudents routine
 1099: 
 1100: sub check_script {
 1101:     my ($form, $type)=@_;
 1102:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1103:     function checkall() {
 1104:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1105:             ele = document.forms.'.$form.'.elements[i];
 1106:             if (ele.name == "'.$type.'") {
 1107:             document.forms.'.$form.'.elements[i].checked=true;
 1108:                                        }
 1109:         }
 1110:     }
 1111: 
 1112:     function checksec() {
 1113:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1114:             ele = document.forms.'.$form.'.elements[i];
 1115:            string = document.forms.'.$form.'.chksec.value;
 1116:            if
 1117:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1118:               document.forms.'.$form.'.elements[i].checked=true;
 1119:             }
 1120:         }
 1121:     }
 1122: 
 1123: 
 1124:     function uncheckall() {
 1125:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1126:             ele = document.forms.'.$form.'.elements[i];
 1127:             if (ele.name == "'.$type.'") {
 1128:             document.forms.'.$form.'.elements[i].checked=false;
 1129:                                        }
 1130:         }
 1131:     }
 1132: 
 1133: '."\n");
 1134:     return $chkallscript;
 1135: }
 1136: 
 1137: sub check_buttons {
 1138:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1139:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1140:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1141:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1142:     return $buttons;
 1143: }
 1144: 
 1145: #     Displays the submissions for one student or a group of students
 1146: sub processGroup {
 1147:     my ($request,$symb)  = @_;
 1148:     my $ctr        = 0;
 1149:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1150:     my $total      = scalar(@stuchecked)-1;
 1151: 
 1152:     foreach my $student (@stuchecked) {
 1153: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1154: 	$env{'form.student'}        = $uname;
 1155: 	$env{'form.userdom'}        = $udom;
 1156: 	$env{'form.fullname'}       = $fullname;
 1157: 	&submission($request,$ctr,$total,$symb);
 1158: 	$ctr++;
 1159:     }
 1160:     return '';
 1161: }
 1162: 
 1163: #------------------------------------------------------------------------------------
 1164: #
 1165: #-------------------------- Next few routines handles grading by student, essentially
 1166: #                           handles essay response type problem/part
 1167: #
 1168: #--- Javascript to handle the submission page functionality ---
 1169: sub sub_page_js {
 1170:     my $request = shift;
 1171: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1172:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1173:     function updateRadio(formname,id,weight) {
 1174: 	var gradeBox = formname["GD_BOX"+id];
 1175: 	var radioButton = formname["RADVAL"+id];
 1176: 	var oldpts = formname["oldpts"+id].value;
 1177: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1178: 	gradeBox.value = pts;
 1179: 	var resetbox = false;
 1180: 	if (isNaN(pts) || pts < 0) {
 1181: 	    alert("$alertmsg"+pts);
 1182: 	    for (var i=0; i<radioButton.length; i++) {
 1183: 		if (radioButton[i].checked) {
 1184: 		    gradeBox.value = i;
 1185: 		    resetbox = true;
 1186: 		}
 1187: 	    }
 1188: 	    if (!resetbox) {
 1189: 		formtextbox.value = "";
 1190: 	    }
 1191: 	    return;
 1192: 	}
 1193: 
 1194: 	if (pts > weight) {
 1195: 	    var resp = confirm("You entered a value ("+pts+
 1196: 			       ") greater than the weight for the part. Accept?");
 1197: 	    if (resp == false) {
 1198: 		gradeBox.value = oldpts;
 1199: 		return;
 1200: 	    }
 1201: 	}
 1202: 
 1203: 	for (var i=0; i<radioButton.length; i++) {
 1204: 	    radioButton[i].checked=false;
 1205: 	    if (pts == i && pts != "") {
 1206: 		radioButton[i].checked=true;
 1207: 	    }
 1208: 	}
 1209: 	updateSelect(formname,id);
 1210: 	formname["stores"+id].value = "0";
 1211:     }
 1212: 
 1213:     function writeBox(formname,id,pts) {
 1214: 	var gradeBox = formname["GD_BOX"+id];
 1215: 	if (checkSolved(formname,id) == 'update') {
 1216: 	    gradeBox.value = pts;
 1217: 	} else {
 1218: 	    var oldpts = formname["oldpts"+id].value;
 1219: 	    gradeBox.value = oldpts;
 1220: 	    var radioButton = formname["RADVAL"+id];
 1221: 	    for (var i=0; i<radioButton.length; i++) {
 1222: 		radioButton[i].checked=false;
 1223: 		if (i == oldpts) {
 1224: 		    radioButton[i].checked=true;
 1225: 		}
 1226: 	    }
 1227: 	}
 1228: 	formname["stores"+id].value = "0";
 1229: 	updateSelect(formname,id);
 1230: 	return;
 1231:     }
 1232: 
 1233:     function clearRadBox(formname,id) {
 1234: 	if (checkSolved(formname,id) == 'noupdate') {
 1235: 	    updateSelect(formname,id);
 1236: 	    return;
 1237: 	}
 1238: 	gradeSelect = formname["GD_SEL"+id];
 1239: 	for (var i=0; i<gradeSelect.length; i++) {
 1240: 	    if (gradeSelect[i].selected) {
 1241: 		var selectx=i;
 1242: 	    }
 1243: 	}
 1244: 	var stores = formname["stores"+id];
 1245: 	if (selectx == stores.value) { return };
 1246: 	var gradeBox = formname["GD_BOX"+id];
 1247: 	gradeBox.value = "";
 1248: 	var radioButton = formname["RADVAL"+id];
 1249: 	for (var i=0; i<radioButton.length; i++) {
 1250: 	    radioButton[i].checked=false;
 1251: 	}
 1252: 	stores.value = selectx;
 1253:     }
 1254: 
 1255:     function checkSolved(formname,id) {
 1256: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1257: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1258: 	    if (!reply) {return "noupdate";}
 1259: 	    formname.overRideScore.value = 'yes';
 1260: 	}
 1261: 	return "update";
 1262:     }
 1263: 
 1264:     function updateSelect(formname,id) {
 1265: 	formname["GD_SEL"+id][0].selected = true;
 1266: 	return;
 1267:     }
 1268: 
 1269: //=========== Check that a point is assigned for all the parts  ============
 1270:     function checksubmit(formname,val,total,parttot) {
 1271: 	formname.gradeOpt.value = val;
 1272: 	if (val == "Save & Next") {
 1273: 	    for (i=0;i<=total;i++) {
 1274: 		for (j=0;j<parttot;j++) {
 1275: 		    var partid = formname["partid"+i+"_"+j].value;
 1276: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1277: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1278: 			if (points == "") {
 1279: 			    var name = formname["name"+i].value;
 1280: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1281: 			    var resp = confirm("You did not assign a score for "+studentID+
 1282: 					       ", part "+partid+". Continue?");
 1283: 			    if (resp == false) {
 1284: 				formname["GD_BOX"+i+"_"+partid].focus();
 1285: 				return false;
 1286: 			    }
 1287: 			}
 1288: 		    }
 1289: 		    
 1290: 		}
 1291: 	    }
 1292: 	    
 1293: 	}
 1294: 	formname.submit();
 1295:     }
 1296: 
 1297: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1298:     function checkSubmitPage(formname,total) {
 1299: 	noscore = new Array(100);
 1300: 	var ptr = 0;
 1301: 	for (i=1;i<total;i++) {
 1302: 	    var partid = formname["q_"+i].value;
 1303: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1304: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1305: 		var status = formname["solved"+i+"_"+partid].value;
 1306: 		if (points == "" && status != "correct_by_student") {
 1307: 		    noscore[ptr] = i;
 1308: 		    ptr++;
 1309: 		}
 1310: 	    }
 1311: 	}
 1312: 	if (ptr != 0) {
 1313: 	    var sense = ptr == 1 ? ": " : "s: ";
 1314: 	    var prolist = "";
 1315: 	    if (ptr == 1) {
 1316: 		prolist = noscore[0];
 1317: 	    } else {
 1318: 		var i = 0;
 1319: 		while (i < ptr-1) {
 1320: 		    prolist += noscore[i]+", ";
 1321: 		    i++;
 1322: 		}
 1323: 		prolist += "and "+noscore[i];
 1324: 	    }
 1325: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1326: 	    if (resp == false) {
 1327: 		return false;
 1328: 	    }
 1329: 	}
 1330: 
 1331: 	formname.submit();
 1332:     }
 1333: SUBJAVASCRIPT
 1334: }
 1335: 
 1336: #--- javascript for essay type problem --
 1337: sub sub_page_kw_js {
 1338:     my $request = shift;
 1339:     my $iconpath = $request->dir_config('lonIconsURL');
 1340:     &commonJSfunctions($request);
 1341: 
 1342:     my $inner_js_msg_central= (<<INNERJS);
 1343: <script type="text/javascript">
 1344:     function checkInput() {
 1345:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1346:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1347:       var usrctr = document.msgcenter.usrctr.value;
 1348:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1349:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1350: 
 1351:       var msgchk = "";
 1352:       if (document.msgcenter.subchk.checked) {
 1353:          msgchk = "msgsub,";
 1354:       }
 1355:       var includemsg = 0;
 1356:       for (var i=1; i<=nmsg; i++) {
 1357:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1358:           var frmmsg = document.msgcenter["msg"+i];
 1359:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1360:           var showflg = opener.document.SCORE["shownOnce"+i];
 1361:           showflg.value = "1";
 1362:           var chkbox = document.msgcenter["msgn"+i];
 1363:           if (chkbox.checked) {
 1364:              msgchk += "savemsg"+i+",";
 1365:              includemsg = 1;
 1366:           }
 1367:       }
 1368:       if (document.msgcenter.newmsgchk.checked) {
 1369:          msgchk += "newmsg"+usrctr;
 1370:          includemsg = 1;
 1371:       }
 1372:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1373:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1374:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1375:       includemsg.value = msgchk;
 1376: 
 1377:       self.close()
 1378: 
 1379:     }
 1380: </script>
 1381: INNERJS
 1382: 
 1383:     my $inner_js_highlight_central= (<<INNERJS);
 1384: <script type="text/javascript">
 1385:     function updateChoice(flag) {
 1386:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1387:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1388:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1389:       opener.document.SCORE.refresh.value = "on";
 1390:       if (opener.document.SCORE.keywords.value!=""){
 1391:          opener.document.SCORE.submit();
 1392:       }
 1393:       self.close()
 1394:     }
 1395: </script>
 1396: INNERJS
 1397: 
 1398:     my $start_page_msg_central = 
 1399:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1400: 				       {'js_ready'  => 1,
 1401: 					'only_body' => 1,
 1402: 					'bgcolor'   =>'#FFFFFF',});
 1403:     my $end_page_msg_central = 
 1404: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1405: 
 1406: 
 1407:     my $start_page_highlight_central = 
 1408:         &Apache::loncommon::start_page('Highlight Central',
 1409: 				       $inner_js_highlight_central,
 1410: 				       {'js_ready'  => 1,
 1411: 					'only_body' => 1,
 1412: 					'bgcolor'   =>'#FFFFFF',});
 1413:     my $end_page_highlight_central = 
 1414: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1415: 
 1416:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1417:     $docopen=~s/^document\.//;
 1418:     my %lt = &Apache::lonlocal::texthash(
 1419:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1420:                 plse => 'Please select a word or group of words from document and then click this link.',
 1421:                 adds => 'Add selection to keyword list? Edit if desired.',
 1422:                 comp => 'Compose Message for: ',
 1423:                 incl => 'Include',
 1424:                 type => 'Type',
 1425:                 subj => 'Subject',
 1426:                 mesa => 'Message',
 1427:                 new  => 'New',
 1428:                 save => 'Save',
 1429:                 canc => 'Cancel',
 1430:                 kehi => 'Keyword Highlight Options',
 1431:                 txtc => 'Text Color',
 1432:                 font => 'Font Size',
 1433:                 fnst => 'Font Style',
 1434:              );
 1435:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1436: 
 1437: //===================== Show list of keywords ====================
 1438:   function keywords(formname) {
 1439:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1440:     if (nret==null) return;
 1441:     formname.keywords.value = nret;
 1442: 
 1443:     if (formname.keywords.value != "") {
 1444: 	formname.refresh.value = "on";
 1445: 	formname.submit();
 1446:     }
 1447:     return;
 1448:   }
 1449: 
 1450: //===================== Script to view submitted by ==================
 1451:   function viewSubmitter(submitter) {
 1452:     document.SCORE.refresh.value = "on";
 1453:     document.SCORE.NCT.value = "1";
 1454:     document.SCORE.unamedom0.value = submitter;
 1455:     document.SCORE.submit();
 1456:     return;
 1457:   }
 1458: 
 1459: //===================== Script to add keyword(s) ==================
 1460:   function getSel() {
 1461:     if (document.getSelection) txt = document.getSelection();
 1462:     else if (document.selection) txt = document.selection.createRange().text;
 1463:     else return;
 1464:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1465:     if (cleantxt=="") {
 1466: 	alert("$lt{'plse'}");
 1467: 	return;
 1468:     }
 1469:     var nret = prompt("$lt{'adds'}",cleantxt);
 1470:     if (nret==null) return;
 1471:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1472:     if (document.SCORE.keywords.value != "") {
 1473: 	document.SCORE.refresh.value = "on";
 1474: 	document.SCORE.submit();
 1475:     }
 1476:     return;
 1477:   }
 1478: 
 1479: //====================== Script for composing message ==============
 1480:    // preload images
 1481:    img1 = new Image();
 1482:    img1.src = "$iconpath/mailbkgrd.gif";
 1483:    img2 = new Image();
 1484:    img2.src = "$iconpath/mailto.gif";
 1485: 
 1486:   function msgCenter(msgform,usrctr,fullname) {
 1487:     var Nmsg  = msgform.savemsgN.value;
 1488:     savedMsgHeader(Nmsg,usrctr,fullname);
 1489:     var subject = msgform.msgsub.value;
 1490:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1491:     re = /msgsub/;
 1492:     var shwsel = "";
 1493:     if (re.test(msgchk)) { shwsel = "checked" }
 1494:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1495:     displaySubject(checkEntities(subject),shwsel);
 1496:     for (var i=1; i<=Nmsg; i++) {
 1497: 	var testmsg = "savemsg"+i+",";
 1498: 	re = new RegExp(testmsg,"g");
 1499: 	shwsel = "";
 1500: 	if (re.test(msgchk)) { shwsel = "checked" }
 1501: 	var message = document.SCORE["savemsg"+i].value;
 1502: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1503: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1504: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1505:     }
 1506:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1507:     shwsel = "";
 1508:     re = /newmsg/;
 1509:     if (re.test(msgchk)) { shwsel = "checked" }
 1510:     newMsg(newmsg,shwsel);
 1511:     msgTail(); 
 1512:     return;
 1513:   }
 1514: 
 1515:   function checkEntities(strx) {
 1516:     if (strx.length == 0) return strx;
 1517:     var orgStr = ["&", "<", ">", '"']; 
 1518:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1519:     var counter = 0;
 1520:     while (counter < 4) {
 1521: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1522: 	counter++;
 1523:     }
 1524:     return strx;
 1525:   }
 1526: 
 1527:   function strReplace(strx, orgStr, newStr) {
 1528:     return strx.split(orgStr).join(newStr);
 1529:   }
 1530: 
 1531:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1532:     var height = 70*Nmsg+250;
 1533:     if (height > 600) {
 1534: 	height = 600;
 1535:     }
 1536:     var xpos = (screen.width-600)/2;
 1537:     xpos = (xpos < 0) ? '0' : xpos;
 1538:     var ypos = (screen.height-height)/2-30;
 1539:     ypos = (ypos < 0) ? '0' : ypos;
 1540: 
 1541:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1542:     pWin.focus();
 1543:     pDoc = pWin.document;
 1544:     pDoc.$docopen;
 1545:     pDoc.write('$start_page_msg_central');
 1546: 
 1547:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1548:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1549:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
 1550: 
 1551:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1552:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1553: }
 1554:     function displaySubject(msg,shwsel) {
 1555:     pDoc = pWin.document;
 1556:     pDoc.write("<tr>");
 1557:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1558:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1559:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1560: }
 1561: 
 1562:   function displaySavedMsg(ctr,msg,shwsel) {
 1563:     pDoc = pWin.document;
 1564:     pDoc.write("<tr>");
 1565:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1566:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1567:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1568: }
 1569: 
 1570:   function newMsg(newmsg,shwsel) {
 1571:     pDoc = pWin.document;
 1572:     pDoc.write("<tr>");
 1573:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1574:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1575:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1576: }
 1577: 
 1578:   function msgTail() {
 1579:     pDoc = pWin.document;
 1580:     //pDoc.write("<\\/table>");
 1581:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1582:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1583:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1584:     pDoc.write("<\\/form>");
 1585:     pDoc.write('$end_page_msg_central');
 1586:     pDoc.close();
 1587: }
 1588: 
 1589: //====================== Script for keyword highlight options ==============
 1590:   function kwhighlight() {
 1591:     var kwclr    = document.SCORE.kwclr.value;
 1592:     var kwsize   = document.SCORE.kwsize.value;
 1593:     var kwstyle  = document.SCORE.kwstyle.value;
 1594:     var redsel = "";
 1595:     var grnsel = "";
 1596:     var blusel = "";
 1597:     if (kwclr=="red")   {var redsel="checked"};
 1598:     if (kwclr=="green") {var grnsel="checked"};
 1599:     if (kwclr=="blue")  {var blusel="checked"};
 1600:     var sznsel = "";
 1601:     var sz1sel = "";
 1602:     var sz2sel = "";
 1603:     if (kwsize=="0")  {var sznsel="checked"};
 1604:     if (kwsize=="+1") {var sz1sel="checked"};
 1605:     if (kwsize=="+2") {var sz2sel="checked"};
 1606:     var synsel = "";
 1607:     var syisel = "";
 1608:     var sybsel = "";
 1609:     if (kwstyle=="")    {var synsel="checked"};
 1610:     if (kwstyle=="<i>") {var syisel="checked"};
 1611:     if (kwstyle=="<b>") {var sybsel="checked"};
 1612:     highlightCentral();
 1613:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1614:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1615:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1616:     highlightend();
 1617:     return;
 1618:   }
 1619: 
 1620:   function highlightCentral() {
 1621: //    if (window.hwdWin) window.hwdWin.close();
 1622:     var xpos = (screen.width-400)/2;
 1623:     xpos = (xpos < 0) ? '0' : xpos;
 1624:     var ypos = (screen.height-330)/2-30;
 1625:     ypos = (ypos < 0) ? '0' : ypos;
 1626: 
 1627:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1628:     hwdWin.focus();
 1629:     var hDoc = hwdWin.document;
 1630:     hDoc.$docopen;
 1631:     hDoc.write('$start_page_highlight_central');
 1632:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1633:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1634: 
 1635:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1636:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1637:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1638:   }
 1639: 
 1640:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1641:     var hDoc = hwdWin.document;
 1642:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1643:     hDoc.write("<td align=\\"left\\">");
 1644:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1645:     hDoc.write("<td align=\\"left\\">");
 1646:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1647:     hDoc.write("<td align=\\"left\\">");
 1648:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1649:     hDoc.write("<\\/tr>");
 1650:   }
 1651: 
 1652:   function highlightend() { 
 1653:     var hDoc = hwdWin.document;
 1654:     hDoc.write("<\\/table>");
 1655:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1656:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1657:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1658:     hDoc.write("<\\/form>");
 1659:     hDoc.write('$end_page_highlight_central');
 1660:     hDoc.close();
 1661:   }
 1662: 
 1663: SUBJAVASCRIPT
 1664: }
 1665: 
 1666: sub get_increment {
 1667:     my $increment = $env{'form.increment'};
 1668:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1669:         $increment != .1) {
 1670:         $increment = 1;
 1671:     }
 1672:     return $increment;
 1673: }
 1674: 
 1675: sub gradeBox_start {
 1676:     return (
 1677:         &Apache::loncommon::start_data_table()
 1678:        .&Apache::loncommon::start_data_table_header_row()
 1679:        .'<th>'.&mt('Part').'</th>'
 1680:        .'<th>'.&mt('Points').'</th>'
 1681:        .'<th>&nbsp;</th>'
 1682:        .'<th>'.&mt('Assign Grade').'</th>'
 1683:        .'<th>'.&mt('Weight').'</th>'
 1684:        .'<th>'.&mt('Grade Status').'</th>'
 1685:        .&Apache::loncommon::end_data_table_header_row()
 1686:     );
 1687: }
 1688: 
 1689: sub gradeBox_end {
 1690:     return (
 1691:         &Apache::loncommon::end_data_table()
 1692:     );
 1693: }
 1694: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1695: sub gradeBox {
 1696:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1697:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1698: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1699:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1700:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1701:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1702:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1703:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1704: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1705:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1706:     my $display_part= &get_display_part($partid,$symb);
 1707:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1708: 				       [$partid]);
 1709:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1710:     if ($last_resets{$partid}) {
 1711:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1712:     }
 1713:     my $result=&Apache::loncommon::start_data_table_row();
 1714:     my $ctr = 0;
 1715:     my $thisweight = 0;
 1716:     my $increment = &get_increment();
 1717: 
 1718:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1719:     while ($thisweight<=$wgt) {
 1720: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1721:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1722: 	    $thisweight.')" value="'.$thisweight.'" '.
 1723: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1724: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1725:         $thisweight += $increment;
 1726: 	$ctr++;
 1727:     }
 1728:     $radio.='</tr></table>';
 1729: 
 1730:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1731: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1732: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1733: 	$wgt.')" /></td>'."\n";
 1734:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1735: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1736: 	' </td>'."\n";
 1737:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1738: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1739:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1740: 	$line.='<option></option>'.
 1741: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1742:     } else {
 1743: 	$line.='<option selected="selected"></option>'.
 1744: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1745:     }
 1746:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1747: 
 1748: 
 1749:     $result .= 
 1750: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1751:     $result.=&Apache::loncommon::end_data_table_row();
 1752:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1753:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1754: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1755: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1756: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1757:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1758:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1759:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1760:         $aggtries.'" />'."\n";
 1761:     my $res_error;
 1762:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1763:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1764:     if ($res_error) {
 1765:         return &navmap_errormsg();
 1766:     }
 1767:     return $result;
 1768: }
 1769: 
 1770: sub handback_box {
 1771:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1772:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1773:     my (@respids);
 1774:     my @part_response_id = &flatten_responseType($responseType);
 1775:     foreach my $part_response_id (@part_response_id) {
 1776:     	my ($part,$resp) = @{ $part_response_id };
 1777:         if ($part eq $partid) {
 1778:             push(@respids,$resp);
 1779:         }
 1780:     }
 1781:     my $result;
 1782:     foreach my $respid (@respids) {
 1783: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1784: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1785: 	next if (!@$files);
 1786: 	my $file_counter = 0;
 1787: 	foreach my $file (@$files) {
 1788: 	    if ($file =~ /\/portfolio\//) {
 1789:                 $file_counter++;
 1790:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1791:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1792:     	        $file_disp = "$name.$ext";
 1793:     	        $file = $file_path.$file_disp;
 1794:     	        $result.=&mt('Return commented version of [_1] to student.',
 1795:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1796:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1797:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1798: 	    }
 1799: 	}
 1800:         if ($file_counter) {
 1801:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1802:                        '<span class="LC_info">'.
 1803:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1804:         }
 1805:     }
 1806:     return $result;    
 1807: }
 1808: 
 1809: sub show_problem {
 1810:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1811:     my $rendered;
 1812:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1813:     &Apache::lonxml::remember_problem_counter();
 1814:     if ($mode eq 'both' or $mode eq 'text') {
 1815: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1816: 						       $env{'request.course.id'},
 1817: 						       undef,\%form);
 1818:     }
 1819:     if ($removeform) {
 1820: 	$rendered=~s|<form(.*?)>||g;
 1821: 	$rendered=~s|</form>||g;
 1822: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1823:     }
 1824:     my $companswer;
 1825:     if ($mode eq 'both' or $mode eq 'answer') {
 1826: 	&Apache::lonxml::restore_problem_counter();
 1827: 	$companswer=
 1828: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1829: 						    $env{'request.course.id'},
 1830: 						    %form);
 1831:     }
 1832:     if ($removeform) {
 1833: 	$companswer=~s|<form(.*?)>||g;
 1834: 	$companswer=~s|</form>||g;
 1835: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1836:     }
 1837:     my $renderheading = &mt('View of the problem');
 1838:     my $answerheading = &mt('Correct answer');
 1839:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1840:         my $stu_fullname = $env{'form.fullname'};
 1841:         if ($stu_fullname eq '') {
 1842:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1843:         }
 1844:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1845:         if ($forwhom ne '') {
 1846:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1847:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1848:         }
 1849:     }
 1850:     $rendered=
 1851:         '<div class="LC_Box">'
 1852:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1853:        .$rendered
 1854:        .'</div>';
 1855:     $companswer=
 1856:         '<div class="LC_Box">'
 1857:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1858:        .$companswer
 1859:        .'</div>';
 1860:     my $result;
 1861:     if ($mode eq 'both') {
 1862:         $result=$rendered.$companswer;
 1863:     } elsif ($mode eq 'text') {
 1864:         $result=$rendered;
 1865:     } elsif ($mode eq 'answer') {
 1866:         $result=$companswer;
 1867:     }
 1868:     return $result;
 1869: }
 1870: 
 1871: sub files_exist {
 1872:     my ($r, $symb) = @_;
 1873:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1874: 
 1875:     foreach my $student (@students) {
 1876:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1877:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1878: 					      $udom,$uname);
 1879:         my ($string,$timestamp)= &get_last_submission(\%record);
 1880:         foreach my $submission (@$string) {
 1881:             my ($partid,$respid) =
 1882: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1883:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1884: 					   \%record);
 1885:             return 1 if (@$files);
 1886:         }
 1887:     }
 1888:     return 0;
 1889: }
 1890: 
 1891: sub download_all_link {
 1892:     my ($r,$symb) = @_;
 1893:     unless (&files_exist($r, $symb)) {
 1894:        $r->print(&mt('There are currently no submitted documents.'));
 1895:        return;
 1896:     }
 1897: 
 1898:     my $all_students = 
 1899: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1900: 
 1901:     my $parts =
 1902: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1903: 
 1904:     my $identifier = &Apache::loncommon::get_cgi_id();
 1905:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1906:                              'cgi.'.$identifier.'.symb' => $symb,
 1907:                              'cgi.'.$identifier.'.parts' => $parts,});
 1908:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1909: 	      &mt('Download All Submitted Documents').'</a>');
 1910:     return;
 1911: }
 1912: 
 1913: sub submit_download_link {
 1914:     my ($request,$symb) = @_;
 1915:     if (!$symb) { return ''; }
 1916: #FIXME: Figure out which type of problem this is and provide appropriate download
 1917:     &download_all_link($request,$symb);
 1918: }
 1919: 
 1920: sub build_section_inputs {
 1921:     my $section_inputs;
 1922:     if ($env{'form.section'} eq '') {
 1923:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1924:     } else {
 1925:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1926:         foreach my $section (@sections) {
 1927:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1928:         }
 1929:     }
 1930:     return $section_inputs;
 1931: }
 1932: 
 1933: # --------------------------- show submissions of a student, option to grade 
 1934: sub submission {
 1935:     my ($request,$counter,$total,$symb) = @_;
 1936:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1937:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1938:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1939:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1940: 
 1941:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1942:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1943: 
 1944:     if (!&canview($usec)) {
 1945: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1946: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1947: 			$env{'request.course.id'}.')</span>');
 1948: 	return;
 1949:     }
 1950: 
 1951:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1952:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1953:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1954:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1955:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1956: 	'" src="'.$request->dir_config('lonIconsURL').
 1957: 	'/check.gif" height="16" border="0" />';
 1958: 
 1959:     # header info
 1960:     if ($counter == 0) {
 1961: 	&sub_page_js($request);
 1962: 	&sub_page_kw_js($request);
 1963: 
 1964: 	# option to display problem, only once else it cause problems 
 1965:         # with the form later since the problem has a form.
 1966: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1967: 	    my $mode;
 1968: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1969: 		$mode='both';
 1970: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1971: 		$mode='text';
 1972: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1973: 		$mode='answer';
 1974: 	    }
 1975: 	    &Apache::lonxml::clear_problem_counter();
 1976: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1977: 	}
 1978: 
 1979: 	# kwclr is the only variable that is guaranteed not to be blank 
 1980:         # if this subroutine has been called once.
 1981: 	my %keyhash = ();
 1982: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1983:         if (1) {
 1984: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1985: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1986: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1987: 
 1988: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1989: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1990: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1991: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1992: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1993: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1994: 		$keyhash{$symb.'_subject'} : $probtitle;
 1995: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1996: 	}
 1997: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1998: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1999: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2000: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2001: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2002: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2003: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2004: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2005: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2006: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2007: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2008: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2009: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2010: 			&build_section_inputs().
 2011: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2012: 			'<input type="hidden" name="NCT"'.
 2013: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2014: #	if ($env{'form.handgrade'} eq 'yes') {
 2015:         if (1) {
 2016: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2017: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2018: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2019: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2020: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2021: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2022: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2023: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2024: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2025: 	    }
 2026: 	}
 2027: 	
 2028: 	my ($cts,$prnmsg) = (1,'');
 2029: 	while ($cts <= $env{'form.savemsgN'}) {
 2030: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2031: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2032: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2033: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2034: 		'" />'."\n".
 2035: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2036: 	    $cts++;
 2037: 	}
 2038: 	$request->print($prnmsg);
 2039: 
 2040: #	if ($env{'form.handgrade'} eq 'yes') {
 2041:         if (1) {
 2042: 
 2043:             my %lt = &Apache::lonlocal::texthash(
 2044:                           keyw => 'Keyword Options',
 2045:                           list => 'List',
 2046:                           past => 'Paste Selection to List',
 2047:                           high => 'Highlight Attribute',
 2048:                      );    
 2049: #
 2050: # Print out the keyword options line
 2051: #
 2052: 	    $request->print(<<KEYWORDS);
 2053: <br /><b>$lt{'keyw'}:</b>&nbsp;
 2054: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2055: <a href="#" onmousedown="javascript:getSel(); return false"
 2056:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
 2057: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2058: KEYWORDS
 2059: #
 2060: # Load the other essays for similarity check
 2061: #
 2062:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2063: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2064: 	    $apath=&escape($apath);
 2065: 	    $apath=~s/\W/\_/gs;
 2066:             &init_old_essays($symb,$apath,$adom,$aname);
 2067:         }
 2068:     }
 2069: 
 2070: # This is where output for one specific student would start
 2071:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2072:     $request->print(
 2073:         "\n\n"
 2074:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2075:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2076:        ."\n"
 2077:     );
 2078: 
 2079:     # Show additional functions if allowed
 2080:     if ($perm{'vgr'}) {
 2081:         $request->print(
 2082:             &Apache::loncommon::track_student_link(
 2083:                 &mt('View recent activity'),
 2084:                 $uname,$udom,'check')
 2085:            .' '
 2086:         );
 2087:     }
 2088:     if ($perm{'opa'}) {
 2089:         $request->print(
 2090:             &Apache::loncommon::pprmlink(
 2091:                 &mt('Set/Change parameters'),
 2092:                 $uname,$udom,$symb,'check'));
 2093:     }
 2094: 
 2095:     # Show Problem
 2096:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2097: 	my $mode;
 2098: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2099: 	    $mode='both';
 2100: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2101: 	    $mode='text';
 2102: 	} elsif ($env{'form.vAns'} eq 'all') {
 2103: 	    $mode='answer';
 2104: 	}
 2105: 	&Apache::lonxml::clear_problem_counter();
 2106: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2107:     }
 2108: 
 2109:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2110:     my $res_error;
 2111:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2112:     if ($res_error) {
 2113:         $request->print(&navmap_errormsg());
 2114:         return;
 2115:     }
 2116: 
 2117:     # Display student info
 2118:     $request->print(($counter == 0 ? '' : '<br />'));
 2119: 
 2120:     my $result='<div class="LC_Box">'
 2121:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2122:     $result.='<input type="hidden" name="name'.$counter.
 2123:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2124: #    if ($env{'form.handgrade'} eq 'no') {
 2125:     if (1) {
 2126:         $result.='<p class="LC_info">'
 2127:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2128:                 ."</p>\n";
 2129:     }
 2130: 
 2131:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2132:     my $fullname;
 2133:     my $col_fullnames = [];
 2134: #    if ($env{'form.handgrade'} eq 'yes') {
 2135:     if (1) {
 2136: 	(my $sub_result,$fullname,$col_fullnames)=
 2137: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2138: 				 $counter);
 2139: 	$result.=$sub_result;
 2140:     }
 2141:     $request->print($result."\n");
 2142:     
 2143:     # print student answer/submission
 2144:     # Options are (1) Handgraded submission only
 2145:     #             (2) Last submission, includes submission that is not handgraded 
 2146:     #                  (for multi-response type part)
 2147:     #             (3) Last submission plus the parts info
 2148:     #             (4) The whole record for this student
 2149:     
 2150:     my ($string,$timestamp)= &get_last_submission(\%record);
 2151: 	
 2152:     my $lastsubonly;
 2153: 
 2154:     if ($$timestamp eq '') {
 2155:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2156:     } else {
 2157:         $lastsubonly =
 2158:             '<div class="LC_grade_submissions_body">'
 2159:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2160: 
 2161: 	my %seenparts;
 2162: 	my @part_response_id = &flatten_responseType($responseType);
 2163: 	foreach my $part (@part_response_id) {
 2164: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2165: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2166: 
 2167: 	    my ($partid,$respid) = @{ $part };
 2168: 	    my $display_part=&get_display_part($partid,$symb);
 2169: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2170: 		if (exists($seenparts{$partid})) { next; }
 2171: 		$seenparts{$partid}=1;
 2172:                 $request->print(
 2173:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2174:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2175:                                '<a href="javascript:viewSubmitter(\''.
 2176:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2177:                                '\');" target="_self">'.
 2178:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2179:                     '<br />');
 2180: 		next;
 2181: 		}
 2182: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2183: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2184:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2185:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2186:                     ' <span class="LC_internal_info">'.
 2187:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2188:                     '</span>&nbsp; &nbsp;'.
 2189: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2190: 		next;
 2191: 	    }
 2192: 	    foreach my $submission (@$string) {
 2193: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2194: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2195: 		my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2196: 		# Similarity check
 2197:                 my $similar='';
 2198:                 my ($type,$trial,$rndseed);
 2199:                 if ($hide eq 'rand') {
 2200:                     $type = 'randomizetry';
 2201:                     $trial = $record{"resource.$partid.tries"};
 2202:                     $rndseed = $record{"resource.$partid.rndseed"};
 2203:                 }
 2204: 	        if ($env{'form.checkPlag'}) {
 2205:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2206: 		        &most_similar($uname,$udom,$symb,$subval);
 2207: 		    if ($osim) {
 2208: 			$osim=int($osim*100.0);
 2209: 			my %old_course_desc = 
 2210: 			    &Apache::lonnet::coursedescription($ocrsid,
 2211: 							{'one_time' => 1});
 2212: 
 2213:                         if ($hide eq 'anon') {
 2214:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2215:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2216:                         } else {
 2217: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2218: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2219: 				    $osim,
 2220: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2221: 				        $old_course_desc{'description'},
 2222: 				        $old_course_desc{'num'},
 2223: 				        $old_course_desc{'domain'}).
 2224: 				    '</span></h3><blockquote><i>'.
 2225: 				    &keywords_highlight($oessay).
 2226: 				    '</i></blockquote><hr />';
 2227:                         }
 2228: 	            }
 2229: 		}
 2230: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2231:                                      undef,$type,$trial,$rndseed);
 2232:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2233: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2234: 		    my $display_part=&get_display_part($partid,$symb);
 2235:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2236:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2237:                         ' <span class="LC_internal_info">'.
 2238:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2239:                         '</span>&nbsp; &nbsp;';
 2240: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2241:                         
 2242: 		    if (@$files) {
 2243:                         if ($hide eq 'anon') {
 2244:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2245:                         } else {
 2246:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2247:                                         .'<br /><span class="LC_warning">';
 2248:                             if(@$files == 1) {
 2249:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2250:                             } else {
 2251:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2252:                             }
 2253:                             $lastsubonly .= '</span>';                         
 2254:                             foreach my $file (@$files) {
 2255:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2256:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2257:                             }
 2258:                         }
 2259: 			$lastsubonly.='<br />';
 2260:                     }
 2261:                     if ($hide eq 'anon') {
 2262:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2263:                     } else {
 2264:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
 2265: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2266: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2267:                     }
 2268: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2269: 		    $lastsubonly.='</div>';
 2270: 		}
 2271:             }
 2272: 	}
 2273: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2274:     }
 2275:     $request->print($lastsubonly);
 2276:     if ($env{'form.lastSub'} eq 'datesub') {
 2277:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2278: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2279:     } 
 2280:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2281:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2282: 								 $env{'request.course.id'},
 2283: 								 $last,'.submission',
 2284: 								 'Apache::grades::keywords_highlight'));
 2285:     }
 2286:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2287: 	.$udom.'" />'."\n");
 2288:     # return if view submission with no grading option
 2289:     if (!&canmodify($usec)) {
 2290: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2291: 	return;
 2292:     } else {
 2293: 	$request->print('</div>'."\n");
 2294:     }
 2295: 
 2296:     # essay grading message center
 2297: #    if ($env{'form.handgrade'} eq 'yes') {
 2298:     if (1) {
 2299: 	my $result='<div class="LC_grade_message_center">';
 2300:     
 2301: 	$result.='<div class="LC_grade_message_center_header">'.
 2302: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2303: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2304: 	my $msgfor = $givenn.' '.$lastname;
 2305: 	if (scalar(@$col_fullnames) > 0) {
 2306: 	    my $lastone = pop(@$col_fullnames);
 2307: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2308: 	}
 2309: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2310: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2311: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2312: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2313: 	    ',\''.$msgfor.'\');" target="_self">'.
 2314: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2315: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2316: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2317: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2318: 	    '<br />&nbsp;('.
 2319: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2320: 	$result.='</div></div>';
 2321: 	$request->print($result);
 2322:     }
 2323: 
 2324:     my %seen = ();
 2325:     my @partlist;
 2326:     my @gradePartRespid;
 2327:     my @part_response_id = &flatten_responseType($responseType);
 2328:     $request->print(
 2329:         '<div class="LC_Box">'
 2330:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2331:     );
 2332:     $request->print(&gradeBox_start());
 2333:     foreach my $part_response_id (@part_response_id) {
 2334:     	my ($partid,$respid) = @{ $part_response_id };
 2335: 	my $part_resp = join('_',@{ $part_response_id });
 2336: 	next if ($seen{$partid} > 0);
 2337: 	$seen{$partid}++;
 2338: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2339: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2340: 	push(@partlist,$partid);
 2341: 	push(@gradePartRespid,$partid.'.'.$respid);
 2342: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2343:     }
 2344:     $request->print(&gradeBox_end()); # </div>
 2345:     $request->print('</div>');
 2346: 
 2347:     $request->print('<div class="LC_grade_info_links">');
 2348:     $request->print('</div>');
 2349: 
 2350:     $result='<input type="hidden" name="partlist'.$counter.
 2351: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2352:     $result.='<input type="hidden" name="gradePartRespid'.
 2353: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2354:     my $ctr = 0;
 2355:     while ($ctr < scalar(@partlist)) {
 2356: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2357: 	    $partlist[$ctr].'" />'."\n";
 2358: 	$ctr++;
 2359:     }
 2360:     $request->print($result.''."\n");
 2361: 
 2362: # Done with printing info for one student
 2363: 
 2364:     $request->print('</div>');#LC_grade_show_user
 2365: 
 2366: 
 2367:     # print end of form
 2368:     if ($counter == $total) {
 2369:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2370: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2371: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2372: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2373: 	my $ntstu ='<select name="NTSTU">'.
 2374: 	    '<option>1</option><option>2</option>'.
 2375: 	    '<option>3</option><option>5</option>'.
 2376: 	    '<option>7</option><option>10</option></select>'."\n";
 2377: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2378: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2379:         $endform.=&mt('[_1]student(s)',$ntstu);
 2380: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2381: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2382: 	    '<input type="button" value="'.&mt('Next').'" '.
 2383: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2384:         $endform.='<span class="LC_warning">'.
 2385:                   &mt('(Next and Previous (student) do not save the scores.)').
 2386:                   '</span>'."\n" ;
 2387:         $endform.="<input type='hidden' value='".&get_increment().
 2388:             "' name='increment' />";
 2389: 	$endform.='</td></tr></table></form>';
 2390: 	$request->print($endform);
 2391:     }
 2392:     return '';
 2393: }
 2394: 
 2395: sub check_collaborators {
 2396:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2397:     my ($result,@col_fullnames);
 2398:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2399:     foreach my $part (keys(%$handgrade)) {
 2400: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2401: 					'.maxcollaborators',
 2402: 					$symb,$udom,$uname);
 2403: 	next if ($ncol <= 0);
 2404: 	$part =~ s/\_/\./g;
 2405: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2406: 	my (@good_collaborators, @bad_collaborators);
 2407: 	foreach my $possible_collaborator
 2408: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2409: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2410: 	    next if ($possible_collaborator eq '');
 2411: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2412: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2413: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2414: 	    # Doing this grep allows 'fuzzy' specification
 2415: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2416: 			       keys(%$classlist));
 2417: 	    if (! scalar(@matches)) {
 2418: 		push(@bad_collaborators, $possible_collaborator);
 2419: 	    } else {
 2420: 		push(@good_collaborators, @matches);
 2421: 	    }
 2422: 	}
 2423: 	if (scalar(@good_collaborators) != 0) {
 2424: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2425: 	    foreach my $name (@good_collaborators) {
 2426: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2427: 		push(@col_fullnames, $givenn.' '.$lastname);
 2428: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2429: 	    }
 2430: 	    $result.='</ol><br />'."\n";
 2431: 	    my ($part)=split(/\./,$part);
 2432: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2433: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2434: 		"\n";
 2435: 	}
 2436: 	if (scalar(@bad_collaborators) > 0) {
 2437: 	    $result.='<div class="LC_warning">';
 2438: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2439: 	    $result .= '</div>';
 2440: 	}         
 2441: 	if (scalar(@bad_collaborators > $ncol)) {
 2442: 	    $result .= '<div class="LC_warning">';
 2443: 	    $result .= &mt('This student has submitted too many '.
 2444: 		'collaborators.  Maximum is [_1].',$ncol);
 2445: 	    $result .= '</div>';
 2446: 	}
 2447:     }
 2448:     return ($result,$fullname,\@col_fullnames);
 2449: }
 2450: 
 2451: #--- Retrieve the last submission for all the parts
 2452: sub get_last_submission {
 2453:     my ($returnhash)=@_;
 2454:     my (@string,$timestamp,%lasthidden);
 2455:     if ($$returnhash{'version'}) {
 2456: 	my %lasthash=();
 2457: 	my ($version);
 2458: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2459: 	    foreach my $key (sort(split(/\:/,
 2460: 					$$returnhash{$version.':keys'}))) {
 2461: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2462: 		$timestamp = 
 2463: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2464: 	    }
 2465: 	}
 2466:         my (%typeparts,%randombytry);
 2467:         my $showsurv = 
 2468:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2469:         foreach my $key (sort(keys(%lasthash))) {
 2470:             if ($key =~ /\.type$/) {
 2471:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2472:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2473:                     ($lasthash{$key} eq 'randomizetry')) {
 2474:                     my ($ign,@parts) = split(/\./,$key);
 2475:                     pop(@parts);
 2476:                     my $id = join('.',@parts);
 2477:                     if ($lasthash{$key} eq 'randomizetry') {
 2478:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2479:                     } else {
 2480:                         unless ($showsurv) {
 2481:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2482:                         }
 2483:                     }
 2484:                     delete($lasthash{$key});
 2485:                 }
 2486:             }
 2487:         }
 2488:         my @hidden = keys(%typeparts);
 2489:         my @randomize = keys(%randombytry);
 2490: 	foreach my $key (keys(%lasthash)) {
 2491: 	    next if ($key !~ /\.submission$/);
 2492:             my $hide;
 2493:             if (@hidden) {
 2494:                 foreach my $id (@hidden) {
 2495:                     if ($key =~ /^\Q$id\E/) {
 2496:                         $hide = 'anon';
 2497:                         last;
 2498:                     }
 2499:                 }
 2500:             }
 2501:             unless ($hide) {
 2502:                 if (@randomize) {
 2503:                     foreach my $id (@hidden) {
 2504:                         if ($key =~ /^\Q$id\E/) {
 2505:                             $hide = 'rand';
 2506:                             last;
 2507:                         }
 2508:                     }
 2509:                 }
 2510:             }
 2511: 	    my ($partid,$foo) = split(/submission$/,$key);
 2512: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2513: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2514: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2515: 	}
 2516:     }
 2517:     if (!@string) {
 2518: 	$string[0] =
 2519: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2520:     }
 2521:     return (\@string,\$timestamp);
 2522: }
 2523: 
 2524: #--- High light keywords, with style choosen by user.
 2525: sub keywords_highlight {
 2526:     my $string    = shift;
 2527:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2528:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2529:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2530:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2531:     foreach my $keyword (@keylist) {
 2532: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2533:     }
 2534:     return $string;
 2535: }
 2536: 
 2537: # For Tasks provide a mechanism to display previous version for one specific student
 2538: 
 2539: sub show_previous_task_version {
 2540:     my ($request,$symb) = @_;
 2541:     if ($symb eq '') {
 2542:         $request->print("Unable to handle ambiguous references.");
 2543: 
 2544:         return '';
 2545:     }
 2546:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2547:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2548:     if (!&canview($usec)) {
 2549:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
 2550:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
 2551:                         $env{'request.course.id'}.')</span>');
 2552:         return;
 2553:     }
 2554:     my $mode = 'both';
 2555:     my $isTask = ($symb =~/\.task$/);
 2556:     if ($isTask) {
 2557:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2558:             if ($env{'form.fullname'} eq '') {
 2559:                 $env{'form.fullname'} =
 2560:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2561:             }
 2562:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2563:             $request->print("\n\n".
 2564:                             '<div class="LC_grade_show_user">'.
 2565:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2566:                             '</h2>'."\n");
 2567:             &Apache::lonxml::clear_problem_counter();
 2568:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2569:                             {'previousversion' => $env{'form.previousversion'} }));
 2570:             $request->print("\n</div>");
 2571:         }
 2572:     }
 2573:     return;
 2574: }
 2575: 
 2576: sub choose_task_version_form {
 2577:     my ($symb,$uname,$udom,$nomenu) = @_;
 2578:     my $isTask = ($symb =~/\.task$/);
 2579:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2580:     if ($isTask) {
 2581:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2582:                                               $udom,$uname);
 2583:         if (($record{'resource.0.version'} eq '') ||
 2584:             ($record{'resource.0.version'} < 2)) {
 2585:             return ($record{'resource.0.version'},
 2586:                     $record{'resource.0.version'},$result,$js);
 2587:         } else {
 2588:             $current = $record{'resource.0.version'};
 2589:         }
 2590:         if ($env{'form.previousversion'}) {
 2591:             $displayed = $env{'form.previousversion'};
 2592:             $rowtitle = &mt('Choose another version:')
 2593:         } else {
 2594:             $displayed = $current;
 2595:             $rowtitle = &mt('Show earlier version:');
 2596:         }
 2597:         $result = '<div class="LC_left_float">';
 2598:         my $list;
 2599:         my $numversions = 0;
 2600:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2601:             if ($i == $current) {
 2602:                 if (!$env{'form.previousversion'} || $nomenu) {
 2603:                     next;
 2604:                 } else {
 2605:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2606:                     $numversions ++;
 2607:                 }
 2608:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2609:                 unless ($i == $env{'form.previousversion'}) {
 2610:                     $numversions ++;
 2611:                 }
 2612:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2613:             }
 2614:         }
 2615:         if ($numversions) {
 2616:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2617:             $result .=
 2618:                 '<form name="getprev" method="post" action=""'.
 2619:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2620:                 &Apache::loncommon::start_data_table().
 2621:                 &Apache::loncommon::start_data_table_row().
 2622:                 '<th align="left">'.$rowtitle.'</th>'.
 2623:                 '<td><select name="version">'.
 2624:                 '<option>'.&mt('Select').'</option>'.
 2625:                 $list.
 2626:                 '</select></td>'.
 2627:                 &Apache::loncommon::end_data_table_row();
 2628:             unless ($nomenu) {
 2629:                 $result .= &Apache::loncommon::start_data_table_row().
 2630:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2631:                 '<td><span class="LC_nobreak">'.
 2632:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2633:                 &mt('Yes').'</label>'.
 2634:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2635:                 '</span></td>'.
 2636:                 &Apache::loncommon::end_data_table_row();
 2637:             }
 2638:             $result .=
 2639:                 &Apache::loncommon::start_data_table_row().
 2640:                 '<th align="left">&nbsp;</th>'.
 2641:                 '<td>'.
 2642:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2643:                 '</td>'.
 2644:                 &Apache::loncommon::end_data_table_row().
 2645:                 &Apache::loncommon::end_data_table().
 2646:                 '</form>';
 2647:             $js = &previous_display_javascript($nomenu,$current);
 2648:         } elsif ($displayed && $nomenu) {
 2649:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2650:         } else {
 2651:             $result .= &mt('No previous versions to show for this student');
 2652:         }
 2653:         $result .= '</div>';
 2654:     }
 2655:     return ($current,$displayed,$result,$js);
 2656: }
 2657: 
 2658: sub previous_display_javascript {
 2659:     my ($nomenu,$current) = @_;
 2660:     my $js = <<"JSONE";
 2661: <script type="text/javascript">
 2662: // <![CDATA[
 2663: function previousVersion(uname,udom,symb) {
 2664:     var current = '$current';
 2665:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2666:     var prevstr = new RegExp("^\\\\d+\$");
 2667:     if (!prevstr.test(version)) {
 2668:         return false;
 2669:     }
 2670:     var url = '';
 2671:     if (version == current) {
 2672:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2673:     } else {
 2674:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2675:     }
 2676: JSONE
 2677:     if ($nomenu) {
 2678:         $js .= <<"JSTWO";
 2679:     document.location.href = url;
 2680: JSTWO
 2681:     } else {
 2682:         $js .= <<"JSTHREE";
 2683:     var newwin = 0;
 2684:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2685:         if (document.getprev.prevwin[i].checked == true) {
 2686:             newwin = document.getprev.prevwin[i].value;
 2687:         }
 2688:     }
 2689:     if (newwin == 1) {
 2690:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2691:         url = url+'&inhibitmenu=yes';
 2692:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2693:             previousWin = window.open(url,'',options,1);
 2694:         } else {
 2695:             previousWin.location.href = url;
 2696:         }
 2697:         previousWin.focus();
 2698:         return false;
 2699:     } else {
 2700:         document.location.href = url;
 2701:         return false;
 2702:     }
 2703: JSTHREE
 2704:     }
 2705:     $js .= <<"ENDJS";
 2706:     return false;
 2707: }
 2708: // ]]>
 2709: </script>
 2710: ENDJS
 2711: 
 2712: }
 2713: 
 2714: #--- Called from submission routine
 2715: sub processHandGrade {
 2716:     my ($request,$symb) = @_;
 2717:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2718:     my $button = $env{'form.gradeOpt'};
 2719:     my $ngrade = $env{'form.NCT'};
 2720:     my $ntstu  = $env{'form.NTSTU'};
 2721:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2722:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2723: 
 2724:     if ($button eq 'Save & Next') {
 2725: 	my $ctr = 0;
 2726: 	while ($ctr < $ngrade) {
 2727: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2728: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2729: 	    if ($errorflag eq 'no_score') {
 2730: 		$ctr++;
 2731: 		next;
 2732: 	    }
 2733: 	    if ($errorflag eq 'not_allowed') {
 2734: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2735: 		$ctr++;
 2736: 		next;
 2737: 	    }
 2738: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2739: 	    my ($subject,$message,$msgstatus) = ('','','');
 2740: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2741:             my ($feedurl,$showsymb) =
 2742: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2743: 	    my $messagetail;
 2744: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2745: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2746: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2747: 		$subject.=' ['.$restitle.']';
 2748: 		my (@msgnum) = split(/,/,$includemsg);
 2749: 		foreach (@msgnum) {
 2750: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2751: 		}
 2752: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2753: 		if ($env{'form.withgrades'.$ctr}) {
 2754: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2755: 		    $messagetail = " for <a href=\"".
 2756: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2757: 		}
 2758: 		$msgstatus = 
 2759:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2760: 						     $message.$messagetail,
 2761:                                                      undef,$feedurl,undef,
 2762:                                                      undef,undef,$showsymb,
 2763:                                                      $restitle);
 2764: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2765: 				$msgstatus.'<br />');
 2766: 	    }
 2767: 	    if ($env{'form.collaborator'.$ctr}) {
 2768: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2769: 		foreach my $collabstr (@collabstrs) {
 2770: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2771: 		    foreach my $collaborator (@collaborators) {
 2772: 			my ($errorflag,$pts,$wgt) = 
 2773: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2774: 					   $env{'form.unamedom'.$ctr},$part);
 2775: 			if ($errorflag eq 'not_allowed') {
 2776: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2777: 			    next;
 2778: 			} elsif ($message ne '') {
 2779: 			    my ($baseurl,$showsymb) = 
 2780: 				&get_feedurl_and_symb($symb,$collaborator,
 2781: 						      $udom);
 2782: 			    if ($env{'form.withgrades'.$ctr}) {
 2783: 				$messagetail = " for <a href=\"".
 2784:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2785: 			    }
 2786: 			    $msgstatus = 
 2787: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2788: 			}
 2789: 		    }
 2790: 		}
 2791: 	    }
 2792: 	    $ctr++;
 2793: 	}
 2794:     }
 2795: 
 2796: #    if ($env{'form.handgrade'} eq 'yes') {
 2797:     if (1) {
 2798: 	# Keywords sorted in alphabatical order
 2799: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2800: 	my %keyhash = ();
 2801: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2802: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2803: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2804: 	$env{'form.keywords'} = join(' ',@keywords);
 2805: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2806: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2807: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2808: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2809: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2810: 
 2811: 	# message center - Order of message gets changed. Blank line is eliminated.
 2812: 	# New messages are saved in env for the next student.
 2813: 	# All messages are saved in nohist_handgrade.db
 2814: 	my ($ctr,$idx) = (1,1);
 2815: 	while ($ctr <= $env{'form.savemsgN'}) {
 2816: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2817: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2818: 		$idx++;
 2819: 	    }
 2820: 	    $ctr++;
 2821: 	}
 2822: 	$ctr = 0;
 2823: 	while ($ctr < $ngrade) {
 2824: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2825: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2826: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2827: 		$idx++;
 2828: 	    }
 2829: 	    $ctr++;
 2830: 	}
 2831: 	$env{'form.savemsgN'} = --$idx;
 2832: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2833: 	my $putresult = &Apache::lonnet::put
 2834: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2835:     }
 2836:     # Called by Save & Refresh from Highlight Attribute Window
 2837:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2838:     if ($env{'form.refresh'} eq 'on') {
 2839: 	my ($ctr,$total) = (0,0);
 2840: 	while ($ctr < $ngrade) {
 2841: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2842: 	    $ctr++;
 2843: 	}
 2844: 	$env{'form.NTSTU'}=$ngrade;
 2845: 	$ctr = 0;
 2846: 	while ($ctr < $total) {
 2847: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2848: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2849: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2850: 	    &submission($request,$ctr,$total-1,$symb);
 2851: 	    $ctr++;
 2852: 	}
 2853: 	return '';
 2854:     }
 2855: 
 2856:     # Get the next/previous one or group of students
 2857:     my $firststu = $env{'form.unamedom0'};
 2858:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2859:     my $ctr = 2;
 2860:     while ($laststu eq '') {
 2861: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2862: 	$ctr++;
 2863: 	$laststu = $firststu if ($ctr > $ngrade);
 2864:     }
 2865: 
 2866:     my (@parsedlist,@nextlist);
 2867:     my ($nextflg) = 0;
 2868:     foreach my $item (sort 
 2869: 	     {
 2870: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2871: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2872: 		 }
 2873: 		 return $a cmp $b;
 2874: 	     } (keys(%$fullname))) {
 2875: # FIXME: this is fishy, looks like the button label
 2876: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2877: 	    push(@parsedlist,$item);
 2878: 	}
 2879: 	$nextflg = 1 if ($item eq $laststu);
 2880: 	if ($button eq 'Previous') {
 2881: 	    last if ($item eq $firststu);
 2882: 	    push(@parsedlist,$item);
 2883: 	}
 2884:     }
 2885:     $ctr = 0;
 2886: # FIXME: this is fishy, looks like the button label
 2887:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2888:     my $res_error;
 2889:     my ($partlist) = &response_type($symb,\$res_error);
 2890:     if ($res_error) {
 2891:         $request->print(&navmap_errormsg());
 2892:         return;
 2893:     }
 2894:     foreach my $student (@parsedlist) {
 2895: 	my $submitonly=$env{'form.submitonly'};
 2896: 	my ($uname,$udom) = split(/:/,$student);
 2897: 	
 2898: 	if ($submitonly eq 'queued') {
 2899: 	    my %queue_status = 
 2900: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2901: 							$udom,$uname);
 2902: 	    next if (!defined($queue_status{'gradingqueue'}));
 2903: 	}
 2904: 
 2905: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2906: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2907: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2908: 	    my $submitted = 0;
 2909: 	    my $ungraded = 0;
 2910: 	    my $incorrect = 0;
 2911: 	    foreach my $item (keys(%status)) {
 2912: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2913: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2914: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2915: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2916: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2917: 		    $submitted = 0;
 2918: 		}
 2919: 	    }
 2920: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2921: 				     $submitonly eq 'incorrect' ||
 2922: 				     $submitonly eq 'graded'));
 2923: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2924: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2925: 	}
 2926: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2927: 	last if ($ctr == $ntstu);
 2928: 	$ctr++;
 2929:     }
 2930: 
 2931:     $ctr = 0;
 2932:     my $total = scalar(@nextlist)-1;
 2933: 
 2934:     foreach (sort(@nextlist)) {
 2935: 	my ($uname,$udom,$submitter) = split(/:/);
 2936: 	$env{'form.student'}  = $uname;
 2937: 	$env{'form.userdom'}  = $udom;
 2938: 	$env{'form.fullname'} = $$fullname{$_};
 2939: 	&submission($request,$ctr,$total,$symb);
 2940: 	$ctr++;
 2941:     }
 2942:     if ($total < 0) {
 2943: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2944: 	$request->print($the_end);
 2945:     }
 2946:     return '';
 2947: }
 2948: 
 2949: #---- Save the score and award for each student, if changed
 2950: sub saveHandGrade {
 2951:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2952:     my @version_parts;
 2953:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2954: 					   $env{'request.course.id'});
 2955:     if (!&canmodify($usec)) { return('not_allowed'); }
 2956:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2957:     my @parts_graded;
 2958:     my %newrecord  = ();
 2959:     my ($pts,$wgt) = ('','');
 2960:     my %aggregate = ();
 2961:     my $aggregateflag = 0;
 2962:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2963:     foreach my $new_part (@parts) {
 2964: 	#collaborator ($submi may vary for different parts
 2965: 	if ($submitter && $new_part ne $part) { next; }
 2966: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2967: 	if ($dropMenu eq 'excused') {
 2968: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2969: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2970: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2971: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2972: 		}
 2973: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2974: 	    }
 2975: 	} elsif ($dropMenu eq 'reset status'
 2976: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2977: 	    foreach my $key (keys(%record)) {
 2978: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2979: 	    }
 2980: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2981: 		"$env{'user.name'}:$env{'user.domain'}";
 2982:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2983: 
 2984:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2985: 					       [$new_part]);
 2986:             my $aggtries =$totaltries;
 2987:             if ($last_resets{$new_part}) {
 2988:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2989: 					   $new_part);
 2990:             }
 2991: 
 2992:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2993:             if ($aggtries > 0) {
 2994:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2995:                 $aggregateflag = 1;
 2996:             }
 2997: 	} elsif ($dropMenu eq '') {
 2998: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2999: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3000: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3001: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3002: 		next;
 3003: 	    }
 3004: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3005: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3006: 	    my $partial= $pts/$wgt;
 3007: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3008: 		#do not update score for part if not changed.
 3009:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3010: 		next;
 3011: 	    } else {
 3012: 	        push(@parts_graded,$new_part);
 3013: 	    }
 3014: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3015: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3016: 	    }
 3017: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3018: 	    if ($partial == 0) {
 3019: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3020: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3021: 		}
 3022: 	    } else {
 3023: 		if ($record{$reckey} ne 'correct_by_override') {
 3024: 		    $newrecord{$reckey} = 'correct_by_override';
 3025: 		}
 3026: 	    }	    
 3027: 	    if ($submitter && 
 3028: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3029: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3030: 	    }
 3031: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3032: 		"$env{'user.name'}:$env{'user.domain'}";
 3033: 	}
 3034: 	# unless problem has been graded, set flag to version the submitted files
 3035: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3036: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3037: 	        $dropMenu eq 'reset status')
 3038: 	   {
 3039: 	    push(@version_parts,$new_part);
 3040: 	}
 3041:     }
 3042:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3043:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3044: 
 3045:     if (%newrecord) {
 3046:         if (@version_parts) {
 3047:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3048:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3049: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3050: 	    foreach my $new_part (@version_parts) {
 3051: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3052: 				$new_part,\%newrecord);
 3053: 	    }
 3054:         }
 3055: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3056: 				$env{'request.course.id'},$domain,$stuname);
 3057: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3058: 				     $cdom,$cnum,$domain,$stuname);
 3059:     }
 3060:     if ($aggregateflag) {
 3061:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3062: 			      $cdom,$cnum);
 3063:     }
 3064:     return ('',$pts,$wgt);
 3065: }
 3066: 
 3067: sub check_and_remove_from_queue {
 3068:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3069:     my @ungraded_parts;
 3070:     foreach my $part (@{$parts}) {
 3071: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3072: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3073: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3074: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3075: 		) {
 3076: 	    push(@ungraded_parts, $part);
 3077: 	}
 3078:     }
 3079:     if ( !@ungraded_parts ) {
 3080: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3081: 					       $cnum,$domain,$stuname);
 3082:     }
 3083: }
 3084: 
 3085: sub handback_files {
 3086:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3087:     my $portfolio_root = '/userfiles/portfolio';
 3088:     my $res_error;
 3089:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3090:     if ($res_error) {
 3091:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3092:         return;
 3093:     }
 3094:     my @handedback;
 3095:     my $file_msg;
 3096:     my @part_response_id = &flatten_responseType($responseType);
 3097:     foreach my $part_response_id (@part_response_id) {
 3098:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3099: 	my $part_resp = join('_',@{ $part_response_id });
 3100:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3101:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3102:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3103:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3104:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3105:                     my ($directory,$answer_file) = 
 3106:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3107:                     my ($answer_name,$answer_ver,$answer_ext) =
 3108: 		        &file_name_version_ext($answer_file);
 3109: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3110:                     my $getpropath = 1;
 3111:                     my ($dir_list,$listerror) = 
 3112:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3113:                                                  $domain,$stuname,$getpropath);
 3114: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3115:                     # fix filename
 3116:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3117:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3118:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3119:             	                                $save_file_name);
 3120:                     if ($result !~ m|^/uploaded/|) {
 3121:                         $request->print('<br /><span class="LC_error">'.
 3122:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3123:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3124:                                         '</span>');
 3125:                     } else {
 3126:                         # mark the file as read only
 3127:                         push(@handedback,$save_file_name);
 3128: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3129: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3130: 			}
 3131:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3132: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3133:                     }
 3134:                     $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>'));
 3135:                 }
 3136:             }
 3137:         }
 3138:     }
 3139:     if (@handedback > 0) {
 3140:         $request->print('<br />');
 3141:         my @what = ($symb,$env{'request.course.id'},'handback');
 3142:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3143:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3144:         my ($subject,$message);
 3145:         if (scalar(@handedback) == 1) {
 3146:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3147:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3148:         } else {
 3149:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3150:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3151:         }
 3152:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3153:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3154:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3155:         my ($feedurl,$showsymb) =
 3156:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3157:         my $restitle = &Apache::lonnet::gettitle($symb);
 3158:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3159:         my $msgstatus =
 3160:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3161:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3162:                  $restitle);
 3163:         if ($msgstatus) {
 3164:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3165:         }
 3166:     }
 3167:     return;
 3168: }
 3169: 
 3170: sub get_feedurl_and_symb {
 3171:     my ($symb,$uname,$udom) = @_;
 3172:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3173:     $url = &Apache::lonnet::clutter($url);
 3174:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3175: 					$symb,$udom,$uname);
 3176:     if ($encrypturl =~ /^yes$/i) {
 3177: 	&Apache::lonenc::encrypted(\$url,1);
 3178: 	&Apache::lonenc::encrypted(\$symb,1);
 3179:     }
 3180:     return ($url,$symb);
 3181: }
 3182: 
 3183: sub get_submitted_files {
 3184:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3185:     my @files;
 3186:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3187:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3188:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3189:     	    push(@files,$file_url.$file);
 3190:         }
 3191:     }
 3192:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3193:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3194:     }
 3195:     return (\@files);
 3196: }
 3197: 
 3198: # ----------- Provides number of tries since last reset.
 3199: sub get_num_tries {
 3200:     my ($record,$last_reset,$part) = @_;
 3201:     my $timestamp = '';
 3202:     my $num_tries = 0;
 3203:     if ($$record{'version'}) {
 3204:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3205:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3206:                 $timestamp = $$record{$version.':timestamp'};
 3207:                 if ($timestamp > $last_reset) {
 3208:                     $num_tries ++;
 3209:                 } else {
 3210:                     last;
 3211:                 }
 3212:             }
 3213:         }
 3214:     }
 3215:     return $num_tries;
 3216: }
 3217: 
 3218: # ----------- Determine decrements required in aggregate totals 
 3219: sub decrement_aggs {
 3220:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3221:     my %decrement = (
 3222:                         attempts => 0,
 3223:                         users => 0,
 3224:                         correct => 0
 3225:                     );
 3226:     $decrement{'attempts'} = $aggtries;
 3227:     if ($solvedstatus =~ /^correct/) {
 3228:         $decrement{'correct'} = 1;
 3229:     }
 3230:     if ($aggtries == $totaltries) {
 3231:         $decrement{'users'} = 1;
 3232:     }
 3233:     foreach my $type (keys(%decrement)) {
 3234:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3235:     }
 3236:     return;
 3237: }
 3238: 
 3239: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3240: sub get_last_resets {
 3241:     my ($symb,$courseid,$partids) =@_;
 3242:     my %last_resets;
 3243:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3244:     my $cname = $env{'course.'.$courseid.'.num'};
 3245:     my @keys;
 3246:     foreach my $part (@{$partids}) {
 3247: 	push(@keys,"$symb\0$part\0resettime");
 3248:     }
 3249:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3250: 				     $cdom,$cname);
 3251:     foreach my $part (@{$partids}) {
 3252: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3253:     }
 3254:     return %last_resets;
 3255: }
 3256: 
 3257: # ----------- Handles creating versions for portfolio files as answers
 3258: sub version_portfiles {
 3259:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3260:     my $version_parts = join('|',@$v_flag);
 3261:     my @returned_keys;
 3262:     my $parts = join('|', @$parts_graded);
 3263:     my $portfolio_root = '/userfiles/portfolio';
 3264:     foreach my $key (keys(%$record)) {
 3265:         my $new_portfiles;
 3266:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3267:             my @versioned_portfiles;
 3268:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3269:             foreach my $file (@portfiles) {
 3270:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3271:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3272: 		my ($answer_name,$answer_ver,$answer_ext) =
 3273: 		    &file_name_version_ext($answer_file);
 3274:                 my $getpropath = 1;    
 3275:                 my ($dir_list,$listerror) = 
 3276:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3277:                                              $stu_name,$getpropath);
 3278:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3279:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3280:                 if ($new_answer ne 'problem getting file') {
 3281:                     push(@versioned_portfiles, $directory.$new_answer);
 3282:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3283:                         [$directory.$new_answer],
 3284:                         [$symb,$env{'request.course.id'},'graded']);
 3285:                 }
 3286:             }
 3287:             $$record{$key} = join(',',@versioned_portfiles);
 3288:             push(@returned_keys,$key);
 3289:         }
 3290:     } 
 3291:     return (@returned_keys);   
 3292: }
 3293: 
 3294: sub get_next_version {
 3295:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3296:     my $version;
 3297:     if (ref($dir_list) eq 'ARRAY') {
 3298:         foreach my $row (@{$dir_list}) {
 3299:             my ($file) = split(/\&/,$row,2);
 3300:             my ($file_name,$file_version,$file_ext) =
 3301: 	        &file_name_version_ext($file);
 3302:             if (($file_name eq $answer_name) && 
 3303: 	        ($file_ext eq $answer_ext)) {
 3304:                      # gets here if filename and extension match, 
 3305:                      # regardless of version
 3306:                 if ($file_version ne '') {
 3307:                     # a versioned file is found  so save it for later
 3308:                     if ($file_version > $version) {
 3309: 		        $version = $file_version;
 3310: 	            }
 3311:                 }
 3312:             }
 3313:         }
 3314:     }
 3315:     $version ++;
 3316:     return($version);
 3317: }
 3318: 
 3319: sub version_selected_portfile {
 3320:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3321:     my ($answer_name,$answer_ver,$answer_ext) =
 3322:         &file_name_version_ext($file_name);
 3323:     my $new_answer;
 3324:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3325:     if($env{'form.copy'} eq '-1') {
 3326:         $new_answer = 'problem getting file';
 3327:     } else {
 3328:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3329:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3330:                             $stu_name,$domain,'copy',
 3331: 		        '/portfolio'.$directory.$new_answer);
 3332:     }    
 3333:     return ($new_answer);
 3334: }
 3335: 
 3336: sub file_name_version_ext {
 3337:     my ($file)=@_;
 3338:     my @file_parts = split(/\./, $file);
 3339:     my ($name,$version,$ext);
 3340:     if (@file_parts > 1) {
 3341: 	$ext=pop(@file_parts);
 3342: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3343: 	    $version=pop(@file_parts);
 3344: 	}
 3345: 	$name=join('.',@file_parts);
 3346:     } else {
 3347: 	$name=join('.',@file_parts);
 3348:     }
 3349:     return($name,$version,$ext);
 3350: }
 3351: 
 3352: #--------------------------------------------------------------------------------------
 3353: #
 3354: #-------------------------- Next few routines handles grading by section or whole class
 3355: #
 3356: #--- Javascript to handle grading by section or whole class
 3357: sub viewgrades_js {
 3358:     my ($request) = shift;
 3359: 
 3360:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3361:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3362:    function writePoint(partid,weight,point) {
 3363: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3364: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3365: 	if (point == "textval") {
 3366: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3367: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3368: 		alert("$alertmsg"+parseFloat(point));
 3369: 		var resetbox = false;
 3370: 		for (var i=0; i<radioButton.length; i++) {
 3371: 		    if (radioButton[i].checked) {
 3372: 			textbox.value = i;
 3373: 			resetbox = true;
 3374: 		    }
 3375: 		}
 3376: 		if (!resetbox) {
 3377: 		    textbox.value = "";
 3378: 		}
 3379: 		return;
 3380: 	    }
 3381: 	    if (parseFloat(point) > parseFloat(weight)) {
 3382: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3383: 				   ") greater than the weight for the part. Accept?");
 3384: 		if (resp == false) {
 3385: 		    textbox.value = "";
 3386: 		    return;
 3387: 		}
 3388: 	    }
 3389: 	    for (var i=0; i<radioButton.length; i++) {
 3390: 		radioButton[i].checked=false;
 3391: 		if (parseFloat(point) == i) {
 3392: 		    radioButton[i].checked=true;
 3393: 		}
 3394: 	    }
 3395: 
 3396: 	} else {
 3397: 	    textbox.value = parseFloat(point);
 3398: 	}
 3399: 	for (i=0;i<document.classgrade.total.value;i++) {
 3400: 	    var user = document.classgrade["ctr"+i].value;
 3401: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3402: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3403: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3404: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3405: 	    if (saveval != "correct") {
 3406: 		scorename.value = point;
 3407: 		if (selname[0].selected != true) {
 3408: 		    selname[0].selected = true;
 3409: 		}
 3410: 	    }
 3411: 	}
 3412: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3413:     }
 3414: 
 3415:     function writeRadText(partid,weight) {
 3416: 	var selval   = document.classgrade["SELVAL_"+partid];
 3417: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3418:         var override = document.classgrade["FORCE_"+partid].checked;
 3419: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3420: 	if (selval[1].selected || selval[2].selected) {
 3421: 	    for (var i=0; i<radioButton.length; i++) {
 3422: 		radioButton[i].checked=false;
 3423: 
 3424: 	    }
 3425: 	    textbox.value = "";
 3426: 
 3427: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3428: 		var user = document.classgrade["ctr"+i].value;
 3429: 		user = user.replace(new RegExp(':', 'g'),"_");
 3430: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3431: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3432: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3433: 		if ((saveval != "correct") || override) {
 3434: 		    scorename.value = "";
 3435: 		    if (selval[1].selected) {
 3436: 			selname[1].selected = true;
 3437: 		    } else {
 3438: 			selname[2].selected = true;
 3439: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3440: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3441: 		    }
 3442: 		}
 3443: 	    }
 3444: 	} else {
 3445: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3446: 		var user = document.classgrade["ctr"+i].value;
 3447: 		user = user.replace(new RegExp(':', 'g'),"_");
 3448: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3449: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3450: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3451: 		if ((saveval != "correct") || override) {
 3452: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3453: 		    selname[0].selected = true;
 3454: 		}
 3455: 	    }
 3456: 	}	    
 3457:     }
 3458: 
 3459:     function changeSelect(partid,user) {
 3460: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3461: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3462: 	var point  = textbox.value;
 3463: 	var weight = document.classgrade["weight_"+partid].value;
 3464: 
 3465: 	if (isNaN(point) || parseFloat(point) < 0) {
 3466: 	    alert("$alertmsg"+parseFloat(point));
 3467: 	    textbox.value = "";
 3468: 	    return;
 3469: 	}
 3470: 	if (parseFloat(point) > parseFloat(weight)) {
 3471: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3472: 			       ") greater than the weight of the part. Accept?");
 3473: 	    if (resp == false) {
 3474: 		textbox.value = "";
 3475: 		return;
 3476: 	    }
 3477: 	}
 3478: 	selval[0].selected = true;
 3479:     }
 3480: 
 3481:     function changeOneScore(partid,user) {
 3482: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3483: 	if (selval[1].selected || selval[2].selected) {
 3484: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3485: 	    if (selval[2].selected) {
 3486: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3487: 	    }
 3488:         }
 3489:     }
 3490: 
 3491:     function resetEntry(numpart) {
 3492: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3493: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3494: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3495: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3496: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3497: 	    for (var i=0; i<radioButton.length; i++) {
 3498: 		radioButton[i].checked=false;
 3499: 
 3500: 	    }
 3501: 	    textbox.value = "";
 3502: 	    selval[0].selected = true;
 3503: 
 3504: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3505: 		var user = document.classgrade["ctr"+i].value;
 3506: 		user = user.replace(new RegExp(':', 'g'),"_");
 3507: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3508: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3509: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3510: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3511: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3512: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3513: 		if (saveselval == "excused") {
 3514: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3515: 		} else {
 3516: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3517: 		}
 3518: 	    }
 3519: 	}
 3520:     }
 3521: 
 3522: VIEWJAVASCRIPT
 3523: }
 3524: 
 3525: #--- show scores for a section or whole class w/ option to change/update a score
 3526: sub viewgrades {
 3527:     my ($request,$symb) = @_;
 3528:     &viewgrades_js($request);
 3529: 
 3530:     #need to make sure we have the correct data for later EXT calls, 
 3531:     #thus invalidate the cache
 3532:     &Apache::lonnet::devalidatecourseresdata(
 3533:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3534:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3535:     &Apache::lonnet::clear_EXT_cache_status();
 3536: 
 3537:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3538: 
 3539:     #view individual student submission form - called using Javascript viewOneStudent
 3540:     $result.=&jscriptNform($symb);
 3541: 
 3542:     #beginning of class grading form
 3543:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3544:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3545: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3546: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3547: 	&build_section_inputs().
 3548: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3549: 
 3550:     my ($common_header,$specific_header);
 3551:     if ($env{'form.section'} eq 'all') {
 3552: 	$common_header = &mt('Assign Common Grade to Class');
 3553:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3554:     } elsif ($env{'form.section'} eq 'none') {
 3555:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3556: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3557:     } else {
 3558:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3559:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3560: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3561:     }
 3562:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3563:     #radio buttons/text box for assigning points for a section or class.
 3564:     #handles different parts of a problem
 3565:     my $res_error;
 3566:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3567:     if ($res_error) {
 3568:         return &navmap_errormsg();
 3569:     }
 3570:     my %weight = ();
 3571:     my $ctsparts = 0;
 3572:     my %seen = ();
 3573:     my @part_response_id = &flatten_responseType($responseType);
 3574:     foreach my $part_response_id (@part_response_id) {
 3575:     	my ($partid,$respid) = @{ $part_response_id };
 3576: 	my $part_resp = join('_',@{ $part_response_id });
 3577: 	next if $seen{$partid};
 3578: 	$seen{$partid}++;
 3579: 	my $handgrade=$$handgrade{$part_resp};
 3580: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3581: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3582: 
 3583: 	my $display_part=&get_display_part($partid,$symb);
 3584: 	my $radio.='<table border="0"><tr>';  
 3585: 	my $ctr = 0;
 3586: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3587: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3588: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3589: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3590: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3591: 	    $ctr++;
 3592: 	}
 3593: 	$radio.='</tr></table>';
 3594: 	my $line = '<input type="text" name="TEXTVAL_'.
 3595: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3596: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3597: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3598:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3599:             '<select name="SELVAL_'.$partid.'" '.
 3600:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3601:                 $weight{$partid}.')"> '.
 3602: 	    '<option selected="selected"> </option>'.
 3603: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3604: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3605: 	    '</select></td>'.
 3606:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3607: 	$line.='<input type="hidden" name="partid_'.
 3608: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3609: 	$line.='<input type="hidden" name="weight_'.
 3610: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3611: 
 3612: 	$result.=
 3613: 	    &Apache::loncommon::start_data_table_row()."\n".
 3614: 	    '<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>'.
 3615: 	    &Apache::loncommon::end_data_table_row()."\n";
 3616: 	$ctsparts++;
 3617:     }
 3618:     $result.=&Apache::loncommon::end_data_table()."\n".
 3619: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3620:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3621: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3622: 
 3623:     #table listing all the students in a section/class
 3624:     #header of table
 3625:     $result.= '<h3>'.$specific_header.'</h3>'.
 3626:               &Apache::loncommon::start_data_table().
 3627: 	      &Apache::loncommon::start_data_table_header_row().
 3628: 	      '<th>'.&mt('No.').'</th>'.
 3629: 	      '<th>'.&nameUserString('header')."</th>\n";
 3630:     my $partserror;
 3631:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3632:     if ($partserror) {
 3633:         return &navmap_errormsg();
 3634:     }
 3635:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3636:     my @partids = ();
 3637:     foreach my $part (@parts) {
 3638: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3639:         my $narrowtext = &mt('Tries');
 3640: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3641: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3642: 	my ($partid) = &split_part_type($part);
 3643:         push(@partids,$partid);
 3644: #
 3645: # FIXME: Looks like $display looks at English text
 3646: #
 3647: 	my $display_part=&get_display_part($partid,$symb);
 3648: 	if ($display =~ /^Partial Credit Factor/) {
 3649: 	    $result.='<th>'.
 3650: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3651: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3652: 	    next;
 3653: 	    
 3654: 	} else {
 3655: 	    if ($display =~ /Problem Status/) {
 3656: 		my $grade_status_mt = &mt('Grade Status');
 3657: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3658: 	    }
 3659: 	    my $part_mt = &mt('Part:');
 3660: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3661: 	}
 3662: 
 3663: 	$result.='<th>'.$display.'</th>'."\n";
 3664:     }
 3665:     $result.=&Apache::loncommon::end_data_table_header_row();
 3666: 
 3667:     my %last_resets = 
 3668: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3669: 
 3670:     #get info for each student
 3671:     #list all the students - with points and grade status
 3672:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3673:     my $ctr = 0;
 3674:     foreach (sort 
 3675: 	     {
 3676: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3677: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3678: 		 }
 3679: 		 return $a cmp $b;
 3680: 	     } (keys(%$fullname))) {
 3681: 	$ctr++;
 3682: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3683: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3684:     }
 3685:     $result.=&Apache::loncommon::end_data_table();
 3686:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3687:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3688: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3689:     if (scalar(%$fullname) eq 0) {
 3690: 	my $colspan=3+scalar(@parts);
 3691: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3692:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3693: 	$result='<span class="LC_warning">'.
 3694: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3695: 	        $section_display, $stu_status).
 3696: 	    '</span>';
 3697:     }
 3698:     return $result;
 3699: }
 3700: 
 3701: #--- call by previous routine to display each student
 3702: sub viewstudentgrade {
 3703:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3704:     my ($uname,$udom) = split(/:/,$student);
 3705:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3706:     my %aggregates = (); 
 3707:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3708: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3709: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3710: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3711: 	'\');" target="_self">'.$fullname.'</a> '.
 3712: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3713:     $student=~s/:/_/; # colon doen't work in javascript for names
 3714:     foreach my $apart (@$parts) {
 3715: 	my ($part,$type) = &split_part_type($apart);
 3716: 	my $score=$record{"resource.$part.$type"};
 3717:         $result.='<td align="center">';
 3718:         my ($aggtries,$totaltries);
 3719:         unless (exists($aggregates{$part})) {
 3720: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3721: 
 3722: 	    $aggtries = $totaltries;
 3723:             if ($$last_resets{$part}) {  
 3724:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3725: 					   $part);
 3726:             }
 3727:             $result.='<input type="hidden" name="'.
 3728:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3729:             $result.='<input type="hidden" name="'.
 3730:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3731:             $aggregates{$part} = 1;
 3732:         }
 3733: 	if ($type eq 'awarded') {
 3734: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3735: 	    $result.='<input type="hidden" name="'.
 3736: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3737: 	    $result.='<input type="text" name="'.
 3738: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3739:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3740: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3741: 	} elsif ($type eq 'solved') {
 3742: 	    my ($status,$foo)=split(/_/,$score,2);
 3743: 	    $status = 'nothing' if ($status eq '');
 3744: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3745: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3746: 	    $result.='&nbsp;<select name="'.
 3747: 		'GD_'.$student.'_'.$part.'_solved" '.
 3748:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3749: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3750: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3751: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3752: 	    $result.="</select>&nbsp;</td>\n";
 3753: 	} else {
 3754: 	    $result.='<input type="hidden" name="'.
 3755: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3756: 		    "\n";
 3757: 	    $result.='<input type="text" name="'.
 3758: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3759: 		'value="'.$score.'" size="4" /></td>'."\n";
 3760: 	}
 3761:     }
 3762:     $result.=&Apache::loncommon::end_data_table_row();
 3763:     return $result;
 3764: }
 3765: 
 3766: #--- change scores for all the students in a section/class
 3767: #    record does not get update if unchanged
 3768: sub editgrades {
 3769:     my ($request,$symb) = @_;
 3770: 
 3771:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3772:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3773:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3774: 
 3775:     my $result= &Apache::loncommon::start_data_table().
 3776: 	&Apache::loncommon::start_data_table_header_row().
 3777: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3778: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3779:     my %scoreptr = (
 3780: 		    'correct'  =>'correct_by_override',
 3781: 		    'incorrect'=>'incorrect_by_override',
 3782: 		    'excused'  =>'excused',
 3783: 		    'ungraded' =>'ungraded_attempted',
 3784:                     'credited' =>'credit_attempted',
 3785: 		    'nothing'  => '',
 3786: 		    );
 3787:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3788: 
 3789:     my (@partid);
 3790:     my %weight = ();
 3791:     my %columns = ();
 3792:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3793: 
 3794:     my $partserror;
 3795:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3796:     if ($partserror) {
 3797:         return &navmap_errormsg();
 3798:     }
 3799:     my $header;
 3800:     while ($ctr < $env{'form.totalparts'}) {
 3801: 	my $partid = $env{'form.partid_'.$ctr};
 3802: 	push(@partid,$partid);
 3803: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3804: 	$ctr++;
 3805:     }
 3806:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3807:     foreach my $partid (@partid) {
 3808: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3809: 	    '<th align="center">'.&mt('New Score').'</th>';
 3810: 	$columns{$partid}=2;
 3811: 	foreach my $stores (@parts) {
 3812: 	    my ($part,$type) = &split_part_type($stores);
 3813: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3814: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3815: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3816: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3817:             my $narrowtext = &mt('Tries');
 3818: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3819: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3820: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3821: 	    $columns{$partid}+=2;
 3822: 	}
 3823:     }
 3824:     foreach my $partid (@partid) {
 3825: 	my $display_part=&get_display_part($partid,$symb);
 3826: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3827: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3828: 	    '</th>';
 3829: 
 3830:     }
 3831:     $result .= &Apache::loncommon::end_data_table_header_row().
 3832: 	&Apache::loncommon::start_data_table_header_row().
 3833: 	$header.
 3834: 	&Apache::loncommon::end_data_table_header_row();
 3835:     my @noupdate;
 3836:     my ($updateCtr,$noupdateCtr) = (1,1);
 3837:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3838: 	my $line;
 3839: 	my $user = $env{'form.ctr'.$i};
 3840: 	my ($uname,$udom)=split(/:/,$user);
 3841: 	my %newrecord;
 3842: 	my $updateflag = 0;
 3843: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3844: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3845: 	if (!&canmodify($usec)) {
 3846: 	    my $numcols=scalar(@partid)*4+2;
 3847: 	    push(@noupdate,
 3848: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3849: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3850: 	    next;
 3851: 	}
 3852:         my %aggregate = ();
 3853:         my $aggregateflag = 0;
 3854: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3855: 	foreach (@partid) {
 3856: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3857: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3858: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3859: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3860: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3861: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3862: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3863: 	    my $score;
 3864: 	    if ($partial eq '') {
 3865: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3866: 	    } elsif ($partial > 0) {
 3867: 		$score = 'correct_by_override';
 3868: 	    } elsif ($partial == 0) {
 3869: 		$score = 'incorrect_by_override';
 3870: 	    }
 3871: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3872: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3873: 
 3874: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3875: 		"$env{'user.name'}:$env{'user.domain'}";
 3876: 	    if ($dropMenu eq 'reset status' &&
 3877: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3878: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3879: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3880: 		$newrecord{'resource.'.$_.'.award'} = '';
 3881: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3882: 		$updateflag = 1;
 3883:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3884:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3885:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3886:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3887:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3888:                     $aggregateflag = 1;
 3889:                 }
 3890: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3891: 		$updateflag = 1;
 3892: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3893: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3894: 		$rec_update++;
 3895: 	    }
 3896: 
 3897: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3898: 		'<td align="center">'.$awarded.
 3899: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3900: 
 3901: 
 3902: 	    my $partid=$_;
 3903: 	    foreach my $stores (@parts) {
 3904: 		my ($part,$type) = &split_part_type($stores);
 3905: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3906: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3907: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3908: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3909: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3910: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3911: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3912: 		    $updateflag=1;
 3913: 		}
 3914: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3915: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3916: 	    }
 3917: 	}
 3918: 	$line.="\n";
 3919: 
 3920: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3921: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3922: 
 3923: 	if ($updateflag) {
 3924: 	    $count++;
 3925: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3926: 				    $udom,$uname);
 3927: 
 3928: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3929: 					      $cnum,$udom,$uname)) {
 3930: 		# need to figure out if should be in queue.
 3931: 		my %record =  
 3932: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3933: 					     $udom,$uname);
 3934: 		my $all_graded = 1;
 3935: 		my $none_graded = 1;
 3936: 		foreach my $part (@parts) {
 3937: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3938: 			$all_graded = 0;
 3939: 		    } else {
 3940: 			$none_graded = 0;
 3941: 		    }
 3942: 		}
 3943: 
 3944: 		if ($all_graded || $none_graded) {
 3945: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3946: 							   $symb,$cdom,$cnum,
 3947: 							   $udom,$uname);
 3948: 		}
 3949: 	    }
 3950: 
 3951: 	    $result.=&Apache::loncommon::start_data_table_row().
 3952: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3953: 		&Apache::loncommon::end_data_table_row();
 3954: 	    $updateCtr++;
 3955: 	} else {
 3956: 	    push(@noupdate,
 3957: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3958: 	    $noupdateCtr++;
 3959: 	}
 3960:         if ($aggregateflag) {
 3961:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3962: 				  $cdom,$cnum);
 3963:         }
 3964:     }
 3965:     if (@noupdate) {
 3966: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3967: 	my $numcols=scalar(@partid)*4+2;
 3968: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3969: 	    '<td align="center" colspan="'.$numcols.'">'.
 3970: 	    &mt('No Changes Occurred For the Students Below').
 3971: 	    '</td>'.
 3972: 	    &Apache::loncommon::end_data_table_row();
 3973: 	foreach my $line (@noupdate) {
 3974: 	    $result.=
 3975: 		&Apache::loncommon::start_data_table_row().
 3976: 		$line.
 3977: 		&Apache::loncommon::end_data_table_row();
 3978: 	}
 3979:     }
 3980:     $result .= &Apache::loncommon::end_data_table();
 3981:     my $msg = '<p><b>'.
 3982: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3983: 	    $rec_update,$count).'</b><br />'.
 3984: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3985: 	'</b></p>';
 3986:     return $title.$msg.$result;
 3987: }
 3988: 
 3989: sub split_part_type {
 3990:     my ($partstr) = @_;
 3991:     my ($temp,@allparts)=split(/_/,$partstr);
 3992:     my $type=pop(@allparts);
 3993:     my $part=join('_',@allparts);
 3994:     return ($part,$type);
 3995: }
 3996: 
 3997: #------------- end of section for handling grading by section/class ---------
 3998: #
 3999: #----------------------------------------------------------------------------
 4000: 
 4001: 
 4002: #----------------------------------------------------------------------------
 4003: #
 4004: #-------------------------- Next few routines handles grading by csv upload
 4005: #
 4006: #--- Javascript to handle csv upload
 4007: sub csvupload_javascript_reverse_associate {
 4008:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4009:     my $error2=&mt('You need to specify at least one grading field');
 4010:   return(<<ENDPICK);
 4011:   function verify(vf) {
 4012:     var foundsomething=0;
 4013:     var founduname=0;
 4014:     var foundID=0;
 4015:     for (i=0;i<=vf.nfields.value;i++) {
 4016:       tw=eval('vf.f'+i+'.selectedIndex');
 4017:       if (i==0 && tw!=0) { foundID=1; }
 4018:       if (i==1 && tw!=0) { founduname=1; }
 4019:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4020:     }
 4021:     if (founduname==0 && foundID==0) {
 4022: 	alert('$error1');
 4023: 	return;
 4024:     }
 4025:     if (foundsomething==0) {
 4026: 	alert('$error2');
 4027: 	return;
 4028:     }
 4029:     vf.submit();
 4030:   }
 4031:   function flip(vf,tf) {
 4032:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4033:     var i;
 4034:     for (i=0;i<=vf.nfields.value;i++) {
 4035:       //can not pick the same destination field for both name and domain
 4036:       if (((i ==0)||(i ==1)) && 
 4037:           ((tf==0)||(tf==1)) && 
 4038:           (i!=tf) &&
 4039:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4040:         eval('vf.f'+i+'.selectedIndex=0;')
 4041:       }
 4042:     }
 4043:   }
 4044: ENDPICK
 4045: }
 4046: 
 4047: sub csvupload_javascript_forward_associate {
 4048:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4049:     my $error2=&mt('You need to specify at least one grading field');
 4050:   return(<<ENDPICK);
 4051:   function verify(vf) {
 4052:     var foundsomething=0;
 4053:     var founduname=0;
 4054:     var foundID=0;
 4055:     for (i=0;i<=vf.nfields.value;i++) {
 4056:       tw=eval('vf.f'+i+'.selectedIndex');
 4057:       if (tw==1) { foundID=1; }
 4058:       if (tw==2) { founduname=1; }
 4059:       if (tw>3) { foundsomething=1; }
 4060:     }
 4061:     if (founduname==0 && foundID==0) {
 4062: 	alert('$error1');
 4063: 	return;
 4064:     }
 4065:     if (foundsomething==0) {
 4066: 	alert('$error2');
 4067: 	return;
 4068:     }
 4069:     vf.submit();
 4070:   }
 4071:   function flip(vf,tf) {
 4072:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4073:     var i;
 4074:     //can not pick the same destination field twice
 4075:     for (i=0;i<=vf.nfields.value;i++) {
 4076:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4077:         eval('vf.f'+i+'.selectedIndex=0;')
 4078:       }
 4079:     }
 4080:   }
 4081: ENDPICK
 4082: }
 4083: 
 4084: sub csvuploadmap_header {
 4085:     my ($request,$symb,$datatoken,$distotal)= @_;
 4086:     my $javascript;
 4087:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4088: 	$javascript=&csvupload_javascript_reverse_associate();
 4089:     } else {
 4090: 	$javascript=&csvupload_javascript_forward_associate();
 4091:     }
 4092: 
 4093:     $symb = &Apache::lonenc::check_encrypt($symb);
 4094:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4095:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4096:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4097:     my $reverse=&mt("Reverse Association");
 4098:     $request->print(<<ENDPICK);
 4099: <br />
 4100: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4101: <input type="hidden" name="associate"  value="" />
 4102: <input type="hidden" name="phase"      value="three" />
 4103: <input type="hidden" name="datatoken"  value="$datatoken" />
 4104: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4105: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4106: <input type="hidden" name="upfile_associate" 
 4107:                                        value="$env{'form.upfile_associate'}" />
 4108: <input type="hidden" name="symb"       value="$symb" />
 4109: <input type="hidden" name="command"    value="csvuploadoptions" />
 4110: <hr />
 4111: ENDPICK
 4112:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4113:     return '';
 4114: 
 4115: }
 4116: 
 4117: sub csvupload_fields {
 4118:     my ($symb,$errorref) = @_;
 4119:     my (@parts) = &getpartlist($symb,$errorref);
 4120:     if (ref($errorref)) {
 4121:         if ($$errorref) {
 4122:             return;
 4123:         }
 4124:     }
 4125: 
 4126:     my @fields=(['ID','Student/Employee ID'],
 4127: 		['username','Student Username'],
 4128: 		['domain','Student Domain']);
 4129:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4130:     foreach my $part (sort(@parts)) {
 4131: 	my @datum;
 4132: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4133: 	my $name=$part;
 4134: 	if  (!$display) { $display = $name; }
 4135: 	@datum=($name,$display);
 4136: 	if ($name=~/^stores_(.*)_awarded/) {
 4137: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4138: 	}
 4139: 	push(@fields,\@datum);
 4140:     }
 4141:     return (@fields);
 4142: }
 4143: 
 4144: sub csvuploadmap_footer {
 4145:     my ($request,$i,$keyfields) =@_;
 4146:     my $buttontext = &mt('Assign Grades');
 4147:     $request->print(<<ENDPICK);
 4148: </table>
 4149: <input type="hidden" name="nfields" value="$i" />
 4150: <input type="hidden" name="keyfields" value="$keyfields" />
 4151: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4152: </form>
 4153: ENDPICK
 4154: }
 4155: 
 4156: sub checkforfile_js {
 4157:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4158:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4159:     function checkUpload(formname) {
 4160: 	if (formname.upfile.value == "") {
 4161: 	    alert("$alertmsg");
 4162: 	    return false;
 4163: 	}
 4164: 	formname.submit();
 4165:     }
 4166: CSVFORMJS
 4167:     return $result;
 4168: }
 4169: 
 4170: sub upcsvScores_form {
 4171:     my ($request,$symb) = @_;
 4172:     if (!$symb) {return '';}
 4173:     my $result=&checkforfile_js();
 4174:     $result.=&Apache::loncommon::start_data_table().
 4175:              &Apache::loncommon::start_data_table_header_row().
 4176:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4177:              &Apache::loncommon::end_data_table_header_row().
 4178:              &Apache::loncommon::start_data_table_row().'<td>';
 4179:     my $upload=&mt("Upload Scores");
 4180:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4181:     my $ignore=&mt('Ignore First Line');
 4182:     $symb = &Apache::lonenc::check_encrypt($symb);
 4183:     $result.=<<ENDUPFORM;
 4184: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4185: <input type="hidden" name="symb" value="$symb" />
 4186: <input type="hidden" name="command" value="csvuploadmap" />
 4187: $upfile_select
 4188: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4189: </form>
 4190: ENDUPFORM
 4191:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4192:                            &mt("How do I create a CSV file from a spreadsheet")).
 4193:              '</td>'.
 4194:             &Apache::loncommon::end_data_table_row().
 4195:             &Apache::loncommon::end_data_table();
 4196:     return $result;
 4197: }
 4198: 
 4199: 
 4200: sub csvuploadmap {
 4201:     my ($request,$symb)= @_;
 4202:     if (!$symb) {return '';}
 4203: 
 4204:     my $datatoken;
 4205:     if (!$env{'form.datatoken'}) {
 4206: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4207:     } else {
 4208: 	$datatoken=$env{'form.datatoken'};
 4209: 	&Apache::loncommon::load_tmp_file($request);
 4210:     }
 4211:     my @records=&Apache::loncommon::upfile_record_sep();
 4212:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4213:     my ($i,$keyfields);
 4214:     if (@records) {
 4215:         my $fieldserror;
 4216: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4217:         if ($fieldserror) {
 4218:             $request->print(&navmap_errormsg());
 4219:             return;
 4220:         }
 4221: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4222: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4223: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4224: 							  \@fields);
 4225: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4226: 	    chop($keyfields);
 4227: 	} else {
 4228: 	    unshift(@fields,['none','']);
 4229: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4230: 							    \@fields);
 4231:             foreach my $rec (@records) {
 4232:                 my %temp = &Apache::loncommon::record_sep($rec);
 4233:                 if (%temp) {
 4234:                     $keyfields=join(',',sort(keys(%temp)));
 4235:                     last;
 4236:                 }
 4237:             }
 4238: 	}
 4239:     }
 4240:     &csvuploadmap_footer($request,$i,$keyfields);
 4241: 
 4242:     return '';
 4243: }
 4244: 
 4245: sub csvuploadoptions {
 4246:     my ($request,$symb)= @_;
 4247:     my $overwrite=&mt('Overwrite any existing score');
 4248:     $request->print(<<ENDPICK);
 4249: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4250: <input type="hidden" name="command"    value="csvuploadassign" />
 4251: <p>
 4252: <label>
 4253:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4254:    $overwrite
 4255: </label>
 4256: </p>
 4257: ENDPICK
 4258:     my %fields=&get_fields();
 4259:     if (!defined($fields{'domain'})) {
 4260: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4261: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4262:     }
 4263:     foreach my $key (sort(keys(%env))) {
 4264: 	if ($key !~ /^form\.(.*)$/) { next; }
 4265: 	my $cleankey=$1;
 4266: 	if ($cleankey eq 'command') { next; }
 4267: 	$request->print('<input type="hidden" name="'.$cleankey.
 4268: 			'"  value="'.$env{$key}.'" />'."\n");
 4269:     }
 4270:     # FIXME do a check for any duplicated user ids...
 4271:     # FIXME do a check for any invalid user ids?...
 4272:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4273: <hr /></form>'."\n");
 4274:     return '';
 4275: }
 4276: 
 4277: sub get_fields {
 4278:     my %fields;
 4279:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4280:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4281: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4282: 	    if ($env{'form.f'.$i} ne 'none') {
 4283: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4284: 	    }
 4285: 	} else {
 4286: 	    if ($env{'form.f'.$i} ne 'none') {
 4287: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4288: 	    }
 4289: 	}
 4290:     }
 4291:     return %fields;
 4292: }
 4293: 
 4294: sub csvuploadassign {
 4295:     my ($request,$symb)= @_;
 4296:     if (!$symb) {return '';}
 4297:     my $error_msg = '';
 4298:     &Apache::loncommon::load_tmp_file($request);
 4299:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4300:     my %fields=&get_fields();
 4301:     my $courseid=$env{'request.course.id'};
 4302:     my ($classlist) = &getclasslist('all',0);
 4303:     my @notallowed;
 4304:     my @skipped;
 4305:     my @warnings;
 4306:     my $countdone=0;
 4307:     foreach my $grade (@gradedata) {
 4308: 	my %entries=&Apache::loncommon::record_sep($grade);
 4309: 	my $domain;
 4310: 	if ($entries{$fields{'domain'}}) {
 4311: 	    $domain=$entries{$fields{'domain'}};
 4312: 	} else {
 4313: 	    $domain=$env{'form.default_domain'};
 4314: 	}
 4315: 	$domain=~s/\s//g;
 4316: 	my $username=$entries{$fields{'username'}};
 4317: 	$username=~s/\s//g;
 4318: 	if (!$username) {
 4319: 	    my $id=$entries{$fields{'ID'}};
 4320: 	    $id=~s/\s//g;
 4321: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4322: 	    $username=$ids{$id};
 4323: 	}
 4324: 	if (!exists($$classlist{"$username:$domain"})) {
 4325: 	    my $id=$entries{$fields{'ID'}};
 4326: 	    $id=~s/\s//g;
 4327: 	    if ($id) {
 4328: 		push(@skipped,"$id:$domain");
 4329: 	    } else {
 4330: 		push(@skipped,"$username:$domain");
 4331: 	    }
 4332: 	    next;
 4333: 	}
 4334: 	my $usec=$classlist->{"$username:$domain"}[5];
 4335: 	if (!&canmodify($usec)) {
 4336: 	    push(@notallowed,"$username:$domain");
 4337: 	    next;
 4338: 	}
 4339: 	my %points;
 4340: 	my %grades;
 4341: 	foreach my $dest (keys(%fields)) {
 4342: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4343: 		$dest eq 'domain') { next; }
 4344: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4345: 	    if ($dest=~/stores_(.*)_points/) {
 4346: 		my $part=$1;
 4347: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4348: 					      $symb,$domain,$username);
 4349:                 if ($wgt) {
 4350:                     $entries{$fields{$dest}}=~s/\s//g;
 4351:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4352:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4353:                                           : 'correct_by_override';
 4354:                     if ($pcr>1) {
 4355:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4356:                     }
 4357:                     $grades{"resource.$part.awarded"}=$pcr;
 4358:                     $grades{"resource.$part.solved"}=$award;
 4359:                     $points{$part}=1;
 4360:                 } else {
 4361:                     $error_msg = "<br />" .
 4362:                         &mt("Some point values were assigned"
 4363:                             ." for problems with a weight "
 4364:                             ."of zero. These values were "
 4365:                             ."ignored.");
 4366:                 }
 4367: 	    } else {
 4368: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4369: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4370: 		my $store_key=$dest;
 4371: 		$store_key=~s/^stores/resource/;
 4372: 		$store_key=~s/_/\./g;
 4373: 		$grades{$store_key}=$entries{$fields{$dest}};
 4374: 	    }
 4375: 	}
 4376: 	if (! %grades) { 
 4377:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4378:         } else {
 4379: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4380: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4381: 					   $env{'request.course.id'},
 4382: 					   $domain,$username);
 4383: 	   if ($result eq 'ok') {
 4384: # Successfully stored
 4385: 	      $request->print('.');
 4386: # Remove from grading queue
 4387:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4388:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4389:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4390:                                              $domain,$username);
 4391:               $countdone++;
 4392:            } else {
 4393: 	      $request->print("<p><span class=\"LC_error\">".
 4394:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4395:                                   "$username:$domain",$result)."</span></p>");
 4396: 	   }
 4397: 	   $request->rflush();
 4398:         }
 4399:     }
 4400:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4401:     if (@warnings) {
 4402:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4403:         $request->print(join(', ',@warnings));
 4404:     }
 4405:     if (@skipped) {
 4406: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4407:         $request->print(join(', ',@skipped));
 4408:     }
 4409:     if (@notallowed) {
 4410: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4411: 	$request->print(join(', ',@notallowed));
 4412:     }
 4413:     $request->print("<br />\n");
 4414:     return $error_msg;
 4415: }
 4416: #------------- end of section for handling csv file upload ---------
 4417: #
 4418: #-------------------------------------------------------------------
 4419: #
 4420: #-------------- Next few routines handle grading by page/sequence
 4421: #
 4422: #--- Select a page/sequence and a student to grade
 4423: sub pickStudentPage {
 4424:     my ($request,$symb) = @_;
 4425: 
 4426:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4427:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4428: 
 4429: function checkPickOne(formname) {
 4430:     if (radioSelection(formname.student) == null) {
 4431: 	alert("$alertmsg");
 4432: 	return;
 4433:     }
 4434:     ptr = pullDownSelection(formname.selectpage);
 4435:     formname.page.value = formname["page"+ptr].value;
 4436:     formname.title.value = formname["title"+ptr].value;
 4437:     formname.submit();
 4438: }
 4439: 
 4440: LISTJAVASCRIPT
 4441:     &commonJSfunctions($request);
 4442: 
 4443:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4444:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4445:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4446: 
 4447:     my $result='<h3><span class="LC_info">&nbsp;'.
 4448: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4449: 
 4450:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4451:     my $map_error;
 4452:     my ($titles,$symbx) = &getSymbMap($map_error);
 4453:     if ($map_error) {
 4454:         $request->print(&navmap_errormsg());
 4455:         return; 
 4456:     }
 4457:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4458: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4459: #    my $type=($curpage =~ /\.(page|sequence)/);
 4460: 
 4461:     # Collection of hidden fields
 4462:     my $ctr=0;
 4463:     foreach (@$titles) {
 4464:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4465:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4466:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4467:         $ctr++;
 4468:     }
 4469:     $result.='<input type="hidden" name="page" />'."\n".
 4470:         '<input type="hidden" name="title" />'."\n";
 4471: 
 4472:     $result.=&build_section_inputs();
 4473:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4474:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4475: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4476: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4477: 
 4478:     # Show grading options
 4479:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4480:     my $select = '<select name="selectpage">'."\n";
 4481:     $ctr=0;
 4482:     foreach (@$titles) {
 4483: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4484: 	$select.='<option value="'.$ctr.'"'.
 4485: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4486: 	    '>'.$showtitle.'</option>'."\n";
 4487: 	$ctr++;
 4488:     }
 4489:     $select.= '</select>';
 4490: 
 4491:     $result.=
 4492:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4493:        .$select
 4494:        .&Apache::lonhtmlcommon::row_closure();
 4495: 
 4496:     $result.=
 4497:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4498:        .'<label><input type="radio" name="vProb" value="no"'
 4499:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4500:        .'<label><input type="radio" name="vProb" value="yes" />'
 4501:            .&mt('yes').'</label>'."\n"
 4502:        .&Apache::lonhtmlcommon::row_closure();
 4503: 
 4504:     $result.=
 4505:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4506:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4507:            .&mt('none').' </label>'."\n"
 4508:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4509:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4510:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4511:            .&mt('all submissions with details').' </label>'
 4512:        .&Apache::lonhtmlcommon::row_closure();
 4513:     
 4514:     $result.=
 4515:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4516:        .'<input type="text" name="CODE" value="" />'
 4517:        .&Apache::lonhtmlcommon::row_closure(1)
 4518:        .&Apache::lonhtmlcommon::end_pick_box();
 4519: 
 4520:     # Show list of students to select for grading
 4521:     $result.='<br /><input type="button" '.
 4522:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4523: 
 4524:     $request->print($result);
 4525: 
 4526:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4527: 	&Apache::loncommon::start_data_table().
 4528: 	&Apache::loncommon::start_data_table_header_row().
 4529: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4530: 	'<th>'.&nameUserString('header').'</th>'.
 4531: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4532: 	'<th>'.&nameUserString('header').'</th>'.
 4533: 	&Apache::loncommon::end_data_table_header_row();
 4534:  
 4535:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4536:     my $ptr = 1;
 4537:     foreach my $student (sort 
 4538: 			 {
 4539: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4540: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4541: 			     }
 4542: 			     return $a cmp $b;
 4543: 			 } (keys(%$fullname))) {
 4544: 	my ($uname,$udom) = split(/:/,$student);
 4545: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4546:                                   : '</td>');
 4547: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4548: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4549: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4550: 	$studentTable.=
 4551: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4552:                          : '');
 4553: 	$ptr++;
 4554:     }
 4555:     if ($ptr%2 == 0) {
 4556: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4557: 	    &Apache::loncommon::end_data_table_row();
 4558:     }
 4559:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4560:     $studentTable.='<input type="button" '.
 4561:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4562: 
 4563:     $request->print($studentTable);
 4564: 
 4565:     return '';
 4566: }
 4567: 
 4568: sub getSymbMap {
 4569:     my ($map_error) = @_;
 4570:     my $navmap = Apache::lonnavmaps::navmap->new();
 4571:     unless (ref($navmap)) {
 4572:         if (ref($map_error)) {
 4573:             $$map_error = 'navmap';
 4574:         }
 4575:         return;
 4576:     }
 4577:     my %symbx = ();
 4578:     my @titles = ();
 4579:     my $minder = 0;
 4580: 
 4581:     # Gather every sequence that has problems.
 4582:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4583: 					       1,0,1);
 4584:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4585: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4586: 	    my $title = $minder.'.'.
 4587: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4588: 	    push(@titles, $title); # minder in case two titles are identical
 4589: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4590: 	    $minder++;
 4591: 	}
 4592:     }
 4593:     return \@titles,\%symbx;
 4594: }
 4595: 
 4596: #
 4597: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4598: sub displayPage {
 4599:     my ($request,$symb) = @_;
 4600:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4601:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4602:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4603:     my $pageTitle = $env{'form.page'};
 4604:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4605:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4606:     my $usec=$classlist->{$env{'form.student'}}[5];
 4607: 
 4608:     #need to make sure we have the correct data for later EXT calls, 
 4609:     #thus invalidate the cache
 4610:     &Apache::lonnet::devalidatecourseresdata(
 4611:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4612:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4613:     &Apache::lonnet::clear_EXT_cache_status();
 4614: 
 4615:     if (!&canview($usec)) {
 4616: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4617: 	return;
 4618:     }
 4619:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4620:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4621: 	'</h3>'."\n";
 4622:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4623:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4624: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4625:     } else {
 4626: 	delete($env{'form.CODE'});
 4627:     }
 4628:     &sub_page_js($request);
 4629:     $request->print($result);
 4630: 
 4631:     my $navmap = Apache::lonnavmaps::navmap->new();
 4632:     unless (ref($navmap)) {
 4633:         $request->print(&navmap_errormsg());
 4634:         return;
 4635:     }
 4636:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4637:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4638:     if (!$map) {
 4639: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4640: 	return; 
 4641:     }
 4642:     my $iterator = $navmap->getIterator($map->map_start(),
 4643: 					$map->map_finish());
 4644: 
 4645:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4646: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4647: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4648: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4649: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4650: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4651: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4652: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4653: 
 4654:     if (defined($env{'form.CODE'})) {
 4655: 	$studentTable.=
 4656: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4657:     }
 4658:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4659: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4660: 
 4661:     $studentTable.='&nbsp;<span class="LC_info">'.
 4662:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4663:         '</span>'."\n".
 4664: 	&Apache::loncommon::start_data_table().
 4665: 	&Apache::loncommon::start_data_table_header_row().
 4666: 	'<th>'.&mt('Prob.').'</th>'.
 4667: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4668: 	&Apache::loncommon::end_data_table_header_row();
 4669: 
 4670:     &Apache::lonxml::clear_problem_counter();
 4671:     my ($depth,$question,$prob) = (1,1,1);
 4672:     $iterator->next(); # skip the first BEGIN_MAP
 4673:     my $curRes = $iterator->next(); # for "current resource"
 4674:     while ($depth > 0) {
 4675:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4676:         if($curRes == $iterator->END_MAP) { $depth--; }
 4677: 
 4678:         if (ref($curRes) && $curRes->is_problem()) {
 4679: 	    my $parts = $curRes->parts();
 4680:             my $title = $curRes->compTitle();
 4681: 	    my $symbx = $curRes->symb();
 4682: 	    $studentTable.=
 4683: 		&Apache::loncommon::start_data_table_row().
 4684: 		'<td align="center" valign="top" >'.$prob.
 4685: 		(scalar(@{$parts}) == 1 ? '' 
 4686: 		                        : '<br />('.&mt('[_1]parts',
 4687: 							scalar(@{$parts}).'&nbsp;').')'
 4688: 		 ).
 4689: 		 '</td>';
 4690: 	    $studentTable.='<td valign="top">';
 4691: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4692: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4693: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4694: 					     undef,'both',\%form);
 4695: 	    } else {
 4696: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4697: 		$companswer =~ s|<form(.*?)>||g;
 4698: 		$companswer =~ s|</form>||g;
 4699: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4700: #		    $companswer =~ s/$1/ /ms;
 4701: #		    $request->print('match='.$1."<br />\n");
 4702: #		}
 4703: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4704: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4705: 	    }
 4706: 
 4707: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4708: 
 4709: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4710: 		if ($record{'version'} eq '') {
 4711: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4712: 		} else {
 4713: 		    my %responseType = ();
 4714: 		    foreach my $partid (@{$parts}) {
 4715: 			my @responseIds =$curRes->responseIds($partid);
 4716: 			my @responseType =$curRes->responseType($partid);
 4717: 			my %responseIds;
 4718: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4719: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4720: 			}
 4721: 			$responseType{$partid} = \%responseIds;
 4722: 		    }
 4723: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4724: 
 4725: 		}
 4726: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4727: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4728: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4729: 									$env{'request.course.id'},
 4730: 									'','.submission');
 4731:  
 4732: 	    }
 4733: 	    if (&canmodify($usec)) {
 4734:             $studentTable.=&gradeBox_start();
 4735: 		foreach my $partid (@{$parts}) {
 4736: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4737: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4738: 		    $question++;
 4739: 		}
 4740:             $studentTable.=&gradeBox_end();
 4741: 		$prob++;
 4742: 	    }
 4743: 	    $studentTable.='</td></tr>';
 4744: 
 4745: 	}
 4746:         $curRes = $iterator->next();
 4747:     }
 4748: 
 4749:     $studentTable.=
 4750:         '</table>'."\n".
 4751:         '<input type="button" value="'.&mt('Save').'" '.
 4752:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4753:         '</form>'."\n";
 4754:     $request->print($studentTable);
 4755: 
 4756:     return '';
 4757: }
 4758: 
 4759: sub displaySubByDates {
 4760:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4761:     my $isCODE=0;
 4762:     my $isTask = ($symb =~/\.task$/);
 4763:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4764:     my $studentTable=&Apache::loncommon::start_data_table().
 4765: 	&Apache::loncommon::start_data_table_header_row().
 4766: 	'<th>'.&mt('Date/Time').'</th>'.
 4767: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4768:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4769: 	'<th>'.&mt('Submission').'</th>'.
 4770: 	'<th>'.&mt('Status').'</th>'.
 4771: 	&Apache::loncommon::end_data_table_header_row();
 4772:     my ($version);
 4773:     my %mark;
 4774:     my %orders;
 4775:     $mark{'correct_by_student'} = $checkIcon;
 4776:     if (!exists($$record{'1:timestamp'})) {
 4777: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4778:     }
 4779: 
 4780:     my $interaction;
 4781:     my $no_increment = 1;
 4782:     my %lastrndseed;
 4783:     for ($version=1;$version<=$$record{'version'};$version++) {
 4784: 	my $timestamp = 
 4785: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4786: 	if (exists($$record{$version.':resource.0.version'})) {
 4787: 	    $interaction = $$record{$version.':resource.0.version'};
 4788: 	}
 4789:         if ($isTask && $env{'form.previousversion'}) {
 4790:             next unless ($interaction == $env{'form.previousversion'});
 4791:         }
 4792: 	my $where = ($isTask ? "$version:resource.$interaction"
 4793: 		             : "$version:resource");
 4794: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4795: 	    '<td>'.$timestamp.'</td>';
 4796: 	if ($isCODE) {
 4797: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4798: 	}
 4799:         if ($isTask) {
 4800:             $studentTable.='<td>'.$interaction.'</td>';
 4801:         }
 4802: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4803: 	my @displaySub = ();
 4804: 	foreach my $partid (@{$parts}) {
 4805:             my ($hidden,$type);
 4806:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4807:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4808:                 $hidden = 1;
 4809:             }
 4810: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4811: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4812: 	    
 4813: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4814: 	    my $display_part=&get_display_part($partid,$symb);
 4815: 	    foreach my $matchKey (@matchKey) {
 4816: 		if (exists($$record{$version.':'.$matchKey}) &&
 4817: 		    $$record{$version.':'.$matchKey} ne '') {
 4818:                     
 4819: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4820: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4821:                     $displaySub[0].='<span class="LC_nobreak">';
 4822:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4823:                                    .' <span class="LC_internal_info">'
 4824:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4825:                                    .'</span>'
 4826:                                    .' <b>';
 4827:                     if ($hidden) {
 4828:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4829:                     } else {
 4830:                         my ($trial,$rndseed,$newvariation);
 4831:                         if ($type eq 'randomizetry') {
 4832:                             $trial = $$record{"$where.$partid.tries"};
 4833:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4834:                         }
 4835: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4836: 			    $displaySub[0].=&mt('Trial not counted');
 4837: 		        } else {
 4838: 			    $displaySub[0].=&mt('Trial: [_1]',
 4839: 					    $$record{"$where.$partid.tries"});
 4840:                             if ($rndseed || $lastrndseed{$partid}) {
 4841:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4842:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4843:                                 }
 4844:                             }
 4845:                             $lastrndseed{$partid} = $rndseed;
 4846: 		        }
 4847: 		        my $responseType=($isTask ? 'Task'
 4848:                                               : $responseType->{$partid}->{$responseId});
 4849: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4850: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4851: 			    $orders{$partid}->{$responseId}=
 4852: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4853:                                            $no_increment,$type,$trial,$rndseed);
 4854: 		        }
 4855: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4856: 		        $displaySub[0].='&nbsp; '.
 4857: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4858:                     }
 4859: 		}
 4860: 	    }
 4861: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4862: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4863: 				    $$record{"$where.$partid.checkedin"},
 4864: 				    $$record{"$where.$partid.checkedin.slot"}).
 4865: 					'<br />';
 4866: 	    }
 4867: 	    if (exists $$record{"$where.$partid.award"}) {
 4868: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4869: 		    lc($$record{"$where.$partid.award"}).' '.
 4870: 		    $mark{$$record{"$where.$partid.solved"}}.
 4871: 		    '<br />';
 4872: 	    }
 4873: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4874: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4875: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4876: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4877: 		$displaySub[2].=
 4878: 		    $$record{"$version:resource.$partid.regrader"}.
 4879: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4880: 	    }
 4881: 	}
 4882: 	# needed because old essay regrader has not parts info
 4883: 	if (exists $$record{"$version:resource.regrader"}) {
 4884: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4885: 	}
 4886: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4887: 	if ($displaySub[2]) {
 4888: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4889: 	}
 4890: 	$studentTable.='&nbsp;</td>'.
 4891: 	    &Apache::loncommon::end_data_table_row();
 4892:     }
 4893:     $studentTable.=&Apache::loncommon::end_data_table();
 4894:     return $studentTable;
 4895: }
 4896: 
 4897: sub updateGradeByPage {
 4898:     my ($request,$symb) = @_;
 4899: 
 4900:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4901:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4902:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4903:     my $pageTitle = $env{'form.page'};
 4904:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4905:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4906:     my $usec=$classlist->{$env{'form.student'}}[5];
 4907:     if (!&canmodify($usec)) {
 4908: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4909: 	return;
 4910:     }
 4911:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4912:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4913: 	'</h3>'."\n";
 4914: 
 4915:     $request->print($result);
 4916: 
 4917: 
 4918:     my $navmap = Apache::lonnavmaps::navmap->new();
 4919:     unless (ref($navmap)) {
 4920:         $request->print(&navmap_errormsg());
 4921:         return;
 4922:     }
 4923:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4924:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4925:     if (!$map) {
 4926: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4927: 	return; 
 4928:     }
 4929:     my $iterator = $navmap->getIterator($map->map_start(),
 4930: 					$map->map_finish());
 4931: 
 4932:     my $studentTable=
 4933: 	&Apache::loncommon::start_data_table().
 4934: 	&Apache::loncommon::start_data_table_header_row().
 4935: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4936: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4937: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4938: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4939: 	&Apache::loncommon::end_data_table_header_row();
 4940: 
 4941:     $iterator->next(); # skip the first BEGIN_MAP
 4942:     my $curRes = $iterator->next(); # for "current resource"
 4943:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4944:     while ($depth > 0) {
 4945:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4946:         if($curRes == $iterator->END_MAP) { $depth--; }
 4947: 
 4948:         if (ref($curRes) && $curRes->is_problem()) {
 4949: 	    my $parts = $curRes->parts();
 4950:             my $title = $curRes->compTitle();
 4951: 	    my $symbx = $curRes->symb();
 4952: 	    $studentTable.=
 4953: 		&Apache::loncommon::start_data_table_row().
 4954: 		'<td align="center" valign="top" >'.$prob.
 4955: 		(scalar(@{$parts}) == 1 ? '' 
 4956:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4957: 		.')').'</td>';
 4958: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4959: 
 4960: 	    my %newrecord=();
 4961: 	    my @displayPts=();
 4962:             my %aggregate = ();
 4963:             my $aggregateflag = 0;
 4964: 	    foreach my $partid (@{$parts}) {
 4965: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4966: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4967: 
 4968: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4969: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4970: 		my $partial = $newpts/$wgt;
 4971: 		my $score;
 4972: 		if ($partial > 0) {
 4973: 		    $score = 'correct_by_override';
 4974: 		} elsif ($newpts ne '') { #empty is taken as 0
 4975: 		    $score = 'incorrect_by_override';
 4976: 		}
 4977: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4978: 		if ($dropMenu eq 'excused') {
 4979: 		    $partial = '';
 4980: 		    $score = 'excused';
 4981: 		} elsif ($dropMenu eq 'reset status'
 4982: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4983: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4984: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4985: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4986: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4987: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4988: 		    $changeflag++;
 4989: 		    $newpts = '';
 4990:                     
 4991:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4992:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4993:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4994:                     if ($aggtries > 0) {
 4995:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4996:                         $aggregateflag = 1;
 4997:                     }
 4998: 		}
 4999: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5000: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5001: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5002: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5003: 		    '&nbsp;<br />';
 5004: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5005: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5006: 		    '&nbsp;<br />';
 5007: 		$question++;
 5008: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5009: 
 5010: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5011: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5012: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5013: 		    if (scalar(keys(%newrecord)) > 0);
 5014: 
 5015: 		$changeflag++;
 5016: 	    }
 5017: 	    if (scalar(keys(%newrecord)) > 0) {
 5018: 		my %record = 
 5019: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5020: 					     $udom,$uname);
 5021: 
 5022: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5023: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5024: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5025: 		    $newrecord{'resource.CODE'} = '';
 5026: 		}
 5027: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5028: 					$udom,$uname);
 5029: 		%record = &Apache::lonnet::restore($symbx,
 5030: 						   $env{'request.course.id'},
 5031: 						   $udom,$uname);
 5032: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5033: 					     $cdom,$cnum,$udom,$uname);
 5034: 	    }
 5035: 	    
 5036:             if ($aggregateflag) {
 5037:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5038:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5039:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5040:             }
 5041: 
 5042: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5043: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5044: 		&Apache::loncommon::end_data_table_row();
 5045: 
 5046: 	    $prob++;
 5047: 	}
 5048:         $curRes = $iterator->next();
 5049:     }
 5050: 
 5051:     $studentTable.=&Apache::loncommon::end_data_table();
 5052:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5053: 		  &mt('The scores were changed for [quant,_1,problem].',
 5054: 		  $changeflag));
 5055:     $request->print($grademsg.$studentTable);
 5056: 
 5057:     return '';
 5058: }
 5059: 
 5060: #-------- end of section for handling grading by page/sequence ---------
 5061: #
 5062: #-------------------------------------------------------------------
 5063: 
 5064: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5065: #
 5066: #------ start of section for handling grading by page/sequence ---------
 5067: 
 5068: =pod
 5069: 
 5070: =head1 Bubble sheet grading routines
 5071: 
 5072:   For this documentation:
 5073: 
 5074:    'scanline' refers to the full line of characters
 5075:    from the file that we are parsing that represents one entire sheet
 5076: 
 5077:    'bubble line' refers to the data
 5078:    representing the line of bubbles that are on the physical bubblesheet
 5079: 
 5080: 
 5081: The overall process is that a scanned in bubblesheet data is uploaded
 5082: into a course. When a user wants to grade, they select a
 5083: sequence/folder of resources, a file of bubblesheet info, and pick
 5084: one of the predefined configurations for what each scanline looks
 5085: like.
 5086: 
 5087: Next each scanline is checked for any errors of either 'missing
 5088: bubbles' (it's an error because it may have been mis-scanned
 5089: because too light bubbling), 'double bubble' (each bubble line should
 5090: have no more than one letter picked), invalid or duplicated CODE,
 5091: invalid student/employee ID
 5092: 
 5093: If the CODE option is used that determines the randomization of the
 5094: homework problems, either way the student/employee ID is looked up into a
 5095: username:domain.
 5096: 
 5097: During the validation phase the instructor can choose to skip scanlines. 
 5098: 
 5099: After the validation phase, there are now 3 bubblesheet files
 5100: 
 5101:   scantron_original_filename (unmodified original file)
 5102:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5103:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5104: 
 5105: Also there is a separate hash nohist_scantrondata that contains extra
 5106: correction information that isn't representable in the bubblesheet
 5107: file (see &scantron_getfile() for more information)
 5108: 
 5109: After all scanlines are either valid, marked as valid or skipped, then
 5110: foreach line foreach problem in the picked sequence, an ssi request is
 5111: made that simulates a user submitting their selected letter(s) against
 5112: the homework problem.
 5113: 
 5114: =over 4
 5115: 
 5116: 
 5117: 
 5118: =item defaultFormData
 5119: 
 5120:   Returns html hidden inputs used to hold context/default values.
 5121: 
 5122:  Arguments:
 5123:   $symb - $symb of the current resource 
 5124: 
 5125: =cut
 5126: 
 5127: sub defaultFormData {
 5128:     my ($symb)=@_;
 5129:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5130: }
 5131: 
 5132: 
 5133: =pod 
 5134: 
 5135: =item getSequenceDropDown
 5136: 
 5137:    Return html dropdown of possible sequences to grade
 5138:  
 5139:  Arguments:
 5140:    $symb - $symb of the current resource
 5141:    $map_error - ref to scalar which will container error if
 5142:                 $navmap object is unavailable in &getSymbMap().
 5143: 
 5144: =cut
 5145: 
 5146: sub getSequenceDropDown {
 5147:     my ($symb,$map_error)=@_;
 5148:     my $result='<select name="selectpage">'."\n";
 5149:     my ($titles,$symbx) = &getSymbMap($map_error);
 5150:     if (ref($map_error)) {
 5151:         return if ($$map_error);
 5152:     }
 5153:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5154:     my $ctr=0;
 5155:     foreach (@$titles) {
 5156: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5157: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5158: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5159: 	    '>'.$showtitle.'</option>'."\n";
 5160: 	$ctr++;
 5161:     }
 5162:     $result.= '</select>';
 5163:     return $result;
 5164: }
 5165: 
 5166: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5167:                                    # key is zero-based index - 0, 1, 2 ...
 5168: 
 5169: my %first_bubble_line;             # First bubble line no. for each bubble.
 5170: 
 5171: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5172:                                    # matchresponse or rankresponse, where 
 5173:                                    # an individual response can have multiple 
 5174:                                    # lines
 5175: 
 5176: my %responsetype_per_response;     # responsetype for each response
 5177: 
 5178: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5179:                                    # numbered response. Needed when randomorder
 5180:                                    # or randompick are in use. Key is ID, value 
 5181:                                    # is response number.
 5182: 
 5183: # Save and restore the bubble lines array to the form env.
 5184: 
 5185: 
 5186: sub save_bubble_lines {
 5187:     foreach my $line (keys(%bubble_lines_per_response)) {
 5188: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5189: 	$env{"form.scantron.first_bubble_line.$line"} =
 5190: 	    $first_bubble_line{$line};
 5191:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5192:             $subdivided_bubble_lines{$line};
 5193:         $env{"form.scantron.responsetype.$line"} =
 5194:             $responsetype_per_response{$line};
 5195:     }
 5196:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5197:         my $line = $masterseq_id_responsenum{$resid};
 5198:         $env{"form.scantron.residpart.$line"} = $resid;
 5199:     }
 5200: }
 5201: 
 5202: 
 5203: sub restore_bubble_lines {
 5204:     my $line = 0;
 5205:     %bubble_lines_per_response = ();
 5206:     %masterseq_id_responsenum = ();
 5207:     while ($env{"form.scantron.bubblelines.$line"}) {
 5208: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5209: 	$bubble_lines_per_response{$line} = $value;
 5210: 	$first_bubble_line{$line}  =
 5211: 	    $env{"form.scantron.first_bubble_line.$line"};
 5212:         $subdivided_bubble_lines{$line} =
 5213:             $env{"form.scantron.sub_bubblelines.$line"};
 5214:         $responsetype_per_response{$line} =
 5215:             $env{"form.scantron.responsetype.$line"};
 5216:         my $id = $env{"form.scantron.residpart.$line"};
 5217:         $masterseq_id_responsenum{$id} = $line;
 5218: 	$line++;
 5219:     }
 5220: }
 5221: 
 5222: =pod 
 5223: 
 5224: =item scantron_filenames
 5225: 
 5226:    Returns a list of the scantron files in the current course 
 5227: 
 5228: =cut
 5229: 
 5230: sub scantron_filenames {
 5231:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5232:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5233:     my $getpropath = 1;
 5234:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5235:                                                         $cname,$getpropath);
 5236:     my @possiblenames;
 5237:     if (ref($dirlist) eq 'ARRAY') {
 5238:         foreach my $filename (sort(@{$dirlist})) {
 5239: 	    ($filename)=split(/&/,$filename);
 5240: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5241: 	    $filename=~s/^scantron_orig_//;
 5242: 	    push(@possiblenames,$filename);
 5243:         }
 5244:     }
 5245:     return @possiblenames;
 5246: }
 5247: 
 5248: =pod 
 5249: 
 5250: =item scantron_uploads
 5251: 
 5252:    Returns  html drop-down list of scantron files in current course.
 5253: 
 5254:  Arguments:
 5255:    $file2grade - filename to set as selected in the dropdown
 5256: 
 5257: =cut
 5258: 
 5259: sub scantron_uploads {
 5260:     my ($file2grade) = @_;
 5261:     my $result=	'<select name="scantron_selectfile">';
 5262:     $result.="<option></option>";
 5263:     foreach my $filename (sort(&scantron_filenames())) {
 5264: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5265:     }
 5266:     $result.="</select>";
 5267:     return $result;
 5268: }
 5269: 
 5270: =pod 
 5271: 
 5272: =item scantron_scantab
 5273: 
 5274:   Returns html drop down of the scantron formats in the scantronformat.tab
 5275:   file.
 5276: 
 5277: =cut
 5278: 
 5279: sub scantron_scantab {
 5280:     my $result='<select name="scantron_format">'."\n";
 5281:     $result.='<option></option>'."\n";
 5282:     my @lines = &get_scantronformat_file();
 5283:     if (@lines > 0) {
 5284:         foreach my $line (@lines) {
 5285:             next if (($line =~ /^\#/) || ($line eq ''));
 5286: 	    my ($name,$descrip)=split(/:/,$line);
 5287: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5288:         }
 5289:     }
 5290:     $result.='</select>'."\n";
 5291:     return $result;
 5292: }
 5293: 
 5294: =pod
 5295: 
 5296: =item get_scantronformat_file
 5297: 
 5298:   Returns an array containing lines from the scantron format file for
 5299:   the domain of the course.
 5300: 
 5301:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5302:   lines are from this file.
 5303: 
 5304:   Otherwise, if a default.tab has been published in RES space by the 
 5305:   domainconfig user, lines are from this file.
 5306: 
 5307:   Otherwise, fall back to getting lines from the legacy file on the
 5308:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5309: 
 5310: =cut
 5311: 
 5312: sub get_scantronformat_file {
 5313:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5314:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5315:     my $gottab = 0;
 5316:     my @lines;
 5317:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5318:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5319:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5320:             if ($formatfile ne '-1') {
 5321:                 @lines = split("\n",$formatfile,-1);
 5322:                 $gottab = 1;
 5323:             }
 5324:         }
 5325:     }
 5326:     if (!$gottab) {
 5327:         my $confname = $cdom.'-domainconfig';
 5328:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5329:         my $formatfile =  &Apache::lonnet::getfile($default);
 5330:         if ($formatfile ne '-1') {
 5331:             @lines = split("\n",$formatfile,-1);
 5332:             $gottab = 1;
 5333:         }
 5334:     }
 5335:     if (!$gottab) {
 5336:         my @domains = &Apache::lonnet::current_machine_domains();
 5337:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5338:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5339:             @lines = <$fh>;
 5340:             close($fh);
 5341:         } else {
 5342:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5343:             @lines = <$fh>;
 5344:             close($fh);
 5345:         }
 5346:     }
 5347:     return @lines;
 5348: }
 5349: 
 5350: =pod 
 5351: 
 5352: =item scantron_CODElist
 5353: 
 5354:   Returns html drop down of the saved CODE lists from current course,
 5355:   generated from earlier printings.
 5356: 
 5357: =cut
 5358: 
 5359: sub scantron_CODElist {
 5360:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5361:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5362:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5363:     my $namechoice='<option></option>';
 5364:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5365: 	if ($name =~ /^error: 2 /) { next; }
 5366: 	if ($name =~ /^type\0/) { next; }
 5367: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5368:     }
 5369:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5370:     return $namechoice;
 5371: }
 5372: 
 5373: =pod 
 5374: 
 5375: =item scantron_CODEunique
 5376: 
 5377:   Returns the html for "Each CODE to be used once" radio.
 5378: 
 5379: =cut
 5380: 
 5381: sub scantron_CODEunique {
 5382:     my $result='<span class="LC_nobreak">
 5383:                  <label><input type="radio" name="scantron_CODEunique"
 5384:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5385:                 </span>
 5386:                 <span class="LC_nobreak">
 5387:                  <label><input type="radio" name="scantron_CODEunique"
 5388:                         value="no" />'.&mt('No').' </label>
 5389:                 </span>';
 5390:     return $result;
 5391: }
 5392: 
 5393: =pod 
 5394: 
 5395: =item scantron_selectphase
 5396: 
 5397:   Generates the initial screen to start the bubblesheet process.
 5398:   Allows for - starting a grading run.
 5399:              - downloading existing scan data (original, corrected
 5400:                                                 or skipped info)
 5401: 
 5402:              - uploading new scan data
 5403: 
 5404:  Arguments:
 5405:   $r          - The Apache request object
 5406:   $file2grade - name of the file that contain the scanned data to score
 5407: 
 5408: =cut
 5409: 
 5410: sub scantron_selectphase {
 5411:     my ($r,$file2grade,$symb) = @_;
 5412:     if (!$symb) {return '';}
 5413:     my $map_error;
 5414:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5415:     if ($map_error) {
 5416:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5417:         return;
 5418:     }
 5419:     my $default_form_data=&defaultFormData($symb);
 5420:     my $file_selector=&scantron_uploads($file2grade);
 5421:     my $format_selector=&scantron_scantab();
 5422:     my $CODE_selector=&scantron_CODElist();
 5423:     my $CODE_unique=&scantron_CODEunique();
 5424:     my $result;
 5425: 
 5426:     $ssi_error = 0;
 5427: 
 5428:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5429:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5430: 
 5431: 	# Chunk of form to prompt for a scantron file upload.
 5432: 
 5433:         $r->print('
 5434:     <br />
 5435:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5436:        '.&Apache::loncommon::start_data_table_header_row().'
 5437:             <th>
 5438:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5439:             </th>
 5440:        '.&Apache::loncommon::end_data_table_header_row().'
 5441:        '.&Apache::loncommon::start_data_table_row().'
 5442:             <td>
 5443: ');
 5444:     my $default_form_data=&defaultFormData($symb);
 5445:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5446:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5447:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5448:     function checkUpload(formname) {
 5449: 	if (formname.upfile.value == "") {
 5450: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5451: 	    return false;
 5452: 	}
 5453: 	formname.submit();
 5454:     }'));
 5455:     $r->print('
 5456:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5457:                 '.$default_form_data.'
 5458:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5459:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5460:                 <input name="command" value="scantronupload_save" type="hidden" />
 5461:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5462:                 <br />
 5463:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5464:               </form>
 5465: ');
 5466: 
 5467:         $r->print('
 5468:             </td>
 5469:        '.&Apache::loncommon::end_data_table_row().'
 5470:        '.&Apache::loncommon::end_data_table().'
 5471: ');
 5472:     }
 5473: 
 5474:     # Chunk of form to prompt for a file to grade and how:
 5475: 
 5476:     $result.= '
 5477:     <br />
 5478:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5479:     <input type="hidden" name="command" value="scantron_warning" />
 5480:     '.$default_form_data.'
 5481:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5482:        '.&Apache::loncommon::start_data_table_header_row().'
 5483:             <th colspan="2">
 5484:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5485:             </th>
 5486:        '.&Apache::loncommon::end_data_table_header_row().'
 5487:        '.&Apache::loncommon::start_data_table_row().'
 5488:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5489:        '.&Apache::loncommon::end_data_table_row().'
 5490:        '.&Apache::loncommon::start_data_table_row().'
 5491:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5492:        '.&Apache::loncommon::end_data_table_row().'
 5493:        '.&Apache::loncommon::start_data_table_row().'
 5494:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5495:        '.&Apache::loncommon::end_data_table_row().'
 5496:        '.&Apache::loncommon::start_data_table_row().'
 5497:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5498:        '.&Apache::loncommon::end_data_table_row().'
 5499:        '.&Apache::loncommon::start_data_table_row().'
 5500:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5501:        '.&Apache::loncommon::end_data_table_row().'
 5502:        '.&Apache::loncommon::start_data_table_row().'
 5503: 	    <td> '.&mt('Options:').' </td>
 5504:             <td>
 5505: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5506:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5507:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5508: 	    </td>
 5509:        '.&Apache::loncommon::end_data_table_row().'
 5510:        '.&Apache::loncommon::start_data_table_row().'
 5511:             <td colspan="2">
 5512:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5513:             </td>
 5514:        '.&Apache::loncommon::end_data_table_row().'
 5515:     '.&Apache::loncommon::end_data_table().'
 5516:     </form>
 5517: ';
 5518:    
 5519:     $r->print($result);
 5520: 
 5521: 
 5522: 
 5523:     # Chunk of the form that prompts to view a scoring office file,
 5524:     # corrected file, skipped records in a file.
 5525: 
 5526:     $r->print('
 5527:    <br />
 5528:    <form action="/adm/grades" name="scantron_download">
 5529:      '.$default_form_data.'
 5530:      <input type="hidden" name="command" value="scantron_download" />
 5531:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5532:        '.&Apache::loncommon::start_data_table_header_row().'
 5533:               <th>
 5534:                 &nbsp;'.&mt('Download a scoring office file').'
 5535:               </th>
 5536:        '.&Apache::loncommon::end_data_table_header_row().'
 5537:        '.&Apache::loncommon::start_data_table_row().'
 5538:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5539:                 <br />
 5540:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5541:        '.&Apache::loncommon::end_data_table_row().'
 5542:      '.&Apache::loncommon::end_data_table().'
 5543:    </form>
 5544:    <br />
 5545: ');
 5546: 
 5547:     &Apache::lonpickcode::code_list($r,2);
 5548: 
 5549:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5550:              $default_form_data."\n".
 5551:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5552:              &Apache::loncommon::start_data_table_header_row()."\n".
 5553:              '<th colspan="2">
 5554:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5555:              '</th>'."\n".
 5556:               &Apache::loncommon::end_data_table_header_row()."\n".
 5557:               &Apache::loncommon::start_data_table_row()."\n".
 5558:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5559:               '<td> '.$sequence_selector.' </td>'.
 5560:               &Apache::loncommon::end_data_table_row()."\n".
 5561:               &Apache::loncommon::start_data_table_row()."\n".
 5562:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5563:               '<td> '.$file_selector.' </td>'."\n".
 5564:               &Apache::loncommon::end_data_table_row()."\n".
 5565:               &Apache::loncommon::start_data_table_row()."\n".
 5566:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5567:               '<td> '.$format_selector.' </td>'."\n".
 5568:               &Apache::loncommon::end_data_table_row()."\n".
 5569:               &Apache::loncommon::start_data_table_row()."\n".
 5570:               '<td> '.&mt('Options').' </td>'."\n".
 5571:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5572:               &Apache::loncommon::end_data_table_row()."\n".
 5573:               &Apache::loncommon::start_data_table_row()."\n".
 5574:               '<td colspan="2">'."\n".
 5575:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5576:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5577:               '</td>'."\n".
 5578:               &Apache::loncommon::end_data_table_row()."\n".
 5579:               &Apache::loncommon::end_data_table()."\n".
 5580:               '</form><br />');
 5581:     return;
 5582: }
 5583: 
 5584: =pod
 5585: 
 5586: =item get_scantron_config
 5587: 
 5588:    Parse and return the scantron configuration line selected as a
 5589:    hash of configuration file fields.
 5590: 
 5591:  Arguments:
 5592:     which - the name of the configuration to parse from the file.
 5593: 
 5594: 
 5595:  Returns:
 5596:             If the named configuration is not in the file, an empty
 5597:             hash is returned.
 5598:     a hash with the fields
 5599:       name         - internal name for the this configuration setup
 5600:       description  - text to display to operator that describes this config
 5601:       CODElocation - if 0 or the string 'none'
 5602:                           - no CODE exists for this config
 5603:                      if -1 || the string 'letter'
 5604:                           - a CODE exists for this config and is
 5605:                             a string of letters
 5606:                      Unsupported value (but planned for future support)
 5607:                           if a positive integer
 5608:                                - The CODE exists as the first n items from
 5609:                                  the question section of the form
 5610:                           if the string 'number'
 5611:                                - The CODE exists for this config and is
 5612:                                  a string of numbers
 5613:       CODEstart   - (only matter if a CODE exists) column in the line where
 5614:                      the CODE starts
 5615:       CODElength  - length of the CODE
 5616:       IDstart     - column where the student/employee ID starts
 5617:       IDlength    - length of the student/employee ID info
 5618:       Qstart      - column where the information from the bubbled
 5619:                     'questions' start
 5620:       Qlength     - number of columns comprising a single bubble line from
 5621:                     the sheet. (usually either 1 or 10)
 5622:       Qon         - either a single character representing the character used
 5623:                     to signal a bubble was chosen in the positional setup, or
 5624:                     the string 'letter' if the letter of the chosen bubble is
 5625:                     in the final, or 'number' if a number representing the
 5626:                     chosen bubble is in the file (1->A 0->J)
 5627:       Qoff        - the character used to represent that a bubble was
 5628:                     left blank
 5629:       PaperID     - if the scanning process generates a unique number for each
 5630:                     sheet scanned the column that this ID number starts in
 5631:       PaperIDlength - number of columns that comprise the unique ID number
 5632:                       for the sheet of paper
 5633:       FirstName   - column that the first name starts in
 5634:       FirstNameLength - number of columns that the first name spans
 5635:  
 5636:       LastName    - column that the last name starts in
 5637:       LastNameLength - number of columns that the last name spans
 5638:       BubblesPerRow - number of bubbles available in each row used to 
 5639:                       bubble an answer. (If not specified, 10 assumed).
 5640: 
 5641: =cut
 5642: 
 5643: sub get_scantron_config {
 5644:     my ($which) = @_;
 5645:     my @lines = &get_scantronformat_file();
 5646:     my %config;
 5647:     #FIXME probably should move to XML it has already gotten a bit much now
 5648:     foreach my $line (@lines) {
 5649: 	my ($name,$descrip)=split(/:/,$line);
 5650: 	if ($name ne $which ) { next; }
 5651: 	chomp($line);
 5652: 	my @config=split(/:/,$line);
 5653: 	$config{'name'}=$config[0];
 5654: 	$config{'description'}=$config[1];
 5655: 	$config{'CODElocation'}=$config[2];
 5656: 	$config{'CODEstart'}=$config[3];
 5657: 	$config{'CODElength'}=$config[4];
 5658: 	$config{'IDstart'}=$config[5];
 5659: 	$config{'IDlength'}=$config[6];
 5660: 	$config{'Qstart'}=$config[7];
 5661:  	$config{'Qlength'}=$config[8];
 5662: 	$config{'Qoff'}=$config[9];
 5663: 	$config{'Qon'}=$config[10];
 5664: 	$config{'PaperID'}=$config[11];
 5665: 	$config{'PaperIDlength'}=$config[12];
 5666: 	$config{'FirstName'}=$config[13];
 5667: 	$config{'FirstNamelength'}=$config[14];
 5668: 	$config{'LastName'}=$config[15];
 5669: 	$config{'LastNamelength'}=$config[16];
 5670:         $config{'BubblesPerRow'}=$config[17];
 5671: 	last;
 5672:     }
 5673:     return %config;
 5674: }
 5675: 
 5676: =pod 
 5677: 
 5678: =item username_to_idmap
 5679: 
 5680:     creates a hash keyed by student/employee ID with values of the corresponding
 5681:     student username:domain.
 5682: 
 5683:   Arguments:
 5684: 
 5685:     $classlist - reference to the class list hash. This is a hash
 5686:                  keyed by student name:domain  whose elements are references
 5687:                  to arrays containing various chunks of information
 5688:                  about the student. (See loncoursedata for more info).
 5689: 
 5690:   Returns
 5691:     %idmap - the constructed hash
 5692: 
 5693: =cut
 5694: 
 5695: sub username_to_idmap {
 5696:     my ($classlist)= @_;
 5697:     my %idmap;
 5698:     foreach my $student (keys(%$classlist)) {
 5699: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5700: 	    $student;
 5701:     }
 5702:     return %idmap;
 5703: }
 5704: 
 5705: =pod
 5706: 
 5707: =item scantron_fixup_scanline
 5708: 
 5709:    Process a requested correction to a scanline.
 5710: 
 5711:   Arguments:
 5712:     $scantron_config   - hash from &get_scantron_config()
 5713:     $scan_data         - hash of correction information 
 5714:                           (see &scantron_getfile())
 5715:     $line              - existing scanline
 5716:     $whichline         - line number of the passed in scanline
 5717:     $field             - type of change to process 
 5718:                          (either 
 5719:                           'ID'     -> correct the student/employee ID
 5720:                           'CODE'   -> correct the CODE
 5721:                           'answer' -> fixup the submitted answers)
 5722:     
 5723:    $args               - hash of additional info,
 5724:                           - 'ID' 
 5725:                                'newid' -> studentID to use in replacement
 5726:                                           of existing one
 5727:                           - 'CODE' 
 5728:                                'CODE_ignore_dup' - set to true if duplicates
 5729:                                                    should be ignored.
 5730: 	                       'CODE' - is new code or 'use_unfound'
 5731:                                         if the existing unfound code should
 5732:                                         be used as is
 5733:                           - 'answer'
 5734:                                'response' - new answer or 'none' if blank
 5735:                                'question' - the bubble line to change
 5736:                                'questionnum' - the question identifier,
 5737:                                                may include subquestion. 
 5738: 
 5739:   Returns:
 5740:     $line - the modified scanline
 5741: 
 5742:   Side effects: 
 5743:     $scan_data - may be updated
 5744: 
 5745: =cut
 5746: 
 5747: 
 5748: sub scantron_fixup_scanline {
 5749:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5750:     if ($field eq 'ID') {
 5751: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5752: 	    return ($line,1,'New value too large');
 5753: 	}
 5754: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5755: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5756: 				     $args->{'newid'});
 5757: 	}
 5758: 	substr($line,$$scantron_config{'IDstart'}-1,
 5759: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5760: 	if ($args->{'newid'}=~/^\s*$/) {
 5761: 	    &scan_data($scan_data,"$whichline.user",
 5762: 		       $args->{'username'}.':'.$args->{'domain'});
 5763: 	}
 5764:     } elsif ($field eq 'CODE') {
 5765: 	if ($args->{'CODE_ignore_dup'}) {
 5766: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5767: 	}
 5768: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5769: 	if ($args->{'CODE'} ne 'use_unfound') {
 5770: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5771: 		return ($line,1,'New CODE value too large');
 5772: 	    }
 5773: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5774: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5775: 	    }
 5776: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5777: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5778: 	}
 5779:     } elsif ($field eq 'answer') {
 5780: 	my $length=$scantron_config->{'Qlength'};
 5781: 	my $off=$scantron_config->{'Qoff'};
 5782: 	my $on=$scantron_config->{'Qon'};
 5783: 	my $answer=${off}x$length;
 5784: 	if ($args->{'response'} eq 'none') {
 5785: 	    &scan_data($scan_data,
 5786: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5787: 	} else {
 5788: 	    if ($on eq 'letter') {
 5789: 		my @alphabet=('A'..'Z');
 5790: 		$answer=$alphabet[$args->{'response'}];
 5791: 	    } elsif ($on eq 'number') {
 5792: 		$answer=$args->{'response'}+1;
 5793: 		if ($answer == 10) { $answer = '0'; }
 5794: 	    } else {
 5795: 		substr($answer,$args->{'response'},1)=$on;
 5796: 	    }
 5797: 	    &scan_data($scan_data,
 5798: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5799: 	}
 5800: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5801: 	substr($line,$where-1,$length)=$answer;
 5802:     }
 5803:     return $line;
 5804: }
 5805: 
 5806: =pod
 5807: 
 5808: =item scan_data
 5809: 
 5810:     Edit or look up  an item in the scan_data hash.
 5811: 
 5812:   Arguments:
 5813:     $scan_data  - The hash (see scantron_getfile)
 5814:     $key        - shorthand of the key to edit (actual key is
 5815:                   scantronfilename_key).
 5816:     $data        - New value of the hash entry.
 5817:     $delete      - If true, the entry is removed from the hash.
 5818: 
 5819:   Returns:
 5820:     The new value of the hash table field (undefined if deleted).
 5821: 
 5822: =cut
 5823: 
 5824: 
 5825: sub scan_data {
 5826:     my ($scan_data,$key,$value,$delete)=@_;
 5827:     my $filename=$env{'form.scantron_selectfile'};
 5828:     if (defined($value)) {
 5829: 	$scan_data->{$filename.'_'.$key} = $value;
 5830:     }
 5831:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5832:     return $scan_data->{$filename.'_'.$key};
 5833: }
 5834: 
 5835: # ----- These first few routines are general use routines.----
 5836: 
 5837: # Return the number of occurences of a pattern in a string.
 5838: 
 5839: sub occurence_count {
 5840:     my ($string, $pattern) = @_;
 5841: 
 5842:     my @matches = ($string =~ /$pattern/g);
 5843: 
 5844:     return scalar(@matches);
 5845: }
 5846: 
 5847: 
 5848: # Take a string known to have digits and convert all the
 5849: # digits into letters in the range J,A..I.
 5850: 
 5851: sub digits_to_letters {
 5852:     my ($input) = @_;
 5853: 
 5854:     my @alphabet = ('J', 'A'..'I');
 5855: 
 5856:     my @input    = split(//, $input);
 5857:     my $output ='';
 5858:     for (my $i = 0; $i < scalar(@input); $i++) {
 5859: 	if ($input[$i] =~ /\d/) {
 5860: 	    $output .= $alphabet[$input[$i]];
 5861: 	} else {
 5862: 	    $output .= $input[$i];
 5863: 	}
 5864:     }
 5865:     return $output;
 5866: }
 5867: 
 5868: =pod 
 5869: 
 5870: =item scantron_parse_scanline
 5871: 
 5872:   Decodes a scanline from the selected scantron file
 5873: 
 5874:  Arguments:
 5875:     line             - The text of the scantron file line to process
 5876:     whichline        - Line number
 5877:     scantron_config  - Hash describing the format of the scantron lines.
 5878:     scan_data        - Hash of extra information about the scanline
 5879:                        (see scantron_getfile for more information)
 5880:     just_header      - True if should not process question answers but only
 5881:                        the stuff to the left of the answers.
 5882:     randomorder      - True if randomorder in use
 5883:     randompick       - True if randompick in use
 5884:     sequence         - Exam folder URL
 5885:     master_seq       - Ref to array containing symbs in exam folder
 5886:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5887:                        (corresponding values are resource objects)
 5888:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5889:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5890:                        are refs to an array of resource objects, ordered
 5891:                        according to order used for CODE, when randomorder
 5892:                        and or randompick are in use.
 5893:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 5894:                        for current line to question number used for same question
 5895:                         in "Master Sequence" (as seen by Course Coordinator).
 5896:     startline        - Ref to hash where key is question number (0 is first)
 5897:                        and value is number of first bubble line for current 
 5898:                        student or code-based randompick and/or randomorder.
 5899:     totalref         - Ref of scalar used to score total number of bubble
 5900:                        lines needed for responses in a scan line (used when
 5901:                        randompick in use. 
 5902:     
 5903:  Returns:
 5904:    Hash containing the result of parsing the scanline
 5905: 
 5906:    Keys are all proceeded by the string 'scantron.'
 5907: 
 5908:        CODE    - the CODE in use for this scanline
 5909:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5910:                  by the operator
 5911:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5912:                             CODEs were selected, but the usage has been
 5913:                             forced by the operator
 5914:        ID  - student/employee ID
 5915:        PaperID - if used, the ID number printed on the sheet when the 
 5916:                  paper was scanned
 5917:        FirstName - first name from the sheet
 5918:        LastName  - last name from the sheet
 5919: 
 5920:      if just_header was not true these key may also exist
 5921: 
 5922:        missingerror - a list of bubble ranges that are considered to be answers
 5923:                       to a single question that don't have any bubbles filled in.
 5924:                       Of the form questionnumber:firstbubblenumber:count.
 5925:        doubleerror  - a list of bubble ranges that are considered to be answers
 5926:                       to a single question that have more than one bubble filled in.
 5927:                       Of the form questionnumber::firstbubblenumber:count
 5928:    
 5929:                 In the above, count is the number of bubble responses in the
 5930:                 input line needed to represent the possible answers to the question.
 5931:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5932:                 per line would have count = 2.
 5933: 
 5934:        maxquest     - the number of the last bubble line that was parsed
 5935: 
 5936:        (<number> starts at 1)
 5937:        <number>.answer - zero or more letters representing the selected
 5938:                          letters from the scanline for the bubble line 
 5939:                          <number>.
 5940:                          if blank there was either no bubble or there where
 5941:                          multiple bubbles, (consult the keys missingerror and
 5942:                          doubleerror if this is an error condition)
 5943: 
 5944: =cut
 5945: 
 5946: sub scantron_parse_scanline {
 5947:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 5948:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 5949:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 5950: 
 5951:     my %record;
 5952:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 5953:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5954: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5955: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5956: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5957: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5958: 	    $record{'scantron.CODE'}=substr($data,
 5959: 					    $$scantron_config{'CODEstart'}-1,
 5960: 					    $$scantron_config{'CODElength'});
 5961: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5962: 		$record{'scantron.useCODE'}=1;
 5963: 	    }
 5964: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5965: 		$record{'scantron.CODE_ignore_dup'}=1;
 5966: 	    }
 5967: 	} else {
 5968: 	    #FIXME interpret first N questions
 5969: 	}
 5970:     }
 5971:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5972: 				  $$scantron_config{'IDlength'});
 5973:     $record{'scantron.PaperID'}=
 5974: 	substr($data,$$scantron_config{'PaperID'}-1,
 5975: 	       $$scantron_config{'PaperIDlength'});
 5976:     $record{'scantron.FirstName'}=
 5977: 	substr($data,$$scantron_config{'FirstName'}-1,
 5978: 	       $$scantron_config{'FirstNamelength'});
 5979:     $record{'scantron.LastName'}=
 5980: 	substr($data,$$scantron_config{'LastName'}-1,
 5981: 	       $$scantron_config{'LastNamelength'});
 5982:     if ($just_header) { return \%record; }
 5983: 
 5984:     my @alphabet=('A'..'Z');
 5985:     my $questnum=0;
 5986:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5987: 
 5988:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5989:     if ($randompick || $randomorder) {
 5990:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 5991:                                          $master_seq,$symb_to_resource,
 5992:                                          $partids_by_symb,$orderedforcode,
 5993:                                          $respnumlookup,$startline);
 5994:         if ($total) {
 5995:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 5996:         }
 5997:         if (ref($totalref)) {
 5998:             $$totalref = $total;
 5999:         }
 6000:     }
 6001:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6002:     chomp($questions);		# Get rid of any trailing \n.
 6003:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6004:     while (length($questions)) {
 6005:         my $answers_needed;
 6006:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6007:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6008:         } else {
 6009: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6010:         }
 6011:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6012:                              || 1;
 6013:         $questnum++;
 6014:         my $quest_id = $questnum;
 6015:         my $currentquest = substr($questions,0,$answer_length);
 6016:         $questions       = substr($questions,$answer_length);
 6017:         if (length($currentquest) < $answer_length) { next; }
 6018: 
 6019:         my $subdivided;
 6020:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6021:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6022:         } else {
 6023:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6024:         }
 6025:         if ($subdivided =~ /,/) {
 6026:             my $subquestnum = 1;
 6027:             my $subquestions = $currentquest;
 6028:             my @subanswers_needed = split(/,/,$subdivided);
 6029:             foreach my $subans (@subanswers_needed) {
 6030:                 my $subans_length =
 6031:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6032:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6033:                 $subquestions   = substr($subquestions,$subans_length);
 6034:                 $quest_id = "$questnum.$subquestnum";
 6035:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6036:                     ($$scantron_config{'Qon'} eq 'number')) {
 6037:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6038:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6039:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6040:                         $randomorder,$randompick,$respnumlookup);
 6041:                 } else {
 6042:                     $ansnum = &scantron_validator_positional($ansnum,
 6043:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6044:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6045:                         $randomorder,$randompick,$respnumlookup);
 6046:                 }
 6047:                 $subquestnum ++;
 6048:             }
 6049:         } else {
 6050:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6051:                 ($$scantron_config{'Qon'} eq 'number')) {
 6052:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6053:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6054:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6055:                     $randomorder,$randompick,$respnumlookup);
 6056:             } else {
 6057:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6058:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6059:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6060:                     $randomorder,$randompick,$respnumlookup);
 6061:             }
 6062:         }
 6063:     }
 6064:     $record{'scantron.maxquest'}=$questnum;
 6065:     return \%record;
 6066: }
 6067: 
 6068: sub get_master_seq {
 6069:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6070:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6071:                    (ref($symb_to_resource) eq 'HASH'));
 6072:     my $resource_error;
 6073:     foreach my $resource (@{$resources}) {
 6074:         my $ressymb;
 6075:         if (ref($resource)) {
 6076:             $ressymb = $resource->symb();
 6077:             push(@{$master_seq},$ressymb);
 6078:             $symb_to_resource->{$ressymb} = $resource;
 6079:         } else {
 6080:             $resource_error = 1;
 6081:             last;
 6082:         }
 6083:     }
 6084:     return $resource_error;
 6085: }
 6086: 
 6087: sub get_respnum_lookups {
 6088:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6089:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6090:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6091:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6092:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6093:                    (ref($startline) eq 'HASH'));
 6094:     my ($user,$scancode);
 6095:     if ((exists($record->{'scantron.CODE'})) &&
 6096:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6097:         $scancode = $record->{'scantron.CODE'};
 6098:     } else {
 6099:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6100:     }
 6101:     my @mapresources =
 6102:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6103:                      $orderedforcode);
 6104:     my $total = 0;
 6105:     my $count = 0;
 6106:     foreach my $resource (@mapresources) {
 6107:         my $id = $resource->id();
 6108:         my $symb = $resource->symb();
 6109:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6110:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6111:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6112:                 if ($respnum ne '') {
 6113:                     $respnumlookup->{$count} = $respnum;
 6114:                     $startline->{$count} = $total;
 6115:                     $total += $bubble_lines_per_response{$respnum};
 6116:                     $count ++;
 6117:                 }
 6118:             }
 6119:         }
 6120:     }
 6121:     return $total;
 6122: }
 6123: 
 6124: sub scantron_validator_lettnum {
 6125:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6126:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6127:         $randompick,$respnumlookup) = @_;
 6128: 
 6129:     # Qon 'letter' implies for each slot in currquest we have:
 6130:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6131:     #    about anything else (esp. a value of Qoff) for missing
 6132:     #    bubbles.
 6133:     #
 6134:     # Qon 'number' implies each slot gives a digit that indexes the
 6135:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6136:     #    and * or ? for double bubbles on a single line.
 6137:     #
 6138: 
 6139:     my $matchon;
 6140:     if ($$scantron_config{'Qon'} eq 'letter') {
 6141:         $matchon = '[A-Z]';
 6142:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6143:         $matchon = '\d';
 6144:     }
 6145:     my $occurrences = 0;
 6146:     my $responsenum = $questnum-1;
 6147:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6148:        $responsenum = $respnumlookup->{$questnum-1} 
 6149:     }
 6150:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6151:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6152:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6153:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6154:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6155:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6156:         my @singlelines = split('',$currquest);
 6157:         foreach my $entry (@singlelines) {
 6158:             $occurrences = &occurence_count($entry,$matchon);
 6159:             if ($occurrences > 1) {
 6160:                 last;
 6161:             }
 6162:         }
 6163:     } else {
 6164:         $occurrences = &occurence_count($currquest,$matchon); 
 6165:     }
 6166:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6167:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6168:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6169:             my $bubble = substr($currquest,$ans,1);
 6170:             if ($bubble =~ /$matchon/ ) {
 6171:                 if ($$scantron_config{'Qon'} eq 'number') {
 6172:                     if ($bubble == 0) {
 6173:                         $bubble = 10; 
 6174:                     }
 6175:                     $record->{"scantron.$ansnum.answer"} = 
 6176:                         $alphabet->[$bubble-1];
 6177:                 } else {
 6178:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6179:                 }
 6180:             } else {
 6181:                 $record->{"scantron.$ansnum.answer"}='';
 6182:             }
 6183:             $ansnum++;
 6184:         }
 6185:     } elsif (!defined($currquest)
 6186:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6187:             || (&occurence_count($currquest,$matchon) == 0)) {
 6188:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6189:             $record->{"scantron.$ansnum.answer"}='';
 6190:             $ansnum++;
 6191:         }
 6192:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6193:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6194:         }
 6195:     } else {
 6196:         if ($$scantron_config{'Qon'} eq 'number') {
 6197:             $currquest = &digits_to_letters($currquest);            
 6198:         }
 6199:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6200:             my $bubble = substr($currquest,$ans,1);
 6201:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6202:             $ansnum++;
 6203:         }
 6204:     }
 6205:     return $ansnum;
 6206: }
 6207: 
 6208: sub scantron_validator_positional {
 6209:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6210:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6211:         $randomorder,$randompick,$respnumlookup) = @_;
 6212: 
 6213:     # Otherwise there's a positional notation;
 6214:     # each bubble line requires Qlength items, and there are filled in
 6215:     # bubbles for each case where there 'Qon' characters.
 6216:     #
 6217: 
 6218:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6219: 
 6220:     # If the split only gives us one element.. the full length of the
 6221:     # answer string, no bubbles are filled in:
 6222: 
 6223:     if ($answers_needed eq '') {
 6224:         return;
 6225:     }
 6226: 
 6227:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6228:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6229:             $record->{"scantron.$ansnum.answer"}='';
 6230:             $ansnum++;
 6231:         }
 6232:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6233:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6234:         }
 6235:     } elsif (scalar(@array) == 2) {
 6236:         my $location = length($array[0]);
 6237:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6238:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6239:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6240:             if ($ans eq $line_num) {
 6241:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6242:             } else {
 6243:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6244:             }
 6245:             $ansnum++;
 6246:          }
 6247:     } else {
 6248:         #  If there's more than one instance of a bubble character
 6249:         #  That's a double bubble; with positional notation we can
 6250:         #  record all the bubbles filled in as well as the
 6251:         #  fact this response consists of multiple bubbles.
 6252:         #
 6253:         my $responsenum = $questnum-1;
 6254:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6255:             $responsenum = $respnumlookup->{$questnum-1}
 6256:         }
 6257:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6258:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6259:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6260:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6261:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6262:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6263:             my $doubleerror = 0;
 6264:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6265:                    (!$doubleerror)) {
 6266:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6267:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6268:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6269:                if (length(@currarray) > 2) {
 6270:                    $doubleerror = 1;
 6271:                } 
 6272:             }
 6273:             if ($doubleerror) {
 6274:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6275:             }
 6276:         } else {
 6277:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6278:         }
 6279:         my $item = $ansnum;
 6280:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6281:             $record->{"scantron.$item.answer"} = '';
 6282:             $item ++;
 6283:         }
 6284: 
 6285:         my @ans=@array;
 6286:         my $i=0;
 6287:         my $increment = 0;
 6288:         while ($#ans) {
 6289:             $i+=length($ans[0]) + $increment;
 6290:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6291:             my $bubble = $i%$$scantron_config{'Qlength'};
 6292:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6293:             shift(@ans);
 6294:             $increment = 1;
 6295:         }
 6296:         $ansnum += $answers_needed;
 6297:     }
 6298:     return $ansnum;
 6299: }
 6300: 
 6301: =pod
 6302: 
 6303: =item scantron_add_delay
 6304: 
 6305:    Adds an error message that occurred during the grading phase to a
 6306:    queue of messages to be shown after grading pass is complete
 6307: 
 6308:  Arguments:
 6309:    $delayqueue  - arrary ref of hash ref of error messages
 6310:    $scanline    - the scanline that caused the error
 6311:    $errormesage - the error message
 6312:    $errorcode   - a numeric code for the error
 6313: 
 6314:  Side Effects:
 6315:    updates the $delayqueue to have a new hash ref of the error
 6316: 
 6317: =cut
 6318: 
 6319: sub scantron_add_delay {
 6320:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6321:     push(@$delayqueue,
 6322: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6323: 	  'ecode' => $errorcode }
 6324: 	 );
 6325: }
 6326: 
 6327: =pod
 6328: 
 6329: =item scantron_find_student
 6330: 
 6331:    Finds the username for the current scanline
 6332: 
 6333:   Arguments:
 6334:    $scantron_record - hash result from scantron_parse_scanline
 6335:    $scan_data       - hash of correction information 
 6336:                       (see &scantron_getfile() form more information)
 6337:    $idmap           - hash from &username_to_idmap()
 6338:    $line            - number of current scanline
 6339:  
 6340:   Returns:
 6341:    Either 'username:domain' or undef if unknown
 6342: 
 6343: =cut
 6344: 
 6345: sub scantron_find_student {
 6346:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6347:     my $scanID=$$scantron_record{'scantron.ID'};
 6348:     if ($scanID =~ /^\s*$/) {
 6349:  	return &scan_data($scan_data,"$line.user");
 6350:     }
 6351:     foreach my $id (keys(%$idmap)) {
 6352:  	if (lc($id) eq lc($scanID)) {
 6353:  	    return $$idmap{$id};
 6354:  	}
 6355:     }
 6356:     return undef;
 6357: }
 6358: 
 6359: =pod
 6360: 
 6361: =item scantron_filter
 6362: 
 6363:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6364:    hidden resources was selected
 6365: 
 6366: =cut
 6367: 
 6368: sub scantron_filter {
 6369:     my ($curres)=@_;
 6370: 
 6371:     if (ref($curres) && $curres->is_problem()) {
 6372: 	# if the user has asked to not have either hidden
 6373: 	# or 'randomout' controlled resources to be graded
 6374: 	# don't include them
 6375: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6376: 	    && $curres->randomout) {
 6377: 	    return 0;
 6378: 	}
 6379: 	return 1;
 6380:     }
 6381:     return 0;
 6382: }
 6383: 
 6384: =pod
 6385: 
 6386: =item scantron_process_corrections
 6387: 
 6388:    Gets correction information out of submitted form data and corrects
 6389:    the scanline
 6390: 
 6391: =cut
 6392: 
 6393: sub scantron_process_corrections {
 6394:     my ($r) = @_;
 6395:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6396:     my ($scanlines,$scan_data)=&scantron_getfile();
 6397:     my $classlist=&Apache::loncoursedata::get_classlist();
 6398:     my $which=$env{'form.scantron_line'};
 6399:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6400:     my ($skip,$err,$errmsg);
 6401:     if ($env{'form.scantron_skip_record'}) {
 6402: 	$skip=1;
 6403:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6404: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6405: 	    $env{'form.scantron_domain'};
 6406: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6407: 	($line,$err,$errmsg)=
 6408: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6409: 				     'ID',{'newid'=>$newid,
 6410: 				    'username'=>$env{'form.scantron_username'},
 6411: 				    'domain'=>$env{'form.scantron_domain'}});
 6412:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6413: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6414: 	my $newCODE;
 6415: 	my %args;
 6416: 	if      ($resolution eq 'use_unfound') {
 6417: 	    $newCODE='use_unfound';
 6418: 	} elsif ($resolution eq 'use_found') {
 6419: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6420: 	} elsif ($resolution eq 'use_typed') {
 6421: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6422: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6423: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6424: 	}
 6425: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6426: 	    $args{'CODE_ignore_dup'}=1;
 6427: 	}
 6428: 	$args{'CODE'}=$newCODE;
 6429: 	($line,$err,$errmsg)=
 6430: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6431: 				     'CODE',\%args);
 6432:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6433: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6434: 	    ($line,$err,$errmsg)=
 6435: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6436: 					 $which,'answer',
 6437: 					 { 'question'=>$question,
 6438: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6439:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6440: 	    if ($err) { last; }
 6441: 	}
 6442:     }
 6443:     if ($err) {
 6444:         $r->print(
 6445:             '<p class="LC_error">'
 6446:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6447:                 $errmsg)
 6448:            .'</p>');
 6449:     } else {
 6450: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6451: 	&scantron_putfile($scanlines,$scan_data);
 6452:     }
 6453: }
 6454: 
 6455: =pod
 6456: 
 6457: =item reset_skipping_status
 6458: 
 6459:    Forgets the current set of remember skipped scanlines (and thus
 6460:    reverts back to considering all lines in the
 6461:    scantron_skipped_<filename> file)
 6462: 
 6463: =cut
 6464: 
 6465: sub reset_skipping_status {
 6466:     my ($scanlines,$scan_data)=&scantron_getfile();
 6467:     &scan_data($scan_data,'remember_skipping',undef,1);
 6468:     &scantron_putfile(undef,$scan_data);
 6469: }
 6470: 
 6471: =pod
 6472: 
 6473: =item start_skipping
 6474: 
 6475:    Marks a scanline to be skipped. 
 6476: 
 6477: =cut
 6478: 
 6479: sub start_skipping {
 6480:     my ($scan_data,$i)=@_;
 6481:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6482:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6483: 	$remembered{$i}=2;
 6484:     } else {
 6485: 	$remembered{$i}=1;
 6486:     }
 6487:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6488: }
 6489: 
 6490: =pod
 6491: 
 6492: =item should_be_skipped
 6493: 
 6494:    Checks whether a scanline should be skipped.
 6495: 
 6496: =cut
 6497: 
 6498: sub should_be_skipped {
 6499:     my ($scanlines,$scan_data,$i)=@_;
 6500:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6501: 	# not redoing old skips
 6502: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6503: 	return 0;
 6504:     }
 6505:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6506: 
 6507:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6508: 	return 0;
 6509:     }
 6510:     return 1;
 6511: }
 6512: 
 6513: =pod
 6514: 
 6515: =item remember_current_skipped
 6516: 
 6517:    Discovers what scanlines are in the scantron_skipped_<filename>
 6518:    file and remembers them into scan_data for later use.
 6519: 
 6520: =cut
 6521: 
 6522: sub remember_current_skipped {
 6523:     my ($scanlines,$scan_data)=&scantron_getfile();
 6524:     my %to_remember;
 6525:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6526: 	if ($scanlines->{'skipped'}[$i]) {
 6527: 	    $to_remember{$i}=1;
 6528: 	}
 6529:     }
 6530: 
 6531:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6532:     &scantron_putfile(undef,$scan_data);
 6533: }
 6534: 
 6535: =pod
 6536: 
 6537: =item check_for_error
 6538: 
 6539:     Checks if there was an error when attempting to remove a specific
 6540:     scantron_.. bubblesheet data file. Prints out an error if
 6541:     something went wrong.
 6542: 
 6543: =cut
 6544: 
 6545: sub check_for_error {
 6546:     my ($r,$result)=@_;
 6547:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6548: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6549:     }
 6550: }
 6551: 
 6552: =pod
 6553: 
 6554: =item scantron_warning_screen
 6555: 
 6556:    Interstitial screen to make sure the operator has selected the
 6557:    correct options before we start the validation phase.
 6558: 
 6559: =cut
 6560: 
 6561: sub scantron_warning_screen {
 6562:     my ($button_text,$symb)=@_;
 6563:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6564:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6565:     my $CODElist;
 6566:     if ($scantron_config{'CODElocation'} &&
 6567: 	$scantron_config{'CODEstart'} &&
 6568: 	$scantron_config{'CODElength'}) {
 6569: 	$CODElist=$env{'form.scantron_CODElist'};
 6570: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6571: 	$CODElist=
 6572: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6573: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6574:     }
 6575:     my $lastbubblepoints;
 6576:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6577:         $lastbubblepoints =
 6578:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6579:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6580:     }
 6581:     return ('
 6582: <p>
 6583: <span class="LC_warning">
 6584: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6585: </p>
 6586: <table>
 6587: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6588: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6589: '.$CODElist.$lastbubblepoints.'
 6590: </table>
 6591: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6592: '.&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>
 6593: 
 6594: <br />
 6595: ');
 6596: }
 6597: 
 6598: =pod
 6599: 
 6600: =item scantron_do_warning
 6601: 
 6602:    Check if the operator has picked something for all required
 6603:    fields. Error out if something is missing.
 6604: 
 6605: =cut
 6606: 
 6607: sub scantron_do_warning {
 6608:     my ($r,$symb)=@_;
 6609:     if (!$symb) {return '';}
 6610:     my $default_form_data=&defaultFormData($symb);
 6611:     $r->print(&scantron_form_start().$default_form_data);
 6612:     if ( $env{'form.selectpage'} eq '' ||
 6613: 	 $env{'form.scantron_selectfile'} eq '' ||
 6614: 	 $env{'form.scantron_format'} eq '' ) {
 6615: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6616: 	if ( $env{'form.selectpage'} eq '') {
 6617: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6618: 	} 
 6619: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6620: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6621: 	} 
 6622: 	if ( $env{'form.scantron_format'} eq '') {
 6623: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6624: 	} 
 6625:     } else {
 6626: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6627:         my $bubbledbyhand=&hand_bubble_option();
 6628: 	$r->print('
 6629: '.$warning.$bubbledbyhand.'
 6630: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6631: <input type="hidden" name="command" value="scantron_validate" />
 6632: ');
 6633:     }
 6634:     $r->print("</form><br />");
 6635:     return '';
 6636: }
 6637: 
 6638: =pod
 6639: 
 6640: =item scantron_form_start
 6641: 
 6642:     html hidden input for remembering all selected grading options
 6643: 
 6644: =cut
 6645: 
 6646: sub scantron_form_start {
 6647:     my ($max_bubble)=@_;
 6648:     my $result= <<SCANTRONFORM;
 6649: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6650:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6651:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6652:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6653:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6654:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6655:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6656:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6657:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6658:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6659: SCANTRONFORM
 6660: 
 6661:   my $line = 0;
 6662:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6663:        my $chunk =
 6664: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6665:        $chunk .=
 6666: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6667:        $chunk .= 
 6668:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6669:        $chunk .=
 6670:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6671:        $chunk .=
 6672:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6673:        $result .= $chunk;
 6674:        $line++;
 6675:     }
 6676:     return $result;
 6677: }
 6678: 
 6679: =pod
 6680: 
 6681: =item scantron_validate_file
 6682: 
 6683:     Dispatch routine for doing validation of a bubblesheet data file.
 6684: 
 6685:     Also processes any necessary information resets that need to
 6686:     occur before validation begins (ignore previous corrections,
 6687:     restarting the skipped records processing)
 6688: 
 6689: =cut
 6690: 
 6691: sub scantron_validate_file {
 6692:     my ($r,$symb) = @_;
 6693:     if (!$symb) {return '';}
 6694:     my $default_form_data=&defaultFormData($symb);
 6695:     
 6696:     # do the detection of only doing skipped records first before we delete
 6697:     # them when doing the corrections reset
 6698:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6699: 	&reset_skipping_status();
 6700:     }
 6701:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6702: 	&remember_current_skipped();
 6703: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6704:     }
 6705: 
 6706:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6707: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6708: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6709: 	&check_for_error($r,&scantron_remove_scan_data());
 6710: 	$env{'form.scantron_options_ignore'}='done';
 6711:     }
 6712: 
 6713:     if ($env{'form.scantron_corrections'}) {
 6714: 	&scantron_process_corrections($r);
 6715:     }
 6716:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6717:     #get the student pick code ready
 6718:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6719:     my $nav_error;
 6720:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6721:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6722:     if ($nav_error) {
 6723:         $r->print(&navmap_errormsg());
 6724:         return '';
 6725:     }
 6726:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6727:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6728:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6729:     }
 6730:     $r->print($result);
 6731:     
 6732:     my @validate_phases=( 'sequence',
 6733: 			  'ID',
 6734: 			  'CODE',
 6735: 			  'doublebubble',
 6736: 			  'missingbubbles');
 6737:     if (!$env{'form.validatepass'}) {
 6738: 	$env{'form.validatepass'} = 0;
 6739:     }
 6740:     my $currentphase=$env{'form.validatepass'};
 6741: 
 6742: 
 6743:     my $stop=0;
 6744:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6745: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6746: 	$r->rflush();
 6747:      
 6748: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6749: 	{
 6750: 	    no strict 'refs';
 6751: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6752: 	}
 6753:     }
 6754:     if (!$stop) {
 6755: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6756: 	$r->print(&mt('Validation process complete.').'<br />'.
 6757:                   $warning.
 6758:                   &mt('Perform verification for each student after storage of submissions?').
 6759:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6760:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6761:                   ('&nbsp;'x3).'<label>'.
 6762:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6763:                   '</label></span><br />'.
 6764:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6765:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6766:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6767:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6768:     } else {
 6769: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6770: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6771:     }
 6772:     if ($stop) {
 6773: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6774: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6775: 	    $r->print(' '.&mt('this error').' <br />');
 6776: 
 6777: 	    $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>');
 6778: 	} else {
 6779:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6780: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6781:             } else {
 6782:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6783:             }
 6784: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6785: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6786: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6787: 	}
 6788:     }
 6789:     $r->print(" </form><br />");
 6790:     return '';
 6791: }
 6792: 
 6793: 
 6794: =pod
 6795: 
 6796: =item scantron_remove_file
 6797: 
 6798:    Removes the requested bubblesheet data file, makes sure that
 6799:    scantron_original_<filename> is never removed
 6800: 
 6801: 
 6802: =cut
 6803: 
 6804: sub scantron_remove_file {
 6805:     my ($which)=@_;
 6806:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6807:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6808:     my $file='scantron_';
 6809:     if ($which eq 'corrected' || $which eq 'skipped') {
 6810: 	$file.=$which.'_';
 6811:     } else {
 6812: 	return 'refused';
 6813:     }
 6814:     $file.=$env{'form.scantron_selectfile'};
 6815:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6816: }
 6817: 
 6818: 
 6819: =pod
 6820: 
 6821: =item scantron_remove_scan_data
 6822: 
 6823:    Removes all scan_data correction for the requested bubblesheet
 6824:    data file.  (In the case that both the are doing skipped records we need
 6825:    to remember the old skipped lines for the time being so that element
 6826:    persists for a while.)
 6827: 
 6828: =cut
 6829: 
 6830: sub scantron_remove_scan_data {
 6831:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6832:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6833:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6834:     my @todelete;
 6835:     my $filename=$env{'form.scantron_selectfile'};
 6836:     foreach my $key (@keys) {
 6837: 	if ($key=~/^\Q$filename\E_/) {
 6838: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6839: 		$key=~/remember_skipping/) {
 6840: 		next;
 6841: 	    }
 6842: 	    push(@todelete,$key);
 6843: 	}
 6844:     }
 6845:     my $result;
 6846:     if (@todelete) {
 6847: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6848: 				       \@todelete,$cdom,$cname);
 6849:     } else {
 6850: 	$result = 'ok';
 6851:     }
 6852:     return $result;
 6853: }
 6854: 
 6855: 
 6856: =pod
 6857: 
 6858: =item scantron_getfile
 6859: 
 6860:     Fetches the requested bubblesheet data file (all 3 versions), and
 6861:     the scan_data hash
 6862:   
 6863:   Arguments:
 6864:     None
 6865: 
 6866:   Returns:
 6867:     2 hash references
 6868: 
 6869:      - first one has 
 6870:          orig      -
 6871:          corrected -
 6872:          skipped   -  each of which points to an array ref of the specified
 6873:                       file broken up into individual lines
 6874:          count     - number of scanlines
 6875:  
 6876:      - second is the scan_data hash possible keys are
 6877:        ($number refers to scanline numbered $number and thus the key affects
 6878:         only that scanline
 6879:         $bubline refers to the specific bubble line element and the aspects
 6880:         refers to that specific bubble line element)
 6881: 
 6882:        $number.user - username:domain to use
 6883:        $number.CODE_ignore_dup 
 6884:                     - ignore the duplicate CODE error 
 6885:        $number.useCODE
 6886:                     - use the CODE in the scanline as is
 6887:        $number.no_bubble.$bubline
 6888:                     - it is valid that there is no bubbled in bubble
 6889:                       at $number $bubline
 6890:        remember_skipping
 6891:                     - a frozen hash containing keys of $number and values
 6892:                       of either 
 6893:                         1 - we are on a 'do skipped records pass' and plan
 6894:                             on processing this line
 6895:                         2 - we are on a 'do skipped records pass' and this
 6896:                             scanline has been marked to skip yet again
 6897: 
 6898: =cut
 6899: 
 6900: sub scantron_getfile {
 6901:     #FIXME really would prefer a scantron directory
 6902:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6903:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6904:     my $lines;
 6905:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6906: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6907:     my %scanlines;
 6908:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6909:     my $temp=$scanlines{'orig'};
 6910:     $scanlines{'count'}=$#$temp;
 6911: 
 6912:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6913: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6914:     if ($lines eq '-1') {
 6915: 	$scanlines{'corrected'}=[];
 6916:     } else {
 6917: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6918:     }
 6919:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6920: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6921:     if ($lines eq '-1') {
 6922: 	$scanlines{'skipped'}=[];
 6923:     } else {
 6924: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6925:     }
 6926:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6927:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6928:     my %scan_data = @tmp;
 6929:     return (\%scanlines,\%scan_data);
 6930: }
 6931: 
 6932: =pod
 6933: 
 6934: =item lonnet_putfile
 6935: 
 6936:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6937: 
 6938:  Arguments:
 6939:    $contents - data to store
 6940:    $filename - filename to store $contents into
 6941: 
 6942:  Returns:
 6943:    result value from &Apache::lonnet::finishuserfileupload
 6944: 
 6945: =cut
 6946: 
 6947: sub lonnet_putfile {
 6948:     my ($contents,$filename)=@_;
 6949:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6950:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6951:     $env{'form.sillywaytopassafilearound'}=$contents;
 6952:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6953: 
 6954: }
 6955: 
 6956: =pod
 6957: 
 6958: =item scantron_putfile
 6959: 
 6960:     Stores the current version of the bubblesheet data files, and the
 6961:     scan_data hash. (Does not modify the original version only the
 6962:     corrected and skipped versions.
 6963: 
 6964:  Arguments:
 6965:     $scanlines - hash ref that looks like the first return value from
 6966:                  &scantron_getfile()
 6967:     $scan_data - hash ref that looks like the second return value from
 6968:                  &scantron_getfile()
 6969: 
 6970: =cut
 6971: 
 6972: sub scantron_putfile {
 6973:     my ($scanlines,$scan_data) = @_;
 6974:     #FIXME really would prefer a scantron directory
 6975:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6976:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6977:     if ($scanlines) {
 6978: 	my $prefix='scantron_';
 6979: # no need to update orig, shouldn't change
 6980: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6981: #		    $env{'form.scantron_selectfile'});
 6982: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6983: 			$prefix.'corrected_'.
 6984: 			$env{'form.scantron_selectfile'});
 6985: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6986: 			$prefix.'skipped_'.
 6987: 			$env{'form.scantron_selectfile'});
 6988:     }
 6989:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6990: }
 6991: 
 6992: =pod
 6993: 
 6994: =item scantron_get_line
 6995: 
 6996:    Returns the correct version of the scanline
 6997: 
 6998:  Arguments:
 6999:     $scanlines - hash ref that looks like the first return value from
 7000:                  &scantron_getfile()
 7001:     $scan_data - hash ref that looks like the second return value from
 7002:                  &scantron_getfile()
 7003:     $i         - number of the requested line (starts at 0)
 7004: 
 7005:  Returns:
 7006:    A scanline, (either the original or the corrected one if it
 7007:    exists), or undef if the requested scanline should be
 7008:    skipped. (Either because it's an skipped scanline, or it's an
 7009:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7010:    pass.
 7011: 
 7012: =cut
 7013: 
 7014: sub scantron_get_line {
 7015:     my ($scanlines,$scan_data,$i)=@_;
 7016:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7017:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7018:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7019:     return $scanlines->{'orig'}[$i]; 
 7020: }
 7021: 
 7022: =pod
 7023: 
 7024: =item scantron_todo_count
 7025: 
 7026:     Counts the number of scanlines that need processing.
 7027: 
 7028:  Arguments:
 7029:     $scanlines - hash ref that looks like the first return value from
 7030:                  &scantron_getfile()
 7031:     $scan_data - hash ref that looks like the second return value from
 7032:                  &scantron_getfile()
 7033: 
 7034:  Returns:
 7035:     $count - number of scanlines to process
 7036: 
 7037: =cut
 7038: 
 7039: sub get_todo_count {
 7040:     my ($scanlines,$scan_data)=@_;
 7041:     my $count=0;
 7042:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7043: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7044: 	if ($line=~/^[\s\cz]*$/) { next; }
 7045: 	$count++;
 7046:     }
 7047:     return $count;
 7048: }
 7049: 
 7050: =pod
 7051: 
 7052: =item scantron_put_line
 7053: 
 7054:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7055:     data file.
 7056: 
 7057:  Arguments:
 7058:     $scanlines - hash ref that looks like the first return value from
 7059:                  &scantron_getfile()
 7060:     $scan_data - hash ref that looks like the second return value from
 7061:                  &scantron_getfile()
 7062:     $i         - line number to update
 7063:     $newline   - contents of the updated scanline
 7064:     $skip      - if true make the line for skipping and update the
 7065:                  'skipped' file
 7066: 
 7067: =cut
 7068: 
 7069: sub scantron_put_line {
 7070:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7071:     if ($skip) {
 7072: 	$scanlines->{'skipped'}[$i]=$newline;
 7073: 	&start_skipping($scan_data,$i);
 7074: 	return;
 7075:     }
 7076:     $scanlines->{'corrected'}[$i]=$newline;
 7077: }
 7078: 
 7079: =pod
 7080: 
 7081: =item scantron_clear_skip
 7082: 
 7083:    Remove a line from the 'skipped' file
 7084: 
 7085:  Arguments:
 7086:     $scanlines - hash ref that looks like the first return value from
 7087:                  &scantron_getfile()
 7088:     $scan_data - hash ref that looks like the second return value from
 7089:                  &scantron_getfile()
 7090:     $i         - line number to update
 7091: 
 7092: =cut
 7093: 
 7094: sub scantron_clear_skip {
 7095:     my ($scanlines,$scan_data,$i)=@_;
 7096:     if (exists($scanlines->{'skipped'}[$i])) {
 7097: 	undef($scanlines->{'skipped'}[$i]);
 7098: 	return 1;
 7099:     }
 7100:     return 0;
 7101: }
 7102: 
 7103: =pod
 7104: 
 7105: =item scantron_filter_not_exam
 7106: 
 7107:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7108:    filter out resources that are not marked as 'exam' mode
 7109: 
 7110: =cut
 7111: 
 7112: sub scantron_filter_not_exam {
 7113:     my ($curres)=@_;
 7114:     
 7115:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7116: 	# if the user has asked to not have either hidden
 7117: 	# or 'randomout' controlled resources to be graded
 7118: 	# don't include them
 7119: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7120: 	    && $curres->randomout) {
 7121: 	    return 0;
 7122: 	}
 7123: 	return 1;
 7124:     }
 7125:     return 0;
 7126: }
 7127: 
 7128: =pod
 7129: 
 7130: =item scantron_validate_sequence
 7131: 
 7132:     Validates the selected sequence, checking for resource that are
 7133:     not set to exam mode.
 7134: 
 7135: =cut
 7136: 
 7137: sub scantron_validate_sequence {
 7138:     my ($r,$currentphase) = @_;
 7139: 
 7140:     my $navmap=Apache::lonnavmaps::navmap->new();
 7141:     unless (ref($navmap)) {
 7142:         $r->print(&navmap_errormsg());
 7143:         return (1,$currentphase);
 7144:     }
 7145:     my (undef,undef,$sequence)=
 7146: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7147: 
 7148:     my $map=$navmap->getResourceByUrl($sequence);
 7149: 
 7150:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7151:                                     value="ignore" />');
 7152:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7153: 	my @resources=
 7154: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7155: 	if (@resources) {
 7156: 	    $r->print(
 7157:                 '<p class="LC_warning">'
 7158:                .&mt('Some resources in the sequence currently are not set to'
 7159:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7160:                    .' work correctly.')
 7161:                .'</p>'
 7162:             );
 7163: 	    return (1,$currentphase);
 7164: 	}
 7165:     }
 7166: 
 7167:     return (0,$currentphase+1);
 7168: }
 7169: 
 7170: 
 7171: 
 7172: sub scantron_validate_ID {
 7173:     my ($r,$currentphase) = @_;
 7174:     
 7175:     #get student info
 7176:     my $classlist=&Apache::loncoursedata::get_classlist();
 7177:     my %idmap=&username_to_idmap($classlist);
 7178: 
 7179:     #get scantron line setup
 7180:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7181:     my ($scanlines,$scan_data)=&scantron_getfile();
 7182: 
 7183:     my $nav_error;
 7184:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7185:     if ($nav_error) {
 7186:         $r->print(&navmap_errormsg());
 7187:         return(1,$currentphase);
 7188:     }
 7189: 
 7190:     my %found=('ids'=>{},'usernames'=>{});
 7191:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7192: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7193: 	if ($line=~/^[\s\cz]*$/) { next; }
 7194: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7195: 						 $scan_data);
 7196: 	my $id=$$scan_record{'scantron.ID'};
 7197: 	my $found;
 7198: 	foreach my $checkid (keys(%idmap)) {
 7199: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7200: 	}
 7201: 	if ($found) {
 7202: 	    my $username=$idmap{$found};
 7203: 	    if ($found{'ids'}{$found}) {
 7204: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7205: 					 $line,'duplicateID',$found);
 7206: 		return(1,$currentphase);
 7207: 	    } elsif ($found{'usernames'}{$username}) {
 7208: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7209: 					 $line,'duplicateID',$username);
 7210: 		return(1,$currentphase);
 7211: 	    }
 7212: 	    #FIXME store away line we previously saw the ID on to use above
 7213: 	    $found{'ids'}{$found}++;
 7214: 	    $found{'usernames'}{$username}++;
 7215: 	} else {
 7216: 	    if ($id =~ /^\s*$/) {
 7217: 		my $username=&scan_data($scan_data,"$i.user");
 7218: 		if (defined($username) && $found{'usernames'}{$username}) {
 7219: 		    &scantron_get_correction($r,$i,$scan_record,
 7220: 					     \%scantron_config,
 7221: 					     $line,'duplicateID',$username);
 7222: 		    return(1,$currentphase);
 7223: 		} elsif (!defined($username)) {
 7224: 		    &scantron_get_correction($r,$i,$scan_record,
 7225: 					     \%scantron_config,
 7226: 					     $line,'incorrectID');
 7227: 		    return(1,$currentphase);
 7228: 		}
 7229: 		$found{'usernames'}{$username}++;
 7230: 	    } else {
 7231: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7232: 					 $line,'incorrectID');
 7233: 		return(1,$currentphase);
 7234: 	    }
 7235: 	}
 7236:     }
 7237: 
 7238:     return (0,$currentphase+1);
 7239: }
 7240: 
 7241: 
 7242: sub scantron_get_correction {
 7243:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7244:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7245: #FIXME in the case of a duplicated ID the previous line, probably need
 7246: #to show both the current line and the previous one and allow skipping
 7247: #the previous one or the current one
 7248: 
 7249:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7250:         $r->print(
 7251:             '<p class="LC_warning">'
 7252:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7253:                 "<b>$error</b>",
 7254:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7255:            ."</p> \n");
 7256:     } else {
 7257:         $r->print(
 7258:             '<p class="LC_warning">'
 7259:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7260:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7261:            ."</p> \n");
 7262:     }
 7263:     my $message =
 7264:         '<p>'
 7265:        .&mt('The ID on the form is [_1]',
 7266:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7267:        .'<br />'
 7268:        .&mt('The name on the paper is [_1], [_2]',
 7269:             $$scan_record{'scantron.LastName'},
 7270:             $$scan_record{'scantron.FirstName'})
 7271:        .'</p>';
 7272: 
 7273:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7274:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7275:                            # Array populated for doublebubble or
 7276:     my @lines_to_correct;  # missingbubble errors to build javascript
 7277:                            # to validate radio button checking   
 7278: 
 7279:     if ($error =~ /ID$/) {
 7280: 	if ($error eq 'incorrectID') {
 7281:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7282: 		      "</p>\n");
 7283: 	} elsif ($error eq 'duplicateID') {
 7284:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7285: 	}
 7286: 	$r->print($message);
 7287: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7288: 	$r->print("\n<ul><li> ");
 7289: 	#FIXME it would be nice if this sent back the user ID and
 7290: 	#could do partial userID matches
 7291: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7292: 				       'scantron_username','scantron_domain'));
 7293: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7294: 	$r->print("\n:\n".
 7295: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7296: 
 7297: 	$r->print('</li>');
 7298:     } elsif ($error =~ /CODE$/) {
 7299: 	if ($error eq 'incorrectCODE') {
 7300: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7301: 	} elsif ($error eq 'duplicateCODE') {
 7302: 	    $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");
 7303: 	}
 7304: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7305: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7306:                  ."</p>\n");
 7307: 	$r->print($message);
 7308: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7309: 	$r->print("\n<br /> ");
 7310: 	my $i=0;
 7311: 	if ($error eq 'incorrectCODE' 
 7312: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7313: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7314: 	    if ($closest > 0) {
 7315: 		foreach my $testcode (@{$closest}) {
 7316: 		    my $checked='';
 7317: 		    if (!$i) { $checked=' checked="checked"'; }
 7318: 		    $r->print("
 7319:    <label>
 7320:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7321:        ".&mt("Use the similar CODE [_1] instead.",
 7322: 	    "<b><tt>".$testcode."</tt></b>")."
 7323:     </label>
 7324:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7325: 		    $r->print("\n<br />");
 7326: 		    $i++;
 7327: 		}
 7328: 	    }
 7329: 	}
 7330: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7331: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7332: 	    $r->print("
 7333:     <label>
 7334:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7335:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7336: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7337:     </label>");
 7338: 	    $r->print("\n<br />");
 7339: 	}
 7340: 
 7341: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7342: function change_radio(field) {
 7343:     var slct=document.scantronupload.scantron_CODE_resolution;
 7344:     var i;
 7345:     for (i=0;i<slct.length;i++) {
 7346:         if (slct[i].value==field) { slct[i].checked=true; }
 7347:     }
 7348: }
 7349: ENDSCRIPT
 7350: 	my $href="/adm/pickcode?".
 7351: 	   "form=".&escape("scantronupload").
 7352: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7353: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7354: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7355: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7356: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7357: 	    $r->print("
 7358:     <label>
 7359:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7360:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7361: 	     "<a target='_blank' href='$href'>","</a>")."
 7362:     </label> 
 7363:     ".&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\')" />'));
 7364: 	    $r->print("\n<br />");
 7365: 	}
 7366: 	$r->print("
 7367:     <label>
 7368:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7369:        ".&mt("Use [_1] as the CODE.",
 7370: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7371: 	$r->print("\n<br /><br />");
 7372:     } elsif ($error eq 'doublebubble') {
 7373: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7374: 
 7375: 	# The form field scantron_questions is acutally a list of line numbers.
 7376: 	# represented by this form so:
 7377: 
 7378: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7379:                                                 $respnumlookup,$startline);
 7380: 
 7381: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7382: 		  $line_list.'" />');
 7383: 	$r->print($message);
 7384: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7385: 	foreach my $question (@{$arg}) {
 7386: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7387:                                                    $scan_record, $error,
 7388:                                                    $randomorder,$randompick,
 7389:                                                    $respnumlookup,$startline);
 7390:             push(@lines_to_correct,@linenums);
 7391: 	}
 7392:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7393:     } elsif ($error eq 'missingbubble') {
 7394: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7395: 	$r->print($message);
 7396: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7397: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7398: 
 7399: 	# The form field scantron_questions is actually a list of line numbers not
 7400: 	# a list of question numbers. Therefore:
 7401: 	#
 7402: 
 7403: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7404:                                                 $respnumlookup,$startline);
 7405: 
 7406: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7407: 		  $line_list.'" />');
 7408: 	foreach my $question (@{$arg}) {
 7409: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7410:                                                    $scan_record, $error,
 7411:                                                    $randomorder,$randompick,
 7412:                                                    $respnumlookup,$startline);
 7413:             push(@lines_to_correct,@linenums);
 7414: 	}
 7415:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7416:     } else {
 7417: 	$r->print("\n<ul>");
 7418:     }
 7419:     $r->print("\n</li></ul>");
 7420: }
 7421: 
 7422: sub verify_bubbles_checked {
 7423:     my (@ansnums) = @_;
 7424:     my $ansnumstr = join('","',@ansnums);
 7425:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7426:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7427: function verify_bubble_radio(form) {
 7428:     var ansnumArray = new Array ("$ansnumstr");
 7429:     var need_bubble_count = 0;
 7430:     for (var i=0; i<ansnumArray.length; i++) {
 7431:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7432:             var bubble_picked = 0; 
 7433:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7434:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7435:                     bubble_picked = 1;
 7436:                 }
 7437:             }
 7438:             if (bubble_picked == 0) {
 7439:                 need_bubble_count ++;
 7440:             }
 7441:         }
 7442:     }
 7443:     if (need_bubble_count) {
 7444:         alert("$warning");
 7445:         return;
 7446:     }
 7447:     form.submit(); 
 7448: }
 7449: ENDSCRIPT
 7450:     return $output;
 7451: }
 7452: 
 7453: =pod
 7454: 
 7455: =item  questions_to_line_list
 7456: 
 7457: Converts a list of questions into a string of comma separated
 7458: line numbers in the answer sheet used by the questions.  This is
 7459: used to fill in the scantron_questions form field.
 7460: 
 7461:   Arguments:
 7462:      questions    - Reference to an array of questions.
 7463:      randomorder  - True if randomorder in use.
 7464:      randompick   - True if randompick in use.
 7465:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7466:                      for current line to question number used for same question
 7467:                      in "Master Seqence" (as seen by Course Coordinator).
 7468:      startline    - Reference to hash where key is question number (0 is first)
 7469:                     and key is number of first bubble line for current student
 7470:                     or code-based randompick and/or randomorder.
 7471: 
 7472: =cut
 7473: 
 7474: 
 7475: sub questions_to_line_list {
 7476:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7477:     my @lines;
 7478: 
 7479:     foreach my $item (@{$questions}) {
 7480:         my $question = $item;
 7481:         my ($first,$count,$last);
 7482:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7483:             $question = $1;
 7484:             my $subquestion = $2;
 7485:             my $responsenum = $question-1;
 7486:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7487:                 $responsenum = $respnumlookup->{$question-1};
 7488:                 if (ref($startline) eq 'HASH') {
 7489:                     $first = $startline->{$question-1} + 1;
 7490:                 }
 7491:             } else {
 7492:                 $first = $first_bubble_line{$responsenum} + 1;
 7493:             }
 7494:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7495:             my $subcount = 1;
 7496:             while ($subcount<$subquestion) {
 7497:                 $first += $subans[$subcount-1];
 7498:                 $subcount ++;
 7499:             }
 7500:             $count = $subans[$subquestion-1];
 7501:         } else {
 7502:             my $responsenum = $question-1;
 7503:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7504:                 $responsenum = $respnumlookup->{$question-1};
 7505:                 if (ref($startline) eq 'HASH') {
 7506:                     $first = $startline->{$question-1} + 1;
 7507:                 }
 7508:             } else {
 7509:                 $first = $first_bubble_line{$responsenum} + 1;
 7510:             }
 7511: 	    $count   = $bubble_lines_per_response{$responsenum};
 7512:         }
 7513:         $last = $first+$count-1;
 7514:         push(@lines, ($first..$last));
 7515:     }
 7516:     return join(',', @lines);
 7517: }
 7518: 
 7519: =pod 
 7520: 
 7521: =item prompt_for_corrections
 7522: 
 7523: Prompts for a potentially multiline correction to the
 7524: user's bubbling (factors out common code from scantron_get_correction
 7525: for multi and missing bubble cases).
 7526: 
 7527:  Arguments:
 7528:    $r           - Apache request object.
 7529:    $question    - The question number to prompt for.
 7530:    $scan_config - The scantron file configuration hash.
 7531:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7532:    $error       - Type of error
 7533:    $randomorder - True if randomorder in use.
 7534:    $randompick  - True if randompick in use.
 7535:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7536:                     for current line to question number used for same question
 7537:                     in "Master Seqence" (as seen by Course Coordinator).
 7538:    $startline   - Reference to hash where key is question number (0 is first)
 7539:                   and value is number of first bubble line for current student
 7540:                   or code-based randompick and/or randomorder.
 7541: 
 7542: 
 7543:  Implicit inputs:
 7544:    %bubble_lines_per_response   - Starting line numbers for each question.
 7545:                                   Numbered from 0 (but question numbers are from
 7546:                                   1.
 7547:    %first_bubble_line           - Starting bubble line for each question.
 7548:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7549:                                   type problems render as separate sub-questions, 
 7550:                                   in exam mode. This hash contains a 
 7551:                                   comma-separated list of the lines per 
 7552:                                   sub-question.
 7553:    %responsetype_per_response   - essayresponse, formularesponse,
 7554:                                   stringresponse, imageresponse, reactionresponse,
 7555:                                   and organicresponse type problem parts can have
 7556:                                   multiple lines per response if the weight
 7557:                                   assigned exceeds 10.  In this case, only
 7558:                                   one bubble per line is permitted, but more 
 7559:                                   than one line might contain bubbles, e.g.
 7560:                                   bubbling of: line 1 - J, line 2 - J, 
 7561:                                   line 3 - B would assign 22 points.  
 7562: 
 7563: =cut
 7564: 
 7565: sub prompt_for_corrections {
 7566:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7567:         $randompick, $respnumlookup, $startline) = @_;
 7568:     my ($current_line,$lines);
 7569:     my @linenums;
 7570:     my $questionnum = $question;
 7571:     my ($first,$responsenum);
 7572:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7573:         $question = $1;
 7574:         my $subquestion = $2;
 7575:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7576:             $responsenum = $respnumlookup->{$question-1};
 7577:             if (ref($startline) eq 'HASH') {
 7578:                 $first = $startline->{$question-1};
 7579:             }
 7580:         } else {
 7581:             $responsenum = $question-1;
 7582:             $first = $first_bubble_line{$responsenum} + 1;
 7583:         }
 7584:         $current_line = $first + 1 ;
 7585:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7586:         my $subcount = 1;
 7587:         while ($subcount<$subquestion) {
 7588:             $current_line += $subans[$subcount-1];
 7589:             $subcount ++;
 7590:         }
 7591:         $lines = $subans[$subquestion-1];
 7592:     } else {
 7593:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7594:             $responsenum = $respnumlookup->{$question-1};
 7595:             if (ref($startline) eq 'HASH') { 
 7596:                 $first = $startline->{$question-1};
 7597:             }
 7598:         } else {
 7599:             $responsenum = $question-1;
 7600:             $first = $first_bubble_line{$responsenum};
 7601:         }
 7602:         $current_line = $first + 1;
 7603:         $lines        = $bubble_lines_per_response{$responsenum};
 7604:     }
 7605:     if ($lines > 1) {
 7606:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7607:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7608:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7609:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7610:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7611:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7612:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7613:             $r->print(
 7614:                 &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)
 7615:                .'<br /><br />'
 7616:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7617:                .'<br />'
 7618:                .&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.')
 7619:                .'<br />'
 7620:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7621:                .'<br /><br />'
 7622:             );
 7623:         } else {
 7624:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7625:         }
 7626:     }
 7627:     for (my $i =0; $i < $lines; $i++) {
 7628:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7629: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7630: 	        		  $questionnum,$error,split('', $selected));
 7631:         push(@linenums,$current_line);
 7632: 	$current_line++;
 7633:     }
 7634:     if ($lines > 1) {
 7635: 	$r->print("<hr /><br />");
 7636:     }
 7637:     return @linenums;
 7638: }
 7639: 
 7640: =pod
 7641: 
 7642: =item scantron_bubble_selector
 7643:   
 7644:    Generates the html radiobuttons to correct a single bubble line
 7645:    possibly showing the existing the selected bubbles if known
 7646: 
 7647:  Arguments:
 7648:     $r           - Apache request object
 7649:     $scan_config - hash from &get_scantron_config()
 7650:     $line        - Number of the line being displayed.
 7651:     $questionnum - Question number (may include subquestion)
 7652:     $error       - Type of error.
 7653:     @selected    - Array of bubbles picked on this line.
 7654: 
 7655: =cut
 7656: 
 7657: sub scantron_bubble_selector {
 7658:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7659:     my $max=$$scan_config{'Qlength'};
 7660: 
 7661:     my $scmode=$$scan_config{'Qon'};
 7662:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7663:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7664:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7665:             $max=$$scan_config{'BubblesPerRow'};
 7666:             if (($scmode eq 'number') && ($max > 10)) {
 7667:                 $max = 10;
 7668:             } elsif (($scmode eq 'letter') && $max > 26) {
 7669:                 $max = 26;
 7670:             }
 7671:         } else {
 7672:             $max = 10;
 7673:         }
 7674:     }
 7675: 
 7676:     my @alphabet=('A'..'Z');
 7677:     $r->print(&Apache::loncommon::start_data_table().
 7678:               &Apache::loncommon::start_data_table_row());
 7679:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7680:     for (my $i=0;$i<$max+1;$i++) {
 7681: 	$r->print("\n".'<td align="center">');
 7682: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7683: 	else { $r->print('&nbsp;'); }
 7684: 	$r->print('</td>');
 7685:     }
 7686:     $r->print(&Apache::loncommon::end_data_table_row().
 7687:               &Apache::loncommon::start_data_table_row());
 7688:     for (my $i=0;$i<$max;$i++) {
 7689: 	$r->print("\n".
 7690: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7691: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7692:     }
 7693:     my $nobub_checked = ' ';
 7694:     if ($error eq 'missingbubble') {
 7695:         $nobub_checked = ' checked = "checked" ';
 7696:     }
 7697:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7698: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7699:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7700:               $line.'" value="'.$questionnum.'" /></td>');
 7701:     $r->print(&Apache::loncommon::end_data_table_row().
 7702:               &Apache::loncommon::end_data_table());
 7703: }
 7704: 
 7705: =pod
 7706: 
 7707: =item num_matches
 7708: 
 7709:    Counts the number of characters that are the same between the two arguments.
 7710: 
 7711:  Arguments:
 7712:    $orig - CODE from the scanline
 7713:    $code - CODE to match against
 7714: 
 7715:  Returns:
 7716:    $count - integer count of the number of same characters between the
 7717:             two arguments
 7718: 
 7719: =cut
 7720: 
 7721: sub num_matches {
 7722:     my ($orig,$code) = @_;
 7723:     my @code=split(//,$code);
 7724:     my @orig=split(//,$orig);
 7725:     my $same=0;
 7726:     for (my $i=0;$i<scalar(@code);$i++) {
 7727: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7728:     }
 7729:     return $same;
 7730: }
 7731: 
 7732: =pod
 7733: 
 7734: =item scantron_get_closely_matching_CODEs
 7735: 
 7736:    Cycles through all CODEs and finds the set that has the greatest
 7737:    number of same characters as the provided CODE
 7738: 
 7739:  Arguments:
 7740:    $allcodes - hash ref returned by &get_codes()
 7741:    $CODE     - CODE from the current scanline
 7742: 
 7743:  Returns:
 7744:    2 element list
 7745:     - first elements is number of how closely matching the best fit is 
 7746:       (5 means best set has 5 matching characters)
 7747:     - second element is an arrary ref containing the set of valid CODEs
 7748:       that best fit the passed in CODE
 7749: 
 7750: =cut
 7751: 
 7752: sub scantron_get_closely_matching_CODEs {
 7753:     my ($allcodes,$CODE)=@_;
 7754:     my @CODEs;
 7755:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7756: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7757:     }
 7758: 
 7759:     return ($#CODEs,$CODEs[-1]);
 7760: }
 7761: 
 7762: =pod
 7763: 
 7764: =item get_codes
 7765: 
 7766:    Builds a hash which has keys of all of the valid CODEs from the selected
 7767:    set of remembered CODEs.
 7768: 
 7769:  Arguments:
 7770:   $old_name - name of the set of remembered CODEs
 7771:   $cdom     - domain of the course
 7772:   $cnum     - internal course name
 7773: 
 7774:  Returns:
 7775:   %allcodes - keys are the valid CODEs, values are all 1
 7776: 
 7777: =cut
 7778: 
 7779: sub get_codes {
 7780:     my ($old_name, $cdom, $cnum) = @_;
 7781:     if (!$old_name) {
 7782: 	$old_name=$env{'form.scantron_CODElist'};
 7783:     }
 7784:     if (!$cdom) {
 7785: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7786:     }
 7787:     if (!$cnum) {
 7788: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7789:     }
 7790:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7791: 				    $cdom,$cnum);
 7792:     my %allcodes;
 7793:     if ($result{"type\0$old_name"} eq 'number') {
 7794: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7795:     } else {
 7796: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7797:     }
 7798:     return %allcodes;
 7799: }
 7800: 
 7801: =pod
 7802: 
 7803: =item scantron_validate_CODE
 7804: 
 7805:    Validates all scanlines in the selected file to not have any
 7806:    invalid or underspecified CODEs and that none of the codes are
 7807:    duplicated if this was requested.
 7808: 
 7809: =cut
 7810: 
 7811: sub scantron_validate_CODE {
 7812:     my ($r,$currentphase) = @_;
 7813:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7814:     if ($scantron_config{'CODElocation'} &&
 7815: 	$scantron_config{'CODEstart'} &&
 7816: 	$scantron_config{'CODElength'}) {
 7817: 	if (!defined($env{'form.scantron_CODElist'})) {
 7818: 	    &FIXME_blow_up()
 7819: 	}
 7820:     } else {
 7821: 	return (0,$currentphase+1);
 7822:     }
 7823:     
 7824:     my %usedCODEs;
 7825: 
 7826:     my %allcodes=&get_codes();
 7827: 
 7828:     my $nav_error;
 7829:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7830:     if ($nav_error) {
 7831:         $r->print(&navmap_errormsg());
 7832:         return(1,$currentphase);
 7833:     }
 7834: 
 7835:     my ($scanlines,$scan_data)=&scantron_getfile();
 7836:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7837: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7838: 	if ($line=~/^[\s\cz]*$/) { next; }
 7839: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7840: 						 $scan_data);
 7841: 	my $CODE=$$scan_record{'scantron.CODE'};
 7842: 	my $error=0;
 7843: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7844: 	    &scantron_get_correction($r,$i,$scan_record,
 7845: 				     \%scantron_config,
 7846: 				     $line,'incorrectCODE',\%allcodes);
 7847: 	    return(1,$currentphase);
 7848: 	}
 7849: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7850: 	    && !$$scan_record{'scantron.useCODE'}) {
 7851: 	    &scantron_get_correction($r,$i,$scan_record,
 7852: 				     \%scantron_config,
 7853: 				     $line,'incorrectCODE',\%allcodes);
 7854: 	    return(1,$currentphase);
 7855: 	}
 7856: 	if (exists($usedCODEs{$CODE}) 
 7857: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7858: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7859: 	    &scantron_get_correction($r,$i,$scan_record,
 7860: 				     \%scantron_config,
 7861: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7862: 	    return(1,$currentphase);
 7863: 	}
 7864: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7865:     }
 7866:     return (0,$currentphase+1);
 7867: }
 7868: 
 7869: =pod
 7870: 
 7871: =item scantron_validate_doublebubble
 7872: 
 7873:    Validates all scanlines in the selected file to not have any
 7874:    bubble lines with multiple bubbles marked.
 7875: 
 7876: =cut
 7877: 
 7878: sub scantron_validate_doublebubble {
 7879:     my ($r,$currentphase) = @_;
 7880:     #get student info
 7881:     my $classlist=&Apache::loncoursedata::get_classlist();
 7882:     my %idmap=&username_to_idmap($classlist);
 7883:     my (undef,undef,$sequence)=
 7884:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7885: 
 7886:     #get scantron line setup
 7887:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7888:     my ($scanlines,$scan_data)=&scantron_getfile();
 7889: 
 7890:     my $navmap = Apache::lonnavmaps::navmap->new();
 7891:     unless (ref($navmap)) {
 7892:         $r->print(&navmap_errormsg());
 7893:         return(1,$currentphase);
 7894:     }
 7895:     my $map=$navmap->getResourceByUrl($sequence);
 7896:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7897:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 7898:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 7899:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7900: 
 7901:     my $nav_error;
 7902:     if (ref($map)) {
 7903:         $randomorder = $map->randomorder();
 7904:         $randompick = $map->randompick();
 7905:         if ($randomorder || $randompick) {
 7906:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 7907:             if ($nav_error) {
 7908:                 $r->print(&navmap_errormsg());
 7909:                 return(1,$currentphase);
 7910:             }
 7911:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7912:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 7913:         }
 7914:     } else {
 7915:         $r->print(&navmap_errormsg());
 7916:         return(1,$currentphase);
 7917:     }
 7918: 
 7919:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7920:     if ($nav_error) {
 7921:         $r->print(&navmap_errormsg());
 7922:         return(1,$currentphase);
 7923:     }
 7924: 
 7925:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7926: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7927: 	if ($line=~/^[\s\cz]*$/) { next; }
 7928: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7929: 						 $scan_data,undef,\%idmap,$randomorder,
 7930:                                                  $randompick,$sequence,\@master_seq,
 7931:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 7932:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 7933: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7934: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7935: 				 'doublebubble',
 7936: 				 $$scan_record{'scantron.doubleerror'},
 7937:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 7938:     	return (1,$currentphase);
 7939:     }
 7940:     return (0,$currentphase+1);
 7941: }
 7942: 
 7943: 
 7944: sub scantron_get_maxbubble {
 7945:     my ($nav_error,$scantron_config) = @_;
 7946:     if (defined($env{'form.scantron_maxbubble'}) &&
 7947: 	$env{'form.scantron_maxbubble'}) {
 7948: 	&restore_bubble_lines();
 7949: 	return $env{'form.scantron_maxbubble'};
 7950:     }
 7951: 
 7952:     my (undef, undef, $sequence) =
 7953: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7954: 
 7955:     my $navmap=Apache::lonnavmaps::navmap->new();
 7956:     unless (ref($navmap)) {
 7957:         if (ref($nav_error)) {
 7958:             $$nav_error = 1;
 7959:         }
 7960:         return;
 7961:     }
 7962:     my $map=$navmap->getResourceByUrl($sequence);
 7963:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7964:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7965: 
 7966:     &Apache::lonxml::clear_problem_counter();
 7967: 
 7968:     my $uname       = $env{'user.name'};
 7969:     my $udom        = $env{'user.domain'};
 7970:     my $cid         = $env{'request.course.id'};
 7971:     my $total_lines = 0;
 7972:     %bubble_lines_per_response = ();
 7973:     %first_bubble_line         = ();
 7974:     %subdivided_bubble_lines   = ();
 7975:     %responsetype_per_response = ();
 7976:     %masterseq_id_responsenum  = ();
 7977: 
 7978:     my $response_number = 0;
 7979:     my $bubble_line     = 0;
 7980:     foreach my $resource (@resources) {
 7981:         my $resid = $resource->id(); 
 7982:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 7983:                                                           $udom,undef,$bubbles_per_row);
 7984:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7985: 	    foreach my $part_id (@{$parts}) {
 7986:                 my $lines;
 7987: 
 7988: 	        # TODO - make this a persistent hash not an array.
 7989: 
 7990:                 # optionresponse, matchresponse and rankresponse type items 
 7991:                 # render as separate sub-questions in exam mode.
 7992:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7993:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7994:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7995:                     my ($numbub,$numshown);
 7996:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7997:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7998:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7999:                         }
 8000:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8001:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8002:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8003:                         }
 8004:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8005:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8006:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8007:                         }
 8008:                     }
 8009:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8010:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8011:                     }
 8012:                     my $bubbles_per_row =
 8013:                         &bubblesheet_bubbles_per_row($scantron_config);
 8014:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8015:                     if (($numbub % $bubbles_per_row) != 0) {
 8016:                         $inner_bubble_lines++;
 8017:                     }
 8018:                     for (my $i=0; $i<$numshown; $i++) {
 8019:                         $subdivided_bubble_lines{$response_number} .= 
 8020:                             $inner_bubble_lines.',';
 8021:                     }
 8022:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8023:                     $lines = $numshown * $inner_bubble_lines;
 8024:                 } else {
 8025:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8026:                 }
 8027: 
 8028:                 $first_bubble_line{$response_number} = $bubble_line;
 8029: 	        $bubble_lines_per_response{$response_number} = $lines;
 8030:                 $responsetype_per_response{$response_number} = 
 8031:                     $analysis->{$part_id.'.type'};
 8032:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8033: 	        $response_number++;
 8034: 
 8035: 	        $bubble_line +=  $lines;
 8036: 	        $total_lines +=  $lines;
 8037: 	    }
 8038:         }
 8039:     }
 8040:     &Apache::lonnet::delenv('scantron.');
 8041: 
 8042:     &save_bubble_lines();
 8043:     $env{'form.scantron_maxbubble'} =
 8044: 	$total_lines;
 8045:     return $env{'form.scantron_maxbubble'};
 8046: }
 8047: 
 8048: sub bubblesheet_bubbles_per_row {
 8049:     my ($scantron_config) = @_;
 8050:     my $bubbles_per_row;
 8051:     if (ref($scantron_config) eq 'HASH') {
 8052:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8053:     }
 8054:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8055:         $bubbles_per_row = 10;
 8056:     }
 8057:     return $bubbles_per_row;
 8058: }
 8059: 
 8060: sub scantron_validate_missingbubbles {
 8061:     my ($r,$currentphase) = @_;
 8062:     #get student info
 8063:     my $classlist=&Apache::loncoursedata::get_classlist();
 8064:     my %idmap=&username_to_idmap($classlist);
 8065:     my (undef,undef,$sequence)=
 8066:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8067: 
 8068:     #get scantron line setup
 8069:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8070:     my ($scanlines,$scan_data)=&scantron_getfile();
 8071: 
 8072:     my $navmap = Apache::lonnavmaps::navmap->new();
 8073:     unless (ref($navmap)) {
 8074:         $r->print(&navmap_errormsg());
 8075:         return(1,$currentphase);
 8076:     }
 8077: 
 8078:     my $map=$navmap->getResourceByUrl($sequence);
 8079:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8080:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8081:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8082:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8083: 
 8084:     my $nav_error;
 8085:     if (ref($map)) {
 8086:         $randomorder = $map->randomorder();
 8087:         $randompick = $map->randompick();
 8088:         if ($randomorder || $randompick) {
 8089:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8090:             if ($nav_error) {
 8091:                 $r->print(&navmap_errormsg());
 8092:                 return(1,$currentphase);
 8093:             }
 8094:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8095:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8096:         }
 8097:     } else {
 8098:         $r->print(&navmap_errormsg());
 8099:         return(1,$currentphase);
 8100:     }
 8101: 
 8102: 
 8103:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8104:     if ($nav_error) {
 8105:         $r->print(&navmap_errormsg());
 8106:         return(1,$currentphase);
 8107:     }
 8108: 
 8109:     if (!$max_bubble) { $max_bubble=2**31; }
 8110:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8111: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8112: 	if ($line=~/^[\s\cz]*$/) { next; }
 8113: 	my $scan_record =
 8114:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8115: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8116:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8117:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8118: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8119: 	my @to_correct;
 8120: 	
 8121: 	# Probably here's where the error is...
 8122: 
 8123: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8124:             my $lastbubble;
 8125:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8126:                my $question = $1;
 8127:                my $subquestion = $2;
 8128:                my ($first,$responsenum);
 8129:                if ($randomorder || $randompick) {
 8130:                    $responsenum = $respnumlookup{$question-1};
 8131:                    $first = $startline{$question-1};
 8132:                } else {
 8133:                    $responsenum = $question-1; 
 8134:                    $first = $first_bubble_line{$responsenum};
 8135:                }
 8136:                if (!defined($first)) { next; }
 8137:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8138:                my $subcount = 1;
 8139:                while ($subcount<$subquestion) {
 8140:                    $first += $subans[$subcount-1];
 8141:                    $subcount ++;
 8142:                }
 8143:                my $count = $subans[$subquestion-1];
 8144:                $lastbubble = $first + $count;
 8145:             } else {
 8146:                my ($first,$responsenum);
 8147:                if ($randomorder || $randompick) {
 8148:                    $responsenum = $respnumlookup{$missing-1};
 8149:                    $first = $startline{$missing-1};
 8150:                } else {
 8151:                    $responsenum = $missing-1;
 8152:                    $first = $first_bubble_line{$responsenum};
 8153:                }
 8154:                if (!defined($first)) { next; }
 8155:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8156:             }
 8157:             if ($lastbubble > $max_bubble) { next; }
 8158: 	    push(@to_correct,$missing);
 8159: 	}
 8160: 	if (@to_correct) {
 8161: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8162: 				     $line,'missingbubble',\@to_correct,
 8163:                                      $randomorder,$randompick,\%respnumlookup,
 8164:                                      \%startline);
 8165: 	    return (1,$currentphase);
 8166: 	}
 8167: 
 8168:     }
 8169:     return (0,$currentphase+1);
 8170: }
 8171: 
 8172: sub hand_bubble_option {
 8173:     my (undef, undef, $sequence) =
 8174:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8175:     return if ($sequence eq '');
 8176:     my $navmap = Apache::lonnavmaps::navmap->new();
 8177:     unless (ref($navmap)) {
 8178:         return;
 8179:     }
 8180:     my $needs_hand_bubbles;
 8181:     my $map=$navmap->getResourceByUrl($sequence);
 8182:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8183:     foreach my $res (@resources) {
 8184:         if (ref($res)) {
 8185:             if ($res->is_problem()) {
 8186:                 my $partlist = $res->parts();
 8187:                 foreach my $part (@{ $partlist }) {
 8188:                     my @types = $res->responseType($part);
 8189:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8190:                         $needs_hand_bubbles = 1;
 8191:                         last;
 8192:                     }
 8193:                 }
 8194:             }
 8195:         }
 8196:     }
 8197:     if ($needs_hand_bubbles) {
 8198:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8199:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8200:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8201:                &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 />').
 8202:                '<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;'.
 8203:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 8204:     }
 8205:     return;
 8206: }
 8207: 
 8208: sub scantron_process_students {
 8209:     my ($r,$symb) = @_;
 8210: 
 8211:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8212:     if (!$symb) {
 8213: 	return '';
 8214:     }
 8215:     my $default_form_data=&defaultFormData($symb);
 8216: 
 8217:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8218:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8219:     my ($scanlines,$scan_data)=&scantron_getfile();
 8220:     my $classlist=&Apache::loncoursedata::get_classlist();
 8221:     my %idmap=&username_to_idmap($classlist);
 8222:     my $navmap=Apache::lonnavmaps::navmap->new();
 8223:     unless (ref($navmap)) {
 8224:         $r->print(&navmap_errormsg());
 8225:         return '';
 8226:     }
 8227:     my $map=$navmap->getResourceByUrl($sequence);
 8228:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8229:         %grader_randomlists_by_symb);
 8230:     if (ref($map)) {
 8231:         $randomorder = $map->randomorder();
 8232:         $randompick = $map->randompick();
 8233:     } else {
 8234:         $r->print(&navmap_errormsg());
 8235:         return '';
 8236:     }
 8237:     my $nav_error;
 8238:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8239:     if ($randomorder || $randompick) {
 8240:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8241:         if ($nav_error) {
 8242:             $r->print(&navmap_errormsg());
 8243:             return '';
 8244:         }
 8245:     }
 8246:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8247:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8248: 
 8249:     my ($uname,$udom);
 8250:     my $result= <<SCANTRONFORM;
 8251: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8252:   <input type="hidden" name="command" value="scantron_configphase" />
 8253:   $default_form_data
 8254: SCANTRONFORM
 8255:     $r->print($result);
 8256: 
 8257:     my @delayqueue;
 8258:     my (%completedstudents,%scandata);
 8259:     
 8260:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8261:     my $count=&get_todo_count($scanlines,$scan_data);
 8262:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8263:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8264:     $r->print('<br />');
 8265:     my $start=&Time::HiRes::time();
 8266:     my $i=-1;
 8267:     my $started;
 8268: 
 8269:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8270:     if ($nav_error) {
 8271:         $r->print(&navmap_errormsg());
 8272:         return '';
 8273:     }
 8274: 
 8275:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8276:     # the user and return.
 8277: 
 8278:     if ($ssi_error) {
 8279: 	$r->print("</form>");
 8280: 	&ssi_print_error($r);
 8281:         &Apache::lonnet::remove_lock($lock);
 8282: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8283:     }
 8284: 
 8285:     my %lettdig = &letter_to_digits();
 8286:     my $numletts = scalar(keys(%lettdig));
 8287:     my %orderedforcode;
 8288: 
 8289:     while ($i<$scanlines->{'count'}) {
 8290:  	($uname,$udom)=('','');
 8291:  	$i++;
 8292:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8293:  	if ($line=~/^[\s\cz]*$/) { next; }
 8294: 	if ($started) {
 8295: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8296: 	}
 8297: 	$started=1;
 8298:         my %respnumlookup = ();
 8299:         my %startline = ();
 8300:         my $total;
 8301:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8302:                                                  $scan_data,undef,\%idmap,$randomorder,
 8303:                                                  $randompick,$sequence,\@master_seq,
 8304:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8305:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8306:                                                  \$total);
 8307:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8308:  					      \%idmap,$i)) {
 8309:   	    &scantron_add_delay(\@delayqueue,$line,
 8310:  				'Unable to find a student that matches',1);
 8311:  	    next;
 8312:   	}
 8313:  	if (exists $completedstudents{$uname}) {
 8314:  	    &scantron_add_delay(\@delayqueue,$line,
 8315:  				'Student '.$uname.' has multiple sheets',2);
 8316:  	    next;
 8317:  	}
 8318:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8319:         my $user = $uname.':'.$usec;
 8320:   	($uname,$udom)=split(/:/,$uname);
 8321: 
 8322:         my $scancode;
 8323:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8324:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8325:             $scancode = $scan_record->{'scantron.CODE'};
 8326:         } else {
 8327:             $scancode = '';
 8328:         }
 8329: 
 8330:         my @mapresources = @resources;
 8331:         if ($randomorder || $randompick) {
 8332:             @mapresources = 
 8333:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8334:                              \%orderedforcode);
 8335:         }
 8336:         my (%partids_by_symb,$res_error);
 8337:         foreach my $resource (@mapresources) {
 8338:             my $ressymb;
 8339:             if (ref($resource)) {
 8340:                 $ressymb = $resource->symb();
 8341:             } else {
 8342:                 $res_error = 1;
 8343:                 last;
 8344:             }
 8345:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8346:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8347:                 my ($analysis,$parts) =
 8348:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8349:                                               $uname,$udom,undef,$bubbles_per_row);
 8350:                 $partids_by_symb{$ressymb} = $parts;
 8351:             } else {
 8352:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8353:             }
 8354:         }
 8355: 
 8356:         if ($res_error) {
 8357:             &scantron_add_delay(\@delayqueue,$line,
 8358:                                 'An error occurred while grading student '.$uname,2);
 8359:             next;
 8360:         }
 8361: 
 8362: 	&Apache::lonxml::clear_problem_counter();
 8363:   	&Apache::lonnet::appenv($scan_record);
 8364: 
 8365: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8366: 	    &scantron_putfile($scanlines,$scan_data);
 8367: 	}
 8368: 	
 8369:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8370:                                    \@mapresources,\%partids_by_symb,
 8371:                                    $bubbles_per_row,$randomorder,$randompick,
 8372:                                    \%respnumlookup,\%startline) 
 8373:             eq 'ssi_error') {
 8374:             $ssi_error = 0; # So end of handler error message does not trigger.
 8375:             $r->print("</form>");
 8376:             &ssi_print_error($r);
 8377:             &Apache::lonnet::remove_lock($lock);
 8378:             return '';      # Why return ''?  Beats me.
 8379:         }
 8380: 
 8381:         if (($scancode) && ($randomorder || $randompick)) {
 8382:             my $parmresult =
 8383:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8384:                                                        '0_examcode',2,$scancode,
 8385:                                                        'string_examcode',$uname,
 8386:                                                        $udom);
 8387:         }
 8388: 	$completedstudents{$uname}={'line'=>$line};
 8389:         if ($env{'form.verifyrecord'}) {
 8390:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8391:             if ($randompick) {
 8392:                 if ($total) {
 8393:                     $lastpos = $total*$scantron_config{'Qlength'};
 8394:                 }
 8395:             }
 8396: 
 8397:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8398:             chomp($studentdata);
 8399:             $studentdata =~ s/\r$//;
 8400:             my $studentrecord = '';
 8401:             my $counter = -1;
 8402:             foreach my $resource (@mapresources) {
 8403:                 my $ressymb = $resource->symb();
 8404:                 ($counter,my $recording) =
 8405:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8406:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8407:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8408:                                              $randompick,\%respnumlookup,\%startline);
 8409:                 $studentrecord .= $recording;
 8410:             }
 8411:             if ($studentrecord ne $studentdata) {
 8412:                 &Apache::lonxml::clear_problem_counter();
 8413:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8414:                                            \@mapresources,\%partids_by_symb,
 8415:                                            $bubbles_per_row,$randomorder,$randompick,
 8416:                                            \%respnumlookup,\%startline) 
 8417:                     eq 'ssi_error') {
 8418:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8419:                     $r->print("</form>");
 8420:                     &ssi_print_error($r);
 8421:                     &Apache::lonnet::remove_lock($lock);
 8422:                     delete($completedstudents{$uname});
 8423:                     return '';
 8424:                 }
 8425:                 $counter = -1;
 8426:                 $studentrecord = '';
 8427:                 foreach my $resource (@mapresources) {
 8428:                     my $ressymb = $resource->symb();
 8429:                     ($counter,my $recording) =
 8430:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8431:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8432:                                                  \%scantron_config,\%lettdig,$numletts,
 8433:                                                  $randomorder,$randompick,\%respnumlookup,
 8434:                                                  \%startline);
 8435:                     $studentrecord .= $recording;
 8436:                 }
 8437:                 if ($studentrecord ne $studentdata) {
 8438:                     $r->print('<p><span class="LC_warning">');
 8439:                     if ($scancode eq '') {
 8440:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8441:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8442:                     } else {
 8443:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8444:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8445:                     }
 8446:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8447:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8448:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8449:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8450:                               &Apache::loncommon::start_data_table_row().
 8451:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8452:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8453:                               &Apache::loncommon::end_data_table_row().
 8454:                               &Apache::loncommon::start_data_table_row().
 8455:                               '<td>'.&mt('Stored submissions').'</td>'.
 8456:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8457:                               &Apache::loncommon::end_data_table_row().
 8458:                               &Apache::loncommon::end_data_table().'</p>');
 8459:                 } else {
 8460:                     $r->print('<br /><span class="LC_warning">'.
 8461:                              &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 />'.
 8462:                              &mt("As a consequence, this user's submission history records two tries.").
 8463:                                  '</span><br />');
 8464:                 }
 8465:             }
 8466:         }
 8467:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8468:     } continue {
 8469: 	&Apache::lonxml::clear_problem_counter();
 8470: 	&Apache::lonnet::delenv('scantron.');
 8471:     }
 8472:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8473:     &Apache::lonnet::remove_lock($lock);
 8474: #    my $lasttime = &Time::HiRes::time()-$start;
 8475: #    $r->print("<p>took $lasttime</p>");
 8476: 
 8477:     $r->print("</form>");
 8478:     return '';
 8479: }
 8480: 
 8481: sub graders_resources_pass {
 8482:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8483:         $bubbles_per_row) = @_;
 8484:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8485:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8486:         foreach my $resource (@{$resources}) {
 8487:             my $ressymb = $resource->symb();
 8488:             my ($analysis,$parts) =
 8489:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8490:                                           $env{'user.name'},$env{'user.domain'},
 8491:                                           1,$bubbles_per_row);
 8492:             $grader_partids_by_symb->{$ressymb} = $parts;
 8493:             if (ref($analysis) eq 'HASH') {
 8494:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8495:                     $grader_randomlists_by_symb->{$ressymb} =
 8496:                         $analysis->{'parts_withrandomlist'};
 8497:                 }
 8498:             }
 8499:         }
 8500:     }
 8501:     return;
 8502: }
 8503: 
 8504: =pod
 8505: 
 8506: =item users_order
 8507: 
 8508:   Returns array of resources in current map, ordered based on either CODE,
 8509:   if this is a CODEd exam, or based on student's identity if this is a 
 8510:   "NAMEd" exam.
 8511: 
 8512:   Should be used when randomorder and/or randompick applied when the 
 8513:   corresponding exam was printed, prior to students completing bubblesheets 
 8514:   for the version of the exam the student received.
 8515: 
 8516: =cut
 8517: 
 8518: sub users_order  {
 8519:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8520:     my @mapresources;
 8521:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8522:         return @mapresources;
 8523:     }
 8524:     if ($scancode) {
 8525:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8526:             @mapresources = @{$orderedforcode->{$scancode}};
 8527:         } else {
 8528:             $env{'form.CODE'} = $scancode;
 8529:             my $actual_seq =
 8530:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8531:                                                                $master_seq,
 8532:                                                                $user,$scancode,1);
 8533:             if (ref($actual_seq) eq 'ARRAY') {
 8534:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8535:                 if (ref($orderedforcode) eq 'HASH') {
 8536:                     if (@mapresources > 0) { 
 8537:                         $orderedforcode->{$scancode} = \@mapresources;
 8538:                     }
 8539:                 }
 8540:             }
 8541:             delete($env{'form.CODE'});
 8542:         }
 8543:     } else {
 8544:         my $actual_seq =
 8545:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8546:                                                            $master_seq,
 8547:                                                            $user,undef,1);
 8548:         if (ref($actual_seq) eq 'ARRAY') {
 8549:             @mapresources = 
 8550:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8551:         }
 8552:     }
 8553:     return @mapresources;
 8554: }
 8555: 
 8556: sub grade_student_bubbles {
 8557:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8558:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8559:     my $uselookup = 0;
 8560:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8561:         (ref($startline) eq 'HASH')) {
 8562:         $uselookup = 1;
 8563:     }
 8564: 
 8565:     if (ref($resources) eq 'ARRAY') {
 8566:         my $count = 0;
 8567:         foreach my $resource (@{$resources}) {
 8568:             my $ressymb = $resource->symb();
 8569:             my %form = ('submitted'      => 'scantron',
 8570:                         'grade_target'   => 'grade',
 8571:                         'grade_username' => $uname,
 8572:                         'grade_domain'   => $udom,
 8573:                         'grade_courseid' => $env{'request.course.id'},
 8574:                         'grade_symb'     => $ressymb,
 8575:                         'CODE'           => $scancode
 8576:                        );
 8577:             if ($bubbles_per_row ne '') {
 8578:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8579:             }
 8580:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8581:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8582:             }
 8583:             if (ref($parts) eq 'HASH') {
 8584:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8585:                     foreach my $part (@{$parts->{$ressymb}}) {
 8586:                         if ($uselookup) {
 8587:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8588:                         } else {
 8589:                             $form{'scantron_questnum_start.'.$part} =
 8590:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8591:                         }
 8592:                         $count++;
 8593:                     }
 8594:                 }
 8595:             }
 8596:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8597:             return 'ssi_error' if ($ssi_error);
 8598:             last if (&Apache::loncommon::connection_aborted($r));
 8599:         }
 8600:     }
 8601:     return;
 8602: }
 8603: 
 8604: sub scantron_upload_scantron_data {
 8605:     my ($r,$symb)=@_;
 8606:     my $dom = $env{'request.role.domain'};
 8607:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8608:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8609:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8610: 							  'domainid',
 8611: 							  'coursename',$dom);
 8612:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8613:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8614:     my $default_form_data=&defaultFormData($symb);
 8615:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8616:     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.");
 8617:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8618:     function checkUpload(formname) {
 8619: 	if (formname.upfile.value == "") {
 8620: 	    alert("'.$nofile_alert.'");
 8621: 	    return false;
 8622: 	}
 8623:         if (formname.courseid.value == "") {
 8624:             alert("'.$nocourseid_alert.'");
 8625:             return false;
 8626:         }
 8627: 	formname.submit();
 8628:     }
 8629: 
 8630:     function ToSyllabus() {
 8631:         var cdom = '."'$dom'".';
 8632:         var cnum = document.rules.courseid.value;
 8633:         if (cdom == "" || cdom == null) {
 8634:             return;
 8635:         }
 8636:         if (cnum == "" || cnum == null) {
 8637:            return;
 8638:         }
 8639:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8640:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8641:         return;
 8642:     }
 8643: 
 8644: '));
 8645:     $r->print('
 8646: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8647: 
 8648: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8649: '.$default_form_data.
 8650:   &Apache::lonhtmlcommon::start_pick_box().
 8651:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8652:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8653:   &Apache::lonhtmlcommon::row_closure().
 8654:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8655:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8656:   &Apache::lonhtmlcommon::row_closure().
 8657:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8658:   '<input name="domainid" type="hidden" />'.$domdesc.
 8659:   &Apache::lonhtmlcommon::row_closure().
 8660:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8661:   '<input type="file" name="upfile" size="50" />'.
 8662:   &Apache::lonhtmlcommon::row_closure(1).
 8663:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8664: 
 8665: <input name="command" value="scantronupload_save" type="hidden" />
 8666: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8667: </form>
 8668: ');
 8669:     return '';
 8670: }
 8671: 
 8672: 
 8673: sub scantron_upload_scantron_data_save {
 8674:     my($r,$symb)=@_;
 8675:     my $doanotherupload=
 8676: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8677: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8678: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8679: 	'</form>'."\n";
 8680:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8681: 	!&Apache::lonnet::allowed('usc',
 8682: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8683: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8684: 	unless ($symb) {
 8685: 	    $r->print($doanotherupload);
 8686: 	}
 8687: 	return '';
 8688:     }
 8689:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8690:     my $uploadedfile;
 8691:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8692:     if (length($env{'form.upfile'}) < 2) {
 8693:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8694:     } else {
 8695:         my $result = 
 8696:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8697:                                             $env{'form.courseid'},$env{'form.domainid'});
 8698: 	if ($result =~ m{^/uploaded/}) {
 8699: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8700:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8701: 			  '<span class="LC_filename">'.$result.'</span>'));
 8702:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8703:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8704:                                                        $env{'form.courseid'},$uploadedfile));
 8705: 	} else {
 8706: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8707:                           '<span class="LC_error">','</span>',$result,
 8708: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8709: 	}
 8710:     }
 8711:     if ($symb) {
 8712: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8713:     } else {
 8714: 	$r->print($doanotherupload);
 8715:     }
 8716:     return '';
 8717: }
 8718: 
 8719: sub validate_uploaded_scantron_file {
 8720:     my ($cdom,$cname,$fname) = @_;
 8721:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8722:     my @lines;
 8723:     if ($scanlines ne '-1') {
 8724:         @lines=split("\n",$scanlines,-1);
 8725:     }
 8726:     my $output;
 8727:     if (@lines) {
 8728:         my (%counts,$max_match_format);
 8729:         my ($max_match_count,$max_match_pct) = (0,0);
 8730:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8731:         my %idmap = &username_to_idmap($classlist);
 8732:         foreach my $key (keys(%idmap)) {
 8733:             my $lckey = lc($key);
 8734:             $idmap{$lckey} = $idmap{$key};
 8735:         }
 8736:         my %unique_formats;
 8737:         my @formatlines = &get_scantronformat_file();
 8738:         foreach my $line (@formatlines) {
 8739:             chomp($line);
 8740:             my @config = split(/:/,$line);
 8741:             my $idstart = $config[5];
 8742:             my $idlength = $config[6];
 8743:             if (($idstart ne '') && ($idlength > 0)) {
 8744:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8745:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8746:                 } else {
 8747:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8748:                 }
 8749:             }
 8750:         }
 8751:         foreach my $key (keys(%unique_formats)) {
 8752:             my ($idstart,$idlength) = split(':',$key);
 8753:             %{$counts{$key}} = (
 8754:                                'found'   => 0,
 8755:                                'total'   => 0,
 8756:                               );
 8757:             foreach my $line (@lines) {
 8758:                 next if ($line =~ /^#/);
 8759:                 next if ($line =~ /^[\s\cz]*$/);
 8760:                 my $id = substr($line,$idstart-1,$idlength);
 8761:                 $id = lc($id);
 8762:                 if (exists($idmap{$id})) {
 8763:                     $counts{$key}{'found'} ++;
 8764:                 }
 8765:                 $counts{$key}{'total'} ++;
 8766:             }
 8767:             if ($counts{$key}{'total'}) {
 8768:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8769:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8770:                     $max_match_pct = $percent_match;
 8771:                     $max_match_format = $key;
 8772:                     $max_match_count = $counts{$key}{'total'};
 8773:                 }
 8774:             }
 8775:         }
 8776:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8777:             my $format_descs;
 8778:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8779:             for (my $i=0; $i<$numwithformat; $i++) {
 8780:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8781:                 if ($i<$numwithformat-2) {
 8782:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8783:                 } elsif ($i==$numwithformat-2) {
 8784:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8785:                 } elsif ($i==$numwithformat-1) {
 8786:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8787:                 }
 8788:             }
 8789:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8790:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8791:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8792:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8793:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8794:                                   '<i>'.$cdom.'</i>').'</li>'.
 8795:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8796:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8797:                        '</ul>';
 8798:         }
 8799:     } else {
 8800:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8801:     }
 8802:     return $output;
 8803: }
 8804: 
 8805: sub valid_file {
 8806:     my ($requested_file)=@_;
 8807:     foreach my $filename (sort(&scantron_filenames())) {
 8808: 	if ($requested_file eq $filename) { return 1; }
 8809:     }
 8810:     return 0;
 8811: }
 8812: 
 8813: sub scantron_download_scantron_data {
 8814:     my ($r,$symb)=@_;
 8815:     my $default_form_data=&defaultFormData($symb);
 8816:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8817:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8818:     my $file=$env{'form.scantron_selectfile'};
 8819:     if (! &valid_file($file)) {
 8820: 	$r->print('
 8821: 	<p>
 8822: 	    '.&mt('The requested filename was invalid.').'
 8823:         </p>
 8824: ');
 8825: 	return;
 8826:     }
 8827:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8828:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8829:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8830:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8831:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8832:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8833:     $r->print('
 8834:     <p>
 8835: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8836: 	      '<a href="'.$orig.'">','</a>').'
 8837:     </p>
 8838:     <p>
 8839: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8840: 	      '<a href="'.$corrected.'">','</a>').'
 8841:     </p>
 8842:     <p>
 8843: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8844: 	      '<a href="'.$skipped.'">','</a>').'
 8845:     </p>
 8846: ');
 8847:     return '';
 8848: }
 8849: 
 8850: sub checkscantron_results {
 8851:     my ($r,$symb) = @_;
 8852:     if (!$symb) {return '';}
 8853:     my $cid = $env{'request.course.id'};
 8854:     my %lettdig = &letter_to_digits();
 8855:     my $numletts = scalar(keys(%lettdig));
 8856:     my $cnum = $env{'course.'.$cid.'.num'};
 8857:     my $cdom = $env{'course.'.$cid.'.domain'};
 8858:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8859:     my %record;
 8860:     my %scantron_config =
 8861:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8862:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8863:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8864:     my $classlist=&Apache::loncoursedata::get_classlist();
 8865:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8866:     my $navmap=Apache::lonnavmaps::navmap->new();
 8867:     unless (ref($navmap)) {
 8868:         $r->print(&navmap_errormsg());
 8869:         return '';
 8870:     }
 8871:     my $map=$navmap->getResourceByUrl($sequence);
 8872:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8873:         %grader_randomlists_by_symb,%orderedforcode);
 8874:     if (ref($map)) { 
 8875:         $randomorder=$map->randomorder();
 8876:         $randompick=$map->randompick();
 8877:     }
 8878:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8879:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8880:     if ($nav_error) {
 8881:         $r->print(&navmap_errormsg());
 8882:         return '';
 8883:     }
 8884:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8885:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8886:     my ($uname,$udom);
 8887:     my (%scandata,%lastname,%bylast);
 8888:     $r->print('
 8889: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8890: 
 8891:     my @delayqueue;
 8892:     my %completedstudents;
 8893: 
 8894:     my $count=&get_todo_count($scanlines,$scan_data);
 8895:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8896:     my ($username,$domain,$started);
 8897:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8898:     if ($nav_error) {
 8899:         $r->print(&navmap_errormsg());
 8900:         return '';
 8901:     }
 8902: 
 8903:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8904:     my $start=&Time::HiRes::time();
 8905:     my $i=-1;
 8906: 
 8907:     while ($i<$scanlines->{'count'}) {
 8908:         ($username,$domain,$uname)=('','','');
 8909:         $i++;
 8910:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8911:         if ($line=~/^[\s\cz]*$/) { next; }
 8912:         if ($started) {
 8913:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8914:         }
 8915:         $started=1;
 8916:         my $scan_record=
 8917:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8918:                                                      $scan_data);
 8919:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8920:                                               \%idmap,$i)) {
 8921:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8922:                                 'Unable to find a student that matches',1);
 8923:             next;
 8924:         }
 8925:         if (exists $completedstudents{$uname}) {
 8926:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8927:                                 'Student '.$uname.' has multiple sheets',2);
 8928:             next;
 8929:         }
 8930:         my $pid = $scan_record->{'scantron.ID'};
 8931:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8932:         push(@{$bylast{$lastname{$pid}}},$pid);
 8933:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8934:         my $user = $uname.':'.$usec;
 8935:         ($username,$domain)=split(/:/,$uname);
 8936: 
 8937:         my $scancode;
 8938:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8939:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8940:             $scancode = $scan_record->{'scantron.CODE'};
 8941:         } else {
 8942:             $scancode = '';
 8943:         }
 8944: 
 8945:         my @mapresources = @resources;
 8946:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8947:         my %respnumlookup=();
 8948:         my %startline=();
 8949:         if ($randomorder || $randompick) {
 8950:             @mapresources =
 8951:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8952:                              \%orderedforcode);
 8953:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 8954:                                              $scan_record,\@master_seq,\%symb_to_resource,
 8955:                                              \%grader_partids_by_symb,\%orderedforcode,
 8956:                                              \%respnumlookup,\%startline);
 8957:             if ($randompick && $total) {
 8958:                 $lastpos = $total*$scantron_config{'Qlength'};
 8959:             }
 8960:         }
 8961:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8962:         chomp($scandata{$pid});
 8963:         $scandata{$pid} =~ s/\r$//;
 8964: 
 8965:         my $counter = -1;
 8966:         foreach my $resource (@mapresources) {
 8967:             my $parts;
 8968:             my $ressymb = $resource->symb();
 8969:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8970:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8971:                 (my $analysis,$parts) =
 8972:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8973:                                               $username,$domain,undef,
 8974:                                               $bubbles_per_row);
 8975:             } else {
 8976:                 $parts = $grader_partids_by_symb{$ressymb};
 8977:             }
 8978:             ($counter,my $recording) =
 8979:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8980:                                          $scandata{$pid},$parts,
 8981:                                          \%scantron_config,\%lettdig,$numletts,
 8982:                                          $randomorder,$randompick,
 8983:                                          \%respnumlookup,\%startline);
 8984:             $record{$pid} .= $recording;
 8985:         }
 8986:     }
 8987:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8988:     $r->print('<br />');
 8989:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8990:     $passed = 0;
 8991:     $failed = 0;
 8992:     $numstudents = 0;
 8993:     foreach my $last (sort(keys(%bylast))) {
 8994:         if (ref($bylast{$last}) eq 'ARRAY') {
 8995:             foreach my $pid (sort(@{$bylast{$last}})) {
 8996:                 my $showscandata = $scandata{$pid};
 8997:                 my $showrecord = $record{$pid};
 8998:                 $showscandata =~ s/\s/&nbsp;/g;
 8999:                 $showrecord =~ s/\s/&nbsp;/g;
 9000:                 if ($scandata{$pid} eq $record{$pid}) {
 9001:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9002:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9003: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9004: '</tr>'."\n".
 9005: '<tr class="'.$css_class.'">'."\n".
 9006: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 9007:                     $passed ++;
 9008:                 } else {
 9009:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9010:                     $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".
 9011: '</tr>'."\n".
 9012: '<tr class="'.$css_class.'">'."\n".
 9013: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9014: '</tr>'."\n";
 9015:                     $failed ++;
 9016:                 }
 9017:                 $numstudents ++;
 9018:             }
 9019:         }
 9020:     }
 9021:     $r->print(
 9022:         '<p>'
 9023:        .&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).',
 9024:             '<b>',
 9025:             $numstudents,
 9026:             '</b>',
 9027:             $env{'form.scantron_maxbubble'})
 9028:        .'</p>'
 9029:     );
 9030:     $r->print('<p>'
 9031:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9032:              .'<br />'
 9033:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9034:              .'</p>'
 9035:     );
 9036:     if ($passed) {
 9037:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9038:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9039:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9040:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9041:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9042:                  $okstudents."\n".
 9043:                  &Apache::loncommon::end_data_table().'<br />');
 9044:     }
 9045:     if ($failed) {
 9046:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9047:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9048:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9049:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9050:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9051:                  $badstudents."\n".
 9052:                  &Apache::loncommon::end_data_table()).'<br />'.
 9053:                  &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.');  
 9054:     }
 9055:     $r->print('</form><br />');
 9056:     return;
 9057: }
 9058: 
 9059: sub verify_scantron_grading {
 9060:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9061:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9062:         $respnumlookup,$startline) = @_;
 9063:     my ($record,%expected,%startpos);
 9064:     return ($counter,$record) if (!ref($resource));
 9065:     return ($counter,$record) if (!$resource->is_problem());
 9066:     my $symb = $resource->symb();
 9067:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9068:     foreach my $part_id (@{$partids}) {
 9069:         $counter ++;
 9070:         $expected{$part_id} = 0;
 9071:         my $respnum = $counter;
 9072:         if ($randomorder || $randompick) {
 9073:             $respnum = $respnumlookup->{$counter};
 9074:             $startpos{$part_id} = $startline->{$counter} + 1;
 9075:         } else {
 9076:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9077:         }
 9078:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9079:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9080:             foreach my $item (@sub_lines) {
 9081:                 $expected{$part_id} += $item;
 9082:             }
 9083:         } else {
 9084:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9085:         }
 9086:     }
 9087:     if ($symb) {
 9088:         my %recorded;
 9089:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9090:         if ($returnhash{'version'}) {
 9091:             my %lasthash=();
 9092:             my $version;
 9093:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9094:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9095:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9096:                 }
 9097:             }
 9098:             foreach my $key (keys(%lasthash)) {
 9099:                 if ($key =~ /\.scantron$/) {
 9100:                     my $value = &unescape($lasthash{$key});
 9101:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9102:                     if ($value eq '') {
 9103:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9104:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9105:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9106:                             }
 9107:                         }
 9108:                     } else {
 9109:                         my @tocheck;
 9110:                         my @items = split(//,$value);
 9111:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9112:                             ($scantron_config->{'Qon'} eq 'number')) {
 9113:                             if (@items < $expected{$part_id}) {
 9114:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9115:                                 my @singles = split(//,$fragment);
 9116:                                 foreach my $pos (@singles) {
 9117:                                     if ($pos eq ' ') {
 9118:                                         push(@tocheck,$pos);
 9119:                                     } else {
 9120:                                         my $next = shift(@items);
 9121:                                         push(@tocheck,$next);
 9122:                                     }
 9123:                                 }
 9124:                             } else {
 9125:                                 @tocheck = @items;
 9126:                             }
 9127:                             foreach my $letter (@tocheck) {
 9128:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9129:                                     if ($letter !~ /^[A-J]$/) {
 9130:                                         $letter = $scantron_config->{'Qoff'};
 9131:                                     }
 9132:                                     $recorded{$part_id} .= $letter;
 9133:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9134:                                     my $digit;
 9135:                                     if ($letter !~ /^[A-J]$/) {
 9136:                                         $digit = $scantron_config->{'Qoff'};
 9137:                                     } else {
 9138:                                         $digit = $lettdig->{$letter};
 9139:                                     }
 9140:                                     $recorded{$part_id} .= $digit;
 9141:                                 }
 9142:                             }
 9143:                         } else {
 9144:                             @tocheck = @items;
 9145:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9146:                                 my $curr_sub = shift(@tocheck);
 9147:                                 my $digit;
 9148:                                 if ($curr_sub =~ /^[A-J]$/) {
 9149:                                     $digit = $lettdig->{$curr_sub}-1;
 9150:                                 }
 9151:                                 if ($curr_sub eq 'J') {
 9152:                                     $digit += scalar($numletts);
 9153:                                 }
 9154:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9155:                                     if ($j == $digit) {
 9156:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9157:                                     } else {
 9158:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9159:                                     }
 9160:                                 }
 9161:                             }
 9162:                         }
 9163:                     }
 9164:                 }
 9165:             }
 9166:         }
 9167:         foreach my $part_id (@{$partids}) {
 9168:             if ($recorded{$part_id} eq '') {
 9169:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9170:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9171:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9172:                     }
 9173:                 }
 9174:             }
 9175:             $record .= $recorded{$part_id};
 9176:         }
 9177:     }
 9178:     return ($counter,$record);
 9179: }
 9180: 
 9181: sub letter_to_digits {
 9182:     my %lettdig = (
 9183:                     A => 1,
 9184:                     B => 2,
 9185:                     C => 3,
 9186:                     D => 4,
 9187:                     E => 5,
 9188:                     F => 6,
 9189:                     G => 7,
 9190:                     H => 8,
 9191:                     I => 9,
 9192:                     J => 0,
 9193:                   );
 9194:     return %lettdig;
 9195: }
 9196: 
 9197: 
 9198: #-------- end of section for handling grading scantron forms -------
 9199: #
 9200: #-------------------------------------------------------------------
 9201: 
 9202: #-------------------------- Menu interface -------------------------
 9203: #
 9204: #--- Href with symb and command ---
 9205: 
 9206: sub href_symb_cmd {
 9207:     my ($symb,$cmd)=@_;
 9208:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9209: }
 9210: 
 9211: sub grading_menu {
 9212:     my ($request,$symb) = @_;
 9213:     if (!$symb) {return '';}
 9214: 
 9215:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9216:                   'command'=>'individual');
 9217:     
 9218:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9219: 
 9220:     $fields{'command'}='ungraded';
 9221:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9222: 
 9223:     $fields{'command'}='table';
 9224:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9225: 
 9226:     $fields{'command'}='all_for_one';
 9227:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9228: 
 9229:     $fields{'command'}='downloadfilesselect';
 9230:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9231: 
 9232:     $fields{'command'} = 'csvform';
 9233:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9234:     
 9235:     $fields{'command'} = 'processclicker';
 9236:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9237:     
 9238:     $fields{'command'} = 'scantron_selectphase';
 9239:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9240: 
 9241:     $fields{'command'} = 'initialverifyreceipt';
 9242:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9243:     
 9244:     my @menu = ({	categorytitle=>'Hand Grading',
 9245:             items =>[
 9246:                         {	linktext => 'Select individual students to grade',
 9247:                     		url => $url1a,
 9248:                     		permission => 'F',
 9249:                     		icon => 'grade_students.png',
 9250:                     		linktitle => 'Grade current resource for a selection of students.'
 9251:                         }, 
 9252:                         {       linktext => 'Grade ungraded submissions.',
 9253:                                 url => $url1b,
 9254:                                 permission => 'F',
 9255:                                 icon => 'ungrade_sub.png',
 9256:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9257:                         },
 9258: 
 9259:                         {       linktext => 'Grading table',
 9260:                                 url => $url1c,
 9261:                                 permission => 'F',
 9262:                                 icon => 'grading_table.png',
 9263:                                 linktitle => 'Grade current resource for all students.'
 9264:                         },
 9265:                         {       linktext => 'Grade page/folder for one student',
 9266:                                 url => $url1d,
 9267:                                 permission => 'F',
 9268:                                 icon => 'grade_PageFolder.png',
 9269:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9270:                         },
 9271:                         {       linktext => 'Download submissions',
 9272:                                 url => $url1e,
 9273:                                 permission => 'F',
 9274:                                 icon => 'download_sub.png',
 9275:                                 linktitle => 'Download all students submissions.'
 9276:                         }]},
 9277:                          { categorytitle=>'Automated Grading',
 9278:                items =>[
 9279: 
 9280:                 	    {	linktext => 'Upload Scores',
 9281:                     		url => $url2,
 9282:                     		permission => 'F',
 9283:                     		icon => 'uploadscores.png',
 9284:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9285:                 	    },
 9286:                 	    {	linktext => 'Process Clicker',
 9287:                     		url => $url3,
 9288:                     		permission => 'F',
 9289:                     		icon => 'addClickerInfoFile.png',
 9290:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9291:                 	    },
 9292:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9293:                     		url => $url4,
 9294:                     		permission => 'F',
 9295:                     		icon => 'bubblesheet.png',
 9296:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9297:                 	    },
 9298:                             {   linktext => 'Verify Receipt Number',
 9299:                                 url => $url5,
 9300:                                 permission => 'F',
 9301:                                 icon => 'receipt_number.png',
 9302:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9303:                             }
 9304: 
 9305:                     ]
 9306:             });
 9307: 
 9308:     # Create the menu
 9309:     my $Str;
 9310:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9311:     $Str .= '<input type="hidden" name="command" value="" />'.
 9312:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9313: 
 9314:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9315:     return $Str;    
 9316: }
 9317: 
 9318: 
 9319: sub ungraded {
 9320:     my ($request)=@_;
 9321:     &submit_options($request);
 9322: }
 9323: 
 9324: sub submit_options_sequence {
 9325:     my ($request,$symb) = @_;
 9326:     if (!$symb) {return '';}
 9327:     &commonJSfunctions($request);
 9328:     my $result;
 9329: 
 9330:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9331:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9332:     $result.=&selectfield(0).
 9333:             '<input type="hidden" name="command" value="pickStudentPage" />
 9334:             <div>
 9335:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9336:             </div>
 9337:         </div>
 9338:   </form>';
 9339:     return $result;
 9340: }
 9341: 
 9342: sub submit_options_table {
 9343:     my ($request,$symb) = @_;
 9344:     if (!$symb) {return '';}
 9345:     &commonJSfunctions($request);
 9346:     my $result;
 9347: 
 9348:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9349:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9350: 
 9351:     $result.=&selectfield(0).
 9352:             '<input type="hidden" name="command" value="viewgrades" />
 9353:             <div>
 9354:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9355:             </div>
 9356:         </div>
 9357:   </form>';
 9358:     return $result;
 9359: }
 9360: 
 9361: sub submit_options_download {
 9362:     my ($request,$symb) = @_;
 9363:     if (!$symb) {return '';}
 9364: 
 9365:     &commonJSfunctions($request);
 9366: 
 9367:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9368:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9369:     $result.='
 9370: <h2>
 9371:   '.&mt('Select Students for Which to Download Submissions').'
 9372: </h2>'.&selectfield(1).'
 9373:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9374:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9375:             </div>
 9376:           </div>
 9377: 
 9378: 
 9379:   </form>';
 9380:     return $result;
 9381: }
 9382: 
 9383: #--- Displays the submissions first page -------
 9384: sub submit_options {
 9385:     my ($request,$symb) = @_;
 9386:     if (!$symb) {return '';}
 9387: 
 9388:     &commonJSfunctions($request);
 9389:     my $result;
 9390: 
 9391:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9392: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9393:     $result.=&selectfield(1).'
 9394:                 <input type="hidden" name="command" value="submission" /> 
 9395: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9396:             </div>
 9397:           </div>
 9398: 
 9399: 
 9400:   </form>';
 9401:     return $result;
 9402: }
 9403: 
 9404: sub selectfield {
 9405:    my ($full)=@_;
 9406:    my %options = 
 9407:           (&Apache::lonlocal::texthash(
 9408:              'yes'       => 'with submissions',
 9409:              'queued'    => 'in grading queue',
 9410:              'graded'    => 'with ungraded submissions',
 9411:              'incorrect' => 'with incorrect submissions',
 9412:              'all'       => 'with any status'),
 9413:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9414:    my $result='<div class="LC_columnSection">
 9415:   
 9416:     <fieldset>
 9417:       <legend>
 9418:        '.&mt('Sections').'
 9419:       </legend>
 9420:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9421:     </fieldset>
 9422:   
 9423:     <fieldset>
 9424:       <legend>
 9425:         '.&mt('Groups').'
 9426:       </legend>
 9427:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9428:     </fieldset>
 9429:   
 9430:     <fieldset>
 9431:       <legend>
 9432:         '.&mt('Access Status').'
 9433:       </legend>
 9434:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9435:     </fieldset>';
 9436:     if ($full) {
 9437:        $result.='
 9438:     <fieldset>
 9439:       <legend>
 9440:         '.&mt('Submission Status').'
 9441:       </legend>'.
 9442:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9443:    '</fieldset>';
 9444:     }
 9445:     $result.='</div><br />';
 9446:     return $result;
 9447: }
 9448: 
 9449: sub reset_perm {
 9450:     undef(%perm);
 9451: }
 9452: 
 9453: sub init_perm {
 9454:     &reset_perm();
 9455:     foreach my $test_perm ('vgr','mgr','opa') {
 9456: 
 9457: 	my $scope = $env{'request.course.id'};
 9458: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9459: 
 9460: 	    $scope .= '/'.$env{'request.course.sec'};
 9461: 	    if ( $perm{$test_perm}=
 9462: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9463: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9464: 	    } else {
 9465: 		delete($perm{$test_perm});
 9466: 	    }
 9467: 	}
 9468:     }
 9469: }
 9470: 
 9471: sub init_old_essays {
 9472:     my ($symb,$apath,$adom,$aname) = @_;
 9473:     if ($symb ne '') {
 9474:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9475:         if (keys(%essays) > 0) {
 9476:             $old_essays{$symb} = \%essays;
 9477:         }
 9478:     }
 9479:     return;
 9480: }
 9481: 
 9482: sub reset_old_essays {
 9483:     undef(%old_essays);
 9484: }
 9485: 
 9486: sub gather_clicker_ids {
 9487:     my %clicker_ids;
 9488: 
 9489:     my $classlist = &Apache::loncoursedata::get_classlist();
 9490: 
 9491:     # Set up a couple variables.
 9492:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9493:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9494:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9495: 
 9496:     foreach my $student (keys(%$classlist)) {
 9497:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9498:         my $username = $classlist->{$student}->[$username_idx];
 9499:         my $domain   = $classlist->{$student}->[$domain_idx];
 9500:         my $clickers =
 9501: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9502:         foreach my $id (split(/\,/,$clickers)) {
 9503:             $id=~s/^[\#0]+//;
 9504:             $id=~s/[\-\:]//g;
 9505:             if (exists($clicker_ids{$id})) {
 9506: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9507:             } else {
 9508: 		$clicker_ids{$id}=$username.':'.$domain;
 9509:             }
 9510:         }
 9511:     }
 9512:     return %clicker_ids;
 9513: }
 9514: 
 9515: sub gather_adv_clicker_ids {
 9516:     my %clicker_ids;
 9517:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9518:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9519:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9520:     foreach my $element (sort(keys(%coursepersonnel))) {
 9521:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9522:             my ($puname,$pudom)=split(/\:/,$person);
 9523:             my $clickers =
 9524: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9525:             foreach my $id (split(/\,/,$clickers)) {
 9526: 		$id=~s/^[\#0]+//;
 9527:                 $id=~s/[\-\:]//g;
 9528: 		if (exists($clicker_ids{$id})) {
 9529: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9530: 		} else {
 9531: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9532: 		}
 9533:             }
 9534:         }
 9535:     }
 9536:     return %clicker_ids;
 9537: }
 9538: 
 9539: sub clicker_grading_parameters {
 9540:     return ('gradingmechanism' => 'scalar',
 9541:             'upfiletype' => 'scalar',
 9542:             'specificid' => 'scalar',
 9543:             'pcorrect' => 'scalar',
 9544:             'pincorrect' => 'scalar');
 9545: }
 9546: 
 9547: sub process_clicker {
 9548:     my ($r,$symb)=@_;
 9549:     if (!$symb) {return '';}
 9550:     my $result=&checkforfile_js();
 9551:     $result.=&Apache::loncommon::start_data_table().
 9552:              &Apache::loncommon::start_data_table_header_row().
 9553:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9554:              &Apache::loncommon::end_data_table_header_row().
 9555:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9556: # Attempt to restore parameters from last session, set defaults if not present
 9557:     my %Saveable_Parameters=&clicker_grading_parameters();
 9558:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9559:                                                  \%Saveable_Parameters);
 9560:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9561:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9562:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9563:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9564: 
 9565:     my %checked;
 9566:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9567:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9568:           $checked{$gradingmechanism}=' checked="checked"';
 9569:        }
 9570:     }
 9571: 
 9572:     my $upload=&mt("Evaluate File");
 9573:     my $type=&mt("Type");
 9574:     my $attendance=&mt("Award points just for participation");
 9575:     my $personnel=&mt("Correctness determined from response by course personnel");
 9576:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9577:     my $given=&mt("Correctness determined from given list of answers").' '.
 9578:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9579:     my $pcorrect=&mt("Percentage points for correct solution");
 9580:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9581:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9582: 						   {'iclicker' => 'i>clicker',
 9583:                                                     'interwrite' => 'interwrite PRS',
 9584:                                                     'turning' => 'Turning Technologies'});
 9585:     $symb = &Apache::lonenc::check_encrypt($symb);
 9586:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9587: function sanitycheck() {
 9588: // Accept only integer percentages
 9589:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9590:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9591: // Find out grading choice
 9592:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9593:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9594:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9595:       }
 9596:    }
 9597: // By default, new choice equals user selection
 9598:    newgradingchoice=gradingchoice;
 9599: // Not good to give more points for false answers than correct ones
 9600:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9601:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9602:    }
 9603: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9604:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9605:       document.forms.gradesupload.pcorrect.value=100;
 9606:       document.forms.gradesupload.pincorrect.value=100;
 9607:    }
 9608: // If the values are different, cannot be attendance only
 9609:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9610:        (gradingchoice=='attendance')) {
 9611:        newgradingchoice='personnel';
 9612:    }
 9613: // Change grading choice to new one
 9614:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9615:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9616:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9617:       } else {
 9618:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9619:       }
 9620:    }
 9621: // Remember the old state
 9622:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9623: }
 9624: ENDUPFORM
 9625:     $result.= <<ENDUPFORM;
 9626: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9627: <input type="hidden" name="symb" value="$symb" />
 9628: <input type="hidden" name="command" value="processclickerfile" />
 9629: <input type="file" name="upfile" size="50" />
 9630: <br /><label>$type: $selectform</label>
 9631: ENDUPFORM
 9632:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9633:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9634:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9635: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9636: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9637: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9638: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9639: <br />&nbsp;&nbsp;&nbsp;
 9640: <input type="text" name="givenanswer" size="50" />
 9641: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9642: ENDGRADINGFORM
 9643:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9644:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9645:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9646: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9647: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9648: </form>'
 9649: ENDPERCFORM
 9650:     $result.='</td>'.
 9651:              &Apache::loncommon::end_data_table_row().
 9652:              &Apache::loncommon::end_data_table();
 9653:     return $result;
 9654: }
 9655: 
 9656: sub process_clicker_file {
 9657:     my ($r,$symb)=@_;
 9658:     if (!$symb) {return '';}
 9659: 
 9660:     my %Saveable_Parameters=&clicker_grading_parameters();
 9661:     &Apache::loncommon::store_course_settings('grades_clicker',
 9662:                                               \%Saveable_Parameters);
 9663:     my $result='';
 9664:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9665: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9666: 	return $result;
 9667:     }
 9668:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9669:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9670:         return $result;
 9671:     }
 9672:     my $foundgiven=0;
 9673:     if ($env{'form.gradingmechanism'} eq 'given') {
 9674:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9675:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9676:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9677:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9678:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9679:         $foundgiven=$#answers+1;
 9680:     }
 9681:     my %clicker_ids=&gather_clicker_ids();
 9682:     my %correct_ids;
 9683:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9684: 	%correct_ids=&gather_adv_clicker_ids();
 9685:     }
 9686:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9687: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9688: 	   $correct_id=~tr/a-z/A-Z/;
 9689: 	   $correct_id=~s/\s//gs;
 9690: 	   $correct_id=~s/^[\#0]+//;
 9691:            $correct_id=~s/[\-\:]//g;
 9692:            if ($correct_id) {
 9693: 	      $correct_ids{$correct_id}='specified';
 9694:            }
 9695:         }
 9696:     }
 9697:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9698: 	$result.=&mt('Score based on attendance only');
 9699:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9700:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9701:     } else {
 9702: 	my $number=0;
 9703: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9704: 	foreach my $id (sort(keys(%correct_ids))) {
 9705: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9706: 	    if ($correct_ids{$id} eq 'specified') {
 9707: 		$result.=&mt('specified');
 9708: 	    } else {
 9709: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9710: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9711: 	    }
 9712: 	    $number++;
 9713: 	}
 9714:         $result.="</p>\n";
 9715: 	if ($number==0) {
 9716: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9717: 	    return $result;
 9718: 	}
 9719:     }
 9720:     if (length($env{'form.upfile'}) < 2) {
 9721:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9722: 		     '<span class="LC_error">',
 9723: 		     '</span>',
 9724: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9725:         return $result;
 9726:     }
 9727: 
 9728: # Were able to get all the info needed, now analyze the file
 9729: 
 9730:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9731:     $symb = &Apache::lonenc::check_encrypt($symb);
 9732:     $result.=&Apache::loncommon::start_data_table().
 9733:              &Apache::loncommon::start_data_table_header_row().
 9734:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9735:              &Apache::loncommon::end_data_table_header_row().
 9736:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9737: <td>
 9738: <form method="post" action="/adm/grades" name="clickeranalysis">
 9739: <input type="hidden" name="symb" value="$symb" />
 9740: <input type="hidden" name="command" value="assignclickergrades" />
 9741: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9742: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9743: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9744: ENDHEADER
 9745:     if ($env{'form.gradingmechanism'} eq 'given') {
 9746:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9747:     } 
 9748:     my %responses;
 9749:     my @questiontitles;
 9750:     my $errormsg='';
 9751:     my $number=0;
 9752:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9753: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9754:     }
 9755:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9756:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9757:     }
 9758:     if ($env{'form.upfiletype'} eq 'turning') {
 9759:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9760:     }
 9761:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9762:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9763:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9764:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9765:              '<br />';
 9766:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9767:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9768:        return $result;
 9769:     } 
 9770: # Remember Question Titles
 9771: # FIXME: Possibly need delimiter other than ":"
 9772:     for (my $i=0;$i<$number;$i++) {
 9773:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9774:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9775:     }
 9776:     my $correct_count=0;
 9777:     my $student_count=0;
 9778:     my $unknown_count=0;
 9779: # Match answers with usernames
 9780: # FIXME: Possibly need delimiter other than ":"
 9781:     foreach my $id (keys(%responses)) {
 9782:        if ($correct_ids{$id}) {
 9783:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9784:           $correct_count++;
 9785:        } elsif ($clicker_ids{$id}) {
 9786:           if ($clicker_ids{$id}=~/\,/) {
 9787: # More than one user with the same clicker!
 9788:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9789:                            &Apache::loncommon::start_data_table_row()."<td>".
 9790:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9791:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9792:                            "<select name='multi".$id."'>";
 9793:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9794:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9795:              }
 9796:              $result.='</select>';
 9797:              $unknown_count++;
 9798:           } else {
 9799: # Good: found one and only one user with the right clicker
 9800:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9801:              $student_count++;
 9802:           }
 9803:        } else {
 9804:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9805:                            &Apache::loncommon::start_data_table_row()."<td>".
 9806:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9807:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9808:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9809:                    "\n".&mt("Domain").": ".
 9810:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9811:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9812:           $unknown_count++;
 9813:        }
 9814:     }
 9815:     $result.='<hr />'.
 9816:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9817:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9818:        if ($correct_count==0) {
 9819:           $errormsg.="Found no correct answers for grading!";
 9820:        } elsif ($correct_count>1) {
 9821:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9822:        }
 9823:     }
 9824:     if ($number<1) {
 9825:        $errormsg.="Found no questions.";
 9826:     }
 9827:     if ($errormsg) {
 9828:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9829:     } else {
 9830:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9831:     }
 9832:     $result.='</form></td>'.
 9833:              &Apache::loncommon::end_data_table_row().
 9834:              &Apache::loncommon::end_data_table();
 9835:     return $result;
 9836: }
 9837: 
 9838: sub iclicker_eval {
 9839:     my ($questiontitles,$responses)=@_;
 9840:     my $number=0;
 9841:     my $errormsg='';
 9842:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9843:         my %components=&Apache::loncommon::record_sep($line);
 9844:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9845: 	if ($entries[0] eq 'Question') {
 9846: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9847: 		$$questiontitles[$number]=$entries[$i];
 9848: 		$number++;
 9849: 	    }
 9850: 	}
 9851: 	if ($entries[0]=~/^\#/) {
 9852: 	    my $id=$entries[0];
 9853: 	    my @idresponses;
 9854: 	    $id=~s/^[\#0]+//;
 9855: 	    for (my $i=0;$i<$number;$i++) {
 9856: 		my $idx=3+$i*6;
 9857:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9858: 		push(@idresponses,$entries[$idx]);
 9859: 	    }
 9860: 	    $$responses{$id}=join(',',@idresponses);
 9861: 	}
 9862:     }
 9863:     return ($errormsg,$number);
 9864: }
 9865: 
 9866: sub interwrite_eval {
 9867:     my ($questiontitles,$responses)=@_;
 9868:     my $number=0;
 9869:     my $errormsg='';
 9870:     my $skipline=1;
 9871:     my $questionnumber=0;
 9872:     my %idresponses=();
 9873:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9874:         my %components=&Apache::loncommon::record_sep($line);
 9875:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9876:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9877:         if ($entries[1] eq 'Response') { $skipline=1; }
 9878:         next if $skipline;
 9879:         if ($entries[0]!=$questionnumber) {
 9880:            $questionnumber=$entries[0];
 9881:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9882:            $number++;
 9883:         }
 9884:         my $id=$entries[4];
 9885:         $id=~s/^[\#0]+//;
 9886:         $id=~s/^v\d*\://i;
 9887:         $id=~s/[\-\:]//g;
 9888:         $idresponses{$id}[$number]=$entries[6];
 9889:     }
 9890:     foreach my $id (keys(%idresponses)) {
 9891:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9892:        $$responses{$id}=~s/^\s*\,//;
 9893:     }
 9894:     return ($errormsg,$number);
 9895: }
 9896: 
 9897: sub turning_eval {
 9898:     my ($questiontitles,$responses)=@_;
 9899:     my $number=0;
 9900:     my $errormsg='';
 9901:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9902:         my %components=&Apache::loncommon::record_sep($line);
 9903:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9904:         if ($#entries>$number) { $number=$#entries; }
 9905:         my $id=$entries[0];
 9906:         my @idresponses;
 9907:         $id=~s/^[\#0]+//;
 9908:         unless ($id) { next; }
 9909:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9910:             $entries[$idx]=~s/\,/\;/g;
 9911:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
 9912:             push(@idresponses,$entries[$idx]);
 9913:         }
 9914:         $$responses{$id}=join(',',@idresponses);
 9915:     }
 9916:     for (my $i=1; $i<=$number; $i++) {
 9917:         $$questiontitles[$i]=&mt('Question [_1]',$i);
 9918:     }
 9919:     return ($errormsg,$number);
 9920: }
 9921: 
 9922: 
 9923: sub assign_clicker_grades {
 9924:     my ($r,$symb)=@_;
 9925:     if (!$symb) {return '';}
 9926: # See which part we are saving to
 9927:     my $res_error;
 9928:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9929:     if ($res_error) {
 9930:         return &navmap_errormsg();
 9931:     }
 9932: # FIXME: This should probably look for the first handgradeable part
 9933:     my $part=$$partlist[0];
 9934: # Start screen output
 9935:     my $result=&Apache::loncommon::start_data_table().
 9936:              &Apache::loncommon::start_data_table_header_row().
 9937:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9938:              &Apache::loncommon::end_data_table_header_row().
 9939:              &Apache::loncommon::start_data_table_row().'<td>';
 9940: # Get correct result
 9941: # FIXME: Possibly need delimiter other than ":"
 9942:     my @correct=();
 9943:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9944:     my $number=$env{'form.number'};
 9945:     if ($gradingmechanism ne 'attendance') {
 9946:        foreach my $key (keys(%env)) {
 9947:           if ($key=~/^form\.correct\:/) {
 9948:              my @input=split(/\,/,$env{$key});
 9949:              for (my $i=0;$i<=$#input;$i++) {
 9950:                  if (($correct[$i]) && ($input[$i]) &&
 9951:                      ($correct[$i] ne $input[$i])) {
 9952:                     $result.='<br /><span class="LC_warning">'.
 9953:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9954:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9955:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9956:                     $correct[$i]=$input[$i];
 9957:                  }
 9958:              }
 9959:           }
 9960:        }
 9961:        for (my $i=0;$i<$number;$i++) {
 9962:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9963:              $result.='<br /><span class="LC_error">'.
 9964:                       &mt('No correct result given for question "[_1]"!',
 9965:                           $env{'form.question:'.$i}).'</span>';
 9966:           }
 9967:        }
 9968:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9969:     }
 9970: # Start grading
 9971:     my $pcorrect=$env{'form.pcorrect'};
 9972:     my $pincorrect=$env{'form.pincorrect'};
 9973:     my $storecount=0;
 9974:     my %users=();
 9975:     foreach my $key (keys(%env)) {
 9976:        my $user='';
 9977:        if ($key=~/^form\.student\:(.*)$/) {
 9978:           $user=$1;
 9979:        }
 9980:        if ($key=~/^form\.unknown\:(.*)$/) {
 9981:           my $id=$1;
 9982:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9983:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9984:           } elsif ($env{'form.multi'.$id}) {
 9985:              $user=$env{'form.multi'.$id};
 9986:           }
 9987:        }
 9988:        if ($user) {
 9989:           if ($users{$user}) {
 9990:              $result.='<br /><span class="LC_warning">'.
 9991:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
 9992:                       '</span><br />';
 9993:           }
 9994:           $users{$user}=1; 
 9995:           my @answer=split(/\,/,$env{$key});
 9996:           my $sum=0;
 9997:           my $realnumber=$number;
 9998:           for (my $i=0;$i<$number;$i++) {
 9999:              if  ($correct[$i] eq '-') {
10000:                 $realnumber--;
10001:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10002:                 if ($gradingmechanism eq 'attendance') {
10003:                    $sum+=$pcorrect;
10004:                 } elsif ($correct[$i] eq '*') {
10005:                    $sum+=$pcorrect;
10006:                 } else {
10007: # We actually grade if correct or not
10008:                    my $increment=$pincorrect;
10009: # Special case: numerical answer "0"
10010:                    if ($correct[$i] eq '0') {
10011:                       if ($answer[$i]=~/^[0\.]+$/) {
10012:                          $increment=$pcorrect;
10013:                       }
10014: # General numerical answer, both evaluate to something non-zero
10015:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10016:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10017:                          $increment=$pcorrect;
10018:                       }
10019: # Must be just alphanumeric
10020:                    } elsif ($answer[$i] eq $correct[$i]) {
10021:                       $increment=$pcorrect;
10022:                    }
10023:                    $sum+=$increment;
10024:                 }
10025:              }
10026:           }
10027:           my $ave=$sum/(100*$realnumber);
10028: # Store
10029:           my ($username,$domain)=split(/\:/,$user);
10030:           my %grades=();
10031:           $grades{"resource.$part.solved"}='correct_by_override';
10032:           $grades{"resource.$part.awarded"}=$ave;
10033:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10034:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10035:                                                  $env{'request.course.id'},
10036:                                                  $domain,$username);
10037:           if ($returncode ne 'ok') {
10038:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10039:           } else {
10040:              $storecount++;
10041:           }
10042:        }
10043:     }
10044: # We are done
10045:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10046:              '</td>'.
10047:              &Apache::loncommon::end_data_table_row().
10048:              &Apache::loncommon::end_data_table();
10049:     return $result;
10050: }
10051: 
10052: sub navmap_errormsg {
10053:     return '<div class="LC_error">'.
10054:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10055:            &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>').
10056:            '</div>';
10057: }
10058: 
10059: sub startpage {
10060:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10061:     if ($nomenu) {
10062:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10063:     } else {
10064:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10065:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10066:                                                  {'bread_crumbs' => $crumbs}));
10067:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10068:     }
10069:     unless ($nodisplayflag) {
10070:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10071:     }
10072: }
10073: 
10074: sub select_problem {
10075:     my ($r)=@_;
10076:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10077:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10078:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10079:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10080: }
10081: 
10082: sub handler {
10083:     my $request=$_[0];
10084:     &reset_caches();
10085:     if ($request->header_only) {
10086:         &Apache::loncommon::content_type($request,'text/html');
10087:         $request->send_http_header;
10088:         return OK;
10089:     }
10090:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10091: 
10092: # see what command we need to execute
10093: 
10094:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10095:     my $command=$commands[0];
10096: 
10097:     &init_perm();
10098:     if (!$env{'request.course.id'}) {
10099:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10100:                 ($command =~ /^scantronupload/)) {
10101:             # Not in a course.
10102:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10103:             return HTTP_NOT_ACCEPTABLE;
10104:         }
10105:     } elsif (!%perm) {
10106:         $request->internal_redirect('/adm/quickgrades');
10107:         return OK;
10108:     }
10109:     &Apache::loncommon::content_type($request,'text/html');
10110:     $request->send_http_header;
10111: 
10112:     if ($#commands > 0) {
10113: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10114:     }
10115: 
10116: # see what the symb is
10117: 
10118:     my $symb=$env{'form.symb'};
10119:     unless ($symb) {
10120:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10121:        $symb=&Apache::lonnet::symbread($url);
10122:     }
10123:     &Apache::lonenc::check_decrypt(\$symb);
10124: 
10125:     $ssi_error = 0;
10126:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10127: #
10128: # Not called from a resource, but inside a course
10129: #    
10130:         &startpage($request,undef,[],1,1);
10131:         &select_problem($request);
10132:     } else {
10133: 	if ($command eq 'submission' && $perm{'vgr'}) {
10134:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10135:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10136:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10137:                     &choose_task_version_form($symb,$env{'form.student'},
10138:                                               $env{'form.userdom'});
10139:             }
10140:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10141:             if ($versionform) {
10142:                 $request->print($versionform);
10143:             }
10144:             $request->print('<br clear="all" />');
10145: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10146:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10147:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10148:                 &choose_task_version_form($symb,$env{'form.student'},
10149:                                           $env{'form.userdom'},
10150:                                           $env{'form.inhibitmenu'});
10151:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10152:             if ($versionform) {
10153:                 $request->print($versionform);
10154:             }
10155:             $request->print('<br clear="all" />');
10156:             $request->print(&show_previous_task_version($request,$symb));
10157: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10158:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10159:                                        {href=>'',text=>'Select student'}],1,1);
10160: 	    &pickStudentPage($request,$symb);
10161: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10162:             &startpage($request,$symb,
10163:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10164:                                        {href=>'',text=>'Select student'},
10165:                                        {href=>'',text=>'Grade student'}],1,1);
10166: 	    &displayPage($request,$symb);
10167: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10168:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10169:                                        {href=>'',text=>'Select student'},
10170:                                        {href=>'',text=>'Grade student'},
10171:                                        {href=>'',text=>'Store grades'}],1,1);
10172: 	    &updateGradeByPage($request,$symb);
10173: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10174:             &startpage($request,$symb,[{href=>'',text=>'...'},
10175:                                        {href=>'',text=>'Modify grades'}]);
10176: 	    &processGroup($request,$symb);
10177: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10178:             &startpage($request,$symb);
10179: 	    $request->print(&grading_menu($request,$symb));
10180: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10181:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10182: 	    $request->print(&submit_options($request,$symb));
10183:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10184:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10185:             $request->print(&listStudents($request,$symb,'graded'));
10186:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10187:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10188:             $request->print(&submit_options_table($request,$symb));
10189:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10190:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10191:             $request->print(&submit_options_sequence($request,$symb));
10192: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10193:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10194: 	    $request->print(&viewgrades($request,$symb));
10195: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10196:             &startpage($request,$symb,[{href=>'',text=>'...'},
10197:                                        {href=>'',text=>'Store grades'}]);
10198: 	    $request->print(&processHandGrade($request,$symb));
10199: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10200:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10201:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10202:                                                                              text=>"Modify grades"},
10203:                                        {href=>'', text=>"Store grades"}]);
10204: 	    $request->print(&editgrades($request,$symb));
10205:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10206:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10207:             $request->print(&initialverifyreceipt($request,$symb));
10208: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10209:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10210:                                        {href=>'',text=>'Verification Result'}]);
10211: 	    $request->print(&verifyreceipt($request,$symb));
10212:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10213:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10214:             $request->print(&process_clicker($request,$symb));
10215:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10216:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10217:                                        {href=>'', text=>'Process clicker file'}]);
10218:             $request->print(&process_clicker_file($request,$symb));
10219:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10220:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10221:                                        {href=>'', text=>'Process clicker file'},
10222:                                        {href=>'', text=>'Store grades'}]);
10223:             $request->print(&assign_clicker_grades($request,$symb));
10224: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10225:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10226: 	    $request->print(&upcsvScores_form($request,$symb));
10227: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10228:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10229: 	    $request->print(&csvupload($request,$symb));
10230: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10231:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10232: 	    $request->print(&csvuploadmap($request,$symb));
10233: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10234: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10235:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10236: 		$request->print(&csvuploadoptions($request,$symb));
10237: 	    } else {
10238: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10239: 		    $env{'form.upfile_associate'} = 'reverse';
10240: 		} else {
10241: 		    $env{'form.upfile_associate'} = 'forward';
10242: 		}
10243:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10244: 		$request->print(&csvuploadmap($request,$symb));
10245: 	    }
10246: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10247:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10248: 	    $request->print(&csvuploadassign($request,$symb));
10249: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10250:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10251: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10252:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10253:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10254:  	    $request->print(&scantron_do_warning($request,$symb));
10255: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10256:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10257: 	    $request->print(&scantron_validate_file($request,$symb));
10258: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10259:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10260: 	    $request->print(&scantron_process_students($request,$symb));
10261:  	} elsif ($command eq 'scantronupload' && 
10262:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10263: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10264:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10265:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10266:  	} elsif ($command eq 'scantronupload_save' &&
10267:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10268: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10269:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10270:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10271:  	} elsif ($command eq 'scantron_download' &&
10272: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10273:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10274:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10275:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10276:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10277:             $request->print(&checkscantron_results($request,$symb));
10278:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10279:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10280:             $request->print(&submit_options_download($request,$symb));
10281:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10282:             &startpage($request,$symb,
10283:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10284:     {href=>'', text=>'Download submissions'}]);
10285:             &submit_download_link($request,$symb);
10286: 	} elsif ($command) {
10287:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10288: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10289: 	}
10290:     }
10291:     if ($ssi_error) {
10292: 	&ssi_print_error($request);
10293:     }
10294:     if ($env{'form.inhibitmenu'}) {
10295:         $request->print(&Apache::loncommon::end_page());
10296:     } else {
10297:         &Apache::lonquickgrades::endGradeScreen($request);
10298:     }
10299:     &reset_caches();
10300:     return OK;
10301: }
10302: 
10303: 1;
10304: 
10305: __END__;
10306: 
10307: 
10308: =head1 NAME
10309: 
10310: Apache::grades
10311: 
10312: =head1 SYNOPSIS
10313: 
10314: Handles the viewing of grades.
10315: 
10316: This is part of the LearningOnline Network with CAPA project
10317: described at http://www.lon-capa.org.
10318: 
10319: =head1 OVERVIEW
10320: 
10321: Do an ssi with retries:
10322: While I'd love to factor out this with the vesrion in lonprintout,
10323: 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
10324: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10325: 
10326: At least the logic that drives this has been pulled out into loncommon.
10327: 
10328: 
10329: 
10330: ssi_with_retries - Does the server side include of a resource.
10331:                      if the ssi call returns an error we'll retry it up to
10332:                      the number of times requested by the caller.
10333:                      If we still have a proble, no text is appended to the
10334:                      output and we set some global variables.
10335:                      to indicate to the caller an SSI error occurred.  
10336:                      All of this is supposed to deal with the issues described
10337:                      in LonCAPA BZ 5631 see:
10338:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10339:                      by informing the user that this happened.
10340: 
10341: Parameters:
10342:   resource   - The resource to include.  This is passed directly, without
10343:                interpretation to lonnet::ssi.
10344:   form       - The form hash parameters that guide the interpretation of the resource
10345:                
10346:   retries    - Number of retries allowed before giving up completely.
10347: Returns:
10348:   On success, returns the rendered resource identified by the resource parameter.
10349: Side Effects:
10350:   The following global variables can be set:
10351:    ssi_error                - If an unrecoverable error occurred this becomes true.
10352:                               It is up to the caller to initialize this to false
10353:                               if desired.
10354:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10355:                               of the resource that could not be rendered by the ssi
10356:                               call.
10357:    ssi_error_message   - The error string fetched from the ssi response
10358:                               in the event of an error.
10359: 
10360: 
10361: =head1 HANDLER SUBROUTINE
10362: 
10363: ssi_with_retries()
10364: 
10365: =head1 SUBROUTINES
10366: 
10367: =over
10368: 
10369: =head1 Routines to display previous version of a Task for a specific student
10370: 
10371: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10372: can receive another opportunity. Access to tasks is slot-based. If a slot
10373: requires a proctor to check-in the student, a new version of the Task will
10374: be created when the student is checked in to the new opportunity.
10375: 
10376: If a particular student has tried two or more versions of a particular task,
10377: the submission screen provides a user with vgr privileges (e.g., a Course
10378: Coordinator) the ability to display a previous version worked on by the
10379: student.  By default, the current version is displayed. If a previous version
10380: has been selected for display, submission data are only shown that pertain
10381: to that particular version, and the interface to submit grades is not shown.
10382: 
10383: =over 4
10384: 
10385: =item show_previous_task_version()
10386: 
10387: Displays a specified version of a student's Task, as the student sees it.
10388: 
10389: Inputs: 2
10390:         request - request object
10391:         symb    - unique symb for current instance of resource
10392: 
10393: Output: None.
10394: 
10395: Side Effects: calls &show_problem() to print version of Task, with
10396:               version contained in form item: $env{'form.previousversion'}
10397: 
10398: =item choose_task_version_form()
10399: 
10400: Displays a web form used to select which version of a student's view of a
10401: Task should be displayed.  Either launches a pop-up window, or replaces
10402: content in existing pop-up, or replaces page in main window.
10403: 
10404: Inputs: 4
10405:         symb    - unique symb for current instance of resource
10406:         uname   - username of student
10407:         udom    - domain of student
10408:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10409:                   breadcrumbs etc., are displayed
10410: 
10411: Output: 4
10412:         current   - student's current version
10413:         displayed - student's version being displayed
10414:         result    - scalar containing HTML for web form used to switch to
10415:                     a different version (or a link to close window, if pop-up).
10416:         js        - javascript for processing selection in versions web form
10417: 
10418: Side Effects: None.
10419: 
10420: =item previous_display_javascript()
10421: 
10422: Inputs: 2
10423:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10424:                   breadcrumbs etc., are displayed.
10425:         current - student's current version number.
10426: 
10427: Output: 1
10428:         js      - javascript for processing selection in versions web form.
10429: 
10430: Side Effects: None.
10431: 
10432: =back
10433: 
10434: =head1 Routines to process bubblesheet data.
10435: 
10436: =over 4
10437: 
10438: =item scantron_get_correction() : 
10439: 
10440:    Builds the interface screen to interact with the operator to fix a
10441:    specific error condition in a specific scanline
10442: 
10443:  Arguments:
10444:     $r           - Apache request object
10445:     $i           - number of the current scanline
10446:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10447:     $scan_config - hash ref as returned from &get_scantron_config()
10448:     $line        - full contents of the current scanline
10449:     $error       - error condition, valid values are
10450:                    'incorrectCODE', 'duplicateCODE',
10451:                    'doublebubble', 'missingbubble',
10452:                    'duplicateID', 'incorrectID'
10453:     $arg         - extra information needed
10454:        For errors:
10455:          - duplicateID   - paper number that this studentID was seen before on
10456:          - duplicateCODE - array ref of the paper numbers this CODE was
10457:                            seen on before
10458:          - incorrectCODE - current incorrect CODE 
10459:          - doublebubble  - array ref of the bubble lines that have double
10460:                            bubble errors
10461:          - missingbubble - array ref of the bubble lines that have missing
10462:                            bubble errors
10463: 
10464:    $randomorder - True if exam folder has randomorder set
10465:    $randompick  - True if exam folder has randompick set
10466:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10467:                      for current line to question number used for same question
10468:                      in "Master Seqence" (as seen by Course Coordinator).
10469:    $startline   - Reference to hash where key is question number (0 is first)
10470:                   and value is number of first bubble line for current student
10471:                   or code-based randompick and/or randomorder.
10472: 
10473: 
10474: 
10475: =item  scantron_get_maxbubble() : 
10476: 
10477:    Arguments:
10478:        $nav_error  - Reference to scalar which is a flag to indicate a
10479:                       failure to retrieve a navmap object.
10480:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10481:        calling routine should trap the error condition and display the warning
10482:        found in &navmap_errormsg().
10483: 
10484:        $scantron_config - Reference to bubblesheet format configuration hash.
10485: 
10486:    Returns the maximum number of bubble lines that are expected to
10487:    occur. Does this by walking the selected sequence rendering the
10488:    resource and then checking &Apache::lonxml::get_problem_counter()
10489:    for what the current value of the problem counter is.
10490: 
10491:    Caches the results to $env{'form.scantron_maxbubble'},
10492:    $env{'form.scantron.bubble_lines.n'}, 
10493:    $env{'form.scantron.first_bubble_line.n'} and
10494:    $env{"form.scantron.sub_bubblelines.n"}
10495:    which are the total number of bubble lines, the number of bubble
10496:    lines for response n and number of the first bubble line for response n,
10497:    and a comma separated list of numbers of bubble lines for sub-questions
10498:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10499: 
10500: 
10501: =item  scantron_validate_missingbubbles() : 
10502: 
10503:    Validates all scanlines in the selected file to not have any
10504:     answers that don't have bubbles that have not been verified
10505:     to be bubble free.
10506: 
10507: =item  scantron_process_students() : 
10508: 
10509:    Routine that does the actual grading of the bubblesheet information.
10510: 
10511:    The parsed scanline hash is added to %env 
10512: 
10513:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10514:    foreach resource , with the form data of
10515: 
10516: 	'submitted'     =>'scantron' 
10517: 	'grade_target'  =>'grade',
10518: 	'grade_username'=> username of student
10519: 	'grade_domain'  => domain of student
10520: 	'grade_courseid'=> of course
10521: 	'grade_symb'    => symb of resource to grade
10522: 
10523:     This triggers a grading pass. The problem grading code takes care
10524:     of converting the bubbled letter information (now in %env) into a
10525:     valid submission.
10526: 
10527: =item  scantron_upload_scantron_data() :
10528: 
10529:     Creates the screen for adding a new bubblesheet data file to a course.
10530: 
10531: =item  scantron_upload_scantron_data_save() : 
10532: 
10533:    Adds a provided bubble information data file to the course if user
10534:    has the correct privileges to do so. 
10535: 
10536: =item  valid_file() :
10537: 
10538:    Validates that the requested bubble data file exists in the course.
10539: 
10540: =item  scantron_download_scantron_data() : 
10541: 
10542:    Shows a list of the three internal files (original, corrected,
10543:    skipped) for a specific bubblesheet data file that exists in the
10544:    course.
10545: 
10546: =item  scantron_validate_ID() : 
10547: 
10548:    Validates all scanlines in the selected file to not have any
10549:    invalid or underspecified student/employee IDs
10550: 
10551: =item navmap_errormsg() :
10552: 
10553:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10554:    Should be called whenever the request to instantiate a navmap object fails.
10555: 
10556: =back
10557: 
10558: =back
10559: 
10560: =cut

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