File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.715: download - view: text, annotated - select for diffs
Wed Jan 29 16:31:20 2014 UTC (10 years, 3 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Fix documentation typos

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.715 2014/01/29 16:31:20 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. ([quant,_1,student] 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(
 1946:             '<span class="LC_warning">'.
 1947:             &mt('Unable to view requested student.').
 1948:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1949:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1950:             '</span>');
 1951: 	return;
 1952:     }
 1953: 
 1954:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1955:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1956:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1957:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1958:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1959: 	'" src="'.$request->dir_config('lonIconsURL').
 1960: 	'/check.gif" height="16" border="0" />';
 1961: 
 1962:     # header info
 1963:     if ($counter == 0) {
 1964: 	&sub_page_js($request);
 1965: 	&sub_page_kw_js($request);
 1966: 
 1967: 	# option to display problem, only once else it cause problems 
 1968:         # with the form later since the problem has a form.
 1969: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1970: 	    my $mode;
 1971: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1972: 		$mode='both';
 1973: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1974: 		$mode='text';
 1975: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1976: 		$mode='answer';
 1977: 	    }
 1978: 	    &Apache::lonxml::clear_problem_counter();
 1979: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1980: 	}
 1981: 
 1982: 	# kwclr is the only variable that is guaranteed not to be blank 
 1983:         # if this subroutine has been called once.
 1984: 	my %keyhash = ();
 1985: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1986:         if (1) {
 1987: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1988: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1989: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1990: 
 1991: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1992: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1993: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1994: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1995: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1996: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1997: 		$keyhash{$symb.'_subject'} : $probtitle;
 1998: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1999: 	}
 2000: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2001: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2002: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2003: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2004: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2005: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2006: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2007: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2008: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2009: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2010: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2011: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2012: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2013: 			&build_section_inputs().
 2014: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2015: 			'<input type="hidden" name="NCT"'.
 2016: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2017: #	if ($env{'form.handgrade'} eq 'yes') {
 2018:         if (1) {
 2019: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2020: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2021: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2022: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2023: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2024: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2025: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2026: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2027: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2028: 	    }
 2029: 	}
 2030: 	
 2031: 	my ($cts,$prnmsg) = (1,'');
 2032: 	while ($cts <= $env{'form.savemsgN'}) {
 2033: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2034: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2035: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2036: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2037: 		'" />'."\n".
 2038: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2039: 	    $cts++;
 2040: 	}
 2041: 	$request->print($prnmsg);
 2042: 
 2043: #	if ($env{'form.handgrade'} eq 'yes') {
 2044:         if (1) {
 2045: 
 2046:             my %lt = &Apache::lonlocal::texthash(
 2047:                           keyw => 'Keyword Options',
 2048:                           list => 'List',
 2049:                           past => 'Paste Selection to List',
 2050:                           high => 'Highlight Attribute',
 2051:                      );    
 2052: #
 2053: # Print out the keyword options line
 2054: #
 2055: 	    $request->print(<<KEYWORDS);
 2056: <br /><b>$lt{'keyw'}:</b>&nbsp;
 2057: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2058: <a href="#" onmousedown="javascript:getSel(); return false"
 2059:  class="page">$lt{'past'}</a>&nbsp; &nbsp;
 2060: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2061: KEYWORDS
 2062: #
 2063: # Load the other essays for similarity check
 2064: #
 2065:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2066: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2067: 	    $apath=&escape($apath);
 2068: 	    $apath=~s/\W/\_/gs;
 2069:             &init_old_essays($symb,$apath,$adom,$aname);
 2070:         }
 2071:     }
 2072: 
 2073: # This is where output for one specific student would start
 2074:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2075:     $request->print(
 2076:         "\n\n"
 2077:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2078:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2079:        ."\n"
 2080:     );
 2081: 
 2082:     # Show additional functions if allowed
 2083:     if ($perm{'vgr'}) {
 2084:         $request->print(
 2085:             &Apache::loncommon::track_student_link(
 2086:                 'View recent activity',
 2087:                 $uname,$udom,'check')
 2088:            .' '
 2089:         );
 2090:     }
 2091:     if ($perm{'opa'}) {
 2092:         $request->print(
 2093:             &Apache::loncommon::pprmlink(
 2094:                 &mt('Set/Change parameters'),
 2095:                 $uname,$udom,$symb,'check'));
 2096:     }
 2097: 
 2098:     # Show Problem
 2099:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2100: 	my $mode;
 2101: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2102: 	    $mode='both';
 2103: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2104: 	    $mode='text';
 2105: 	} elsif ($env{'form.vAns'} eq 'all') {
 2106: 	    $mode='answer';
 2107: 	}
 2108: 	&Apache::lonxml::clear_problem_counter();
 2109: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2110:     }
 2111: 
 2112:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2113:     my $res_error;
 2114:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2115:     if ($res_error) {
 2116:         $request->print(&navmap_errormsg());
 2117:         return;
 2118:     }
 2119: 
 2120:     # Display student info
 2121:     $request->print(($counter == 0 ? '' : '<br />'));
 2122: 
 2123:     my $result='<div class="LC_Box">'
 2124:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2125:     $result.='<input type="hidden" name="name'.$counter.
 2126:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2127: #    if ($env{'form.handgrade'} eq 'no') {
 2128:     if (1) {
 2129:         $result.='<p class="LC_info">'
 2130:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2131:                 ."</p>\n";
 2132:     }
 2133: 
 2134:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2135:     my $fullname;
 2136:     my $col_fullnames = [];
 2137: #    if ($env{'form.handgrade'} eq 'yes') {
 2138:     if (1) {
 2139: 	(my $sub_result,$fullname,$col_fullnames)=
 2140: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2141: 				 $counter);
 2142: 	$result.=$sub_result;
 2143:     }
 2144:     $request->print($result."\n");
 2145:     
 2146:     # print student answer/submission
 2147:     # Options are (1) Handgraded submission only
 2148:     #             (2) Last submission, includes submission that is not handgraded 
 2149:     #                  (for multi-response type part)
 2150:     #             (3) Last submission plus the parts info
 2151:     #             (4) The whole record for this student
 2152:     
 2153:     my ($string,$timestamp)= &get_last_submission(\%record);
 2154: 	
 2155:     my $lastsubonly;
 2156: 
 2157:     if ($$timestamp eq '') {
 2158:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2159:     } else {
 2160:         $lastsubonly =
 2161:             '<div class="LC_grade_submissions_body">'
 2162:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2163: 
 2164: 	my %seenparts;
 2165: 	my @part_response_id = &flatten_responseType($responseType);
 2166: 	foreach my $part (@part_response_id) {
 2167: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2168: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2169: 
 2170: 	    my ($partid,$respid) = @{ $part };
 2171: 	    my $display_part=&get_display_part($partid,$symb);
 2172: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2173: 		if (exists($seenparts{$partid})) { next; }
 2174: 		$seenparts{$partid}=1;
 2175:                 $request->print(
 2176:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2177:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2178:                                '<a href="javascript:viewSubmitter(\''.
 2179:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2180:                                '\');" target="_self">'.
 2181:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2182:                     '<br />');
 2183: 		next;
 2184: 		}
 2185: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2186: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2187:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2188:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2189:                     ' <span class="LC_internal_info">'.
 2190:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2191:                     '</span>&nbsp; &nbsp;'.
 2192: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2193: 		next;
 2194: 	    }
 2195: 	    foreach my $submission (@$string) {
 2196: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2197: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2198: 		my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2199: 		# Similarity check
 2200:                 my $similar='';
 2201:                 my ($type,$trial,$rndseed);
 2202:                 if ($hide eq 'rand') {
 2203:                     $type = 'randomizetry';
 2204:                     $trial = $record{"resource.$partid.tries"};
 2205:                     $rndseed = $record{"resource.$partid.rndseed"};
 2206:                 }
 2207: 	        if ($env{'form.checkPlag'}) {
 2208:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2209: 		        &most_similar($uname,$udom,$symb,$subval);
 2210: 		    if ($osim) {
 2211: 			$osim=int($osim*100.0);
 2212: 			my %old_course_desc = 
 2213: 			    &Apache::lonnet::coursedescription($ocrsid,
 2214: 							{'one_time' => 1});
 2215: 
 2216:                         if ($hide eq 'anon') {
 2217:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2218:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2219:                         } else {
 2220: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2221: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2222: 				    $osim,
 2223: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2224: 				        $old_course_desc{'description'},
 2225: 				        $old_course_desc{'num'},
 2226: 				        $old_course_desc{'domain'}).
 2227: 				    '</span></h3><blockquote><i>'.
 2228: 				    &keywords_highlight($oessay).
 2229: 				    '</i></blockquote><hr />';
 2230:                         }
 2231: 	            }
 2232: 		}
 2233: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2234:                                      undef,$type,$trial,$rndseed);
 2235:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2236: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2237: 		    my $display_part=&get_display_part($partid,$symb);
 2238:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2239:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2240:                         ' <span class="LC_internal_info">'.
 2241:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2242:                         '</span>&nbsp; &nbsp;';
 2243: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2244:                         
 2245: 		    if (@$files) {
 2246:                         if ($hide eq 'anon') {
 2247:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2248:                         } else {
 2249:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2250:                                         .'<br /><span class="LC_warning">';
 2251:                             if(@$files == 1) {
 2252:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2253:                             } else {
 2254:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2255:                             }
 2256:                             $lastsubonly .= '</span>';                         
 2257:                             foreach my $file (@$files) {
 2258:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2259:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2260:                             }
 2261:                         }
 2262: 			$lastsubonly.='<br />';
 2263:                     }
 2264:                     if ($hide eq 'anon') {
 2265:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2266:                     } else {
 2267:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
 2268: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2269: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2270:                     }
 2271: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2272: 		    $lastsubonly.='</div>';
 2273: 		}
 2274:             }
 2275: 	}
 2276: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2277:     }
 2278:     $request->print($lastsubonly);
 2279:     if ($env{'form.lastSub'} eq 'datesub') {
 2280:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2281: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2282:     } 
 2283:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2284:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2285: 								 $env{'request.course.id'},
 2286: 								 $last,'.submission',
 2287: 								 'Apache::grades::keywords_highlight'));
 2288:     }
 2289:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2290: 	.$udom.'" />'."\n");
 2291:     # return if view submission with no grading option
 2292:     if (!&canmodify($usec)) {
 2293: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2294: 	return;
 2295:     } else {
 2296: 	$request->print('</div>'."\n");
 2297:     }
 2298: 
 2299:     # essay grading message center
 2300: #    if ($env{'form.handgrade'} eq 'yes') {
 2301:     if (1) {
 2302: 	my $result='<div class="LC_grade_message_center">';
 2303:     
 2304: 	$result.='<div class="LC_grade_message_center_header">'.
 2305: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2306: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2307: 	my $msgfor = $givenn.' '.$lastname;
 2308: 	if (scalar(@$col_fullnames) > 0) {
 2309: 	    my $lastone = pop(@$col_fullnames);
 2310: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2311: 	}
 2312: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2313: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2314: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2315: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2316: 	    ',\''.$msgfor.'\');" target="_self">'.
 2317: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2318: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2319: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2320: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2321: 	    '<br />&nbsp;('.
 2322: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2323: 	$result.='</div></div>';
 2324: 	$request->print($result);
 2325:     }
 2326: 
 2327:     my %seen = ();
 2328:     my @partlist;
 2329:     my @gradePartRespid;
 2330:     my @part_response_id = &flatten_responseType($responseType);
 2331:     $request->print(
 2332:         '<div class="LC_Box">'
 2333:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2334:     );
 2335:     $request->print(&gradeBox_start());
 2336:     foreach my $part_response_id (@part_response_id) {
 2337:     	my ($partid,$respid) = @{ $part_response_id };
 2338: 	my $part_resp = join('_',@{ $part_response_id });
 2339: 	next if ($seen{$partid} > 0);
 2340: 	$seen{$partid}++;
 2341: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2342: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2343: 	push(@partlist,$partid);
 2344: 	push(@gradePartRespid,$partid.'.'.$respid);
 2345: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2346:     }
 2347:     $request->print(&gradeBox_end()); # </div>
 2348:     $request->print('</div>');
 2349: 
 2350:     $request->print('<div class="LC_grade_info_links">');
 2351:     $request->print('</div>');
 2352: 
 2353:     $result='<input type="hidden" name="partlist'.$counter.
 2354: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2355:     $result.='<input type="hidden" name="gradePartRespid'.
 2356: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2357:     my $ctr = 0;
 2358:     while ($ctr < scalar(@partlist)) {
 2359: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2360: 	    $partlist[$ctr].'" />'."\n";
 2361: 	$ctr++;
 2362:     }
 2363:     $request->print($result.''."\n");
 2364: 
 2365: # Done with printing info for one student
 2366: 
 2367:     $request->print('</div>');#LC_grade_show_user
 2368: 
 2369: 
 2370:     # print end of form
 2371:     if ($counter == $total) {
 2372:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2373: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2374: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2375: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2376: 	my $ntstu ='<select name="NTSTU">'.
 2377: 	    '<option>1</option><option>2</option>'.
 2378: 	    '<option>3</option><option>5</option>'.
 2379: 	    '<option>7</option><option>10</option></select>'."\n";
 2380: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2381: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2382:         $endform.=&mt('[_1]student(s)',$ntstu);
 2383: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2384: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2385: 	    '<input type="button" value="'.&mt('Next').'" '.
 2386: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2387:         $endform.='<span class="LC_warning">'.
 2388:                   &mt('(Next and Previous (student) do not save the scores.)').
 2389:                   '</span>'."\n" ;
 2390:         $endform.="<input type='hidden' value='".&get_increment().
 2391:             "' name='increment' />";
 2392: 	$endform.='</td></tr></table></form>';
 2393: 	$request->print($endform);
 2394:     }
 2395:     return '';
 2396: }
 2397: 
 2398: sub check_collaborators {
 2399:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2400:     my ($result,@col_fullnames);
 2401:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2402:     foreach my $part (keys(%$handgrade)) {
 2403: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2404: 					'.maxcollaborators',
 2405: 					$symb,$udom,$uname);
 2406: 	next if ($ncol <= 0);
 2407: 	$part =~ s/\_/\./g;
 2408: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2409: 	my (@good_collaborators, @bad_collaborators);
 2410: 	foreach my $possible_collaborator
 2411: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2412: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2413: 	    next if ($possible_collaborator eq '');
 2414: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2415: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2416: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2417: 	    # Doing this grep allows 'fuzzy' specification
 2418: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2419: 			       keys(%$classlist));
 2420: 	    if (! scalar(@matches)) {
 2421: 		push(@bad_collaborators, $possible_collaborator);
 2422: 	    } else {
 2423: 		push(@good_collaborators, @matches);
 2424: 	    }
 2425: 	}
 2426: 	if (scalar(@good_collaborators) != 0) {
 2427: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2428: 	    foreach my $name (@good_collaborators) {
 2429: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2430: 		push(@col_fullnames, $givenn.' '.$lastname);
 2431: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2432: 	    }
 2433: 	    $result.='</ol><br />'."\n";
 2434: 	    my ($part)=split(/\./,$part);
 2435: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2436: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2437: 		"\n";
 2438: 	}
 2439: 	if (scalar(@bad_collaborators) > 0) {
 2440: 	    $result.='<div class="LC_warning">';
 2441: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2442: 	    $result .= '</div>';
 2443: 	}         
 2444: 	if (scalar(@bad_collaborators > $ncol)) {
 2445: 	    $result .= '<div class="LC_warning">';
 2446: 	    $result .= &mt('This student has submitted too many '.
 2447: 		'collaborators.  Maximum is [_1].',$ncol);
 2448: 	    $result .= '</div>';
 2449: 	}
 2450:     }
 2451:     return ($result,$fullname,\@col_fullnames);
 2452: }
 2453: 
 2454: #--- Retrieve the last submission for all the parts
 2455: sub get_last_submission {
 2456:     my ($returnhash)=@_;
 2457:     my (@string,$timestamp,%lasthidden);
 2458:     if ($$returnhash{'version'}) {
 2459: 	my %lasthash=();
 2460: 	my ($version);
 2461: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2462: 	    foreach my $key (sort(split(/\:/,
 2463: 					$$returnhash{$version.':keys'}))) {
 2464: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2465: 		$timestamp = 
 2466: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2467: 	    }
 2468: 	}
 2469:         my (%typeparts,%randombytry);
 2470:         my $showsurv = 
 2471:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2472:         foreach my $key (sort(keys(%lasthash))) {
 2473:             if ($key =~ /\.type$/) {
 2474:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2475:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2476:                     ($lasthash{$key} eq 'randomizetry')) {
 2477:                     my ($ign,@parts) = split(/\./,$key);
 2478:                     pop(@parts);
 2479:                     my $id = join('.',@parts);
 2480:                     if ($lasthash{$key} eq 'randomizetry') {
 2481:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2482:                     } else {
 2483:                         unless ($showsurv) {
 2484:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2485:                         }
 2486:                     }
 2487:                     delete($lasthash{$key});
 2488:                 }
 2489:             }
 2490:         }
 2491:         my @hidden = keys(%typeparts);
 2492:         my @randomize = keys(%randombytry);
 2493: 	foreach my $key (keys(%lasthash)) {
 2494: 	    next if ($key !~ /\.submission$/);
 2495:             my $hide;
 2496:             if (@hidden) {
 2497:                 foreach my $id (@hidden) {
 2498:                     if ($key =~ /^\Q$id\E/) {
 2499:                         $hide = 'anon';
 2500:                         last;
 2501:                     }
 2502:                 }
 2503:             }
 2504:             unless ($hide) {
 2505:                 if (@randomize) {
 2506:                     foreach my $id (@hidden) {
 2507:                         if ($key =~ /^\Q$id\E/) {
 2508:                             $hide = 'rand';
 2509:                             last;
 2510:                         }
 2511:                     }
 2512:                 }
 2513:             }
 2514: 	    my ($partid,$foo) = split(/submission$/,$key);
 2515: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2516: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2517: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2518: 	}
 2519:     }
 2520:     if (!@string) {
 2521: 	$string[0] =
 2522: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2523:     }
 2524:     return (\@string,\$timestamp);
 2525: }
 2526: 
 2527: #--- High light keywords, with style choosen by user.
 2528: sub keywords_highlight {
 2529:     my $string    = shift;
 2530:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2531:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2532:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2533:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2534:     foreach my $keyword (@keylist) {
 2535: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2536:     }
 2537:     return $string;
 2538: }
 2539: 
 2540: # For Tasks provide a mechanism to display previous version for one specific student
 2541: 
 2542: sub show_previous_task_version {
 2543:     my ($request,$symb) = @_;
 2544:     if ($symb eq '') {
 2545:         $request->print("Unable to handle ambiguous references.");
 2546: 
 2547:         return '';
 2548:     }
 2549:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2550:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2551:     if (!&canview($usec)) {
 2552:         $request->print(
 2553:             '<span class="LC_warning">'.
 2554:             &mt('Unable to view previous version for requested student.').
 2555:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2556:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2557:             '</span>');
 2558:         return;
 2559:     }
 2560:     my $mode = 'both';
 2561:     my $isTask = ($symb =~/\.task$/);
 2562:     if ($isTask) {
 2563:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2564:             if ($env{'form.fullname'} eq '') {
 2565:                 $env{'form.fullname'} =
 2566:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2567:             }
 2568:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2569:             $request->print("\n\n".
 2570:                             '<div class="LC_grade_show_user">'.
 2571:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2572:                             '</h2>'."\n");
 2573:             &Apache::lonxml::clear_problem_counter();
 2574:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2575:                             {'previousversion' => $env{'form.previousversion'} }));
 2576:             $request->print("\n</div>");
 2577:         }
 2578:     }
 2579:     return;
 2580: }
 2581: 
 2582: sub choose_task_version_form {
 2583:     my ($symb,$uname,$udom,$nomenu) = @_;
 2584:     my $isTask = ($symb =~/\.task$/);
 2585:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2586:     if ($isTask) {
 2587:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2588:                                               $udom,$uname);
 2589:         if (($record{'resource.0.version'} eq '') ||
 2590:             ($record{'resource.0.version'} < 2)) {
 2591:             return ($record{'resource.0.version'},
 2592:                     $record{'resource.0.version'},$result,$js);
 2593:         } else {
 2594:             $current = $record{'resource.0.version'};
 2595:         }
 2596:         if ($env{'form.previousversion'}) {
 2597:             $displayed = $env{'form.previousversion'};
 2598:             $rowtitle = &mt('Choose another version:')
 2599:         } else {
 2600:             $displayed = $current;
 2601:             $rowtitle = &mt('Show earlier version:');
 2602:         }
 2603:         $result = '<div class="LC_left_float">';
 2604:         my $list;
 2605:         my $numversions = 0;
 2606:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2607:             if ($i == $current) {
 2608:                 if (!$env{'form.previousversion'} || $nomenu) {
 2609:                     next;
 2610:                 } else {
 2611:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2612:                     $numversions ++;
 2613:                 }
 2614:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2615:                 unless ($i == $env{'form.previousversion'}) {
 2616:                     $numversions ++;
 2617:                 }
 2618:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2619:             }
 2620:         }
 2621:         if ($numversions) {
 2622:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2623:             $result .=
 2624:                 '<form name="getprev" method="post" action=""'.
 2625:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2626:                 &Apache::loncommon::start_data_table().
 2627:                 &Apache::loncommon::start_data_table_row().
 2628:                 '<th align="left">'.$rowtitle.'</th>'.
 2629:                 '<td><select name="version">'.
 2630:                 '<option>'.&mt('Select').'</option>'.
 2631:                 $list.
 2632:                 '</select></td>'.
 2633:                 &Apache::loncommon::end_data_table_row();
 2634:             unless ($nomenu) {
 2635:                 $result .= &Apache::loncommon::start_data_table_row().
 2636:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2637:                 '<td><span class="LC_nobreak">'.
 2638:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2639:                 &mt('Yes').'</label>'.
 2640:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2641:                 '</span></td>'.
 2642:                 &Apache::loncommon::end_data_table_row();
 2643:             }
 2644:             $result .=
 2645:                 &Apache::loncommon::start_data_table_row().
 2646:                 '<th align="left">&nbsp;</th>'.
 2647:                 '<td>'.
 2648:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2649:                 '</td>'.
 2650:                 &Apache::loncommon::end_data_table_row().
 2651:                 &Apache::loncommon::end_data_table().
 2652:                 '</form>';
 2653:             $js = &previous_display_javascript($nomenu,$current);
 2654:         } elsif ($displayed && $nomenu) {
 2655:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2656:         } else {
 2657:             $result .= &mt('No previous versions to show for this student');
 2658:         }
 2659:         $result .= '</div>';
 2660:     }
 2661:     return ($current,$displayed,$result,$js);
 2662: }
 2663: 
 2664: sub previous_display_javascript {
 2665:     my ($nomenu,$current) = @_;
 2666:     my $js = <<"JSONE";
 2667: <script type="text/javascript">
 2668: // <![CDATA[
 2669: function previousVersion(uname,udom,symb) {
 2670:     var current = '$current';
 2671:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2672:     var prevstr = new RegExp("^\\\\d+\$");
 2673:     if (!prevstr.test(version)) {
 2674:         return false;
 2675:     }
 2676:     var url = '';
 2677:     if (version == current) {
 2678:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2679:     } else {
 2680:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2681:     }
 2682: JSONE
 2683:     if ($nomenu) {
 2684:         $js .= <<"JSTWO";
 2685:     document.location.href = url;
 2686: JSTWO
 2687:     } else {
 2688:         $js .= <<"JSTHREE";
 2689:     var newwin = 0;
 2690:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2691:         if (document.getprev.prevwin[i].checked == true) {
 2692:             newwin = document.getprev.prevwin[i].value;
 2693:         }
 2694:     }
 2695:     if (newwin == 1) {
 2696:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2697:         url = url+'&inhibitmenu=yes';
 2698:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2699:             previousWin = window.open(url,'',options,1);
 2700:         } else {
 2701:             previousWin.location.href = url;
 2702:         }
 2703:         previousWin.focus();
 2704:         return false;
 2705:     } else {
 2706:         document.location.href = url;
 2707:         return false;
 2708:     }
 2709: JSTHREE
 2710:     }
 2711:     $js .= <<"ENDJS";
 2712:     return false;
 2713: }
 2714: // ]]>
 2715: </script>
 2716: ENDJS
 2717: 
 2718: }
 2719: 
 2720: #--- Called from submission routine
 2721: sub processHandGrade {
 2722:     my ($request,$symb) = @_;
 2723:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2724:     my $button = $env{'form.gradeOpt'};
 2725:     my $ngrade = $env{'form.NCT'};
 2726:     my $ntstu  = $env{'form.NTSTU'};
 2727:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2728:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2729: 
 2730:     if ($button eq 'Save & Next') {
 2731: 	my $ctr = 0;
 2732: 	while ($ctr < $ngrade) {
 2733: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2734: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2735: 	    if ($errorflag eq 'no_score') {
 2736: 		$ctr++;
 2737: 		next;
 2738: 	    }
 2739: 	    if ($errorflag eq 'not_allowed') {
 2740: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2741: 		$ctr++;
 2742: 		next;
 2743: 	    }
 2744: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2745: 	    my ($subject,$message,$msgstatus) = ('','','');
 2746: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2747:             my ($feedurl,$showsymb) =
 2748: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2749: 	    my $messagetail;
 2750: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2751: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2752: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2753: 		$subject.=' ['.$restitle.']';
 2754: 		my (@msgnum) = split(/,/,$includemsg);
 2755: 		foreach (@msgnum) {
 2756: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2757: 		}
 2758: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2759: 		if ($env{'form.withgrades'.$ctr}) {
 2760: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2761: 		    $messagetail = " for <a href=\"".
 2762: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2763: 		}
 2764: 		$msgstatus = 
 2765:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2766: 						     $message.$messagetail,
 2767:                                                      undef,$feedurl,undef,
 2768:                                                      undef,undef,$showsymb,
 2769:                                                      $restitle);
 2770: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2771: 				$msgstatus.'<br />');
 2772: 	    }
 2773: 	    if ($env{'form.collaborator'.$ctr}) {
 2774: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2775: 		foreach my $collabstr (@collabstrs) {
 2776: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2777: 		    foreach my $collaborator (@collaborators) {
 2778: 			my ($errorflag,$pts,$wgt) = 
 2779: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2780: 					   $env{'form.unamedom'.$ctr},$part);
 2781: 			if ($errorflag eq 'not_allowed') {
 2782: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2783: 			    next;
 2784: 			} elsif ($message ne '') {
 2785: 			    my ($baseurl,$showsymb) = 
 2786: 				&get_feedurl_and_symb($symb,$collaborator,
 2787: 						      $udom);
 2788: 			    if ($env{'form.withgrades'.$ctr}) {
 2789: 				$messagetail = " for <a href=\"".
 2790:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2791: 			    }
 2792: 			    $msgstatus = 
 2793: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2794: 			}
 2795: 		    }
 2796: 		}
 2797: 	    }
 2798: 	    $ctr++;
 2799: 	}
 2800:     }
 2801: 
 2802: #    if ($env{'form.handgrade'} eq 'yes') {
 2803:     if (1) {
 2804: 	# Keywords sorted in alphabatical order
 2805: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2806: 	my %keyhash = ();
 2807: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2808: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2809: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2810: 	$env{'form.keywords'} = join(' ',@keywords);
 2811: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2812: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2813: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2814: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2815: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2816: 
 2817: 	# message center - Order of message gets changed. Blank line is eliminated.
 2818: 	# New messages are saved in env for the next student.
 2819: 	# All messages are saved in nohist_handgrade.db
 2820: 	my ($ctr,$idx) = (1,1);
 2821: 	while ($ctr <= $env{'form.savemsgN'}) {
 2822: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2823: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2824: 		$idx++;
 2825: 	    }
 2826: 	    $ctr++;
 2827: 	}
 2828: 	$ctr = 0;
 2829: 	while ($ctr < $ngrade) {
 2830: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2831: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2832: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2833: 		$idx++;
 2834: 	    }
 2835: 	    $ctr++;
 2836: 	}
 2837: 	$env{'form.savemsgN'} = --$idx;
 2838: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2839: 	my $putresult = &Apache::lonnet::put
 2840: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2841:     }
 2842:     # Called by Save & Refresh from Highlight Attribute Window
 2843:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2844:     if ($env{'form.refresh'} eq 'on') {
 2845: 	my ($ctr,$total) = (0,0);
 2846: 	while ($ctr < $ngrade) {
 2847: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2848: 	    $ctr++;
 2849: 	}
 2850: 	$env{'form.NTSTU'}=$ngrade;
 2851: 	$ctr = 0;
 2852: 	while ($ctr < $total) {
 2853: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2854: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2855: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2856: 	    &submission($request,$ctr,$total-1,$symb);
 2857: 	    $ctr++;
 2858: 	}
 2859: 	return '';
 2860:     }
 2861: 
 2862:     # Get the next/previous one or group of students
 2863:     my $firststu = $env{'form.unamedom0'};
 2864:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2865:     my $ctr = 2;
 2866:     while ($laststu eq '') {
 2867: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2868: 	$ctr++;
 2869: 	$laststu = $firststu if ($ctr > $ngrade);
 2870:     }
 2871: 
 2872:     my (@parsedlist,@nextlist);
 2873:     my ($nextflg) = 0;
 2874:     foreach my $item (sort 
 2875: 	     {
 2876: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2877: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2878: 		 }
 2879: 		 return $a cmp $b;
 2880: 	     } (keys(%$fullname))) {
 2881: # FIXME: this is fishy, looks like the button label
 2882: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2883: 	    push(@parsedlist,$item);
 2884: 	}
 2885: 	$nextflg = 1 if ($item eq $laststu);
 2886: 	if ($button eq 'Previous') {
 2887: 	    last if ($item eq $firststu);
 2888: 	    push(@parsedlist,$item);
 2889: 	}
 2890:     }
 2891:     $ctr = 0;
 2892: # FIXME: this is fishy, looks like the button label
 2893:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2894:     my $res_error;
 2895:     my ($partlist) = &response_type($symb,\$res_error);
 2896:     if ($res_error) {
 2897:         $request->print(&navmap_errormsg());
 2898:         return;
 2899:     }
 2900:     foreach my $student (@parsedlist) {
 2901: 	my $submitonly=$env{'form.submitonly'};
 2902: 	my ($uname,$udom) = split(/:/,$student);
 2903: 	
 2904: 	if ($submitonly eq 'queued') {
 2905: 	    my %queue_status = 
 2906: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2907: 							$udom,$uname);
 2908: 	    next if (!defined($queue_status{'gradingqueue'}));
 2909: 	}
 2910: 
 2911: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2912: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2913: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2914: 	    my $submitted = 0;
 2915: 	    my $ungraded = 0;
 2916: 	    my $incorrect = 0;
 2917: 	    foreach my $item (keys(%status)) {
 2918: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2919: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2920: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2921: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2922: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2923: 		    $submitted = 0;
 2924: 		}
 2925: 	    }
 2926: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2927: 				     $submitonly eq 'incorrect' ||
 2928: 				     $submitonly eq 'graded'));
 2929: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2930: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2931: 	}
 2932: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2933: 	last if ($ctr == $ntstu);
 2934: 	$ctr++;
 2935:     }
 2936: 
 2937:     $ctr = 0;
 2938:     my $total = scalar(@nextlist)-1;
 2939: 
 2940:     foreach (sort(@nextlist)) {
 2941: 	my ($uname,$udom,$submitter) = split(/:/);
 2942: 	$env{'form.student'}  = $uname;
 2943: 	$env{'form.userdom'}  = $udom;
 2944: 	$env{'form.fullname'} = $$fullname{$_};
 2945: 	&submission($request,$ctr,$total,$symb);
 2946: 	$ctr++;
 2947:     }
 2948:     if ($total < 0) {
 2949: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2950: 	$request->print($the_end);
 2951:     }
 2952:     return '';
 2953: }
 2954: 
 2955: #---- Save the score and award for each student, if changed
 2956: sub saveHandGrade {
 2957:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2958:     my @version_parts;
 2959:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2960: 					   $env{'request.course.id'});
 2961:     if (!&canmodify($usec)) { return('not_allowed'); }
 2962:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2963:     my @parts_graded;
 2964:     my %newrecord  = ();
 2965:     my ($pts,$wgt) = ('','');
 2966:     my %aggregate = ();
 2967:     my $aggregateflag = 0;
 2968:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2969:     foreach my $new_part (@parts) {
 2970: 	#collaborator ($submi may vary for different parts
 2971: 	if ($submitter && $new_part ne $part) { next; }
 2972: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2973: 	if ($dropMenu eq 'excused') {
 2974: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2975: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2976: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2977: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2978: 		}
 2979: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2980: 	    }
 2981: 	} elsif ($dropMenu eq 'reset status'
 2982: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2983: 	    foreach my $key (keys(%record)) {
 2984: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2985: 	    }
 2986: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2987: 		"$env{'user.name'}:$env{'user.domain'}";
 2988:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2989: 
 2990:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2991: 					       [$new_part]);
 2992:             my $aggtries =$totaltries;
 2993:             if ($last_resets{$new_part}) {
 2994:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2995: 					   $new_part);
 2996:             }
 2997: 
 2998:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2999:             if ($aggtries > 0) {
 3000:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3001:                 $aggregateflag = 1;
 3002:             }
 3003: 	} elsif ($dropMenu eq '') {
 3004: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3005: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3006: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3007: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3008: 		next;
 3009: 	    }
 3010: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3011: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3012: 	    my $partial= $pts/$wgt;
 3013: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3014: 		#do not update score for part if not changed.
 3015:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3016: 		next;
 3017: 	    } else {
 3018: 	        push(@parts_graded,$new_part);
 3019: 	    }
 3020: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3021: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3022: 	    }
 3023: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3024: 	    if ($partial == 0) {
 3025: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3026: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3027: 		}
 3028: 	    } else {
 3029: 		if ($record{$reckey} ne 'correct_by_override') {
 3030: 		    $newrecord{$reckey} = 'correct_by_override';
 3031: 		}
 3032: 	    }	    
 3033: 	    if ($submitter && 
 3034: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3035: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3036: 	    }
 3037: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3038: 		"$env{'user.name'}:$env{'user.domain'}";
 3039: 	}
 3040: 	# unless problem has been graded, set flag to version the submitted files
 3041: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3042: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3043: 	        $dropMenu eq 'reset status')
 3044: 	   {
 3045: 	    push(@version_parts,$new_part);
 3046: 	}
 3047:     }
 3048:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3049:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3050: 
 3051:     if (%newrecord) {
 3052:         if (@version_parts) {
 3053:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3054:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3055: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3056: 	    foreach my $new_part (@version_parts) {
 3057: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3058: 				$new_part,\%newrecord);
 3059: 	    }
 3060:         }
 3061: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3062: 				$env{'request.course.id'},$domain,$stuname);
 3063: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3064: 				     $cdom,$cnum,$domain,$stuname);
 3065:     }
 3066:     if ($aggregateflag) {
 3067:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3068: 			      $cdom,$cnum);
 3069:     }
 3070:     return ('',$pts,$wgt);
 3071: }
 3072: 
 3073: sub check_and_remove_from_queue {
 3074:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3075:     my @ungraded_parts;
 3076:     foreach my $part (@{$parts}) {
 3077: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3078: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3079: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3080: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3081: 		) {
 3082: 	    push(@ungraded_parts, $part);
 3083: 	}
 3084:     }
 3085:     if ( !@ungraded_parts ) {
 3086: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3087: 					       $cnum,$domain,$stuname);
 3088:     }
 3089: }
 3090: 
 3091: sub handback_files {
 3092:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3093:     my $portfolio_root = '/userfiles/portfolio';
 3094:     my $res_error;
 3095:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3096:     if ($res_error) {
 3097:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3098:         return;
 3099:     }
 3100:     my @handedback;
 3101:     my $file_msg;
 3102:     my @part_response_id = &flatten_responseType($responseType);
 3103:     foreach my $part_response_id (@part_response_id) {
 3104:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3105: 	my $part_resp = join('_',@{ $part_response_id });
 3106:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3107:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3108:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3109:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3110:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3111:                     my ($directory,$answer_file) = 
 3112:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3113:                     my ($answer_name,$answer_ver,$answer_ext) =
 3114: 		        &file_name_version_ext($answer_file);
 3115: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3116:                     my $getpropath = 1;
 3117:                     my ($dir_list,$listerror) = 
 3118:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3119:                                                  $domain,$stuname,$getpropath);
 3120: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3121:                     # fix filename
 3122:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3123:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3124:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3125:             	                                $save_file_name);
 3126:                     if ($result !~ m|^/uploaded/|) {
 3127:                         $request->print('<br /><span class="LC_error">'.
 3128:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3129:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3130:                                         '</span>');
 3131:                     } else {
 3132:                         # mark the file as read only
 3133:                         push(@handedback,$save_file_name);
 3134: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3135: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3136: 			}
 3137:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3138: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3139:                     }
 3140:                     $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>'));
 3141:                 }
 3142:             }
 3143:         }
 3144:     }
 3145:     if (@handedback > 0) {
 3146:         $request->print('<br />');
 3147:         my @what = ($symb,$env{'request.course.id'},'handback');
 3148:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3149:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3150:         my ($subject,$message);
 3151:         if (scalar(@handedback) == 1) {
 3152:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3153:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3154:         } else {
 3155:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3156:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3157:         }
 3158:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3159:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3160:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3161:         my ($feedurl,$showsymb) =
 3162:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3163:         my $restitle = &Apache::lonnet::gettitle($symb);
 3164:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3165:         my $msgstatus =
 3166:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3167:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3168:                  $restitle);
 3169:         if ($msgstatus) {
 3170:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3171:         }
 3172:     }
 3173:     return;
 3174: }
 3175: 
 3176: sub get_feedurl_and_symb {
 3177:     my ($symb,$uname,$udom) = @_;
 3178:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3179:     $url = &Apache::lonnet::clutter($url);
 3180:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3181: 					$symb,$udom,$uname);
 3182:     if ($encrypturl =~ /^yes$/i) {
 3183: 	&Apache::lonenc::encrypted(\$url,1);
 3184: 	&Apache::lonenc::encrypted(\$symb,1);
 3185:     }
 3186:     return ($url,$symb);
 3187: }
 3188: 
 3189: sub get_submitted_files {
 3190:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3191:     my @files;
 3192:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3193:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3194:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3195:     	    push(@files,$file_url.$file);
 3196:         }
 3197:     }
 3198:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3199:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3200:     }
 3201:     return (\@files);
 3202: }
 3203: 
 3204: # ----------- Provides number of tries since last reset.
 3205: sub get_num_tries {
 3206:     my ($record,$last_reset,$part) = @_;
 3207:     my $timestamp = '';
 3208:     my $num_tries = 0;
 3209:     if ($$record{'version'}) {
 3210:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3211:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3212:                 $timestamp = $$record{$version.':timestamp'};
 3213:                 if ($timestamp > $last_reset) {
 3214:                     $num_tries ++;
 3215:                 } else {
 3216:                     last;
 3217:                 }
 3218:             }
 3219:         }
 3220:     }
 3221:     return $num_tries;
 3222: }
 3223: 
 3224: # ----------- Determine decrements required in aggregate totals 
 3225: sub decrement_aggs {
 3226:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3227:     my %decrement = (
 3228:                         attempts => 0,
 3229:                         users => 0,
 3230:                         correct => 0
 3231:                     );
 3232:     $decrement{'attempts'} = $aggtries;
 3233:     if ($solvedstatus =~ /^correct/) {
 3234:         $decrement{'correct'} = 1;
 3235:     }
 3236:     if ($aggtries == $totaltries) {
 3237:         $decrement{'users'} = 1;
 3238:     }
 3239:     foreach my $type (keys(%decrement)) {
 3240:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3241:     }
 3242:     return;
 3243: }
 3244: 
 3245: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3246: sub get_last_resets {
 3247:     my ($symb,$courseid,$partids) =@_;
 3248:     my %last_resets;
 3249:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3250:     my $cname = $env{'course.'.$courseid.'.num'};
 3251:     my @keys;
 3252:     foreach my $part (@{$partids}) {
 3253: 	push(@keys,"$symb\0$part\0resettime");
 3254:     }
 3255:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3256: 				     $cdom,$cname);
 3257:     foreach my $part (@{$partids}) {
 3258: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3259:     }
 3260:     return %last_resets;
 3261: }
 3262: 
 3263: # ----------- Handles creating versions for portfolio files as answers
 3264: sub version_portfiles {
 3265:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3266:     my $version_parts = join('|',@$v_flag);
 3267:     my @returned_keys;
 3268:     my $parts = join('|', @$parts_graded);
 3269:     my $portfolio_root = '/userfiles/portfolio';
 3270:     foreach my $key (keys(%$record)) {
 3271:         my $new_portfiles;
 3272:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3273:             my @versioned_portfiles;
 3274:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3275:             foreach my $file (@portfiles) {
 3276:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3277:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3278: 		my ($answer_name,$answer_ver,$answer_ext) =
 3279: 		    &file_name_version_ext($answer_file);
 3280:                 my $getpropath = 1;    
 3281:                 my ($dir_list,$listerror) = 
 3282:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3283:                                              $stu_name,$getpropath);
 3284:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3285:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3286:                 if ($new_answer ne 'problem getting file') {
 3287:                     push(@versioned_portfiles, $directory.$new_answer);
 3288:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3289:                         [$directory.$new_answer],
 3290:                         [$symb,$env{'request.course.id'},'graded']);
 3291:                 }
 3292:             }
 3293:             $$record{$key} = join(',',@versioned_portfiles);
 3294:             push(@returned_keys,$key);
 3295:         }
 3296:     } 
 3297:     return (@returned_keys);   
 3298: }
 3299: 
 3300: sub get_next_version {
 3301:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3302:     my $version;
 3303:     if (ref($dir_list) eq 'ARRAY') {
 3304:         foreach my $row (@{$dir_list}) {
 3305:             my ($file) = split(/\&/,$row,2);
 3306:             my ($file_name,$file_version,$file_ext) =
 3307: 	        &file_name_version_ext($file);
 3308:             if (($file_name eq $answer_name) && 
 3309: 	        ($file_ext eq $answer_ext)) {
 3310:                      # gets here if filename and extension match, 
 3311:                      # regardless of version
 3312:                 if ($file_version ne '') {
 3313:                     # a versioned file is found  so save it for later
 3314:                     if ($file_version > $version) {
 3315: 		        $version = $file_version;
 3316: 	            }
 3317:                 }
 3318:             }
 3319:         }
 3320:     }
 3321:     $version ++;
 3322:     return($version);
 3323: }
 3324: 
 3325: sub version_selected_portfile {
 3326:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3327:     my ($answer_name,$answer_ver,$answer_ext) =
 3328:         &file_name_version_ext($file_name);
 3329:     my $new_answer;
 3330:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3331:     if($env{'form.copy'} eq '-1') {
 3332:         $new_answer = 'problem getting file';
 3333:     } else {
 3334:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3335:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3336:                             $stu_name,$domain,'copy',
 3337: 		        '/portfolio'.$directory.$new_answer);
 3338:     }    
 3339:     return ($new_answer);
 3340: }
 3341: 
 3342: sub file_name_version_ext {
 3343:     my ($file)=@_;
 3344:     my @file_parts = split(/\./, $file);
 3345:     my ($name,$version,$ext);
 3346:     if (@file_parts > 1) {
 3347: 	$ext=pop(@file_parts);
 3348: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3349: 	    $version=pop(@file_parts);
 3350: 	}
 3351: 	$name=join('.',@file_parts);
 3352:     } else {
 3353: 	$name=join('.',@file_parts);
 3354:     }
 3355:     return($name,$version,$ext);
 3356: }
 3357: 
 3358: #--------------------------------------------------------------------------------------
 3359: #
 3360: #-------------------------- Next few routines handles grading by section or whole class
 3361: #
 3362: #--- Javascript to handle grading by section or whole class
 3363: sub viewgrades_js {
 3364:     my ($request) = shift;
 3365: 
 3366:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3367:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3368:    function writePoint(partid,weight,point) {
 3369: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3370: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3371: 	if (point == "textval") {
 3372: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3373: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3374: 		alert("$alertmsg"+parseFloat(point));
 3375: 		var resetbox = false;
 3376: 		for (var i=0; i<radioButton.length; i++) {
 3377: 		    if (radioButton[i].checked) {
 3378: 			textbox.value = i;
 3379: 			resetbox = true;
 3380: 		    }
 3381: 		}
 3382: 		if (!resetbox) {
 3383: 		    textbox.value = "";
 3384: 		}
 3385: 		return;
 3386: 	    }
 3387: 	    if (parseFloat(point) > parseFloat(weight)) {
 3388: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3389: 				   ") greater than the weight for the part. Accept?");
 3390: 		if (resp == false) {
 3391: 		    textbox.value = "";
 3392: 		    return;
 3393: 		}
 3394: 	    }
 3395: 	    for (var i=0; i<radioButton.length; i++) {
 3396: 		radioButton[i].checked=false;
 3397: 		if (parseFloat(point) == i) {
 3398: 		    radioButton[i].checked=true;
 3399: 		}
 3400: 	    }
 3401: 
 3402: 	} else {
 3403: 	    textbox.value = parseFloat(point);
 3404: 	}
 3405: 	for (i=0;i<document.classgrade.total.value;i++) {
 3406: 	    var user = document.classgrade["ctr"+i].value;
 3407: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3408: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3409: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3410: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3411: 	    if (saveval != "correct") {
 3412: 		scorename.value = point;
 3413: 		if (selname[0].selected != true) {
 3414: 		    selname[0].selected = true;
 3415: 		}
 3416: 	    }
 3417: 	}
 3418: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3419:     }
 3420: 
 3421:     function writeRadText(partid,weight) {
 3422: 	var selval   = document.classgrade["SELVAL_"+partid];
 3423: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3424:         var override = document.classgrade["FORCE_"+partid].checked;
 3425: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3426: 	if (selval[1].selected || selval[2].selected) {
 3427: 	    for (var i=0; i<radioButton.length; i++) {
 3428: 		radioButton[i].checked=false;
 3429: 
 3430: 	    }
 3431: 	    textbox.value = "";
 3432: 
 3433: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3434: 		var user = document.classgrade["ctr"+i].value;
 3435: 		user = user.replace(new RegExp(':', 'g'),"_");
 3436: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3437: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3438: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3439: 		if ((saveval != "correct") || override) {
 3440: 		    scorename.value = "";
 3441: 		    if (selval[1].selected) {
 3442: 			selname[1].selected = true;
 3443: 		    } else {
 3444: 			selname[2].selected = true;
 3445: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3446: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3447: 		    }
 3448: 		}
 3449: 	    }
 3450: 	} else {
 3451: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3452: 		var user = document.classgrade["ctr"+i].value;
 3453: 		user = user.replace(new RegExp(':', 'g'),"_");
 3454: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3455: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3456: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3457: 		if ((saveval != "correct") || override) {
 3458: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3459: 		    selname[0].selected = true;
 3460: 		}
 3461: 	    }
 3462: 	}	    
 3463:     }
 3464: 
 3465:     function changeSelect(partid,user) {
 3466: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3467: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3468: 	var point  = textbox.value;
 3469: 	var weight = document.classgrade["weight_"+partid].value;
 3470: 
 3471: 	if (isNaN(point) || parseFloat(point) < 0) {
 3472: 	    alert("$alertmsg"+parseFloat(point));
 3473: 	    textbox.value = "";
 3474: 	    return;
 3475: 	}
 3476: 	if (parseFloat(point) > parseFloat(weight)) {
 3477: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3478: 			       ") greater than the weight of the part. Accept?");
 3479: 	    if (resp == false) {
 3480: 		textbox.value = "";
 3481: 		return;
 3482: 	    }
 3483: 	}
 3484: 	selval[0].selected = true;
 3485:     }
 3486: 
 3487:     function changeOneScore(partid,user) {
 3488: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3489: 	if (selval[1].selected || selval[2].selected) {
 3490: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3491: 	    if (selval[2].selected) {
 3492: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3493: 	    }
 3494:         }
 3495:     }
 3496: 
 3497:     function resetEntry(numpart) {
 3498: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3499: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3500: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3501: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3502: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3503: 	    for (var i=0; i<radioButton.length; i++) {
 3504: 		radioButton[i].checked=false;
 3505: 
 3506: 	    }
 3507: 	    textbox.value = "";
 3508: 	    selval[0].selected = true;
 3509: 
 3510: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3511: 		var user = document.classgrade["ctr"+i].value;
 3512: 		user = user.replace(new RegExp(':', 'g'),"_");
 3513: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3514: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3515: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3516: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3517: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3518: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3519: 		if (saveselval == "excused") {
 3520: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3521: 		} else {
 3522: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3523: 		}
 3524: 	    }
 3525: 	}
 3526:     }
 3527: 
 3528: VIEWJAVASCRIPT
 3529: }
 3530: 
 3531: #--- show scores for a section or whole class w/ option to change/update a score
 3532: sub viewgrades {
 3533:     my ($request,$symb) = @_;
 3534:     &viewgrades_js($request);
 3535: 
 3536:     #need to make sure we have the correct data for later EXT calls, 
 3537:     #thus invalidate the cache
 3538:     &Apache::lonnet::devalidatecourseresdata(
 3539:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3540:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3541:     &Apache::lonnet::clear_EXT_cache_status();
 3542: 
 3543:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3544: 
 3545:     #view individual student submission form - called using Javascript viewOneStudent
 3546:     $result.=&jscriptNform($symb);
 3547: 
 3548:     #beginning of class grading form
 3549:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3550:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3551: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3552: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3553: 	&build_section_inputs().
 3554: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3555: 
 3556:     my ($common_header,$specific_header);
 3557:     if ($env{'form.section'} eq 'all') {
 3558: 	$common_header = &mt('Assign Common Grade to Class');
 3559:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3560:     } elsif ($env{'form.section'} eq 'none') {
 3561:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3562: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3563:     } else {
 3564:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3565:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3566: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3567:     }
 3568:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3569:     #radio buttons/text box for assigning points for a section or class.
 3570:     #handles different parts of a problem
 3571:     my $res_error;
 3572:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3573:     if ($res_error) {
 3574:         return &navmap_errormsg();
 3575:     }
 3576:     my %weight = ();
 3577:     my $ctsparts = 0;
 3578:     my %seen = ();
 3579:     my @part_response_id = &flatten_responseType($responseType);
 3580:     foreach my $part_response_id (@part_response_id) {
 3581:     	my ($partid,$respid) = @{ $part_response_id };
 3582: 	my $part_resp = join('_',@{ $part_response_id });
 3583: 	next if $seen{$partid};
 3584: 	$seen{$partid}++;
 3585: 	my $handgrade=$$handgrade{$part_resp};
 3586: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3587: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3588: 
 3589: 	my $display_part=&get_display_part($partid,$symb);
 3590: 	my $radio.='<table border="0"><tr>';  
 3591: 	my $ctr = 0;
 3592: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3593: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3594: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3595: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3596: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3597: 	    $ctr++;
 3598: 	}
 3599: 	$radio.='</tr></table>';
 3600: 	my $line = '<input type="text" name="TEXTVAL_'.
 3601: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3602: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3603: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3604:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3605:             '<select name="SELVAL_'.$partid.'" '.
 3606:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3607:                 $weight{$partid}.')"> '.
 3608: 	    '<option selected="selected"> </option>'.
 3609: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3610: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3611: 	    '</select></td>'.
 3612:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3613: 	$line.='<input type="hidden" name="partid_'.
 3614: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3615: 	$line.='<input type="hidden" name="weight_'.
 3616: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3617: 
 3618: 	$result.=
 3619: 	    &Apache::loncommon::start_data_table_row()."\n".
 3620: 	    '<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>'.
 3621: 	    &Apache::loncommon::end_data_table_row()."\n";
 3622: 	$ctsparts++;
 3623:     }
 3624:     $result.=&Apache::loncommon::end_data_table()."\n".
 3625: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3626:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3627: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3628: 
 3629:     #table listing all the students in a section/class
 3630:     #header of table
 3631:     $result.= '<h3>'.$specific_header.'</h3>'.
 3632:               &Apache::loncommon::start_data_table().
 3633: 	      &Apache::loncommon::start_data_table_header_row().
 3634: 	      '<th>'.&mt('No.').'</th>'.
 3635: 	      '<th>'.&nameUserString('header')."</th>\n";
 3636:     my $partserror;
 3637:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3638:     if ($partserror) {
 3639:         return &navmap_errormsg();
 3640:     }
 3641:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3642:     my @partids = ();
 3643:     foreach my $part (@parts) {
 3644: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3645:         my $narrowtext = &mt('Tries');
 3646: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3647: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3648: 	my ($partid) = &split_part_type($part);
 3649:         push(@partids,$partid);
 3650: #
 3651: # FIXME: Looks like $display looks at English text
 3652: #
 3653: 	my $display_part=&get_display_part($partid,$symb);
 3654: 	if ($display =~ /^Partial Credit Factor/) {
 3655: 	    $result.='<th>'.
 3656: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3657: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3658: 	    next;
 3659: 	    
 3660: 	} else {
 3661: 	    if ($display =~ /Problem Status/) {
 3662: 		my $grade_status_mt = &mt('Grade Status');
 3663: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3664: 	    }
 3665: 	    my $part_mt = &mt('Part:');
 3666: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3667: 	}
 3668: 
 3669: 	$result.='<th>'.$display.'</th>'."\n";
 3670:     }
 3671:     $result.=&Apache::loncommon::end_data_table_header_row();
 3672: 
 3673:     my %last_resets = 
 3674: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3675: 
 3676:     #get info for each student
 3677:     #list all the students - with points and grade status
 3678:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3679:     my $ctr = 0;
 3680:     foreach (sort 
 3681: 	     {
 3682: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3683: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3684: 		 }
 3685: 		 return $a cmp $b;
 3686: 	     } (keys(%$fullname))) {
 3687: 	$ctr++;
 3688: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3689: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3690:     }
 3691:     $result.=&Apache::loncommon::end_data_table();
 3692:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3693:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3694: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3695:     if (scalar(%$fullname) eq 0) {
 3696: 	my $colspan=3+scalar(@parts);
 3697: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3698:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3699: 	$result='<span class="LC_warning">'.
 3700: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3701: 	        $section_display, $stu_status).
 3702: 	    '</span>';
 3703:     }
 3704:     return $result;
 3705: }
 3706: 
 3707: #--- call by previous routine to display each student
 3708: sub viewstudentgrade {
 3709:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3710:     my ($uname,$udom) = split(/:/,$student);
 3711:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3712:     my %aggregates = (); 
 3713:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3714: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3715: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3716: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3717: 	'\');" target="_self">'.$fullname.'</a> '.
 3718: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3719:     $student=~s/:/_/; # colon doen't work in javascript for names
 3720:     foreach my $apart (@$parts) {
 3721: 	my ($part,$type) = &split_part_type($apart);
 3722: 	my $score=$record{"resource.$part.$type"};
 3723:         $result.='<td align="center">';
 3724:         my ($aggtries,$totaltries);
 3725:         unless (exists($aggregates{$part})) {
 3726: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3727: 
 3728: 	    $aggtries = $totaltries;
 3729:             if ($$last_resets{$part}) {  
 3730:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3731: 					   $part);
 3732:             }
 3733:             $result.='<input type="hidden" name="'.
 3734:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3735:             $result.='<input type="hidden" name="'.
 3736:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3737:             $aggregates{$part} = 1;
 3738:         }
 3739: 	if ($type eq 'awarded') {
 3740: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3741: 	    $result.='<input type="hidden" name="'.
 3742: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3743: 	    $result.='<input type="text" name="'.
 3744: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3745:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3746: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3747: 	} elsif ($type eq 'solved') {
 3748: 	    my ($status,$foo)=split(/_/,$score,2);
 3749: 	    $status = 'nothing' if ($status eq '');
 3750: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3751: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3752: 	    $result.='&nbsp;<select name="'.
 3753: 		'GD_'.$student.'_'.$part.'_solved" '.
 3754:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3755: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3756: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3757: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3758: 	    $result.="</select>&nbsp;</td>\n";
 3759: 	} else {
 3760: 	    $result.='<input type="hidden" name="'.
 3761: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3762: 		    "\n";
 3763: 	    $result.='<input type="text" name="'.
 3764: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3765: 		'value="'.$score.'" size="4" /></td>'."\n";
 3766: 	}
 3767:     }
 3768:     $result.=&Apache::loncommon::end_data_table_row();
 3769:     return $result;
 3770: }
 3771: 
 3772: #--- change scores for all the students in a section/class
 3773: #    record does not get update if unchanged
 3774: sub editgrades {
 3775:     my ($request,$symb) = @_;
 3776: 
 3777:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3778:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3779:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3780: 
 3781:     my $result= &Apache::loncommon::start_data_table().
 3782: 	&Apache::loncommon::start_data_table_header_row().
 3783: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3784: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3785:     my %scoreptr = (
 3786: 		    'correct'  =>'correct_by_override',
 3787: 		    'incorrect'=>'incorrect_by_override',
 3788: 		    'excused'  =>'excused',
 3789: 		    'ungraded' =>'ungraded_attempted',
 3790:                     'credited' =>'credit_attempted',
 3791: 		    'nothing'  => '',
 3792: 		    );
 3793:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3794: 
 3795:     my (@partid);
 3796:     my %weight = ();
 3797:     my %columns = ();
 3798:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3799: 
 3800:     my $partserror;
 3801:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3802:     if ($partserror) {
 3803:         return &navmap_errormsg();
 3804:     }
 3805:     my $header;
 3806:     while ($ctr < $env{'form.totalparts'}) {
 3807: 	my $partid = $env{'form.partid_'.$ctr};
 3808: 	push(@partid,$partid);
 3809: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3810: 	$ctr++;
 3811:     }
 3812:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3813:     foreach my $partid (@partid) {
 3814: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3815: 	    '<th align="center">'.&mt('New Score').'</th>';
 3816: 	$columns{$partid}=2;
 3817: 	foreach my $stores (@parts) {
 3818: 	    my ($part,$type) = &split_part_type($stores);
 3819: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3820: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3821: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3822: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3823:             my $narrowtext = &mt('Tries');
 3824: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3825: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3826: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3827: 	    $columns{$partid}+=2;
 3828: 	}
 3829:     }
 3830:     foreach my $partid (@partid) {
 3831: 	my $display_part=&get_display_part($partid,$symb);
 3832: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3833: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3834: 	    '</th>';
 3835: 
 3836:     }
 3837:     $result .= &Apache::loncommon::end_data_table_header_row().
 3838: 	&Apache::loncommon::start_data_table_header_row().
 3839: 	$header.
 3840: 	&Apache::loncommon::end_data_table_header_row();
 3841:     my @noupdate;
 3842:     my ($updateCtr,$noupdateCtr) = (1,1);
 3843:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3844: 	my $line;
 3845: 	my $user = $env{'form.ctr'.$i};
 3846: 	my ($uname,$udom)=split(/:/,$user);
 3847: 	my %newrecord;
 3848: 	my $updateflag = 0;
 3849: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3850: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3851: 	if (!&canmodify($usec)) {
 3852: 	    my $numcols=scalar(@partid)*4+2;
 3853: 	    push(@noupdate,
 3854: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3855: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3856: 	    next;
 3857: 	}
 3858:         my %aggregate = ();
 3859:         my $aggregateflag = 0;
 3860: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3861: 	foreach (@partid) {
 3862: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3863: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3864: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3865: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3866: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3867: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3868: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3869: 	    my $score;
 3870: 	    if ($partial eq '') {
 3871: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3872: 	    } elsif ($partial > 0) {
 3873: 		$score = 'correct_by_override';
 3874: 	    } elsif ($partial == 0) {
 3875: 		$score = 'incorrect_by_override';
 3876: 	    }
 3877: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3878: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3879: 
 3880: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3881: 		"$env{'user.name'}:$env{'user.domain'}";
 3882: 	    if ($dropMenu eq 'reset status' &&
 3883: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3884: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3885: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3886: 		$newrecord{'resource.'.$_.'.award'} = '';
 3887: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3888: 		$updateflag = 1;
 3889:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3890:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3891:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3892:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3893:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3894:                     $aggregateflag = 1;
 3895:                 }
 3896: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3897: 		$updateflag = 1;
 3898: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3899: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3900: 		$rec_update++;
 3901: 	    }
 3902: 
 3903: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3904: 		'<td align="center">'.$awarded.
 3905: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3906: 
 3907: 
 3908: 	    my $partid=$_;
 3909: 	    foreach my $stores (@parts) {
 3910: 		my ($part,$type) = &split_part_type($stores);
 3911: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3912: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3913: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3914: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3915: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3916: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3917: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3918: 		    $updateflag=1;
 3919: 		}
 3920: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3921: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3922: 	    }
 3923: 	}
 3924: 	$line.="\n";
 3925: 
 3926: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3927: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3928: 
 3929: 	if ($updateflag) {
 3930: 	    $count++;
 3931: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3932: 				    $udom,$uname);
 3933: 
 3934: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3935: 					      $cnum,$udom,$uname)) {
 3936: 		# need to figure out if should be in queue.
 3937: 		my %record =  
 3938: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3939: 					     $udom,$uname);
 3940: 		my $all_graded = 1;
 3941: 		my $none_graded = 1;
 3942: 		foreach my $part (@parts) {
 3943: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3944: 			$all_graded = 0;
 3945: 		    } else {
 3946: 			$none_graded = 0;
 3947: 		    }
 3948: 		}
 3949: 
 3950: 		if ($all_graded || $none_graded) {
 3951: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3952: 							   $symb,$cdom,$cnum,
 3953: 							   $udom,$uname);
 3954: 		}
 3955: 	    }
 3956: 
 3957: 	    $result.=&Apache::loncommon::start_data_table_row().
 3958: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3959: 		&Apache::loncommon::end_data_table_row();
 3960: 	    $updateCtr++;
 3961: 	} else {
 3962: 	    push(@noupdate,
 3963: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3964: 	    $noupdateCtr++;
 3965: 	}
 3966:         if ($aggregateflag) {
 3967:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3968: 				  $cdom,$cnum);
 3969:         }
 3970:     }
 3971:     if (@noupdate) {
 3972: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3973: 	my $numcols=scalar(@partid)*4+2;
 3974: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3975: 	    '<td align="center" colspan="'.$numcols.'">'.
 3976: 	    &mt('No Changes Occurred For the Students Below').
 3977: 	    '</td>'.
 3978: 	    &Apache::loncommon::end_data_table_row();
 3979: 	foreach my $line (@noupdate) {
 3980: 	    $result.=
 3981: 		&Apache::loncommon::start_data_table_row().
 3982: 		$line.
 3983: 		&Apache::loncommon::end_data_table_row();
 3984: 	}
 3985:     }
 3986:     $result .= &Apache::loncommon::end_data_table();
 3987:     my $msg = '<p><b>'.
 3988: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3989: 	    $rec_update,$count).'</b><br />'.
 3990: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3991: 	'</b></p>';
 3992:     return $title.$msg.$result;
 3993: }
 3994: 
 3995: sub split_part_type {
 3996:     my ($partstr) = @_;
 3997:     my ($temp,@allparts)=split(/_/,$partstr);
 3998:     my $type=pop(@allparts);
 3999:     my $part=join('_',@allparts);
 4000:     return ($part,$type);
 4001: }
 4002: 
 4003: #------------- end of section for handling grading by section/class ---------
 4004: #
 4005: #----------------------------------------------------------------------------
 4006: 
 4007: 
 4008: #----------------------------------------------------------------------------
 4009: #
 4010: #-------------------------- Next few routines handles grading by csv upload
 4011: #
 4012: #--- Javascript to handle csv upload
 4013: sub csvupload_javascript_reverse_associate {
 4014:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4015:     my $error2=&mt('You need to specify at least one grading field');
 4016:   return(<<ENDPICK);
 4017:   function verify(vf) {
 4018:     var foundsomething=0;
 4019:     var founduname=0;
 4020:     var foundID=0;
 4021:     for (i=0;i<=vf.nfields.value;i++) {
 4022:       tw=eval('vf.f'+i+'.selectedIndex');
 4023:       if (i==0 && tw!=0) { foundID=1; }
 4024:       if (i==1 && tw!=0) { founduname=1; }
 4025:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4026:     }
 4027:     if (founduname==0 && foundID==0) {
 4028: 	alert('$error1');
 4029: 	return;
 4030:     }
 4031:     if (foundsomething==0) {
 4032: 	alert('$error2');
 4033: 	return;
 4034:     }
 4035:     vf.submit();
 4036:   }
 4037:   function flip(vf,tf) {
 4038:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4039:     var i;
 4040:     for (i=0;i<=vf.nfields.value;i++) {
 4041:       //can not pick the same destination field for both name and domain
 4042:       if (((i ==0)||(i ==1)) && 
 4043:           ((tf==0)||(tf==1)) && 
 4044:           (i!=tf) &&
 4045:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4046:         eval('vf.f'+i+'.selectedIndex=0;')
 4047:       }
 4048:     }
 4049:   }
 4050: ENDPICK
 4051: }
 4052: 
 4053: sub csvupload_javascript_forward_associate {
 4054:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4055:     my $error2=&mt('You need to specify at least one grading field');
 4056:   return(<<ENDPICK);
 4057:   function verify(vf) {
 4058:     var foundsomething=0;
 4059:     var founduname=0;
 4060:     var foundID=0;
 4061:     for (i=0;i<=vf.nfields.value;i++) {
 4062:       tw=eval('vf.f'+i+'.selectedIndex');
 4063:       if (tw==1) { foundID=1; }
 4064:       if (tw==2) { founduname=1; }
 4065:       if (tw>3) { foundsomething=1; }
 4066:     }
 4067:     if (founduname==0 && foundID==0) {
 4068: 	alert('$error1');
 4069: 	return;
 4070:     }
 4071:     if (foundsomething==0) {
 4072: 	alert('$error2');
 4073: 	return;
 4074:     }
 4075:     vf.submit();
 4076:   }
 4077:   function flip(vf,tf) {
 4078:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4079:     var i;
 4080:     //can not pick the same destination field twice
 4081:     for (i=0;i<=vf.nfields.value;i++) {
 4082:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4083:         eval('vf.f'+i+'.selectedIndex=0;')
 4084:       }
 4085:     }
 4086:   }
 4087: ENDPICK
 4088: }
 4089: 
 4090: sub csvuploadmap_header {
 4091:     my ($request,$symb,$datatoken,$distotal)= @_;
 4092:     my $javascript;
 4093:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4094: 	$javascript=&csvupload_javascript_reverse_associate();
 4095:     } else {
 4096: 	$javascript=&csvupload_javascript_forward_associate();
 4097:     }
 4098: 
 4099:     $symb = &Apache::lonenc::check_encrypt($symb);
 4100:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4101:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4102:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4103:     my $reverse=&mt("Reverse Association");
 4104:     $request->print(<<ENDPICK);
 4105: <br />
 4106: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4107: <input type="hidden" name="associate"  value="" />
 4108: <input type="hidden" name="phase"      value="three" />
 4109: <input type="hidden" name="datatoken"  value="$datatoken" />
 4110: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4111: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4112: <input type="hidden" name="upfile_associate" 
 4113:                                        value="$env{'form.upfile_associate'}" />
 4114: <input type="hidden" name="symb"       value="$symb" />
 4115: <input type="hidden" name="command"    value="csvuploadoptions" />
 4116: <hr />
 4117: ENDPICK
 4118:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4119:     return '';
 4120: 
 4121: }
 4122: 
 4123: sub csvupload_fields {
 4124:     my ($symb,$errorref) = @_;
 4125:     my (@parts) = &getpartlist($symb,$errorref);
 4126:     if (ref($errorref)) {
 4127:         if ($$errorref) {
 4128:             return;
 4129:         }
 4130:     }
 4131: 
 4132:     my @fields=(['ID','Student/Employee ID'],
 4133: 		['username','Student Username'],
 4134: 		['domain','Student Domain']);
 4135:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4136:     foreach my $part (sort(@parts)) {
 4137: 	my @datum;
 4138: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4139: 	my $name=$part;
 4140: 	if  (!$display) { $display = $name; }
 4141: 	@datum=($name,$display);
 4142: 	if ($name=~/^stores_(.*)_awarded/) {
 4143: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4144: 	}
 4145: 	push(@fields,\@datum);
 4146:     }
 4147:     return (@fields);
 4148: }
 4149: 
 4150: sub csvuploadmap_footer {
 4151:     my ($request,$i,$keyfields) =@_;
 4152:     my $buttontext = &mt('Assign Grades');
 4153:     $request->print(<<ENDPICK);
 4154: </table>
 4155: <input type="hidden" name="nfields" value="$i" />
 4156: <input type="hidden" name="keyfields" value="$keyfields" />
 4157: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4158: </form>
 4159: ENDPICK
 4160: }
 4161: 
 4162: sub checkforfile_js {
 4163:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4164:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4165:     function checkUpload(formname) {
 4166: 	if (formname.upfile.value == "") {
 4167: 	    alert("$alertmsg");
 4168: 	    return false;
 4169: 	}
 4170: 	formname.submit();
 4171:     }
 4172: CSVFORMJS
 4173:     return $result;
 4174: }
 4175: 
 4176: sub upcsvScores_form {
 4177:     my ($request,$symb) = @_;
 4178:     if (!$symb) {return '';}
 4179:     my $result=&checkforfile_js();
 4180:     $result.=&Apache::loncommon::start_data_table().
 4181:              &Apache::loncommon::start_data_table_header_row().
 4182:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4183:              &Apache::loncommon::end_data_table_header_row().
 4184:              &Apache::loncommon::start_data_table_row().'<td>';
 4185:     my $upload=&mt("Upload Scores");
 4186:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4187:     my $ignore=&mt('Ignore First Line');
 4188:     $symb = &Apache::lonenc::check_encrypt($symb);
 4189:     $result.=<<ENDUPFORM;
 4190: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4191: <input type="hidden" name="symb" value="$symb" />
 4192: <input type="hidden" name="command" value="csvuploadmap" />
 4193: $upfile_select
 4194: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4195: </form>
 4196: ENDUPFORM
 4197:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4198:                            &mt("How do I create a CSV file from a spreadsheet")).
 4199:              '</td>'.
 4200:             &Apache::loncommon::end_data_table_row().
 4201:             &Apache::loncommon::end_data_table();
 4202:     return $result;
 4203: }
 4204: 
 4205: 
 4206: sub csvuploadmap {
 4207:     my ($request,$symb)= @_;
 4208:     if (!$symb) {return '';}
 4209: 
 4210:     my $datatoken;
 4211:     if (!$env{'form.datatoken'}) {
 4212: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4213:     } else {
 4214: 	$datatoken=$env{'form.datatoken'};
 4215: 	&Apache::loncommon::load_tmp_file($request);
 4216:     }
 4217:     my @records=&Apache::loncommon::upfile_record_sep();
 4218:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4219:     my ($i,$keyfields);
 4220:     if (@records) {
 4221:         my $fieldserror;
 4222: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4223:         if ($fieldserror) {
 4224:             $request->print(&navmap_errormsg());
 4225:             return;
 4226:         }
 4227: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4228: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4229: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4230: 							  \@fields);
 4231: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4232: 	    chop($keyfields);
 4233: 	} else {
 4234: 	    unshift(@fields,['none','']);
 4235: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4236: 							    \@fields);
 4237:             foreach my $rec (@records) {
 4238:                 my %temp = &Apache::loncommon::record_sep($rec);
 4239:                 if (%temp) {
 4240:                     $keyfields=join(',',sort(keys(%temp)));
 4241:                     last;
 4242:                 }
 4243:             }
 4244: 	}
 4245:     }
 4246:     &csvuploadmap_footer($request,$i,$keyfields);
 4247: 
 4248:     return '';
 4249: }
 4250: 
 4251: sub csvuploadoptions {
 4252:     my ($request,$symb)= @_;
 4253:     my $overwrite=&mt('Overwrite any existing score');
 4254:     $request->print(<<ENDPICK);
 4255: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4256: <input type="hidden" name="command"    value="csvuploadassign" />
 4257: <p>
 4258: <label>
 4259:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4260:    $overwrite
 4261: </label>
 4262: </p>
 4263: ENDPICK
 4264:     my %fields=&get_fields();
 4265:     if (!defined($fields{'domain'})) {
 4266: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4267: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4268:     }
 4269:     foreach my $key (sort(keys(%env))) {
 4270: 	if ($key !~ /^form\.(.*)$/) { next; }
 4271: 	my $cleankey=$1;
 4272: 	if ($cleankey eq 'command') { next; }
 4273: 	$request->print('<input type="hidden" name="'.$cleankey.
 4274: 			'"  value="'.$env{$key}.'" />'."\n");
 4275:     }
 4276:     # FIXME do a check for any duplicated user ids...
 4277:     # FIXME do a check for any invalid user ids?...
 4278:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4279: <hr /></form>'."\n");
 4280:     return '';
 4281: }
 4282: 
 4283: sub get_fields {
 4284:     my %fields;
 4285:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4286:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4287: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4288: 	    if ($env{'form.f'.$i} ne 'none') {
 4289: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4290: 	    }
 4291: 	} else {
 4292: 	    if ($env{'form.f'.$i} ne 'none') {
 4293: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4294: 	    }
 4295: 	}
 4296:     }
 4297:     return %fields;
 4298: }
 4299: 
 4300: sub csvuploadassign {
 4301:     my ($request,$symb)= @_;
 4302:     if (!$symb) {return '';}
 4303:     my $error_msg = '';
 4304:     &Apache::loncommon::load_tmp_file($request);
 4305:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4306:     my %fields=&get_fields();
 4307:     my $courseid=$env{'request.course.id'};
 4308:     my ($classlist) = &getclasslist('all',0);
 4309:     my @notallowed;
 4310:     my @skipped;
 4311:     my @warnings;
 4312:     my $countdone=0;
 4313:     foreach my $grade (@gradedata) {
 4314: 	my %entries=&Apache::loncommon::record_sep($grade);
 4315: 	my $domain;
 4316: 	if ($entries{$fields{'domain'}}) {
 4317: 	    $domain=$entries{$fields{'domain'}};
 4318: 	} else {
 4319: 	    $domain=$env{'form.default_domain'};
 4320: 	}
 4321: 	$domain=~s/\s//g;
 4322: 	my $username=$entries{$fields{'username'}};
 4323: 	$username=~s/\s//g;
 4324: 	if (!$username) {
 4325: 	    my $id=$entries{$fields{'ID'}};
 4326: 	    $id=~s/\s//g;
 4327: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4328: 	    $username=$ids{$id};
 4329: 	}
 4330: 	if (!exists($$classlist{"$username:$domain"})) {
 4331: 	    my $id=$entries{$fields{'ID'}};
 4332: 	    $id=~s/\s//g;
 4333: 	    if ($id) {
 4334: 		push(@skipped,"$id:$domain");
 4335: 	    } else {
 4336: 		push(@skipped,"$username:$domain");
 4337: 	    }
 4338: 	    next;
 4339: 	}
 4340: 	my $usec=$classlist->{"$username:$domain"}[5];
 4341: 	if (!&canmodify($usec)) {
 4342: 	    push(@notallowed,"$username:$domain");
 4343: 	    next;
 4344: 	}
 4345: 	my %points;
 4346: 	my %grades;
 4347: 	foreach my $dest (keys(%fields)) {
 4348: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4349: 		$dest eq 'domain') { next; }
 4350: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4351: 	    if ($dest=~/stores_(.*)_points/) {
 4352: 		my $part=$1;
 4353: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4354: 					      $symb,$domain,$username);
 4355:                 if ($wgt) {
 4356:                     $entries{$fields{$dest}}=~s/\s//g;
 4357:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4358:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4359:                                           : 'correct_by_override';
 4360:                     if ($pcr>1) {
 4361:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4362:                     }
 4363:                     $grades{"resource.$part.awarded"}=$pcr;
 4364:                     $grades{"resource.$part.solved"}=$award;
 4365:                     $points{$part}=1;
 4366:                 } else {
 4367:                     $error_msg = "<br />" .
 4368:                         &mt("Some point values were assigned"
 4369:                             ." for problems with a weight "
 4370:                             ."of zero. These values were "
 4371:                             ."ignored.");
 4372:                 }
 4373: 	    } else {
 4374: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4375: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4376: 		my $store_key=$dest;
 4377: 		$store_key=~s/^stores/resource/;
 4378: 		$store_key=~s/_/\./g;
 4379: 		$grades{$store_key}=$entries{$fields{$dest}};
 4380: 	    }
 4381: 	}
 4382: 	if (! %grades) { 
 4383:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4384:         } else {
 4385: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4386: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4387: 					   $env{'request.course.id'},
 4388: 					   $domain,$username);
 4389: 	   if ($result eq 'ok') {
 4390: # Successfully stored
 4391: 	      $request->print('.');
 4392: # Remove from grading queue
 4393:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4394:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4395:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4396:                                              $domain,$username);
 4397:               $countdone++;
 4398:            } else {
 4399: 	      $request->print("<p><span class=\"LC_error\">".
 4400:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4401:                                   "$username:$domain",$result)."</span></p>");
 4402: 	   }
 4403: 	   $request->rflush();
 4404:         }
 4405:     }
 4406:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4407:     if (@warnings) {
 4408:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4409:         $request->print(join(', ',@warnings));
 4410:     }
 4411:     if (@skipped) {
 4412: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4413:         $request->print(join(', ',@skipped));
 4414:     }
 4415:     if (@notallowed) {
 4416: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4417: 	$request->print(join(', ',@notallowed));
 4418:     }
 4419:     $request->print("<br />\n");
 4420:     return $error_msg;
 4421: }
 4422: #------------- end of section for handling csv file upload ---------
 4423: #
 4424: #-------------------------------------------------------------------
 4425: #
 4426: #-------------- Next few routines handle grading by page/sequence
 4427: #
 4428: #--- Select a page/sequence and a student to grade
 4429: sub pickStudentPage {
 4430:     my ($request,$symb) = @_;
 4431: 
 4432:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4433:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4434: 
 4435: function checkPickOne(formname) {
 4436:     if (radioSelection(formname.student) == null) {
 4437: 	alert("$alertmsg");
 4438: 	return;
 4439:     }
 4440:     ptr = pullDownSelection(formname.selectpage);
 4441:     formname.page.value = formname["page"+ptr].value;
 4442:     formname.title.value = formname["title"+ptr].value;
 4443:     formname.submit();
 4444: }
 4445: 
 4446: LISTJAVASCRIPT
 4447:     &commonJSfunctions($request);
 4448: 
 4449:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4450:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4451:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4452: 
 4453:     my $result='<h3><span class="LC_info">&nbsp;'.
 4454: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4455: 
 4456:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4457:     my $map_error;
 4458:     my ($titles,$symbx) = &getSymbMap($map_error);
 4459:     if ($map_error) {
 4460:         $request->print(&navmap_errormsg());
 4461:         return; 
 4462:     }
 4463:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4464: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4465: #    my $type=($curpage =~ /\.(page|sequence)/);
 4466: 
 4467:     # Collection of hidden fields
 4468:     my $ctr=0;
 4469:     foreach (@$titles) {
 4470:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4471:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4472:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4473:         $ctr++;
 4474:     }
 4475:     $result.='<input type="hidden" name="page" />'."\n".
 4476:         '<input type="hidden" name="title" />'."\n";
 4477: 
 4478:     $result.=&build_section_inputs();
 4479:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4480:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4481: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4482: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4483: 
 4484:     # Show grading options
 4485:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4486:     my $select = '<select name="selectpage">'."\n";
 4487:     $ctr=0;
 4488:     foreach (@$titles) {
 4489: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4490: 	$select.='<option value="'.$ctr.'"'.
 4491: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4492: 	    '>'.$showtitle.'</option>'."\n";
 4493: 	$ctr++;
 4494:     }
 4495:     $select.= '</select>';
 4496: 
 4497:     $result.=
 4498:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4499:        .$select
 4500:        .&Apache::lonhtmlcommon::row_closure();
 4501: 
 4502:     $result.=
 4503:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4504:        .'<label><input type="radio" name="vProb" value="no"'
 4505:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4506:        .'<label><input type="radio" name="vProb" value="yes" />'
 4507:            .&mt('yes').'</label>'."\n"
 4508:        .&Apache::lonhtmlcommon::row_closure();
 4509: 
 4510:     $result.=
 4511:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4512:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4513:            .&mt('none').' </label>'."\n"
 4514:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4515:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4516:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4517:            .&mt('all submissions with details').' </label>'
 4518:        .&Apache::lonhtmlcommon::row_closure();
 4519:     
 4520:     $result.=
 4521:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4522:        .'<input type="text" name="CODE" value="" />'
 4523:        .&Apache::lonhtmlcommon::row_closure(1)
 4524:        .&Apache::lonhtmlcommon::end_pick_box();
 4525: 
 4526:     # Show list of students to select for grading
 4527:     $result.='<br /><input type="button" '.
 4528:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4529: 
 4530:     $request->print($result);
 4531: 
 4532:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4533: 	&Apache::loncommon::start_data_table().
 4534: 	&Apache::loncommon::start_data_table_header_row().
 4535: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4536: 	'<th>'.&nameUserString('header').'</th>'.
 4537: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4538: 	'<th>'.&nameUserString('header').'</th>'.
 4539: 	&Apache::loncommon::end_data_table_header_row();
 4540:  
 4541:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4542:     my $ptr = 1;
 4543:     foreach my $student (sort 
 4544: 			 {
 4545: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4546: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4547: 			     }
 4548: 			     return $a cmp $b;
 4549: 			 } (keys(%$fullname))) {
 4550: 	my ($uname,$udom) = split(/:/,$student);
 4551: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4552:                                   : '</td>');
 4553: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4554: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4555: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4556: 	$studentTable.=
 4557: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4558:                          : '');
 4559: 	$ptr++;
 4560:     }
 4561:     if ($ptr%2 == 0) {
 4562: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4563: 	    &Apache::loncommon::end_data_table_row();
 4564:     }
 4565:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4566:     $studentTable.='<input type="button" '.
 4567:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4568: 
 4569:     $request->print($studentTable);
 4570: 
 4571:     return '';
 4572: }
 4573: 
 4574: sub getSymbMap {
 4575:     my ($map_error) = @_;
 4576:     my $navmap = Apache::lonnavmaps::navmap->new();
 4577:     unless (ref($navmap)) {
 4578:         if (ref($map_error)) {
 4579:             $$map_error = 'navmap';
 4580:         }
 4581:         return;
 4582:     }
 4583:     my %symbx = ();
 4584:     my @titles = ();
 4585:     my $minder = 0;
 4586: 
 4587:     # Gather every sequence that has problems.
 4588:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4589: 					       1,0,1);
 4590:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4591: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4592: 	    my $title = $minder.'.'.
 4593: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4594: 	    push(@titles, $title); # minder in case two titles are identical
 4595: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4596: 	    $minder++;
 4597: 	}
 4598:     }
 4599:     return \@titles,\%symbx;
 4600: }
 4601: 
 4602: #
 4603: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4604: sub displayPage {
 4605:     my ($request,$symb) = @_;
 4606:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4607:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4608:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4609:     my $pageTitle = $env{'form.page'};
 4610:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4611:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4612:     my $usec=$classlist->{$env{'form.student'}}[5];
 4613: 
 4614:     #need to make sure we have the correct data for later EXT calls, 
 4615:     #thus invalidate the cache
 4616:     &Apache::lonnet::devalidatecourseresdata(
 4617:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4618:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4619:     &Apache::lonnet::clear_EXT_cache_status();
 4620: 
 4621:     if (!&canview($usec)) {
 4622:         $request->print(
 4623:             '<span class="LC_warning">'.
 4624:             &mt('Unable to view requested student. ([_1])',
 4625:                     $env{'form.student'}).
 4626:             '</span>');
 4627:         return;
 4628:     }
 4629:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4630:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4631: 	'</h3>'."\n";
 4632:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4633:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4634: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4635:     } else {
 4636: 	delete($env{'form.CODE'});
 4637:     }
 4638:     &sub_page_js($request);
 4639:     $request->print($result);
 4640: 
 4641:     my $navmap = Apache::lonnavmaps::navmap->new();
 4642:     unless (ref($navmap)) {
 4643:         $request->print(&navmap_errormsg());
 4644:         return;
 4645:     }
 4646:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4647:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4648:     if (!$map) {
 4649: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4650: 	return; 
 4651:     }
 4652:     my $iterator = $navmap->getIterator($map->map_start(),
 4653: 					$map->map_finish());
 4654: 
 4655:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4656: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4657: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4658: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4659: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4660: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4661: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4662: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4663: 
 4664:     if (defined($env{'form.CODE'})) {
 4665: 	$studentTable.=
 4666: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4667:     }
 4668:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4669: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4670: 
 4671:     $studentTable.='&nbsp;<span class="LC_info">'.
 4672:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4673:         '</span>'."\n".
 4674: 	&Apache::loncommon::start_data_table().
 4675: 	&Apache::loncommon::start_data_table_header_row().
 4676: 	'<th>'.&mt('Prob.').'</th>'.
 4677: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4678: 	&Apache::loncommon::end_data_table_header_row();
 4679: 
 4680:     &Apache::lonxml::clear_problem_counter();
 4681:     my ($depth,$question,$prob) = (1,1,1);
 4682:     $iterator->next(); # skip the first BEGIN_MAP
 4683:     my $curRes = $iterator->next(); # for "current resource"
 4684:     while ($depth > 0) {
 4685:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4686:         if($curRes == $iterator->END_MAP) { $depth--; }
 4687: 
 4688:         if (ref($curRes) && $curRes->is_problem()) {
 4689: 	    my $parts = $curRes->parts();
 4690:             my $title = $curRes->compTitle();
 4691: 	    my $symbx = $curRes->symb();
 4692: 	    $studentTable.=
 4693: 		&Apache::loncommon::start_data_table_row().
 4694: 		'<td align="center" valign="top" >'.$prob.
 4695: 		(scalar(@{$parts}) == 1 ? '' 
 4696: 		                        : '<br />('.&mt('[_1]parts',
 4697: 							scalar(@{$parts}).'&nbsp;').')'
 4698: 		 ).
 4699: 		 '</td>';
 4700: 	    $studentTable.='<td valign="top">';
 4701: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4702: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4703: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4704: 					     undef,'both',\%form);
 4705: 	    } else {
 4706: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4707: 		$companswer =~ s|<form(.*?)>||g;
 4708: 		$companswer =~ s|</form>||g;
 4709: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4710: #		    $companswer =~ s/$1/ /ms;
 4711: #		    $request->print('match='.$1."<br />\n");
 4712: #		}
 4713: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4714: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4715: 	    }
 4716: 
 4717: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4718: 
 4719: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4720: 		if ($record{'version'} eq '') {
 4721: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4722: 		} else {
 4723: 		    my %responseType = ();
 4724: 		    foreach my $partid (@{$parts}) {
 4725: 			my @responseIds =$curRes->responseIds($partid);
 4726: 			my @responseType =$curRes->responseType($partid);
 4727: 			my %responseIds;
 4728: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4729: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4730: 			}
 4731: 			$responseType{$partid} = \%responseIds;
 4732: 		    }
 4733: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4734: 
 4735: 		}
 4736: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4737: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4738: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4739: 									$env{'request.course.id'},
 4740: 									'','.submission');
 4741:  
 4742: 	    }
 4743: 	    if (&canmodify($usec)) {
 4744:             $studentTable.=&gradeBox_start();
 4745: 		foreach my $partid (@{$parts}) {
 4746: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4747: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4748: 		    $question++;
 4749: 		}
 4750:             $studentTable.=&gradeBox_end();
 4751: 		$prob++;
 4752: 	    }
 4753: 	    $studentTable.='</td></tr>';
 4754: 
 4755: 	}
 4756:         $curRes = $iterator->next();
 4757:     }
 4758: 
 4759:     $studentTable.=
 4760:         '</table>'."\n".
 4761:         '<input type="button" value="'.&mt('Save').'" '.
 4762:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4763:         '</form>'."\n";
 4764:     $request->print($studentTable);
 4765: 
 4766:     return '';
 4767: }
 4768: 
 4769: sub displaySubByDates {
 4770:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4771:     my $isCODE=0;
 4772:     my $isTask = ($symb =~/\.task$/);
 4773:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4774:     my $studentTable=&Apache::loncommon::start_data_table().
 4775: 	&Apache::loncommon::start_data_table_header_row().
 4776: 	'<th>'.&mt('Date/Time').'</th>'.
 4777: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4778:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4779: 	'<th>'.&mt('Submission').'</th>'.
 4780: 	'<th>'.&mt('Status').'</th>'.
 4781: 	&Apache::loncommon::end_data_table_header_row();
 4782:     my ($version);
 4783:     my %mark;
 4784:     my %orders;
 4785:     $mark{'correct_by_student'} = $checkIcon;
 4786:     if (!exists($$record{'1:timestamp'})) {
 4787: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4788:     }
 4789: 
 4790:     my $interaction;
 4791:     my $no_increment = 1;
 4792:     my %lastrndseed;
 4793:     for ($version=1;$version<=$$record{'version'};$version++) {
 4794: 	my $timestamp = 
 4795: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4796: 	if (exists($$record{$version.':resource.0.version'})) {
 4797: 	    $interaction = $$record{$version.':resource.0.version'};
 4798: 	}
 4799:         if ($isTask && $env{'form.previousversion'}) {
 4800:             next unless ($interaction == $env{'form.previousversion'});
 4801:         }
 4802: 	my $where = ($isTask ? "$version:resource.$interaction"
 4803: 		             : "$version:resource");
 4804: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4805: 	    '<td>'.$timestamp.'</td>';
 4806: 	if ($isCODE) {
 4807: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4808: 	}
 4809:         if ($isTask) {
 4810:             $studentTable.='<td>'.$interaction.'</td>';
 4811:         }
 4812: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4813: 	my @displaySub = ();
 4814: 	foreach my $partid (@{$parts}) {
 4815:             my ($hidden,$type);
 4816:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4817:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4818:                 $hidden = 1;
 4819:             }
 4820: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4821: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4822: 	    
 4823: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4824: 	    my $display_part=&get_display_part($partid,$symb);
 4825: 	    foreach my $matchKey (@matchKey) {
 4826: 		if (exists($$record{$version.':'.$matchKey}) &&
 4827: 		    $$record{$version.':'.$matchKey} ne '') {
 4828:                     
 4829: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4830: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4831:                     $displaySub[0].='<span class="LC_nobreak">';
 4832:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4833:                                    .' <span class="LC_internal_info">'
 4834:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4835:                                    .'</span>'
 4836:                                    .' <b>';
 4837:                     if ($hidden) {
 4838:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4839:                     } else {
 4840:                         my ($trial,$rndseed,$newvariation);
 4841:                         if ($type eq 'randomizetry') {
 4842:                             $trial = $$record{"$where.$partid.tries"};
 4843:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4844:                         }
 4845: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4846: 			    $displaySub[0].=&mt('Trial not counted');
 4847: 		        } else {
 4848: 			    $displaySub[0].=&mt('Trial: [_1]',
 4849: 					    $$record{"$where.$partid.tries"});
 4850:                             if ($rndseed || $lastrndseed{$partid}) {
 4851:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4852:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4853:                                 }
 4854:                             }
 4855:                             $lastrndseed{$partid} = $rndseed;
 4856: 		        }
 4857: 		        my $responseType=($isTask ? 'Task'
 4858:                                               : $responseType->{$partid}->{$responseId});
 4859: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4860: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4861: 			    $orders{$partid}->{$responseId}=
 4862: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4863:                                            $no_increment,$type,$trial,$rndseed);
 4864: 		        }
 4865: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4866: 		        $displaySub[0].='&nbsp; '.
 4867: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4868:                     }
 4869: 		}
 4870: 	    }
 4871: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4872: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4873: 				    $$record{"$where.$partid.checkedin"},
 4874: 				    $$record{"$where.$partid.checkedin.slot"}).
 4875: 					'<br />';
 4876: 	    }
 4877: 	    if (exists $$record{"$where.$partid.award"}) {
 4878: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4879: 		    lc($$record{"$where.$partid.award"}).' '.
 4880: 		    $mark{$$record{"$where.$partid.solved"}}.
 4881: 		    '<br />';
 4882: 	    }
 4883: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4884: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4885: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4886: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4887: 		$displaySub[2].=
 4888: 		    $$record{"$version:resource.$partid.regrader"}.
 4889: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4890: 	    }
 4891: 	}
 4892: 	# needed because old essay regrader has not parts info
 4893: 	if (exists $$record{"$version:resource.regrader"}) {
 4894: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4895: 	}
 4896: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4897: 	if ($displaySub[2]) {
 4898: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4899: 	}
 4900: 	$studentTable.='&nbsp;</td>'.
 4901: 	    &Apache::loncommon::end_data_table_row();
 4902:     }
 4903:     $studentTable.=&Apache::loncommon::end_data_table();
 4904:     return $studentTable;
 4905: }
 4906: 
 4907: sub updateGradeByPage {
 4908:     my ($request,$symb) = @_;
 4909: 
 4910:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4911:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4912:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4913:     my $pageTitle = $env{'form.page'};
 4914:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4915:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4916:     my $usec=$classlist->{$env{'form.student'}}[5];
 4917:     if (!&canmodify($usec)) {
 4918: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4919: 	return;
 4920:     }
 4921:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4922:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4923: 	'</h3>'."\n";
 4924: 
 4925:     $request->print($result);
 4926: 
 4927: 
 4928:     my $navmap = Apache::lonnavmaps::navmap->new();
 4929:     unless (ref($navmap)) {
 4930:         $request->print(&navmap_errormsg());
 4931:         return;
 4932:     }
 4933:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4934:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4935:     if (!$map) {
 4936: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4937: 	return; 
 4938:     }
 4939:     my $iterator = $navmap->getIterator($map->map_start(),
 4940: 					$map->map_finish());
 4941: 
 4942:     my $studentTable=
 4943: 	&Apache::loncommon::start_data_table().
 4944: 	&Apache::loncommon::start_data_table_header_row().
 4945: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4946: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4947: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4948: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4949: 	&Apache::loncommon::end_data_table_header_row();
 4950: 
 4951:     $iterator->next(); # skip the first BEGIN_MAP
 4952:     my $curRes = $iterator->next(); # for "current resource"
 4953:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4954:     while ($depth > 0) {
 4955:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4956:         if($curRes == $iterator->END_MAP) { $depth--; }
 4957: 
 4958:         if (ref($curRes) && $curRes->is_problem()) {
 4959: 	    my $parts = $curRes->parts();
 4960:             my $title = $curRes->compTitle();
 4961: 	    my $symbx = $curRes->symb();
 4962: 	    $studentTable.=
 4963: 		&Apache::loncommon::start_data_table_row().
 4964: 		'<td align="center" valign="top" >'.$prob.
 4965: 		(scalar(@{$parts}) == 1 ? '' 
 4966:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4967: 		.')').'</td>';
 4968: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4969: 
 4970: 	    my %newrecord=();
 4971: 	    my @displayPts=();
 4972:             my %aggregate = ();
 4973:             my $aggregateflag = 0;
 4974: 	    foreach my $partid (@{$parts}) {
 4975: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4976: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4977: 
 4978: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4979: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4980: 		my $partial = $newpts/$wgt;
 4981: 		my $score;
 4982: 		if ($partial > 0) {
 4983: 		    $score = 'correct_by_override';
 4984: 		} elsif ($newpts ne '') { #empty is taken as 0
 4985: 		    $score = 'incorrect_by_override';
 4986: 		}
 4987: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4988: 		if ($dropMenu eq 'excused') {
 4989: 		    $partial = '';
 4990: 		    $score = 'excused';
 4991: 		} elsif ($dropMenu eq 'reset status'
 4992: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4993: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4994: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4995: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4996: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4997: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4998: 		    $changeflag++;
 4999: 		    $newpts = '';
 5000:                     
 5001:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5002:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5003:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5004:                     if ($aggtries > 0) {
 5005:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5006:                         $aggregateflag = 1;
 5007:                     }
 5008: 		}
 5009: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5010: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5011: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5012: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5013: 		    '&nbsp;<br />';
 5014: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5015: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5016: 		    '&nbsp;<br />';
 5017: 		$question++;
 5018: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5019: 
 5020: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5021: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5022: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5023: 		    if (scalar(keys(%newrecord)) > 0);
 5024: 
 5025: 		$changeflag++;
 5026: 	    }
 5027: 	    if (scalar(keys(%newrecord)) > 0) {
 5028: 		my %record = 
 5029: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5030: 					     $udom,$uname);
 5031: 
 5032: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5033: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5034: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5035: 		    $newrecord{'resource.CODE'} = '';
 5036: 		}
 5037: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5038: 					$udom,$uname);
 5039: 		%record = &Apache::lonnet::restore($symbx,
 5040: 						   $env{'request.course.id'},
 5041: 						   $udom,$uname);
 5042: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5043: 					     $cdom,$cnum,$udom,$uname);
 5044: 	    }
 5045: 	    
 5046:             if ($aggregateflag) {
 5047:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5048:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5049:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5050:             }
 5051: 
 5052: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5053: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5054: 		&Apache::loncommon::end_data_table_row();
 5055: 
 5056: 	    $prob++;
 5057: 	}
 5058:         $curRes = $iterator->next();
 5059:     }
 5060: 
 5061:     $studentTable.=&Apache::loncommon::end_data_table();
 5062:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5063: 		  &mt('The scores were changed for [quant,_1,problem].',
 5064: 		  $changeflag));
 5065:     $request->print($grademsg.$studentTable);
 5066: 
 5067:     return '';
 5068: }
 5069: 
 5070: #-------- end of section for handling grading by page/sequence ---------
 5071: #
 5072: #-------------------------------------------------------------------
 5073: 
 5074: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5075: #
 5076: #------ start of section for handling grading by page/sequence ---------
 5077: 
 5078: =pod
 5079: 
 5080: =head1 Bubble sheet grading routines
 5081: 
 5082:   For this documentation:
 5083: 
 5084:    'scanline' refers to the full line of characters
 5085:    from the file that we are parsing that represents one entire sheet
 5086: 
 5087:    'bubble line' refers to the data
 5088:    representing the line of bubbles that are on the physical bubblesheet
 5089: 
 5090: 
 5091: The overall process is that a scanned in bubblesheet data is uploaded
 5092: into a course. When a user wants to grade, they select a
 5093: sequence/folder of resources, a file of bubblesheet info, and pick
 5094: one of the predefined configurations for what each scanline looks
 5095: like.
 5096: 
 5097: Next each scanline is checked for any errors of either 'missing
 5098: bubbles' (it's an error because it may have been mis-scanned
 5099: because too light bubbling), 'double bubble' (each bubble line should
 5100: have no more than one letter picked), invalid or duplicated CODE,
 5101: invalid student/employee ID
 5102: 
 5103: If the CODE option is used that determines the randomization of the
 5104: homework problems, either way the student/employee ID is looked up into a
 5105: username:domain.
 5106: 
 5107: During the validation phase the instructor can choose to skip scanlines. 
 5108: 
 5109: After the validation phase, there are now 3 bubblesheet files
 5110: 
 5111:   scantron_original_filename (unmodified original file)
 5112:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5113:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5114: 
 5115: Also there is a separate hash nohist_scantrondata that contains extra
 5116: correction information that isn't representable in the bubblesheet
 5117: file (see &scantron_getfile() for more information)
 5118: 
 5119: After all scanlines are either valid, marked as valid or skipped, then
 5120: foreach line foreach problem in the picked sequence, an ssi request is
 5121: made that simulates a user submitting their selected letter(s) against
 5122: the homework problem.
 5123: 
 5124: =over 4
 5125: 
 5126: 
 5127: 
 5128: =item defaultFormData
 5129: 
 5130:   Returns html hidden inputs used to hold context/default values.
 5131: 
 5132:  Arguments:
 5133:   $symb - $symb of the current resource 
 5134: 
 5135: =cut
 5136: 
 5137: sub defaultFormData {
 5138:     my ($symb)=@_;
 5139:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5140: }
 5141: 
 5142: 
 5143: =pod 
 5144: 
 5145: =item getSequenceDropDown
 5146: 
 5147:    Return html dropdown of possible sequences to grade
 5148:  
 5149:  Arguments:
 5150:    $symb - $symb of the current resource
 5151:    $map_error - ref to scalar which will container error if
 5152:                 $navmap object is unavailable in &getSymbMap().
 5153: 
 5154: =cut
 5155: 
 5156: sub getSequenceDropDown {
 5157:     my ($symb,$map_error)=@_;
 5158:     my $result='<select name="selectpage">'."\n";
 5159:     my ($titles,$symbx) = &getSymbMap($map_error);
 5160:     if (ref($map_error)) {
 5161:         return if ($$map_error);
 5162:     }
 5163:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5164:     my $ctr=0;
 5165:     foreach (@$titles) {
 5166: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5167: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5168: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5169: 	    '>'.$showtitle.'</option>'."\n";
 5170: 	$ctr++;
 5171:     }
 5172:     $result.= '</select>';
 5173:     return $result;
 5174: }
 5175: 
 5176: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5177:                                    # key is zero-based index - 0, 1, 2 ...
 5178: 
 5179: my %first_bubble_line;             # First bubble line no. for each bubble.
 5180: 
 5181: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5182:                                    # matchresponse or rankresponse, where 
 5183:                                    # an individual response can have multiple 
 5184:                                    # lines
 5185: 
 5186: my %responsetype_per_response;     # responsetype for each response
 5187: 
 5188: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5189:                                    # numbered response. Needed when randomorder
 5190:                                    # or randompick are in use. Key is ID, value 
 5191:                                    # is response number.
 5192: 
 5193: # Save and restore the bubble lines array to the form env.
 5194: 
 5195: 
 5196: sub save_bubble_lines {
 5197:     foreach my $line (keys(%bubble_lines_per_response)) {
 5198: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5199: 	$env{"form.scantron.first_bubble_line.$line"} =
 5200: 	    $first_bubble_line{$line};
 5201:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5202:             $subdivided_bubble_lines{$line};
 5203:         $env{"form.scantron.responsetype.$line"} =
 5204:             $responsetype_per_response{$line};
 5205:     }
 5206:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5207:         my $line = $masterseq_id_responsenum{$resid};
 5208:         $env{"form.scantron.residpart.$line"} = $resid;
 5209:     }
 5210: }
 5211: 
 5212: 
 5213: sub restore_bubble_lines {
 5214:     my $line = 0;
 5215:     %bubble_lines_per_response = ();
 5216:     %masterseq_id_responsenum = ();
 5217:     while ($env{"form.scantron.bubblelines.$line"}) {
 5218: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5219: 	$bubble_lines_per_response{$line} = $value;
 5220: 	$first_bubble_line{$line}  =
 5221: 	    $env{"form.scantron.first_bubble_line.$line"};
 5222:         $subdivided_bubble_lines{$line} =
 5223:             $env{"form.scantron.sub_bubblelines.$line"};
 5224:         $responsetype_per_response{$line} =
 5225:             $env{"form.scantron.responsetype.$line"};
 5226:         my $id = $env{"form.scantron.residpart.$line"};
 5227:         $masterseq_id_responsenum{$id} = $line;
 5228: 	$line++;
 5229:     }
 5230: }
 5231: 
 5232: =pod 
 5233: 
 5234: =item scantron_filenames
 5235: 
 5236:    Returns a list of the scantron files in the current course 
 5237: 
 5238: =cut
 5239: 
 5240: sub scantron_filenames {
 5241:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5242:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5243:     my $getpropath = 1;
 5244:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5245:                                                         $cname,$getpropath);
 5246:     my @possiblenames;
 5247:     if (ref($dirlist) eq 'ARRAY') {
 5248:         foreach my $filename (sort(@{$dirlist})) {
 5249: 	    ($filename)=split(/&/,$filename);
 5250: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5251: 	    $filename=~s/^scantron_orig_//;
 5252: 	    push(@possiblenames,$filename);
 5253:         }
 5254:     }
 5255:     return @possiblenames;
 5256: }
 5257: 
 5258: =pod 
 5259: 
 5260: =item scantron_uploads
 5261: 
 5262:    Returns  html drop-down list of scantron files in current course.
 5263: 
 5264:  Arguments:
 5265:    $file2grade - filename to set as selected in the dropdown
 5266: 
 5267: =cut
 5268: 
 5269: sub scantron_uploads {
 5270:     my ($file2grade) = @_;
 5271:     my $result=	'<select name="scantron_selectfile">';
 5272:     $result.="<option></option>";
 5273:     foreach my $filename (sort(&scantron_filenames())) {
 5274: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5275:     }
 5276:     $result.="</select>";
 5277:     return $result;
 5278: }
 5279: 
 5280: =pod 
 5281: 
 5282: =item scantron_scantab
 5283: 
 5284:   Returns html drop down of the scantron formats in the scantronformat.tab
 5285:   file.
 5286: 
 5287: =cut
 5288: 
 5289: sub scantron_scantab {
 5290:     my $result='<select name="scantron_format">'."\n";
 5291:     $result.='<option></option>'."\n";
 5292:     my @lines = &get_scantronformat_file();
 5293:     if (@lines > 0) {
 5294:         foreach my $line (@lines) {
 5295:             next if (($line =~ /^\#/) || ($line eq ''));
 5296: 	    my ($name,$descrip)=split(/:/,$line);
 5297: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5298:         }
 5299:     }
 5300:     $result.='</select>'."\n";
 5301:     return $result;
 5302: }
 5303: 
 5304: =pod
 5305: 
 5306: =item get_scantronformat_file
 5307: 
 5308:   Returns an array containing lines from the scantron format file for
 5309:   the domain of the course.
 5310: 
 5311:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5312:   lines are from this file.
 5313: 
 5314:   Otherwise, if a default.tab has been published in RES space by the 
 5315:   domainconfig user, lines are from this file.
 5316: 
 5317:   Otherwise, fall back to getting lines from the legacy file on the
 5318:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5319: 
 5320: =cut
 5321: 
 5322: sub get_scantronformat_file {
 5323:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5324:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5325:     my $gottab = 0;
 5326:     my @lines;
 5327:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5328:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5329:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5330:             if ($formatfile ne '-1') {
 5331:                 @lines = split("\n",$formatfile,-1);
 5332:                 $gottab = 1;
 5333:             }
 5334:         }
 5335:     }
 5336:     if (!$gottab) {
 5337:         my $confname = $cdom.'-domainconfig';
 5338:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5339:         my $formatfile =  &Apache::lonnet::getfile($default);
 5340:         if ($formatfile ne '-1') {
 5341:             @lines = split("\n",$formatfile,-1);
 5342:             $gottab = 1;
 5343:         }
 5344:     }
 5345:     if (!$gottab) {
 5346:         my @domains = &Apache::lonnet::current_machine_domains();
 5347:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5348:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5349:             @lines = <$fh>;
 5350:             close($fh);
 5351:         } else {
 5352:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5353:             @lines = <$fh>;
 5354:             close($fh);
 5355:         }
 5356:     }
 5357:     return @lines;
 5358: }
 5359: 
 5360: =pod 
 5361: 
 5362: =item scantron_CODElist
 5363: 
 5364:   Returns html drop down of the saved CODE lists from current course,
 5365:   generated from earlier printings.
 5366: 
 5367: =cut
 5368: 
 5369: sub scantron_CODElist {
 5370:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5371:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5372:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5373:     my $namechoice='<option></option>';
 5374:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5375: 	if ($name =~ /^error: 2 /) { next; }
 5376: 	if ($name =~ /^type\0/) { next; }
 5377: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5378:     }
 5379:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5380:     return $namechoice;
 5381: }
 5382: 
 5383: =pod 
 5384: 
 5385: =item scantron_CODEunique
 5386: 
 5387:   Returns the html for "Each CODE to be used once" radio.
 5388: 
 5389: =cut
 5390: 
 5391: sub scantron_CODEunique {
 5392:     my $result='<span class="LC_nobreak">
 5393:                  <label><input type="radio" name="scantron_CODEunique"
 5394:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5395:                 </span>
 5396:                 <span class="LC_nobreak">
 5397:                  <label><input type="radio" name="scantron_CODEunique"
 5398:                         value="no" />'.&mt('No').' </label>
 5399:                 </span>';
 5400:     return $result;
 5401: }
 5402: 
 5403: =pod 
 5404: 
 5405: =item scantron_selectphase
 5406: 
 5407:   Generates the initial screen to start the bubblesheet process.
 5408:   Allows for - starting a grading run.
 5409:              - downloading existing scan data (original, corrected
 5410:                                                 or skipped info)
 5411: 
 5412:              - uploading new scan data
 5413: 
 5414:  Arguments:
 5415:   $r          - The Apache request object
 5416:   $file2grade - name of the file that contain the scanned data to score
 5417: 
 5418: =cut
 5419: 
 5420: sub scantron_selectphase {
 5421:     my ($r,$file2grade,$symb) = @_;
 5422:     if (!$symb) {return '';}
 5423:     my $map_error;
 5424:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5425:     if ($map_error) {
 5426:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5427:         return;
 5428:     }
 5429:     my $default_form_data=&defaultFormData($symb);
 5430:     my $file_selector=&scantron_uploads($file2grade);
 5431:     my $format_selector=&scantron_scantab();
 5432:     my $CODE_selector=&scantron_CODElist();
 5433:     my $CODE_unique=&scantron_CODEunique();
 5434:     my $result;
 5435: 
 5436:     $ssi_error = 0;
 5437: 
 5438:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5439:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5440: 
 5441: 	# Chunk of form to prompt for a scantron file upload.
 5442: 
 5443:         $r->print('
 5444:     <br />
 5445:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5446:        '.&Apache::loncommon::start_data_table_header_row().'
 5447:             <th>
 5448:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5449:             </th>
 5450:        '.&Apache::loncommon::end_data_table_header_row().'
 5451:        '.&Apache::loncommon::start_data_table_row().'
 5452:             <td>
 5453: ');
 5454:     my $default_form_data=&defaultFormData($symb);
 5455:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5456:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5457:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5458:     function checkUpload(formname) {
 5459: 	if (formname.upfile.value == "") {
 5460: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5461: 	    return false;
 5462: 	}
 5463: 	formname.submit();
 5464:     }'));
 5465:     $r->print('
 5466:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5467:                 '.$default_form_data.'
 5468:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5469:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5470:                 <input name="command" value="scantronupload_save" type="hidden" />
 5471:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5472:                 <br />
 5473:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5474:               </form>
 5475: ');
 5476: 
 5477:         $r->print('
 5478:             </td>
 5479:        '.&Apache::loncommon::end_data_table_row().'
 5480:        '.&Apache::loncommon::end_data_table().'
 5481: ');
 5482:     }
 5483: 
 5484:     # Chunk of form to prompt for a file to grade and how:
 5485: 
 5486:     $result.= '
 5487:     <br />
 5488:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5489:     <input type="hidden" name="command" value="scantron_warning" />
 5490:     '.$default_form_data.'
 5491:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5492:        '.&Apache::loncommon::start_data_table_header_row().'
 5493:             <th colspan="2">
 5494:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5495:             </th>
 5496:        '.&Apache::loncommon::end_data_table_header_row().'
 5497:        '.&Apache::loncommon::start_data_table_row().'
 5498:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5499:        '.&Apache::loncommon::end_data_table_row().'
 5500:        '.&Apache::loncommon::start_data_table_row().'
 5501:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5502:        '.&Apache::loncommon::end_data_table_row().'
 5503:        '.&Apache::loncommon::start_data_table_row().'
 5504:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5505:        '.&Apache::loncommon::end_data_table_row().'
 5506:        '.&Apache::loncommon::start_data_table_row().'
 5507:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5508:        '.&Apache::loncommon::end_data_table_row().'
 5509:        '.&Apache::loncommon::start_data_table_row().'
 5510:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5511:        '.&Apache::loncommon::end_data_table_row().'
 5512:        '.&Apache::loncommon::start_data_table_row().'
 5513: 	    <td> '.&mt('Options:').' </td>
 5514:             <td>
 5515: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5516:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5517:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5518: 	    </td>
 5519:        '.&Apache::loncommon::end_data_table_row().'
 5520:        '.&Apache::loncommon::start_data_table_row().'
 5521:             <td colspan="2">
 5522:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5523:             </td>
 5524:        '.&Apache::loncommon::end_data_table_row().'
 5525:     '.&Apache::loncommon::end_data_table().'
 5526:     </form>
 5527: ';
 5528:    
 5529:     $r->print($result);
 5530: 
 5531: 
 5532: 
 5533:     # Chunk of the form that prompts to view a scoring office file,
 5534:     # corrected file, skipped records in a file.
 5535: 
 5536:     $r->print('
 5537:    <br />
 5538:    <form action="/adm/grades" name="scantron_download">
 5539:      '.$default_form_data.'
 5540:      <input type="hidden" name="command" value="scantron_download" />
 5541:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5542:        '.&Apache::loncommon::start_data_table_header_row().'
 5543:               <th>
 5544:                 &nbsp;'.&mt('Download a scoring office file').'
 5545:               </th>
 5546:        '.&Apache::loncommon::end_data_table_header_row().'
 5547:        '.&Apache::loncommon::start_data_table_row().'
 5548:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5549:                 <br />
 5550:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5551:        '.&Apache::loncommon::end_data_table_row().'
 5552:      '.&Apache::loncommon::end_data_table().'
 5553:    </form>
 5554:    <br />
 5555: ');
 5556: 
 5557:     &Apache::lonpickcode::code_list($r,2);
 5558: 
 5559:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5560:              $default_form_data."\n".
 5561:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5562:              &Apache::loncommon::start_data_table_header_row()."\n".
 5563:              '<th colspan="2">
 5564:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5565:              '</th>'."\n".
 5566:               &Apache::loncommon::end_data_table_header_row()."\n".
 5567:               &Apache::loncommon::start_data_table_row()."\n".
 5568:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5569:               '<td> '.$sequence_selector.' </td>'.
 5570:               &Apache::loncommon::end_data_table_row()."\n".
 5571:               &Apache::loncommon::start_data_table_row()."\n".
 5572:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5573:               '<td> '.$file_selector.' </td>'."\n".
 5574:               &Apache::loncommon::end_data_table_row()."\n".
 5575:               &Apache::loncommon::start_data_table_row()."\n".
 5576:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5577:               '<td> '.$format_selector.' </td>'."\n".
 5578:               &Apache::loncommon::end_data_table_row()."\n".
 5579:               &Apache::loncommon::start_data_table_row()."\n".
 5580:               '<td> '.&mt('Options').' </td>'."\n".
 5581:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5582:               &Apache::loncommon::end_data_table_row()."\n".
 5583:               &Apache::loncommon::start_data_table_row()."\n".
 5584:               '<td colspan="2">'."\n".
 5585:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5586:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5587:               '</td>'."\n".
 5588:               &Apache::loncommon::end_data_table_row()."\n".
 5589:               &Apache::loncommon::end_data_table()."\n".
 5590:               '</form><br />');
 5591:     return;
 5592: }
 5593: 
 5594: =pod
 5595: 
 5596: =item get_scantron_config
 5597: 
 5598:    Parse and return the bubblesheet configuration line selected as a
 5599:    hash of configuration file fields.
 5600: 
 5601:  Arguments:
 5602:     which - the name of the configuration to parse from the file.
 5603: 
 5604: 
 5605:  Returns:
 5606:             If the named configuration is not in the file, an empty
 5607:             hash is returned.
 5608:     a hash with the fields
 5609:       name         - internal name for the this configuration setup
 5610:       description  - text to display to operator that describes this config
 5611:       CODElocation - if 0 or the string 'none'
 5612:                           - no CODE exists for this config
 5613:                      if -1 || the string 'letter'
 5614:                           - a CODE exists for this config and is
 5615:                             a string of letters
 5616:                      Unsupported value (but planned for future support)
 5617:                           if a positive integer
 5618:                                - The CODE exists as the first n items from
 5619:                                  the question section of the form
 5620:                           if the string 'number'
 5621:                                - The CODE exists for this config and is
 5622:                                  a string of numbers
 5623:       CODEstart   - (only matter if a CODE exists) column in the line where
 5624:                      the CODE starts
 5625:       CODElength  - length of the CODE
 5626:       IDstart     - column where the student/employee ID starts
 5627:       IDlength    - length of the student/employee ID info
 5628:       Qstart      - column where the information from the bubbled
 5629:                     'questions' start
 5630:       Qlength     - number of columns comprising a single bubble line from
 5631:                     the sheet. (usually either 1 or 10)
 5632:       Qon         - either a single character representing the character used
 5633:                     to signal a bubble was chosen in the positional setup, or
 5634:                     the string 'letter' if the letter of the chosen bubble is
 5635:                     in the final, or 'number' if a number representing the
 5636:                     chosen bubble is in the file (1->A 0->J)
 5637:       Qoff        - the character used to represent that a bubble was
 5638:                     left blank
 5639:       PaperID     - if the scanning process generates a unique number for each
 5640:                     sheet scanned the column that this ID number starts in
 5641:       PaperIDlength - number of columns that comprise the unique ID number
 5642:                       for the sheet of paper
 5643:       FirstName   - column that the first name starts in
 5644:       FirstNameLength - number of columns that the first name spans
 5645:  
 5646:       LastName    - column that the last name starts in
 5647:       LastNameLength - number of columns that the last name spans
 5648:       BubblesPerRow - number of bubbles available in each row used to 
 5649:                       bubble an answer. (If not specified, 10 assumed).
 5650: 
 5651: =cut
 5652: 
 5653: sub get_scantron_config {
 5654:     my ($which) = @_;
 5655:     my @lines = &get_scantronformat_file();
 5656:     my %config;
 5657:     #FIXME probably should move to XML it has already gotten a bit much now
 5658:     foreach my $line (@lines) {
 5659: 	my ($name,$descrip)=split(/:/,$line);
 5660: 	if ($name ne $which ) { next; }
 5661: 	chomp($line);
 5662: 	my @config=split(/:/,$line);
 5663: 	$config{'name'}=$config[0];
 5664: 	$config{'description'}=$config[1];
 5665: 	$config{'CODElocation'}=$config[2];
 5666: 	$config{'CODEstart'}=$config[3];
 5667: 	$config{'CODElength'}=$config[4];
 5668: 	$config{'IDstart'}=$config[5];
 5669: 	$config{'IDlength'}=$config[6];
 5670: 	$config{'Qstart'}=$config[7];
 5671:  	$config{'Qlength'}=$config[8];
 5672: 	$config{'Qoff'}=$config[9];
 5673: 	$config{'Qon'}=$config[10];
 5674: 	$config{'PaperID'}=$config[11];
 5675: 	$config{'PaperIDlength'}=$config[12];
 5676: 	$config{'FirstName'}=$config[13];
 5677: 	$config{'FirstNamelength'}=$config[14];
 5678: 	$config{'LastName'}=$config[15];
 5679: 	$config{'LastNamelength'}=$config[16];
 5680:         $config{'BubblesPerRow'}=$config[17];
 5681: 	last;
 5682:     }
 5683:     return %config;
 5684: }
 5685: 
 5686: =pod 
 5687: 
 5688: =item username_to_idmap
 5689: 
 5690:     creates a hash keyed by student/employee ID with values of the corresponding
 5691:     student username:domain.
 5692: 
 5693:   Arguments:
 5694: 
 5695:     $classlist - reference to the class list hash. This is a hash
 5696:                  keyed by student name:domain  whose elements are references
 5697:                  to arrays containing various chunks of information
 5698:                  about the student. (See loncoursedata for more info).
 5699: 
 5700:   Returns
 5701:     %idmap - the constructed hash
 5702: 
 5703: =cut
 5704: 
 5705: sub username_to_idmap {
 5706:     my ($classlist)= @_;
 5707:     my %idmap;
 5708:     foreach my $student (keys(%$classlist)) {
 5709: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5710: 	    $student;
 5711:     }
 5712:     return %idmap;
 5713: }
 5714: 
 5715: =pod
 5716: 
 5717: =item scantron_fixup_scanline
 5718: 
 5719:    Process a requested correction to a scanline.
 5720: 
 5721:   Arguments:
 5722:     $scantron_config   - hash from &get_scantron_config()
 5723:     $scan_data         - hash of correction information 
 5724:                           (see &scantron_getfile())
 5725:     $line              - existing scanline
 5726:     $whichline         - line number of the passed in scanline
 5727:     $field             - type of change to process 
 5728:                          (either 
 5729:                           'ID'     -> correct the student/employee ID
 5730:                           'CODE'   -> correct the CODE
 5731:                           'answer' -> fixup the submitted answers)
 5732:     
 5733:    $args               - hash of additional info,
 5734:                           - 'ID' 
 5735:                                'newid' -> studentID to use in replacement
 5736:                                           of existing one
 5737:                           - 'CODE' 
 5738:                                'CODE_ignore_dup' - set to true if duplicates
 5739:                                                    should be ignored.
 5740: 	                       'CODE' - is new code or 'use_unfound'
 5741:                                         if the existing unfound code should
 5742:                                         be used as is
 5743:                           - 'answer'
 5744:                                'response' - new answer or 'none' if blank
 5745:                                'question' - the bubble line to change
 5746:                                'questionnum' - the question identifier,
 5747:                                                may include subquestion. 
 5748: 
 5749:   Returns:
 5750:     $line - the modified scanline
 5751: 
 5752:   Side effects: 
 5753:     $scan_data - may be updated
 5754: 
 5755: =cut
 5756: 
 5757: 
 5758: sub scantron_fixup_scanline {
 5759:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5760:     if ($field eq 'ID') {
 5761: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5762: 	    return ($line,1,'New value too large');
 5763: 	}
 5764: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5765: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5766: 				     $args->{'newid'});
 5767: 	}
 5768: 	substr($line,$$scantron_config{'IDstart'}-1,
 5769: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5770: 	if ($args->{'newid'}=~/^\s*$/) {
 5771: 	    &scan_data($scan_data,"$whichline.user",
 5772: 		       $args->{'username'}.':'.$args->{'domain'});
 5773: 	}
 5774:     } elsif ($field eq 'CODE') {
 5775: 	if ($args->{'CODE_ignore_dup'}) {
 5776: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5777: 	}
 5778: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5779: 	if ($args->{'CODE'} ne 'use_unfound') {
 5780: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5781: 		return ($line,1,'New CODE value too large');
 5782: 	    }
 5783: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5784: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5785: 	    }
 5786: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5787: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5788: 	}
 5789:     } elsif ($field eq 'answer') {
 5790: 	my $length=$scantron_config->{'Qlength'};
 5791: 	my $off=$scantron_config->{'Qoff'};
 5792: 	my $on=$scantron_config->{'Qon'};
 5793: 	my $answer=${off}x$length;
 5794: 	if ($args->{'response'} eq 'none') {
 5795: 	    &scan_data($scan_data,
 5796: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5797: 	} else {
 5798: 	    if ($on eq 'letter') {
 5799: 		my @alphabet=('A'..'Z');
 5800: 		$answer=$alphabet[$args->{'response'}];
 5801: 	    } elsif ($on eq 'number') {
 5802: 		$answer=$args->{'response'}+1;
 5803: 		if ($answer == 10) { $answer = '0'; }
 5804: 	    } else {
 5805: 		substr($answer,$args->{'response'},1)=$on;
 5806: 	    }
 5807: 	    &scan_data($scan_data,
 5808: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5809: 	}
 5810: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5811: 	substr($line,$where-1,$length)=$answer;
 5812:     }
 5813:     return $line;
 5814: }
 5815: 
 5816: =pod
 5817: 
 5818: =item scan_data
 5819: 
 5820:     Edit or look up  an item in the scan_data hash.
 5821: 
 5822:   Arguments:
 5823:     $scan_data  - The hash (see scantron_getfile)
 5824:     $key        - shorthand of the key to edit (actual key is
 5825:                   scantronfilename_key).
 5826:     $data        - New value of the hash entry.
 5827:     $delete      - If true, the entry is removed from the hash.
 5828: 
 5829:   Returns:
 5830:     The new value of the hash table field (undefined if deleted).
 5831: 
 5832: =cut
 5833: 
 5834: 
 5835: sub scan_data {
 5836:     my ($scan_data,$key,$value,$delete)=@_;
 5837:     my $filename=$env{'form.scantron_selectfile'};
 5838:     if (defined($value)) {
 5839: 	$scan_data->{$filename.'_'.$key} = $value;
 5840:     }
 5841:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5842:     return $scan_data->{$filename.'_'.$key};
 5843: }
 5844: 
 5845: # ----- These first few routines are general use routines.----
 5846: 
 5847: # Return the number of occurences of a pattern in a string.
 5848: 
 5849: sub occurence_count {
 5850:     my ($string, $pattern) = @_;
 5851: 
 5852:     my @matches = ($string =~ /$pattern/g);
 5853: 
 5854:     return scalar(@matches);
 5855: }
 5856: 
 5857: 
 5858: # Take a string known to have digits and convert all the
 5859: # digits into letters in the range J,A..I.
 5860: 
 5861: sub digits_to_letters {
 5862:     my ($input) = @_;
 5863: 
 5864:     my @alphabet = ('J', 'A'..'I');
 5865: 
 5866:     my @input    = split(//, $input);
 5867:     my $output ='';
 5868:     for (my $i = 0; $i < scalar(@input); $i++) {
 5869: 	if ($input[$i] =~ /\d/) {
 5870: 	    $output .= $alphabet[$input[$i]];
 5871: 	} else {
 5872: 	    $output .= $input[$i];
 5873: 	}
 5874:     }
 5875:     return $output;
 5876: }
 5877: 
 5878: =pod 
 5879: 
 5880: =item scantron_parse_scanline
 5881: 
 5882:   Decodes a scanline from the selected bubblesheet file
 5883: 
 5884:  Arguments:
 5885:     line             - The text of the bubblesheet file line to process
 5886:     whichline        - Line number
 5887:     scantron_config  - Hash describing the format of the bubblesheet lines.
 5888:     scan_data        - Hash of extra information about the scanline
 5889:                        (see scantron_getfile for more information)
 5890:     just_header      - True if should not process question answers but only
 5891:                        the stuff to the left of the answers.
 5892:     randomorder      - True if randomorder in use
 5893:     randompick       - True if randompick in use
 5894:     sequence         - Exam folder URL
 5895:     master_seq       - Ref to array containing symbs in exam folder
 5896:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 5897:                        (corresponding values are resource objects)
 5898:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 5899:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 5900:                        are refs to an array of resource objects, ordered
 5901:                        according to order used for CODE, when randomorder
 5902:                        and or randompick are in use.
 5903:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 5904:                        for current line to question number used for same question
 5905:                         in "Master Sequence" (as seen by Course Coordinator).
 5906:     startline        - Ref to hash where key is question number (0 is first)
 5907:                        and value is number of first bubble line for current 
 5908:                        student or code-based randompick and/or randomorder.
 5909:     totalref         - Ref of scalar used to score total number of bubble
 5910:                        lines needed for responses in a scan line (used when
 5911:                        randompick in use. 
 5912:     
 5913:  Returns:
 5914:    Hash containing the result of parsing the scanline
 5915: 
 5916:    Keys are all proceeded by the string 'scantron.'
 5917: 
 5918:        CODE    - the CODE in use for this scanline
 5919:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5920:                  by the operator
 5921:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5922:                             CODEs were selected, but the usage has been
 5923:                             forced by the operator
 5924:        ID  - student/employee ID
 5925:        PaperID - if used, the ID number printed on the sheet when the 
 5926:                  paper was scanned
 5927:        FirstName - first name from the sheet
 5928:        LastName  - last name from the sheet
 5929: 
 5930:      if just_header was not true these key may also exist
 5931: 
 5932:        missingerror - a list of bubble ranges that are considered to be answers
 5933:                       to a single question that don't have any bubbles filled in.
 5934:                       Of the form questionnumber:firstbubblenumber:count.
 5935:        doubleerror  - a list of bubble ranges that are considered to be answers
 5936:                       to a single question that have more than one bubble filled in.
 5937:                       Of the form questionnumber::firstbubblenumber:count
 5938:    
 5939:                 In the above, count is the number of bubble responses in the
 5940:                 input line needed to represent the possible answers to the question.
 5941:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5942:                 per line would have count = 2.
 5943: 
 5944:        maxquest     - the number of the last bubble line that was parsed
 5945: 
 5946:        (<number> starts at 1)
 5947:        <number>.answer - zero or more letters representing the selected
 5948:                          letters from the scanline for the bubble line 
 5949:                          <number>.
 5950:                          if blank there was either no bubble or there where
 5951:                          multiple bubbles, (consult the keys missingerror and
 5952:                          doubleerror if this is an error condition)
 5953: 
 5954: =cut
 5955: 
 5956: sub scantron_parse_scanline {
 5957:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 5958:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 5959:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 5960: 
 5961:     my %record;
 5962:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 5963:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5964: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5965: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5966: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5967: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5968: 	    $record{'scantron.CODE'}=substr($data,
 5969: 					    $$scantron_config{'CODEstart'}-1,
 5970: 					    $$scantron_config{'CODElength'});
 5971: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5972: 		$record{'scantron.useCODE'}=1;
 5973: 	    }
 5974: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5975: 		$record{'scantron.CODE_ignore_dup'}=1;
 5976: 	    }
 5977: 	} else {
 5978: 	    #FIXME interpret first N questions
 5979: 	}
 5980:     }
 5981:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5982: 				  $$scantron_config{'IDlength'});
 5983:     $record{'scantron.PaperID'}=
 5984: 	substr($data,$$scantron_config{'PaperID'}-1,
 5985: 	       $$scantron_config{'PaperIDlength'});
 5986:     $record{'scantron.FirstName'}=
 5987: 	substr($data,$$scantron_config{'FirstName'}-1,
 5988: 	       $$scantron_config{'FirstNamelength'});
 5989:     $record{'scantron.LastName'}=
 5990: 	substr($data,$$scantron_config{'LastName'}-1,
 5991: 	       $$scantron_config{'LastNamelength'});
 5992:     if ($just_header) { return \%record; }
 5993: 
 5994:     my @alphabet=('A'..'Z');
 5995:     my $questnum=0;
 5996:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5997: 
 5998:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5999:     if ($randompick || $randomorder) {
 6000:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6001:                                          $master_seq,$symb_to_resource,
 6002:                                          $partids_by_symb,$orderedforcode,
 6003:                                          $respnumlookup,$startline);
 6004:         if ($total) {
 6005:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6006:         }
 6007:         if (ref($totalref)) {
 6008:             $$totalref = $total;
 6009:         }
 6010:     }
 6011:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6012:     chomp($questions);		# Get rid of any trailing \n.
 6013:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6014:     while (length($questions)) {
 6015:         my $answers_needed;
 6016:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6017:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6018:         } else {
 6019: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6020:         }
 6021:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6022:                              || 1;
 6023:         $questnum++;
 6024:         my $quest_id = $questnum;
 6025:         my $currentquest = substr($questions,0,$answer_length);
 6026:         $questions       = substr($questions,$answer_length);
 6027:         if (length($currentquest) < $answer_length) { next; }
 6028: 
 6029:         my $subdivided;
 6030:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6031:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6032:         } else {
 6033:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6034:         }
 6035:         if ($subdivided =~ /,/) {
 6036:             my $subquestnum = 1;
 6037:             my $subquestions = $currentquest;
 6038:             my @subanswers_needed = split(/,/,$subdivided);
 6039:             foreach my $subans (@subanswers_needed) {
 6040:                 my $subans_length =
 6041:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6042:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6043:                 $subquestions   = substr($subquestions,$subans_length);
 6044:                 $quest_id = "$questnum.$subquestnum";
 6045:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6046:                     ($$scantron_config{'Qon'} eq 'number')) {
 6047:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6048:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6049:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6050:                         $randomorder,$randompick,$respnumlookup);
 6051:                 } else {
 6052:                     $ansnum = &scantron_validator_positional($ansnum,
 6053:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6054:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6055:                         $randomorder,$randompick,$respnumlookup);
 6056:                 }
 6057:                 $subquestnum ++;
 6058:             }
 6059:         } else {
 6060:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6061:                 ($$scantron_config{'Qon'} eq 'number')) {
 6062:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6063:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6064:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6065:                     $randomorder,$randompick,$respnumlookup);
 6066:             } else {
 6067:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6068:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6069:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6070:                     $randomorder,$randompick,$respnumlookup);
 6071:             }
 6072:         }
 6073:     }
 6074:     $record{'scantron.maxquest'}=$questnum;
 6075:     return \%record;
 6076: }
 6077: 
 6078: sub get_master_seq {
 6079:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6080:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6081:                    (ref($symb_to_resource) eq 'HASH'));
 6082:     my $resource_error;
 6083:     foreach my $resource (@{$resources}) {
 6084:         my $ressymb;
 6085:         if (ref($resource)) {
 6086:             $ressymb = $resource->symb();
 6087:             push(@{$master_seq},$ressymb);
 6088:             $symb_to_resource->{$ressymb} = $resource;
 6089:         } else {
 6090:             $resource_error = 1;
 6091:             last;
 6092:         }
 6093:     }
 6094:     return $resource_error;
 6095: }
 6096: 
 6097: sub get_respnum_lookups {
 6098:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6099:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6100:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6101:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6102:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6103:                    (ref($startline) eq 'HASH'));
 6104:     my ($user,$scancode);
 6105:     if ((exists($record->{'scantron.CODE'})) &&
 6106:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6107:         $scancode = $record->{'scantron.CODE'};
 6108:     } else {
 6109:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6110:     }
 6111:     my @mapresources =
 6112:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6113:                      $orderedforcode);
 6114:     my $total = 0;
 6115:     my $count = 0;
 6116:     foreach my $resource (@mapresources) {
 6117:         my $id = $resource->id();
 6118:         my $symb = $resource->symb();
 6119:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6120:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6121:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6122:                 if ($respnum ne '') {
 6123:                     $respnumlookup->{$count} = $respnum;
 6124:                     $startline->{$count} = $total;
 6125:                     $total += $bubble_lines_per_response{$respnum};
 6126:                     $count ++;
 6127:                 }
 6128:             }
 6129:         }
 6130:     }
 6131:     return $total;
 6132: }
 6133: 
 6134: sub scantron_validator_lettnum {
 6135:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6136:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6137:         $randompick,$respnumlookup) = @_;
 6138: 
 6139:     # Qon 'letter' implies for each slot in currquest we have:
 6140:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6141:     #    about anything else (esp. a value of Qoff) for missing
 6142:     #    bubbles.
 6143:     #
 6144:     # Qon 'number' implies each slot gives a digit that indexes the
 6145:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6146:     #    and * or ? for double bubbles on a single line.
 6147:     #
 6148: 
 6149:     my $matchon;
 6150:     if ($$scantron_config{'Qon'} eq 'letter') {
 6151:         $matchon = '[A-Z]';
 6152:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6153:         $matchon = '\d';
 6154:     }
 6155:     my $occurrences = 0;
 6156:     my $responsenum = $questnum-1;
 6157:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6158:        $responsenum = $respnumlookup->{$questnum-1} 
 6159:     }
 6160:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6161:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6162:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6163:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6164:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6165:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6166:         my @singlelines = split('',$currquest);
 6167:         foreach my $entry (@singlelines) {
 6168:             $occurrences = &occurence_count($entry,$matchon);
 6169:             if ($occurrences > 1) {
 6170:                 last;
 6171:             }
 6172:         }
 6173:     } else {
 6174:         $occurrences = &occurence_count($currquest,$matchon); 
 6175:     }
 6176:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6177:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6178:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6179:             my $bubble = substr($currquest,$ans,1);
 6180:             if ($bubble =~ /$matchon/ ) {
 6181:                 if ($$scantron_config{'Qon'} eq 'number') {
 6182:                     if ($bubble == 0) {
 6183:                         $bubble = 10; 
 6184:                     }
 6185:                     $record->{"scantron.$ansnum.answer"} = 
 6186:                         $alphabet->[$bubble-1];
 6187:                 } else {
 6188:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6189:                 }
 6190:             } else {
 6191:                 $record->{"scantron.$ansnum.answer"}='';
 6192:             }
 6193:             $ansnum++;
 6194:         }
 6195:     } elsif (!defined($currquest)
 6196:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6197:             || (&occurence_count($currquest,$matchon) == 0)) {
 6198:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6199:             $record->{"scantron.$ansnum.answer"}='';
 6200:             $ansnum++;
 6201:         }
 6202:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6203:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6204:         }
 6205:     } else {
 6206:         if ($$scantron_config{'Qon'} eq 'number') {
 6207:             $currquest = &digits_to_letters($currquest);            
 6208:         }
 6209:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6210:             my $bubble = substr($currquest,$ans,1);
 6211:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6212:             $ansnum++;
 6213:         }
 6214:     }
 6215:     return $ansnum;
 6216: }
 6217: 
 6218: sub scantron_validator_positional {
 6219:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6220:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6221:         $randomorder,$randompick,$respnumlookup) = @_;
 6222: 
 6223:     # Otherwise there's a positional notation;
 6224:     # each bubble line requires Qlength items, and there are filled in
 6225:     # bubbles for each case where there 'Qon' characters.
 6226:     #
 6227: 
 6228:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6229: 
 6230:     # If the split only gives us one element.. the full length of the
 6231:     # answer string, no bubbles are filled in:
 6232: 
 6233:     if ($answers_needed eq '') {
 6234:         return;
 6235:     }
 6236: 
 6237:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6238:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6239:             $record->{"scantron.$ansnum.answer"}='';
 6240:             $ansnum++;
 6241:         }
 6242:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6243:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6244:         }
 6245:     } elsif (scalar(@array) == 2) {
 6246:         my $location = length($array[0]);
 6247:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6248:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6249:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6250:             if ($ans eq $line_num) {
 6251:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6252:             } else {
 6253:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6254:             }
 6255:             $ansnum++;
 6256:          }
 6257:     } else {
 6258:         #  If there's more than one instance of a bubble character
 6259:         #  That's a double bubble; with positional notation we can
 6260:         #  record all the bubbles filled in as well as the
 6261:         #  fact this response consists of multiple bubbles.
 6262:         #
 6263:         my $responsenum = $questnum-1;
 6264:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6265:             $responsenum = $respnumlookup->{$questnum-1}
 6266:         }
 6267:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6268:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6269:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6270:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6271:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6272:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6273:             my $doubleerror = 0;
 6274:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6275:                    (!$doubleerror)) {
 6276:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6277:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6278:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6279:                if (length(@currarray) > 2) {
 6280:                    $doubleerror = 1;
 6281:                } 
 6282:             }
 6283:             if ($doubleerror) {
 6284:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6285:             }
 6286:         } else {
 6287:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6288:         }
 6289:         my $item = $ansnum;
 6290:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6291:             $record->{"scantron.$item.answer"} = '';
 6292:             $item ++;
 6293:         }
 6294: 
 6295:         my @ans=@array;
 6296:         my $i=0;
 6297:         my $increment = 0;
 6298:         while ($#ans) {
 6299:             $i+=length($ans[0]) + $increment;
 6300:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6301:             my $bubble = $i%$$scantron_config{'Qlength'};
 6302:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6303:             shift(@ans);
 6304:             $increment = 1;
 6305:         }
 6306:         $ansnum += $answers_needed;
 6307:     }
 6308:     return $ansnum;
 6309: }
 6310: 
 6311: =pod
 6312: 
 6313: =item scantron_add_delay
 6314: 
 6315:    Adds an error message that occurred during the grading phase to a
 6316:    queue of messages to be shown after grading pass is complete
 6317: 
 6318:  Arguments:
 6319:    $delayqueue  - arrary ref of hash ref of error messages
 6320:    $scanline    - the scanline that caused the error
 6321:    $errormesage - the error message
 6322:    $errorcode   - a numeric code for the error
 6323: 
 6324:  Side Effects:
 6325:    updates the $delayqueue to have a new hash ref of the error
 6326: 
 6327: =cut
 6328: 
 6329: sub scantron_add_delay {
 6330:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6331:     push(@$delayqueue,
 6332: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6333: 	  'ecode' => $errorcode }
 6334: 	 );
 6335: }
 6336: 
 6337: =pod
 6338: 
 6339: =item scantron_find_student
 6340: 
 6341:    Finds the username for the current scanline
 6342: 
 6343:   Arguments:
 6344:    $scantron_record - hash result from scantron_parse_scanline
 6345:    $scan_data       - hash of correction information 
 6346:                       (see &scantron_getfile() form more information)
 6347:    $idmap           - hash from &username_to_idmap()
 6348:    $line            - number of current scanline
 6349:  
 6350:   Returns:
 6351:    Either 'username:domain' or undef if unknown
 6352: 
 6353: =cut
 6354: 
 6355: sub scantron_find_student {
 6356:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6357:     my $scanID=$$scantron_record{'scantron.ID'};
 6358:     if ($scanID =~ /^\s*$/) {
 6359:  	return &scan_data($scan_data,"$line.user");
 6360:     }
 6361:     foreach my $id (keys(%$idmap)) {
 6362:  	if (lc($id) eq lc($scanID)) {
 6363:  	    return $$idmap{$id};
 6364:  	}
 6365:     }
 6366:     return undef;
 6367: }
 6368: 
 6369: =pod
 6370: 
 6371: =item scantron_filter
 6372: 
 6373:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6374:    hidden resources was selected
 6375: 
 6376: =cut
 6377: 
 6378: sub scantron_filter {
 6379:     my ($curres)=@_;
 6380: 
 6381:     if (ref($curres) && $curres->is_problem()) {
 6382: 	# if the user has asked to not have either hidden
 6383: 	# or 'randomout' controlled resources to be graded
 6384: 	# don't include them
 6385: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6386: 	    && $curres->randomout) {
 6387: 	    return 0;
 6388: 	}
 6389: 	return 1;
 6390:     }
 6391:     return 0;
 6392: }
 6393: 
 6394: =pod
 6395: 
 6396: =item scantron_process_corrections
 6397: 
 6398:    Gets correction information out of submitted form data and corrects
 6399:    the scanline
 6400: 
 6401: =cut
 6402: 
 6403: sub scantron_process_corrections {
 6404:     my ($r) = @_;
 6405:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6406:     my ($scanlines,$scan_data)=&scantron_getfile();
 6407:     my $classlist=&Apache::loncoursedata::get_classlist();
 6408:     my $which=$env{'form.scantron_line'};
 6409:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6410:     my ($skip,$err,$errmsg);
 6411:     if ($env{'form.scantron_skip_record'}) {
 6412: 	$skip=1;
 6413:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6414: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6415: 	    $env{'form.scantron_domain'};
 6416: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6417: 	($line,$err,$errmsg)=
 6418: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6419: 				     'ID',{'newid'=>$newid,
 6420: 				    'username'=>$env{'form.scantron_username'},
 6421: 				    'domain'=>$env{'form.scantron_domain'}});
 6422:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6423: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6424: 	my $newCODE;
 6425: 	my %args;
 6426: 	if      ($resolution eq 'use_unfound') {
 6427: 	    $newCODE='use_unfound';
 6428: 	} elsif ($resolution eq 'use_found') {
 6429: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6430: 	} elsif ($resolution eq 'use_typed') {
 6431: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6432: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6433: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6434: 	}
 6435: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6436: 	    $args{'CODE_ignore_dup'}=1;
 6437: 	}
 6438: 	$args{'CODE'}=$newCODE;
 6439: 	($line,$err,$errmsg)=
 6440: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6441: 				     'CODE',\%args);
 6442:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6443: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6444: 	    ($line,$err,$errmsg)=
 6445: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6446: 					 $which,'answer',
 6447: 					 { 'question'=>$question,
 6448: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6449:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6450: 	    if ($err) { last; }
 6451: 	}
 6452:     }
 6453:     if ($err) {
 6454:         $r->print(
 6455:             '<p class="LC_error">'
 6456:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6457:                 $errmsg)
 6458:            .'</p>');
 6459:     } else {
 6460: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6461: 	&scantron_putfile($scanlines,$scan_data);
 6462:     }
 6463: }
 6464: 
 6465: =pod
 6466: 
 6467: =item reset_skipping_status
 6468: 
 6469:    Forgets the current set of remember skipped scanlines (and thus
 6470:    reverts back to considering all lines in the
 6471:    scantron_skipped_<filename> file)
 6472: 
 6473: =cut
 6474: 
 6475: sub reset_skipping_status {
 6476:     my ($scanlines,$scan_data)=&scantron_getfile();
 6477:     &scan_data($scan_data,'remember_skipping',undef,1);
 6478:     &scantron_putfile(undef,$scan_data);
 6479: }
 6480: 
 6481: =pod
 6482: 
 6483: =item start_skipping
 6484: 
 6485:    Marks a scanline to be skipped. 
 6486: 
 6487: =cut
 6488: 
 6489: sub start_skipping {
 6490:     my ($scan_data,$i)=@_;
 6491:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6492:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6493: 	$remembered{$i}=2;
 6494:     } else {
 6495: 	$remembered{$i}=1;
 6496:     }
 6497:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6498: }
 6499: 
 6500: =pod
 6501: 
 6502: =item should_be_skipped
 6503: 
 6504:    Checks whether a scanline should be skipped.
 6505: 
 6506: =cut
 6507: 
 6508: sub should_be_skipped {
 6509:     my ($scanlines,$scan_data,$i)=@_;
 6510:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6511: 	# not redoing old skips
 6512: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6513: 	return 0;
 6514:     }
 6515:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6516: 
 6517:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6518: 	return 0;
 6519:     }
 6520:     return 1;
 6521: }
 6522: 
 6523: =pod
 6524: 
 6525: =item remember_current_skipped
 6526: 
 6527:    Discovers what scanlines are in the scantron_skipped_<filename>
 6528:    file and remembers them into scan_data for later use.
 6529: 
 6530: =cut
 6531: 
 6532: sub remember_current_skipped {
 6533:     my ($scanlines,$scan_data)=&scantron_getfile();
 6534:     my %to_remember;
 6535:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6536: 	if ($scanlines->{'skipped'}[$i]) {
 6537: 	    $to_remember{$i}=1;
 6538: 	}
 6539:     }
 6540: 
 6541:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6542:     &scantron_putfile(undef,$scan_data);
 6543: }
 6544: 
 6545: =pod
 6546: 
 6547: =item check_for_error
 6548: 
 6549:     Checks if there was an error when attempting to remove a specific
 6550:     scantron_.. bubblesheet data file. Prints out an error if
 6551:     something went wrong.
 6552: 
 6553: =cut
 6554: 
 6555: sub check_for_error {
 6556:     my ($r,$result)=@_;
 6557:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6558: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6559:     }
 6560: }
 6561: 
 6562: =pod
 6563: 
 6564: =item scantron_warning_screen
 6565: 
 6566:    Interstitial screen to make sure the operator has selected the
 6567:    correct options before we start the validation phase.
 6568: 
 6569: =cut
 6570: 
 6571: sub scantron_warning_screen {
 6572:     my ($button_text,$symb)=@_;
 6573:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6574:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6575:     my $CODElist;
 6576:     if ($scantron_config{'CODElocation'} &&
 6577: 	$scantron_config{'CODEstart'} &&
 6578: 	$scantron_config{'CODElength'}) {
 6579: 	$CODElist=$env{'form.scantron_CODElist'};
 6580: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6581: 	$CODElist=
 6582: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6583: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6584:     }
 6585:     my $lastbubblepoints;
 6586:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6587:         $lastbubblepoints =
 6588:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6589:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6590:     }
 6591:     return ('
 6592: <p>
 6593: <span class="LC_warning">
 6594: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6595: </p>
 6596: <table>
 6597: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6598: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6599: '.$CODElist.$lastbubblepoints.'
 6600: </table>
 6601: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6602: '.&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>
 6603: 
 6604: <br />
 6605: ');
 6606: }
 6607: 
 6608: =pod
 6609: 
 6610: =item scantron_do_warning
 6611: 
 6612:    Check if the operator has picked something for all required
 6613:    fields. Error out if something is missing.
 6614: 
 6615: =cut
 6616: 
 6617: sub scantron_do_warning {
 6618:     my ($r,$symb)=@_;
 6619:     if (!$symb) {return '';}
 6620:     my $default_form_data=&defaultFormData($symb);
 6621:     $r->print(&scantron_form_start().$default_form_data);
 6622:     if ( $env{'form.selectpage'} eq '' ||
 6623: 	 $env{'form.scantron_selectfile'} eq '' ||
 6624: 	 $env{'form.scantron_format'} eq '' ) {
 6625: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6626: 	if ( $env{'form.selectpage'} eq '') {
 6627: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6628: 	} 
 6629: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6630: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6631: 	} 
 6632: 	if ( $env{'form.scantron_format'} eq '') {
 6633: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6634: 	} 
 6635:     } else {
 6636: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6637:         my $bubbledbyhand=&hand_bubble_option();
 6638: 	$r->print('
 6639: '.$warning.$bubbledbyhand.'
 6640: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6641: <input type="hidden" name="command" value="scantron_validate" />
 6642: ');
 6643:     }
 6644:     $r->print("</form><br />");
 6645:     return '';
 6646: }
 6647: 
 6648: =pod
 6649: 
 6650: =item scantron_form_start
 6651: 
 6652:     html hidden input for remembering all selected grading options
 6653: 
 6654: =cut
 6655: 
 6656: sub scantron_form_start {
 6657:     my ($max_bubble)=@_;
 6658:     my $result= <<SCANTRONFORM;
 6659: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6660:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6661:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6662:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6663:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6664:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6665:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6666:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6667:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6668:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6669: SCANTRONFORM
 6670: 
 6671:   my $line = 0;
 6672:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6673:        my $chunk =
 6674: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6675:        $chunk .=
 6676: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6677:        $chunk .= 
 6678:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6679:        $chunk .=
 6680:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6681:        $chunk .=
 6682:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6683:        $result .= $chunk;
 6684:        $line++;
 6685:     }
 6686:     return $result;
 6687: }
 6688: 
 6689: =pod
 6690: 
 6691: =item scantron_validate_file
 6692: 
 6693:     Dispatch routine for doing validation of a bubblesheet data file.
 6694: 
 6695:     Also processes any necessary information resets that need to
 6696:     occur before validation begins (ignore previous corrections,
 6697:     restarting the skipped records processing)
 6698: 
 6699: =cut
 6700: 
 6701: sub scantron_validate_file {
 6702:     my ($r,$symb) = @_;
 6703:     if (!$symb) {return '';}
 6704:     my $default_form_data=&defaultFormData($symb);
 6705:     
 6706:     # do the detection of only doing skipped records first before we delete
 6707:     # them when doing the corrections reset
 6708:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6709: 	&reset_skipping_status();
 6710:     }
 6711:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6712: 	&remember_current_skipped();
 6713: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6714:     }
 6715: 
 6716:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6717: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6718: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6719: 	&check_for_error($r,&scantron_remove_scan_data());
 6720: 	$env{'form.scantron_options_ignore'}='done';
 6721:     }
 6722: 
 6723:     if ($env{'form.scantron_corrections'}) {
 6724: 	&scantron_process_corrections($r);
 6725:     }
 6726:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6727:     #get the student pick code ready
 6728:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6729:     my $nav_error;
 6730:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6731:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6732:     if ($nav_error) {
 6733:         $r->print(&navmap_errormsg());
 6734:         return '';
 6735:     }
 6736:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6737:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6738:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6739:     }
 6740:     $r->print($result);
 6741:     
 6742:     my @validate_phases=( 'sequence',
 6743: 			  'ID',
 6744: 			  'CODE',
 6745: 			  'doublebubble',
 6746: 			  'missingbubbles');
 6747:     if (!$env{'form.validatepass'}) {
 6748: 	$env{'form.validatepass'} = 0;
 6749:     }
 6750:     my $currentphase=$env{'form.validatepass'};
 6751: 
 6752: 
 6753:     my $stop=0;
 6754:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6755: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6756: 	$r->rflush();
 6757:      
 6758: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6759: 	{
 6760: 	    no strict 'refs';
 6761: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6762: 	}
 6763:     }
 6764:     if (!$stop) {
 6765: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6766: 	$r->print(&mt('Validation process complete.').'<br />'.
 6767:                   $warning.
 6768:                   &mt('Perform verification for each student after storage of submissions?').
 6769:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6770:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6771:                   ('&nbsp;'x3).'<label>'.
 6772:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6773:                   '</label></span><br />'.
 6774:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6775:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6776:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6777:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6778:     } else {
 6779: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6780: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6781:     }
 6782:     if ($stop) {
 6783: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6784: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6785: 	    $r->print(' '.&mt('this error').' <br />');
 6786: 
 6787: 	    $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>');
 6788: 	} else {
 6789:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6790: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6791:             } else {
 6792:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6793:             }
 6794: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6795: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6796: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6797: 	}
 6798:     }
 6799:     $r->print(" </form><br />");
 6800:     return '';
 6801: }
 6802: 
 6803: 
 6804: =pod
 6805: 
 6806: =item scantron_remove_file
 6807: 
 6808:    Removes the requested bubblesheet data file, makes sure that
 6809:    scantron_original_<filename> is never removed
 6810: 
 6811: 
 6812: =cut
 6813: 
 6814: sub scantron_remove_file {
 6815:     my ($which)=@_;
 6816:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6817:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6818:     my $file='scantron_';
 6819:     if ($which eq 'corrected' || $which eq 'skipped') {
 6820: 	$file.=$which.'_';
 6821:     } else {
 6822: 	return 'refused';
 6823:     }
 6824:     $file.=$env{'form.scantron_selectfile'};
 6825:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6826: }
 6827: 
 6828: 
 6829: =pod
 6830: 
 6831: =item scantron_remove_scan_data
 6832: 
 6833:    Removes all scan_data correction for the requested bubblesheet
 6834:    data file.  (In the case that both the are doing skipped records we need
 6835:    to remember the old skipped lines for the time being so that element
 6836:    persists for a while.)
 6837: 
 6838: =cut
 6839: 
 6840: sub scantron_remove_scan_data {
 6841:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6842:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6843:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6844:     my @todelete;
 6845:     my $filename=$env{'form.scantron_selectfile'};
 6846:     foreach my $key (@keys) {
 6847: 	if ($key=~/^\Q$filename\E_/) {
 6848: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6849: 		$key=~/remember_skipping/) {
 6850: 		next;
 6851: 	    }
 6852: 	    push(@todelete,$key);
 6853: 	}
 6854:     }
 6855:     my $result;
 6856:     if (@todelete) {
 6857: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6858: 				       \@todelete,$cdom,$cname);
 6859:     } else {
 6860: 	$result = 'ok';
 6861:     }
 6862:     return $result;
 6863: }
 6864: 
 6865: 
 6866: =pod
 6867: 
 6868: =item scantron_getfile
 6869: 
 6870:     Fetches the requested bubblesheet data file (all 3 versions), and
 6871:     the scan_data hash
 6872:   
 6873:   Arguments:
 6874:     None
 6875: 
 6876:   Returns:
 6877:     2 hash references
 6878: 
 6879:      - first one has 
 6880:          orig      -
 6881:          corrected -
 6882:          skipped   -  each of which points to an array ref of the specified
 6883:                       file broken up into individual lines
 6884:          count     - number of scanlines
 6885:  
 6886:      - second is the scan_data hash possible keys are
 6887:        ($number refers to scanline numbered $number and thus the key affects
 6888:         only that scanline
 6889:         $bubline refers to the specific bubble line element and the aspects
 6890:         refers to that specific bubble line element)
 6891: 
 6892:        $number.user - username:domain to use
 6893:        $number.CODE_ignore_dup 
 6894:                     - ignore the duplicate CODE error 
 6895:        $number.useCODE
 6896:                     - use the CODE in the scanline as is
 6897:        $number.no_bubble.$bubline
 6898:                     - it is valid that there is no bubbled in bubble
 6899:                       at $number $bubline
 6900:        remember_skipping
 6901:                     - a frozen hash containing keys of $number and values
 6902:                       of either 
 6903:                         1 - we are on a 'do skipped records pass' and plan
 6904:                             on processing this line
 6905:                         2 - we are on a 'do skipped records pass' and this
 6906:                             scanline has been marked to skip yet again
 6907: 
 6908: =cut
 6909: 
 6910: sub scantron_getfile {
 6911:     #FIXME really would prefer a scantron directory
 6912:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6913:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6914:     my $lines;
 6915:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6916: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6917:     my %scanlines;
 6918:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6919:     my $temp=$scanlines{'orig'};
 6920:     $scanlines{'count'}=$#$temp;
 6921: 
 6922:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6923: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6924:     if ($lines eq '-1') {
 6925: 	$scanlines{'corrected'}=[];
 6926:     } else {
 6927: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6928:     }
 6929:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6930: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6931:     if ($lines eq '-1') {
 6932: 	$scanlines{'skipped'}=[];
 6933:     } else {
 6934: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6935:     }
 6936:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6937:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6938:     my %scan_data = @tmp;
 6939:     return (\%scanlines,\%scan_data);
 6940: }
 6941: 
 6942: =pod
 6943: 
 6944: =item lonnet_putfile
 6945: 
 6946:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6947: 
 6948:  Arguments:
 6949:    $contents - data to store
 6950:    $filename - filename to store $contents into
 6951: 
 6952:  Returns:
 6953:    result value from &Apache::lonnet::finishuserfileupload
 6954: 
 6955: =cut
 6956: 
 6957: sub lonnet_putfile {
 6958:     my ($contents,$filename)=@_;
 6959:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6960:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6961:     $env{'form.sillywaytopassafilearound'}=$contents;
 6962:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6963: 
 6964: }
 6965: 
 6966: =pod
 6967: 
 6968: =item scantron_putfile
 6969: 
 6970:     Stores the current version of the bubblesheet data files, and the
 6971:     scan_data hash. (Does not modify the original version only the
 6972:     corrected and skipped versions.
 6973: 
 6974:  Arguments:
 6975:     $scanlines - hash ref that looks like the first return value from
 6976:                  &scantron_getfile()
 6977:     $scan_data - hash ref that looks like the second return value from
 6978:                  &scantron_getfile()
 6979: 
 6980: =cut
 6981: 
 6982: sub scantron_putfile {
 6983:     my ($scanlines,$scan_data) = @_;
 6984:     #FIXME really would prefer a scantron directory
 6985:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6986:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6987:     if ($scanlines) {
 6988: 	my $prefix='scantron_';
 6989: # no need to update orig, shouldn't change
 6990: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6991: #		    $env{'form.scantron_selectfile'});
 6992: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6993: 			$prefix.'corrected_'.
 6994: 			$env{'form.scantron_selectfile'});
 6995: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6996: 			$prefix.'skipped_'.
 6997: 			$env{'form.scantron_selectfile'});
 6998:     }
 6999:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7000: }
 7001: 
 7002: =pod
 7003: 
 7004: =item scantron_get_line
 7005: 
 7006:    Returns the correct version of the scanline
 7007: 
 7008:  Arguments:
 7009:     $scanlines - hash ref that looks like the first return value from
 7010:                  &scantron_getfile()
 7011:     $scan_data - hash ref that looks like the second return value from
 7012:                  &scantron_getfile()
 7013:     $i         - number of the requested line (starts at 0)
 7014: 
 7015:  Returns:
 7016:    A scanline, (either the original or the corrected one if it
 7017:    exists), or undef if the requested scanline should be
 7018:    skipped. (Either because it's an skipped scanline, or it's an
 7019:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7020:    pass.
 7021: 
 7022: =cut
 7023: 
 7024: sub scantron_get_line {
 7025:     my ($scanlines,$scan_data,$i)=@_;
 7026:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7027:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7028:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7029:     return $scanlines->{'orig'}[$i]; 
 7030: }
 7031: 
 7032: =pod
 7033: 
 7034: =item scantron_todo_count
 7035: 
 7036:     Counts the number of scanlines that need processing.
 7037: 
 7038:  Arguments:
 7039:     $scanlines - hash ref that looks like the first return value from
 7040:                  &scantron_getfile()
 7041:     $scan_data - hash ref that looks like the second return value from
 7042:                  &scantron_getfile()
 7043: 
 7044:  Returns:
 7045:     $count - number of scanlines to process
 7046: 
 7047: =cut
 7048: 
 7049: sub get_todo_count {
 7050:     my ($scanlines,$scan_data)=@_;
 7051:     my $count=0;
 7052:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7053: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7054: 	if ($line=~/^[\s\cz]*$/) { next; }
 7055: 	$count++;
 7056:     }
 7057:     return $count;
 7058: }
 7059: 
 7060: =pod
 7061: 
 7062: =item scantron_put_line
 7063: 
 7064:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7065:     data file.
 7066: 
 7067:  Arguments:
 7068:     $scanlines - hash ref that looks like the first return value from
 7069:                  &scantron_getfile()
 7070:     $scan_data - hash ref that looks like the second return value from
 7071:                  &scantron_getfile()
 7072:     $i         - line number to update
 7073:     $newline   - contents of the updated scanline
 7074:     $skip      - if true make the line for skipping and update the
 7075:                  'skipped' file
 7076: 
 7077: =cut
 7078: 
 7079: sub scantron_put_line {
 7080:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7081:     if ($skip) {
 7082: 	$scanlines->{'skipped'}[$i]=$newline;
 7083: 	&start_skipping($scan_data,$i);
 7084: 	return;
 7085:     }
 7086:     $scanlines->{'corrected'}[$i]=$newline;
 7087: }
 7088: 
 7089: =pod
 7090: 
 7091: =item scantron_clear_skip
 7092: 
 7093:    Remove a line from the 'skipped' file
 7094: 
 7095:  Arguments:
 7096:     $scanlines - hash ref that looks like the first return value from
 7097:                  &scantron_getfile()
 7098:     $scan_data - hash ref that looks like the second return value from
 7099:                  &scantron_getfile()
 7100:     $i         - line number to update
 7101: 
 7102: =cut
 7103: 
 7104: sub scantron_clear_skip {
 7105:     my ($scanlines,$scan_data,$i)=@_;
 7106:     if (exists($scanlines->{'skipped'}[$i])) {
 7107: 	undef($scanlines->{'skipped'}[$i]);
 7108: 	return 1;
 7109:     }
 7110:     return 0;
 7111: }
 7112: 
 7113: =pod
 7114: 
 7115: =item scantron_filter_not_exam
 7116: 
 7117:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7118:    filter out resources that are not marked as 'exam' mode
 7119: 
 7120: =cut
 7121: 
 7122: sub scantron_filter_not_exam {
 7123:     my ($curres)=@_;
 7124:     
 7125:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7126: 	# if the user has asked to not have either hidden
 7127: 	# or 'randomout' controlled resources to be graded
 7128: 	# don't include them
 7129: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7130: 	    && $curres->randomout) {
 7131: 	    return 0;
 7132: 	}
 7133: 	return 1;
 7134:     }
 7135:     return 0;
 7136: }
 7137: 
 7138: =pod
 7139: 
 7140: =item scantron_validate_sequence
 7141: 
 7142:     Validates the selected sequence, checking for resource that are
 7143:     not set to exam mode.
 7144: 
 7145: =cut
 7146: 
 7147: sub scantron_validate_sequence {
 7148:     my ($r,$currentphase) = @_;
 7149: 
 7150:     my $navmap=Apache::lonnavmaps::navmap->new();
 7151:     unless (ref($navmap)) {
 7152:         $r->print(&navmap_errormsg());
 7153:         return (1,$currentphase);
 7154:     }
 7155:     my (undef,undef,$sequence)=
 7156: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7157: 
 7158:     my $map=$navmap->getResourceByUrl($sequence);
 7159: 
 7160:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7161:                                     value="ignore" />');
 7162:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7163: 	my @resources=
 7164: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7165: 	if (@resources) {
 7166: 	    $r->print(
 7167:                 '<p class="LC_warning">'
 7168:                .&mt('Some resources in the sequence currently are not set to'
 7169:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7170:                    .' work correctly.')
 7171:                .'</p>'
 7172:             );
 7173: 	    return (1,$currentphase);
 7174: 	}
 7175:     }
 7176: 
 7177:     return (0,$currentphase+1);
 7178: }
 7179: 
 7180: 
 7181: 
 7182: sub scantron_validate_ID {
 7183:     my ($r,$currentphase) = @_;
 7184:     
 7185:     #get student info
 7186:     my $classlist=&Apache::loncoursedata::get_classlist();
 7187:     my %idmap=&username_to_idmap($classlist);
 7188: 
 7189:     #get scantron line setup
 7190:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7191:     my ($scanlines,$scan_data)=&scantron_getfile();
 7192: 
 7193:     my $nav_error;
 7194:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7195:     if ($nav_error) {
 7196:         $r->print(&navmap_errormsg());
 7197:         return(1,$currentphase);
 7198:     }
 7199: 
 7200:     my %found=('ids'=>{},'usernames'=>{});
 7201:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7202: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7203: 	if ($line=~/^[\s\cz]*$/) { next; }
 7204: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7205: 						 $scan_data);
 7206: 	my $id=$$scan_record{'scantron.ID'};
 7207: 	my $found;
 7208: 	foreach my $checkid (keys(%idmap)) {
 7209: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7210: 	}
 7211: 	if ($found) {
 7212: 	    my $username=$idmap{$found};
 7213: 	    if ($found{'ids'}{$found}) {
 7214: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7215: 					 $line,'duplicateID',$found);
 7216: 		return(1,$currentphase);
 7217: 	    } elsif ($found{'usernames'}{$username}) {
 7218: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7219: 					 $line,'duplicateID',$username);
 7220: 		return(1,$currentphase);
 7221: 	    }
 7222: 	    #FIXME store away line we previously saw the ID on to use above
 7223: 	    $found{'ids'}{$found}++;
 7224: 	    $found{'usernames'}{$username}++;
 7225: 	} else {
 7226: 	    if ($id =~ /^\s*$/) {
 7227: 		my $username=&scan_data($scan_data,"$i.user");
 7228: 		if (defined($username) && $found{'usernames'}{$username}) {
 7229: 		    &scantron_get_correction($r,$i,$scan_record,
 7230: 					     \%scantron_config,
 7231: 					     $line,'duplicateID',$username);
 7232: 		    return(1,$currentphase);
 7233: 		} elsif (!defined($username)) {
 7234: 		    &scantron_get_correction($r,$i,$scan_record,
 7235: 					     \%scantron_config,
 7236: 					     $line,'incorrectID');
 7237: 		    return(1,$currentphase);
 7238: 		}
 7239: 		$found{'usernames'}{$username}++;
 7240: 	    } else {
 7241: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7242: 					 $line,'incorrectID');
 7243: 		return(1,$currentphase);
 7244: 	    }
 7245: 	}
 7246:     }
 7247: 
 7248:     return (0,$currentphase+1);
 7249: }
 7250: 
 7251: 
 7252: sub scantron_get_correction {
 7253:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7254:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7255: #FIXME in the case of a duplicated ID the previous line, probably need
 7256: #to show both the current line and the previous one and allow skipping
 7257: #the previous one or the current one
 7258: 
 7259:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7260:         $r->print(
 7261:             '<p class="LC_warning">'
 7262:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7263:                 "<b>$error</b>",
 7264:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7265:            ."</p> \n");
 7266:     } else {
 7267:         $r->print(
 7268:             '<p class="LC_warning">'
 7269:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7270:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7271:            ."</p> \n");
 7272:     }
 7273:     my $message =
 7274:         '<p>'
 7275:        .&mt('The ID on the form is [_1]',
 7276:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7277:        .'<br />'
 7278:        .&mt('The name on the paper is [_1], [_2]',
 7279:             $$scan_record{'scantron.LastName'},
 7280:             $$scan_record{'scantron.FirstName'})
 7281:        .'</p>';
 7282: 
 7283:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7284:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7285:                            # Array populated for doublebubble or
 7286:     my @lines_to_correct;  # missingbubble errors to build javascript
 7287:                            # to validate radio button checking   
 7288: 
 7289:     if ($error =~ /ID$/) {
 7290: 	if ($error eq 'incorrectID') {
 7291:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7292: 		      "</p>\n");
 7293: 	} elsif ($error eq 'duplicateID') {
 7294:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7295: 	}
 7296: 	$r->print($message);
 7297: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7298: 	$r->print("\n<ul><li> ");
 7299: 	#FIXME it would be nice if this sent back the user ID and
 7300: 	#could do partial userID matches
 7301: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7302: 				       'scantron_username','scantron_domain'));
 7303: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7304: 	$r->print("\n:\n".
 7305: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7306: 
 7307: 	$r->print('</li>');
 7308:     } elsif ($error =~ /CODE$/) {
 7309: 	if ($error eq 'incorrectCODE') {
 7310: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7311: 	} elsif ($error eq 'duplicateCODE') {
 7312: 	    $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");
 7313: 	}
 7314: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7315: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7316:                  ."</p>\n");
 7317: 	$r->print($message);
 7318: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7319: 	$r->print("\n<br /> ");
 7320: 	my $i=0;
 7321: 	if ($error eq 'incorrectCODE' 
 7322: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7323: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7324: 	    if ($closest > 0) {
 7325: 		foreach my $testcode (@{$closest}) {
 7326: 		    my $checked='';
 7327: 		    if (!$i) { $checked=' checked="checked"'; }
 7328: 		    $r->print("
 7329:    <label>
 7330:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7331:        ".&mt("Use the similar CODE [_1] instead.",
 7332: 	    "<b><tt>".$testcode."</tt></b>")."
 7333:     </label>
 7334:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7335: 		    $r->print("\n<br />");
 7336: 		    $i++;
 7337: 		}
 7338: 	    }
 7339: 	}
 7340: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7341: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7342: 	    $r->print("
 7343:     <label>
 7344:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7345:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7346: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7347:     </label>");
 7348: 	    $r->print("\n<br />");
 7349: 	}
 7350: 
 7351: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7352: function change_radio(field) {
 7353:     var slct=document.scantronupload.scantron_CODE_resolution;
 7354:     var i;
 7355:     for (i=0;i<slct.length;i++) {
 7356:         if (slct[i].value==field) { slct[i].checked=true; }
 7357:     }
 7358: }
 7359: ENDSCRIPT
 7360: 	my $href="/adm/pickcode?".
 7361: 	   "form=".&escape("scantronupload").
 7362: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7363: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7364: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7365: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7366: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7367: 	    $r->print("
 7368:     <label>
 7369:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7370:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7371: 	     "<a target='_blank' href='$href'>","</a>")."
 7372:     </label> 
 7373:     ".&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\')" />'));
 7374: 	    $r->print("\n<br />");
 7375: 	}
 7376: 	$r->print("
 7377:     <label>
 7378:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7379:        ".&mt("Use [_1] as the CODE.",
 7380: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7381: 	$r->print("\n<br /><br />");
 7382:     } elsif ($error eq 'doublebubble') {
 7383: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7384: 
 7385: 	# The form field scantron_questions is acutally a list of line numbers.
 7386: 	# represented by this form so:
 7387: 
 7388: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7389:                                                 $respnumlookup,$startline);
 7390: 
 7391: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7392: 		  $line_list.'" />');
 7393: 	$r->print($message);
 7394: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7395: 	foreach my $question (@{$arg}) {
 7396: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7397:                                                    $scan_record, $error,
 7398:                                                    $randomorder,$randompick,
 7399:                                                    $respnumlookup,$startline);
 7400:             push(@lines_to_correct,@linenums);
 7401: 	}
 7402:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7403:     } elsif ($error eq 'missingbubble') {
 7404: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7405: 	$r->print($message);
 7406: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7407: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7408: 
 7409: 	# The form field scantron_questions is actually a list of line numbers not
 7410: 	# a list of question numbers. Therefore:
 7411: 	#
 7412: 
 7413: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7414:                                                 $respnumlookup,$startline);
 7415: 
 7416: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7417: 		  $line_list.'" />');
 7418: 	foreach my $question (@{$arg}) {
 7419: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7420:                                                    $scan_record, $error,
 7421:                                                    $randomorder,$randompick,
 7422:                                                    $respnumlookup,$startline);
 7423:             push(@lines_to_correct,@linenums);
 7424: 	}
 7425:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7426:     } else {
 7427: 	$r->print("\n<ul>");
 7428:     }
 7429:     $r->print("\n</li></ul>");
 7430: }
 7431: 
 7432: sub verify_bubbles_checked {
 7433:     my (@ansnums) = @_;
 7434:     my $ansnumstr = join('","',@ansnums);
 7435:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7436:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7437: function verify_bubble_radio(form) {
 7438:     var ansnumArray = new Array ("$ansnumstr");
 7439:     var need_bubble_count = 0;
 7440:     for (var i=0; i<ansnumArray.length; i++) {
 7441:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7442:             var bubble_picked = 0; 
 7443:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7444:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7445:                     bubble_picked = 1;
 7446:                 }
 7447:             }
 7448:             if (bubble_picked == 0) {
 7449:                 need_bubble_count ++;
 7450:             }
 7451:         }
 7452:     }
 7453:     if (need_bubble_count) {
 7454:         alert("$warning");
 7455:         return;
 7456:     }
 7457:     form.submit(); 
 7458: }
 7459: ENDSCRIPT
 7460:     return $output;
 7461: }
 7462: 
 7463: =pod
 7464: 
 7465: =item  questions_to_line_list
 7466: 
 7467: Converts a list of questions into a string of comma separated
 7468: line numbers in the answer sheet used by the questions.  This is
 7469: used to fill in the scantron_questions form field.
 7470: 
 7471:   Arguments:
 7472:      questions    - Reference to an array of questions.
 7473:      randomorder  - True if randomorder in use.
 7474:      randompick   - True if randompick in use.
 7475:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7476:                      for current line to question number used for same question
 7477:                      in "Master Seqence" (as seen by Course Coordinator).
 7478:      startline    - Reference to hash where key is question number (0 is first)
 7479:                     and key is number of first bubble line for current student
 7480:                     or code-based randompick and/or randomorder.
 7481: 
 7482: =cut
 7483: 
 7484: 
 7485: sub questions_to_line_list {
 7486:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7487:     my @lines;
 7488: 
 7489:     foreach my $item (@{$questions}) {
 7490:         my $question = $item;
 7491:         my ($first,$count,$last);
 7492:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7493:             $question = $1;
 7494:             my $subquestion = $2;
 7495:             my $responsenum = $question-1;
 7496:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7497:                 $responsenum = $respnumlookup->{$question-1};
 7498:                 if (ref($startline) eq 'HASH') {
 7499:                     $first = $startline->{$question-1} + 1;
 7500:                 }
 7501:             } else {
 7502:                 $first = $first_bubble_line{$responsenum} + 1;
 7503:             }
 7504:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7505:             my $subcount = 1;
 7506:             while ($subcount<$subquestion) {
 7507:                 $first += $subans[$subcount-1];
 7508:                 $subcount ++;
 7509:             }
 7510:             $count = $subans[$subquestion-1];
 7511:         } else {
 7512:             my $responsenum = $question-1;
 7513:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7514:                 $responsenum = $respnumlookup->{$question-1};
 7515:                 if (ref($startline) eq 'HASH') {
 7516:                     $first = $startline->{$question-1} + 1;
 7517:                 }
 7518:             } else {
 7519:                 $first = $first_bubble_line{$responsenum} + 1;
 7520:             }
 7521: 	    $count   = $bubble_lines_per_response{$responsenum};
 7522:         }
 7523:         $last = $first+$count-1;
 7524:         push(@lines, ($first..$last));
 7525:     }
 7526:     return join(',', @lines);
 7527: }
 7528: 
 7529: =pod 
 7530: 
 7531: =item prompt_for_corrections
 7532: 
 7533: Prompts for a potentially multiline correction to the
 7534: user's bubbling (factors out common code from scantron_get_correction
 7535: for multi and missing bubble cases).
 7536: 
 7537:  Arguments:
 7538:    $r           - Apache request object.
 7539:    $question    - The question number to prompt for.
 7540:    $scan_config - The scantron file configuration hash.
 7541:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7542:    $error       - Type of error
 7543:    $randomorder - True if randomorder in use.
 7544:    $randompick  - True if randompick in use.
 7545:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7546:                     for current line to question number used for same question
 7547:                     in "Master Seqence" (as seen by Course Coordinator).
 7548:    $startline   - Reference to hash where key is question number (0 is first)
 7549:                   and value is number of first bubble line for current student
 7550:                   or code-based randompick and/or randomorder.
 7551: 
 7552: 
 7553:  Implicit inputs:
 7554:    %bubble_lines_per_response   - Starting line numbers for each question.
 7555:                                   Numbered from 0 (but question numbers are from
 7556:                                   1.
 7557:    %first_bubble_line           - Starting bubble line for each question.
 7558:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7559:                                   type problems render as separate sub-questions, 
 7560:                                   in exam mode. This hash contains a 
 7561:                                   comma-separated list of the lines per 
 7562:                                   sub-question.
 7563:    %responsetype_per_response   - essayresponse, formularesponse,
 7564:                                   stringresponse, imageresponse, reactionresponse,
 7565:                                   and organicresponse type problem parts can have
 7566:                                   multiple lines per response if the weight
 7567:                                   assigned exceeds 10.  In this case, only
 7568:                                   one bubble per line is permitted, but more 
 7569:                                   than one line might contain bubbles, e.g.
 7570:                                   bubbling of: line 1 - J, line 2 - J, 
 7571:                                   line 3 - B would assign 22 points.  
 7572: 
 7573: =cut
 7574: 
 7575: sub prompt_for_corrections {
 7576:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7577:         $randompick, $respnumlookup, $startline) = @_;
 7578:     my ($current_line,$lines);
 7579:     my @linenums;
 7580:     my $questionnum = $question;
 7581:     my ($first,$responsenum);
 7582:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7583:         $question = $1;
 7584:         my $subquestion = $2;
 7585:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7586:             $responsenum = $respnumlookup->{$question-1};
 7587:             if (ref($startline) eq 'HASH') {
 7588:                 $first = $startline->{$question-1};
 7589:             }
 7590:         } else {
 7591:             $responsenum = $question-1;
 7592:             $first = $first_bubble_line{$responsenum};
 7593:         }
 7594:         $current_line = $first + 1 ;
 7595:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7596:         my $subcount = 1;
 7597:         while ($subcount<$subquestion) {
 7598:             $current_line += $subans[$subcount-1];
 7599:             $subcount ++;
 7600:         }
 7601:         $lines = $subans[$subquestion-1];
 7602:     } else {
 7603:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7604:             $responsenum = $respnumlookup->{$question-1};
 7605:             if (ref($startline) eq 'HASH') { 
 7606:                 $first = $startline->{$question-1};
 7607:             }
 7608:         } else {
 7609:             $responsenum = $question-1;
 7610:             $first = $first_bubble_line{$responsenum};
 7611:         }
 7612:         $current_line = $first + 1;
 7613:         $lines        = $bubble_lines_per_response{$responsenum};
 7614:     }
 7615:     if ($lines > 1) {
 7616:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7617:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7618:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7619:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7620:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7621:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7622:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7623:             $r->print(
 7624:                 &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)
 7625:                .'<br /><br />'
 7626:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7627:                .'<br />'
 7628:                .&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.')
 7629:                .'<br />'
 7630:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7631:                .'<br /><br />'
 7632:             );
 7633:         } else {
 7634:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7635:         }
 7636:     }
 7637:     for (my $i =0; $i < $lines; $i++) {
 7638:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7639: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7640: 	        		  $questionnum,$error,split('', $selected));
 7641:         push(@linenums,$current_line);
 7642: 	$current_line++;
 7643:     }
 7644:     if ($lines > 1) {
 7645: 	$r->print("<hr /><br />");
 7646:     }
 7647:     return @linenums;
 7648: }
 7649: 
 7650: =pod
 7651: 
 7652: =item scantron_bubble_selector
 7653:   
 7654:    Generates the html radiobuttons to correct a single bubble line
 7655:    possibly showing the existing the selected bubbles if known
 7656: 
 7657:  Arguments:
 7658:     $r           - Apache request object
 7659:     $scan_config - hash from &get_scantron_config()
 7660:     $line        - Number of the line being displayed.
 7661:     $questionnum - Question number (may include subquestion)
 7662:     $error       - Type of error.
 7663:     @selected    - Array of bubbles picked on this line.
 7664: 
 7665: =cut
 7666: 
 7667: sub scantron_bubble_selector {
 7668:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7669:     my $max=$$scan_config{'Qlength'};
 7670: 
 7671:     my $scmode=$$scan_config{'Qon'};
 7672:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7673:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7674:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7675:             $max=$$scan_config{'BubblesPerRow'};
 7676:             if (($scmode eq 'number') && ($max > 10)) {
 7677:                 $max = 10;
 7678:             } elsif (($scmode eq 'letter') && $max > 26) {
 7679:                 $max = 26;
 7680:             }
 7681:         } else {
 7682:             $max = 10;
 7683:         }
 7684:     }
 7685: 
 7686:     my @alphabet=('A'..'Z');
 7687:     $r->print(&Apache::loncommon::start_data_table().
 7688:               &Apache::loncommon::start_data_table_row());
 7689:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7690:     for (my $i=0;$i<$max+1;$i++) {
 7691: 	$r->print("\n".'<td align="center">');
 7692: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7693: 	else { $r->print('&nbsp;'); }
 7694: 	$r->print('</td>');
 7695:     }
 7696:     $r->print(&Apache::loncommon::end_data_table_row().
 7697:               &Apache::loncommon::start_data_table_row());
 7698:     for (my $i=0;$i<$max;$i++) {
 7699: 	$r->print("\n".
 7700: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7701: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7702:     }
 7703:     my $nobub_checked = ' ';
 7704:     if ($error eq 'missingbubble') {
 7705:         $nobub_checked = ' checked = "checked" ';
 7706:     }
 7707:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7708: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7709:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7710:               $line.'" value="'.$questionnum.'" /></td>');
 7711:     $r->print(&Apache::loncommon::end_data_table_row().
 7712:               &Apache::loncommon::end_data_table());
 7713: }
 7714: 
 7715: =pod
 7716: 
 7717: =item num_matches
 7718: 
 7719:    Counts the number of characters that are the same between the two arguments.
 7720: 
 7721:  Arguments:
 7722:    $orig - CODE from the scanline
 7723:    $code - CODE to match against
 7724: 
 7725:  Returns:
 7726:    $count - integer count of the number of same characters between the
 7727:             two arguments
 7728: 
 7729: =cut
 7730: 
 7731: sub num_matches {
 7732:     my ($orig,$code) = @_;
 7733:     my @code=split(//,$code);
 7734:     my @orig=split(//,$orig);
 7735:     my $same=0;
 7736:     for (my $i=0;$i<scalar(@code);$i++) {
 7737: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7738:     }
 7739:     return $same;
 7740: }
 7741: 
 7742: =pod
 7743: 
 7744: =item scantron_get_closely_matching_CODEs
 7745: 
 7746:    Cycles through all CODEs and finds the set that has the greatest
 7747:    number of same characters as the provided CODE
 7748: 
 7749:  Arguments:
 7750:    $allcodes - hash ref returned by &get_codes()
 7751:    $CODE     - CODE from the current scanline
 7752: 
 7753:  Returns:
 7754:    2 element list
 7755:     - first elements is number of how closely matching the best fit is 
 7756:       (5 means best set has 5 matching characters)
 7757:     - second element is an arrary ref containing the set of valid CODEs
 7758:       that best fit the passed in CODE
 7759: 
 7760: =cut
 7761: 
 7762: sub scantron_get_closely_matching_CODEs {
 7763:     my ($allcodes,$CODE)=@_;
 7764:     my @CODEs;
 7765:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7766: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7767:     }
 7768: 
 7769:     return ($#CODEs,$CODEs[-1]);
 7770: }
 7771: 
 7772: =pod
 7773: 
 7774: =item get_codes
 7775: 
 7776:    Builds a hash which has keys of all of the valid CODEs from the selected
 7777:    set of remembered CODEs.
 7778: 
 7779:  Arguments:
 7780:   $old_name - name of the set of remembered CODEs
 7781:   $cdom     - domain of the course
 7782:   $cnum     - internal course name
 7783: 
 7784:  Returns:
 7785:   %allcodes - keys are the valid CODEs, values are all 1
 7786: 
 7787: =cut
 7788: 
 7789: sub get_codes {
 7790:     my ($old_name, $cdom, $cnum) = @_;
 7791:     if (!$old_name) {
 7792: 	$old_name=$env{'form.scantron_CODElist'};
 7793:     }
 7794:     if (!$cdom) {
 7795: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7796:     }
 7797:     if (!$cnum) {
 7798: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7799:     }
 7800:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7801: 				    $cdom,$cnum);
 7802:     my %allcodes;
 7803:     if ($result{"type\0$old_name"} eq 'number') {
 7804: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7805:     } else {
 7806: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7807:     }
 7808:     return %allcodes;
 7809: }
 7810: 
 7811: =pod
 7812: 
 7813: =item scantron_validate_CODE
 7814: 
 7815:    Validates all scanlines in the selected file to not have any
 7816:    invalid or underspecified CODEs and that none of the codes are
 7817:    duplicated if this was requested.
 7818: 
 7819: =cut
 7820: 
 7821: sub scantron_validate_CODE {
 7822:     my ($r,$currentphase) = @_;
 7823:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7824:     if ($scantron_config{'CODElocation'} &&
 7825: 	$scantron_config{'CODEstart'} &&
 7826: 	$scantron_config{'CODElength'}) {
 7827: 	if (!defined($env{'form.scantron_CODElist'})) {
 7828: 	    &FIXME_blow_up()
 7829: 	}
 7830:     } else {
 7831: 	return (0,$currentphase+1);
 7832:     }
 7833:     
 7834:     my %usedCODEs;
 7835: 
 7836:     my %allcodes=&get_codes();
 7837: 
 7838:     my $nav_error;
 7839:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7840:     if ($nav_error) {
 7841:         $r->print(&navmap_errormsg());
 7842:         return(1,$currentphase);
 7843:     }
 7844: 
 7845:     my ($scanlines,$scan_data)=&scantron_getfile();
 7846:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7847: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7848: 	if ($line=~/^[\s\cz]*$/) { next; }
 7849: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7850: 						 $scan_data);
 7851: 	my $CODE=$$scan_record{'scantron.CODE'};
 7852: 	my $error=0;
 7853: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7854: 	    &scantron_get_correction($r,$i,$scan_record,
 7855: 				     \%scantron_config,
 7856: 				     $line,'incorrectCODE',\%allcodes);
 7857: 	    return(1,$currentphase);
 7858: 	}
 7859: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7860: 	    && !$$scan_record{'scantron.useCODE'}) {
 7861: 	    &scantron_get_correction($r,$i,$scan_record,
 7862: 				     \%scantron_config,
 7863: 				     $line,'incorrectCODE',\%allcodes);
 7864: 	    return(1,$currentphase);
 7865: 	}
 7866: 	if (exists($usedCODEs{$CODE}) 
 7867: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7868: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7869: 	    &scantron_get_correction($r,$i,$scan_record,
 7870: 				     \%scantron_config,
 7871: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7872: 	    return(1,$currentphase);
 7873: 	}
 7874: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7875:     }
 7876:     return (0,$currentphase+1);
 7877: }
 7878: 
 7879: =pod
 7880: 
 7881: =item scantron_validate_doublebubble
 7882: 
 7883:    Validates all scanlines in the selected file to not have any
 7884:    bubble lines with multiple bubbles marked.
 7885: 
 7886: =cut
 7887: 
 7888: sub scantron_validate_doublebubble {
 7889:     my ($r,$currentphase) = @_;
 7890:     #get student info
 7891:     my $classlist=&Apache::loncoursedata::get_classlist();
 7892:     my %idmap=&username_to_idmap($classlist);
 7893:     my (undef,undef,$sequence)=
 7894:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7895: 
 7896:     #get scantron line setup
 7897:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7898:     my ($scanlines,$scan_data)=&scantron_getfile();
 7899: 
 7900:     my $navmap = Apache::lonnavmaps::navmap->new();
 7901:     unless (ref($navmap)) {
 7902:         $r->print(&navmap_errormsg());
 7903:         return(1,$currentphase);
 7904:     }
 7905:     my $map=$navmap->getResourceByUrl($sequence);
 7906:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7907:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 7908:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 7909:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7910: 
 7911:     my $nav_error;
 7912:     if (ref($map)) {
 7913:         $randomorder = $map->randomorder();
 7914:         $randompick = $map->randompick();
 7915:         if ($randomorder || $randompick) {
 7916:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 7917:             if ($nav_error) {
 7918:                 $r->print(&navmap_errormsg());
 7919:                 return(1,$currentphase);
 7920:             }
 7921:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7922:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 7923:         }
 7924:     } else {
 7925:         $r->print(&navmap_errormsg());
 7926:         return(1,$currentphase);
 7927:     }
 7928: 
 7929:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7930:     if ($nav_error) {
 7931:         $r->print(&navmap_errormsg());
 7932:         return(1,$currentphase);
 7933:     }
 7934: 
 7935:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7936: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7937: 	if ($line=~/^[\s\cz]*$/) { next; }
 7938: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7939: 						 $scan_data,undef,\%idmap,$randomorder,
 7940:                                                  $randompick,$sequence,\@master_seq,
 7941:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 7942:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 7943: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7944: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7945: 				 'doublebubble',
 7946: 				 $$scan_record{'scantron.doubleerror'},
 7947:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 7948:     	return (1,$currentphase);
 7949:     }
 7950:     return (0,$currentphase+1);
 7951: }
 7952: 
 7953: 
 7954: sub scantron_get_maxbubble {
 7955:     my ($nav_error,$scantron_config) = @_;
 7956:     if (defined($env{'form.scantron_maxbubble'}) &&
 7957: 	$env{'form.scantron_maxbubble'}) {
 7958: 	&restore_bubble_lines();
 7959: 	return $env{'form.scantron_maxbubble'};
 7960:     }
 7961: 
 7962:     my (undef, undef, $sequence) =
 7963: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7964: 
 7965:     my $navmap=Apache::lonnavmaps::navmap->new();
 7966:     unless (ref($navmap)) {
 7967:         if (ref($nav_error)) {
 7968:             $$nav_error = 1;
 7969:         }
 7970:         return;
 7971:     }
 7972:     my $map=$navmap->getResourceByUrl($sequence);
 7973:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7974:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7975: 
 7976:     &Apache::lonxml::clear_problem_counter();
 7977: 
 7978:     my $uname       = $env{'user.name'};
 7979:     my $udom        = $env{'user.domain'};
 7980:     my $cid         = $env{'request.course.id'};
 7981:     my $total_lines = 0;
 7982:     %bubble_lines_per_response = ();
 7983:     %first_bubble_line         = ();
 7984:     %subdivided_bubble_lines   = ();
 7985:     %responsetype_per_response = ();
 7986:     %masterseq_id_responsenum  = ();
 7987: 
 7988:     my $response_number = 0;
 7989:     my $bubble_line     = 0;
 7990:     foreach my $resource (@resources) {
 7991:         my $resid = $resource->id(); 
 7992:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 7993:                                                           $udom,undef,$bubbles_per_row);
 7994:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7995: 	    foreach my $part_id (@{$parts}) {
 7996:                 my $lines;
 7997: 
 7998: 	        # TODO - make this a persistent hash not an array.
 7999: 
 8000:                 # optionresponse, matchresponse and rankresponse type items 
 8001:                 # render as separate sub-questions in exam mode.
 8002:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8003:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8004:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8005:                     my ($numbub,$numshown);
 8006:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8007:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8008:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8009:                         }
 8010:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8011:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8012:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8013:                         }
 8014:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8015:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8016:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8017:                         }
 8018:                     }
 8019:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8020:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8021:                     }
 8022:                     my $bubbles_per_row =
 8023:                         &bubblesheet_bubbles_per_row($scantron_config);
 8024:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8025:                     if (($numbub % $bubbles_per_row) != 0) {
 8026:                         $inner_bubble_lines++;
 8027:                     }
 8028:                     for (my $i=0; $i<$numshown; $i++) {
 8029:                         $subdivided_bubble_lines{$response_number} .= 
 8030:                             $inner_bubble_lines.',';
 8031:                     }
 8032:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8033:                     $lines = $numshown * $inner_bubble_lines;
 8034:                 } else {
 8035:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8036:                 }
 8037: 
 8038:                 $first_bubble_line{$response_number} = $bubble_line;
 8039: 	        $bubble_lines_per_response{$response_number} = $lines;
 8040:                 $responsetype_per_response{$response_number} = 
 8041:                     $analysis->{$part_id.'.type'};
 8042:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8043: 	        $response_number++;
 8044: 
 8045: 	        $bubble_line +=  $lines;
 8046: 	        $total_lines +=  $lines;
 8047: 	    }
 8048:         }
 8049:     }
 8050:     &Apache::lonnet::delenv('scantron.');
 8051: 
 8052:     &save_bubble_lines();
 8053:     $env{'form.scantron_maxbubble'} =
 8054: 	$total_lines;
 8055:     return $env{'form.scantron_maxbubble'};
 8056: }
 8057: 
 8058: sub bubblesheet_bubbles_per_row {
 8059:     my ($scantron_config) = @_;
 8060:     my $bubbles_per_row;
 8061:     if (ref($scantron_config) eq 'HASH') {
 8062:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8063:     }
 8064:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8065:         $bubbles_per_row = 10;
 8066:     }
 8067:     return $bubbles_per_row;
 8068: }
 8069: 
 8070: sub scantron_validate_missingbubbles {
 8071:     my ($r,$currentphase) = @_;
 8072:     #get student info
 8073:     my $classlist=&Apache::loncoursedata::get_classlist();
 8074:     my %idmap=&username_to_idmap($classlist);
 8075:     my (undef,undef,$sequence)=
 8076:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8077: 
 8078:     #get scantron line setup
 8079:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8080:     my ($scanlines,$scan_data)=&scantron_getfile();
 8081: 
 8082:     my $navmap = Apache::lonnavmaps::navmap->new();
 8083:     unless (ref($navmap)) {
 8084:         $r->print(&navmap_errormsg());
 8085:         return(1,$currentphase);
 8086:     }
 8087: 
 8088:     my $map=$navmap->getResourceByUrl($sequence);
 8089:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8090:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8091:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8092:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8093: 
 8094:     my $nav_error;
 8095:     if (ref($map)) {
 8096:         $randomorder = $map->randomorder();
 8097:         $randompick = $map->randompick();
 8098:         if ($randomorder || $randompick) {
 8099:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8100:             if ($nav_error) {
 8101:                 $r->print(&navmap_errormsg());
 8102:                 return(1,$currentphase);
 8103:             }
 8104:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8105:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8106:         }
 8107:     } else {
 8108:         $r->print(&navmap_errormsg());
 8109:         return(1,$currentphase);
 8110:     }
 8111: 
 8112: 
 8113:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8114:     if ($nav_error) {
 8115:         $r->print(&navmap_errormsg());
 8116:         return(1,$currentphase);
 8117:     }
 8118: 
 8119:     if (!$max_bubble) { $max_bubble=2**31; }
 8120:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8121: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8122: 	if ($line=~/^[\s\cz]*$/) { next; }
 8123: 	my $scan_record =
 8124:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8125: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8126:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8127:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8128: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8129: 	my @to_correct;
 8130: 	
 8131: 	# Probably here's where the error is...
 8132: 
 8133: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8134:             my $lastbubble;
 8135:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8136:                my $question = $1;
 8137:                my $subquestion = $2;
 8138:                my ($first,$responsenum);
 8139:                if ($randomorder || $randompick) {
 8140:                    $responsenum = $respnumlookup{$question-1};
 8141:                    $first = $startline{$question-1};
 8142:                } else {
 8143:                    $responsenum = $question-1; 
 8144:                    $first = $first_bubble_line{$responsenum};
 8145:                }
 8146:                if (!defined($first)) { next; }
 8147:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8148:                my $subcount = 1;
 8149:                while ($subcount<$subquestion) {
 8150:                    $first += $subans[$subcount-1];
 8151:                    $subcount ++;
 8152:                }
 8153:                my $count = $subans[$subquestion-1];
 8154:                $lastbubble = $first + $count;
 8155:             } else {
 8156:                my ($first,$responsenum);
 8157:                if ($randomorder || $randompick) {
 8158:                    $responsenum = $respnumlookup{$missing-1};
 8159:                    $first = $startline{$missing-1};
 8160:                } else {
 8161:                    $responsenum = $missing-1;
 8162:                    $first = $first_bubble_line{$responsenum};
 8163:                }
 8164:                if (!defined($first)) { next; }
 8165:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8166:             }
 8167:             if ($lastbubble > $max_bubble) { next; }
 8168: 	    push(@to_correct,$missing);
 8169: 	}
 8170: 	if (@to_correct) {
 8171: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8172: 				     $line,'missingbubble',\@to_correct,
 8173:                                      $randomorder,$randompick,\%respnumlookup,
 8174:                                      \%startline);
 8175: 	    return (1,$currentphase);
 8176: 	}
 8177: 
 8178:     }
 8179:     return (0,$currentphase+1);
 8180: }
 8181: 
 8182: sub hand_bubble_option {
 8183:     my (undef, undef, $sequence) =
 8184:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8185:     return if ($sequence eq '');
 8186:     my $navmap = Apache::lonnavmaps::navmap->new();
 8187:     unless (ref($navmap)) {
 8188:         return;
 8189:     }
 8190:     my $needs_hand_bubbles;
 8191:     my $map=$navmap->getResourceByUrl($sequence);
 8192:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8193:     foreach my $res (@resources) {
 8194:         if (ref($res)) {
 8195:             if ($res->is_problem()) {
 8196:                 my $partlist = $res->parts();
 8197:                 foreach my $part (@{ $partlist }) {
 8198:                     my @types = $res->responseType($part);
 8199:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8200:                         $needs_hand_bubbles = 1;
 8201:                         last;
 8202:                     }
 8203:                 }
 8204:             }
 8205:         }
 8206:     }
 8207:     if ($needs_hand_bubbles) {
 8208:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8209:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8210:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8211:                &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 />').
 8212:                '<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;'.
 8213:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 8214:     }
 8215:     return;
 8216: }
 8217: 
 8218: sub scantron_process_students {
 8219:     my ($r,$symb) = @_;
 8220: 
 8221:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8222:     if (!$symb) {
 8223: 	return '';
 8224:     }
 8225:     my $default_form_data=&defaultFormData($symb);
 8226: 
 8227:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8228:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8229:     my ($scanlines,$scan_data)=&scantron_getfile();
 8230:     my $classlist=&Apache::loncoursedata::get_classlist();
 8231:     my %idmap=&username_to_idmap($classlist);
 8232:     my $navmap=Apache::lonnavmaps::navmap->new();
 8233:     unless (ref($navmap)) {
 8234:         $r->print(&navmap_errormsg());
 8235:         return '';
 8236:     }
 8237:     my $map=$navmap->getResourceByUrl($sequence);
 8238:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8239:         %grader_randomlists_by_symb);
 8240:     if (ref($map)) {
 8241:         $randomorder = $map->randomorder();
 8242:         $randompick = $map->randompick();
 8243:     } else {
 8244:         $r->print(&navmap_errormsg());
 8245:         return '';
 8246:     }
 8247:     my $nav_error;
 8248:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8249:     if ($randomorder || $randompick) {
 8250:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8251:         if ($nav_error) {
 8252:             $r->print(&navmap_errormsg());
 8253:             return '';
 8254:         }
 8255:     }
 8256:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8257:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8258: 
 8259:     my ($uname,$udom);
 8260:     my $result= <<SCANTRONFORM;
 8261: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8262:   <input type="hidden" name="command" value="scantron_configphase" />
 8263:   $default_form_data
 8264: SCANTRONFORM
 8265:     $r->print($result);
 8266: 
 8267:     my @delayqueue;
 8268:     my (%completedstudents,%scandata);
 8269:     
 8270:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8271:     my $count=&get_todo_count($scanlines,$scan_data);
 8272:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8273:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8274:     $r->print('<br />');
 8275:     my $start=&Time::HiRes::time();
 8276:     my $i=-1;
 8277:     my $started;
 8278: 
 8279:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8280:     if ($nav_error) {
 8281:         $r->print(&navmap_errormsg());
 8282:         return '';
 8283:     }
 8284: 
 8285:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8286:     # the user and return.
 8287: 
 8288:     if ($ssi_error) {
 8289: 	$r->print("</form>");
 8290: 	&ssi_print_error($r);
 8291:         &Apache::lonnet::remove_lock($lock);
 8292: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8293:     }
 8294: 
 8295:     my %lettdig = &letter_to_digits();
 8296:     my $numletts = scalar(keys(%lettdig));
 8297:     my %orderedforcode;
 8298: 
 8299:     while ($i<$scanlines->{'count'}) {
 8300:  	($uname,$udom)=('','');
 8301:  	$i++;
 8302:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8303:  	if ($line=~/^[\s\cz]*$/) { next; }
 8304: 	if ($started) {
 8305: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8306: 	}
 8307: 	$started=1;
 8308:         my %respnumlookup = ();
 8309:         my %startline = ();
 8310:         my $total;
 8311:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8312:                                                  $scan_data,undef,\%idmap,$randomorder,
 8313:                                                  $randompick,$sequence,\@master_seq,
 8314:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8315:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8316:                                                  \$total);
 8317:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8318:  					      \%idmap,$i)) {
 8319:   	    &scantron_add_delay(\@delayqueue,$line,
 8320:  				'Unable to find a student that matches',1);
 8321:  	    next;
 8322:   	}
 8323:  	if (exists $completedstudents{$uname}) {
 8324:  	    &scantron_add_delay(\@delayqueue,$line,
 8325:  				'Student '.$uname.' has multiple sheets',2);
 8326:  	    next;
 8327:  	}
 8328:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8329:         my $user = $uname.':'.$usec;
 8330:   	($uname,$udom)=split(/:/,$uname);
 8331: 
 8332:         my $scancode;
 8333:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8334:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8335:             $scancode = $scan_record->{'scantron.CODE'};
 8336:         } else {
 8337:             $scancode = '';
 8338:         }
 8339: 
 8340:         my @mapresources = @resources;
 8341:         if ($randomorder || $randompick) {
 8342:             @mapresources = 
 8343:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8344:                              \%orderedforcode);
 8345:         }
 8346:         my (%partids_by_symb,$res_error);
 8347:         foreach my $resource (@mapresources) {
 8348:             my $ressymb;
 8349:             if (ref($resource)) {
 8350:                 $ressymb = $resource->symb();
 8351:             } else {
 8352:                 $res_error = 1;
 8353:                 last;
 8354:             }
 8355:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8356:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8357:                 my ($analysis,$parts) =
 8358:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8359:                                               $uname,$udom,undef,$bubbles_per_row);
 8360:                 $partids_by_symb{$ressymb} = $parts;
 8361:             } else {
 8362:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8363:             }
 8364:         }
 8365: 
 8366:         if ($res_error) {
 8367:             &scantron_add_delay(\@delayqueue,$line,
 8368:                                 'An error occurred while grading student '.$uname,2);
 8369:             next;
 8370:         }
 8371: 
 8372: 	&Apache::lonxml::clear_problem_counter();
 8373:   	&Apache::lonnet::appenv($scan_record);
 8374: 
 8375: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8376: 	    &scantron_putfile($scanlines,$scan_data);
 8377: 	}
 8378: 	
 8379:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8380:                                    \@mapresources,\%partids_by_symb,
 8381:                                    $bubbles_per_row,$randomorder,$randompick,
 8382:                                    \%respnumlookup,\%startline) 
 8383:             eq 'ssi_error') {
 8384:             $ssi_error = 0; # So end of handler error message does not trigger.
 8385:             $r->print("</form>");
 8386:             &ssi_print_error($r);
 8387:             &Apache::lonnet::remove_lock($lock);
 8388:             return '';      # Why return ''?  Beats me.
 8389:         }
 8390: 
 8391:         if (($scancode) && ($randomorder || $randompick)) {
 8392:             my $parmresult =
 8393:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8394:                                                        '0_examcode',2,$scancode,
 8395:                                                        'string_examcode',$uname,
 8396:                                                        $udom);
 8397:         }
 8398: 	$completedstudents{$uname}={'line'=>$line};
 8399:         if ($env{'form.verifyrecord'}) {
 8400:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8401:             if ($randompick) {
 8402:                 if ($total) {
 8403:                     $lastpos = $total*$scantron_config{'Qlength'};
 8404:                 }
 8405:             }
 8406: 
 8407:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8408:             chomp($studentdata);
 8409:             $studentdata =~ s/\r$//;
 8410:             my $studentrecord = '';
 8411:             my $counter = -1;
 8412:             foreach my $resource (@mapresources) {
 8413:                 my $ressymb = $resource->symb();
 8414:                 ($counter,my $recording) =
 8415:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8416:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8417:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8418:                                              $randompick,\%respnumlookup,\%startline);
 8419:                 $studentrecord .= $recording;
 8420:             }
 8421:             if ($studentrecord ne $studentdata) {
 8422:                 &Apache::lonxml::clear_problem_counter();
 8423:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8424:                                            \@mapresources,\%partids_by_symb,
 8425:                                            $bubbles_per_row,$randomorder,$randompick,
 8426:                                            \%respnumlookup,\%startline) 
 8427:                     eq 'ssi_error') {
 8428:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8429:                     $r->print("</form>");
 8430:                     &ssi_print_error($r);
 8431:                     &Apache::lonnet::remove_lock($lock);
 8432:                     delete($completedstudents{$uname});
 8433:                     return '';
 8434:                 }
 8435:                 $counter = -1;
 8436:                 $studentrecord = '';
 8437:                 foreach my $resource (@mapresources) {
 8438:                     my $ressymb = $resource->symb();
 8439:                     ($counter,my $recording) =
 8440:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8441:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8442:                                                  \%scantron_config,\%lettdig,$numletts,
 8443:                                                  $randomorder,$randompick,\%respnumlookup,
 8444:                                                  \%startline);
 8445:                     $studentrecord .= $recording;
 8446:                 }
 8447:                 if ($studentrecord ne $studentdata) {
 8448:                     $r->print('<p><span class="LC_warning">');
 8449:                     if ($scancode eq '') {
 8450:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8451:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8452:                     } else {
 8453:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8454:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8455:                     }
 8456:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8457:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8458:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8459:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8460:                               &Apache::loncommon::start_data_table_row().
 8461:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8462:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8463:                               &Apache::loncommon::end_data_table_row().
 8464:                               &Apache::loncommon::start_data_table_row().
 8465:                               '<td>'.&mt('Stored submissions').'</td>'.
 8466:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8467:                               &Apache::loncommon::end_data_table_row().
 8468:                               &Apache::loncommon::end_data_table().'</p>');
 8469:                 } else {
 8470:                     $r->print('<br /><span class="LC_warning">'.
 8471:                              &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 />'.
 8472:                              &mt("As a consequence, this user's submission history records two tries.").
 8473:                                  '</span><br />');
 8474:                 }
 8475:             }
 8476:         }
 8477:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8478:     } continue {
 8479: 	&Apache::lonxml::clear_problem_counter();
 8480: 	&Apache::lonnet::delenv('scantron.');
 8481:     }
 8482:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8483:     &Apache::lonnet::remove_lock($lock);
 8484: #    my $lasttime = &Time::HiRes::time()-$start;
 8485: #    $r->print("<p>took $lasttime</p>");
 8486: 
 8487:     $r->print("</form>");
 8488:     return '';
 8489: }
 8490: 
 8491: sub graders_resources_pass {
 8492:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8493:         $bubbles_per_row) = @_;
 8494:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8495:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8496:         foreach my $resource (@{$resources}) {
 8497:             my $ressymb = $resource->symb();
 8498:             my ($analysis,$parts) =
 8499:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8500:                                           $env{'user.name'},$env{'user.domain'},
 8501:                                           1,$bubbles_per_row);
 8502:             $grader_partids_by_symb->{$ressymb} = $parts;
 8503:             if (ref($analysis) eq 'HASH') {
 8504:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8505:                     $grader_randomlists_by_symb->{$ressymb} =
 8506:                         $analysis->{'parts_withrandomlist'};
 8507:                 }
 8508:             }
 8509:         }
 8510:     }
 8511:     return;
 8512: }
 8513: 
 8514: =pod
 8515: 
 8516: =item users_order
 8517: 
 8518:   Returns array of resources in current map, ordered based on either CODE,
 8519:   if this is a CODEd exam, or based on student's identity if this is a 
 8520:   "NAMEd" exam.
 8521: 
 8522:   Should be used when randomorder and/or randompick applied when the 
 8523:   corresponding exam was printed, prior to students completing bubblesheets 
 8524:   for the version of the exam the student received.
 8525: 
 8526: =cut
 8527: 
 8528: sub users_order  {
 8529:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8530:     my @mapresources;
 8531:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8532:         return @mapresources;
 8533:     }
 8534:     if ($scancode) {
 8535:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8536:             @mapresources = @{$orderedforcode->{$scancode}};
 8537:         } else {
 8538:             $env{'form.CODE'} = $scancode;
 8539:             my $actual_seq =
 8540:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8541:                                                                $master_seq,
 8542:                                                                $user,$scancode,1);
 8543:             if (ref($actual_seq) eq 'ARRAY') {
 8544:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8545:                 if (ref($orderedforcode) eq 'HASH') {
 8546:                     if (@mapresources > 0) { 
 8547:                         $orderedforcode->{$scancode} = \@mapresources;
 8548:                     }
 8549:                 }
 8550:             }
 8551:             delete($env{'form.CODE'});
 8552:         }
 8553:     } else {
 8554:         my $actual_seq =
 8555:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8556:                                                            $master_seq,
 8557:                                                            $user,undef,1);
 8558:         if (ref($actual_seq) eq 'ARRAY') {
 8559:             @mapresources = 
 8560:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8561:         }
 8562:     }
 8563:     return @mapresources;
 8564: }
 8565: 
 8566: sub grade_student_bubbles {
 8567:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8568:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8569:     my $uselookup = 0;
 8570:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8571:         (ref($startline) eq 'HASH')) {
 8572:         $uselookup = 1;
 8573:     }
 8574: 
 8575:     if (ref($resources) eq 'ARRAY') {
 8576:         my $count = 0;
 8577:         foreach my $resource (@{$resources}) {
 8578:             my $ressymb = $resource->symb();
 8579:             my %form = ('submitted'      => 'scantron',
 8580:                         'grade_target'   => 'grade',
 8581:                         'grade_username' => $uname,
 8582:                         'grade_domain'   => $udom,
 8583:                         'grade_courseid' => $env{'request.course.id'},
 8584:                         'grade_symb'     => $ressymb,
 8585:                         'CODE'           => $scancode
 8586:                        );
 8587:             if ($bubbles_per_row ne '') {
 8588:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8589:             }
 8590:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8591:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8592:             }
 8593:             if (ref($parts) eq 'HASH') {
 8594:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8595:                     foreach my $part (@{$parts->{$ressymb}}) {
 8596:                         if ($uselookup) {
 8597:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8598:                         } else {
 8599:                             $form{'scantron_questnum_start.'.$part} =
 8600:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8601:                         }
 8602:                         $count++;
 8603:                     }
 8604:                 }
 8605:             }
 8606:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8607:             return 'ssi_error' if ($ssi_error);
 8608:             last if (&Apache::loncommon::connection_aborted($r));
 8609:         }
 8610:     }
 8611:     return;
 8612: }
 8613: 
 8614: sub scantron_upload_scantron_data {
 8615:     my ($r,$symb)=@_;
 8616:     my $dom = $env{'request.role.domain'};
 8617:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8618:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8619:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8620: 							  'domainid',
 8621: 							  'coursename',$dom);
 8622:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8623:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8624:     my $default_form_data=&defaultFormData($symb);
 8625:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8626:     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.");
 8627:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8628:     function checkUpload(formname) {
 8629: 	if (formname.upfile.value == "") {
 8630: 	    alert("'.$nofile_alert.'");
 8631: 	    return false;
 8632: 	}
 8633:         if (formname.courseid.value == "") {
 8634:             alert("'.$nocourseid_alert.'");
 8635:             return false;
 8636:         }
 8637: 	formname.submit();
 8638:     }
 8639: 
 8640:     function ToSyllabus() {
 8641:         var cdom = '."'$dom'".';
 8642:         var cnum = document.rules.courseid.value;
 8643:         if (cdom == "" || cdom == null) {
 8644:             return;
 8645:         }
 8646:         if (cnum == "" || cnum == null) {
 8647:            return;
 8648:         }
 8649:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8650:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8651:         return;
 8652:     }
 8653: 
 8654: '));
 8655:     $r->print('
 8656: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8657: 
 8658: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8659: '.$default_form_data.
 8660:   &Apache::lonhtmlcommon::start_pick_box().
 8661:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8662:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8663:   &Apache::lonhtmlcommon::row_closure().
 8664:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8665:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8666:   &Apache::lonhtmlcommon::row_closure().
 8667:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8668:   '<input name="domainid" type="hidden" />'.$domdesc.
 8669:   &Apache::lonhtmlcommon::row_closure().
 8670:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8671:   '<input type="file" name="upfile" size="50" />'.
 8672:   &Apache::lonhtmlcommon::row_closure(1).
 8673:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8674: 
 8675: <input name="command" value="scantronupload_save" type="hidden" />
 8676: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8677: </form>
 8678: ');
 8679:     return '';
 8680: }
 8681: 
 8682: 
 8683: sub scantron_upload_scantron_data_save {
 8684:     my($r,$symb)=@_;
 8685:     my $doanotherupload=
 8686: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8687: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8688: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8689: 	'</form>'."\n";
 8690:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8691: 	!&Apache::lonnet::allowed('usc',
 8692: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8693: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8694: 	unless ($symb) {
 8695: 	    $r->print($doanotherupload);
 8696: 	}
 8697: 	return '';
 8698:     }
 8699:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8700:     my $uploadedfile;
 8701:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8702:     if (length($env{'form.upfile'}) < 2) {
 8703:         $r->print(
 8704:             &Apache::lonhtmlcommon::confirm_success(
 8705:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8706:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8707:     } else {
 8708:         my $result = 
 8709:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8710:                                             $env{'form.courseid'},$env{'form.domainid'});
 8711:         if ($result =~ m{^/uploaded/}) {
 8712:             $r->print(
 8713:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8714:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8715:                         (length($env{'form.upfile'})-1),
 8716:                         '<span class="LC_filename">'.$result.'</span>'));
 8717:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8718:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8719:                                                        $env{'form.courseid'},$uploadedfile));
 8720:         } else {
 8721:             $r->print(
 8722:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8723:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8724:                           $result,
 8725: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8726: 	}
 8727:     }
 8728:     if ($symb) {
 8729: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8730:     } else {
 8731: 	$r->print($doanotherupload);
 8732:     }
 8733:     return '';
 8734: }
 8735: 
 8736: sub validate_uploaded_scantron_file {
 8737:     my ($cdom,$cname,$fname) = @_;
 8738:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8739:     my @lines;
 8740:     if ($scanlines ne '-1') {
 8741:         @lines=split("\n",$scanlines,-1);
 8742:     }
 8743:     my $output;
 8744:     if (@lines) {
 8745:         my (%counts,$max_match_format);
 8746:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8747:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8748:         my %idmap = &username_to_idmap($classlist);
 8749:         foreach my $key (keys(%idmap)) {
 8750:             my $lckey = lc($key);
 8751:             $idmap{$lckey} = $idmap{$key};
 8752:         }
 8753:         my %unique_formats;
 8754:         my @formatlines = &get_scantronformat_file();
 8755:         foreach my $line (@formatlines) {
 8756:             chomp($line);
 8757:             my @config = split(/:/,$line);
 8758:             my $idstart = $config[5];
 8759:             my $idlength = $config[6];
 8760:             if (($idstart ne '') && ($idlength > 0)) {
 8761:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8762:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8763:                 } else {
 8764:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8765:                 }
 8766:             }
 8767:         }
 8768:         foreach my $key (keys(%unique_formats)) {
 8769:             my ($idstart,$idlength) = split(':',$key);
 8770:             %{$counts{$key}} = (
 8771:                                'found'   => 0,
 8772:                                'total'   => 0,
 8773:                               );
 8774:             foreach my $line (@lines) {
 8775:                 next if ($line =~ /^#/);
 8776:                 next if ($line =~ /^[\s\cz]*$/);
 8777:                 my $id = substr($line,$idstart-1,$idlength);
 8778:                 $id = lc($id);
 8779:                 if (exists($idmap{$id})) {
 8780:                     $counts{$key}{'found'} ++;
 8781:                 }
 8782:                 $counts{$key}{'total'} ++;
 8783:             }
 8784:             if ($counts{$key}{'total'}) {
 8785:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8786:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8787:                     $max_match_pct = $percent_match;
 8788:                     $max_match_format = $key;
 8789:                     $found_match_count = $counts{$key}{'found'};
 8790:                     $max_match_count = $counts{$key}{'total'};
 8791:                 }
 8792:             }
 8793:         }
 8794:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8795:             my $format_descs;
 8796:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8797:             for (my $i=0; $i<$numwithformat; $i++) {
 8798:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8799:                 if ($i<$numwithformat-2) {
 8800:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8801:                 } elsif ($i==$numwithformat-2) {
 8802:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8803:                 } elsif ($i==$numwithformat-1) {
 8804:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8805:                 }
 8806:             }
 8807:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8808:             $output .= '<br />';
 8809:             if ($found_match_count == $max_match_count) {
 8810:                 # 100% matching entries
 8811:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 8812:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 8813:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 8814:                 &mt('Comparison of student IDs in the uploaded file with'.
 8815:                     ' the course roster found matches for [_1] of the [_2] entries'.
 8816:                     ' in the file (for the format defined for [_3]).',
 8817:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 8818:             } else {
 8819:                 # Not all entries matching? -> Show warning and additional info
 8820:                 $output .=
 8821:                     &Apache::lonhtmlcommon::confirm_success(
 8822:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 8823:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 8824:                         &mt('Not all entries could be matched!'),1).'<br />'.
 8825:                     &mt('Comparison of student IDs in the uploaded file with'.
 8826:                         ' the course roster found matches for [_1] of the [_2] entries'.
 8827:                         ' in the file (for the format defined for [_3]).',
 8828:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8829:                     '<p class="LC_info">'.
 8830:                     &mt('A low percentage of matches results from one of the following:').
 8831:                     '</p><ul>'.
 8832:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 8833:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 8834:                                '<i>'.$cdom.'</i>').'</li>'.
 8835:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8836:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 8837:                     '</ul>';
 8838:             }
 8839:         }
 8840:     } else {
 8841:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 8842:     }
 8843:     return $output;
 8844: }
 8845: 
 8846: sub valid_file {
 8847:     my ($requested_file)=@_;
 8848:     foreach my $filename (sort(&scantron_filenames())) {
 8849: 	if ($requested_file eq $filename) { return 1; }
 8850:     }
 8851:     return 0;
 8852: }
 8853: 
 8854: sub scantron_download_scantron_data {
 8855:     my ($r,$symb)=@_;
 8856:     my $default_form_data=&defaultFormData($symb);
 8857:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8858:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8859:     my $file=$env{'form.scantron_selectfile'};
 8860:     if (! &valid_file($file)) {
 8861: 	$r->print('
 8862: 	<p>
 8863: 	    '.&mt('The requested filename was invalid.').'
 8864:         </p>
 8865: ');
 8866: 	return;
 8867:     }
 8868:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8869:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8870:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8871:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8872:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8873:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8874:     $r->print('
 8875:     <p>
 8876: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
 8877: 	      '<a href="'.$orig.'">','</a>').'
 8878:     </p>
 8879:     <p>
 8880: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8881: 	      '<a href="'.$corrected.'">','</a>').'
 8882:     </p>
 8883:     <p>
 8884: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8885: 	      '<a href="'.$skipped.'">','</a>').'
 8886:     </p>
 8887: ');
 8888:     return '';
 8889: }
 8890: 
 8891: sub checkscantron_results {
 8892:     my ($r,$symb) = @_;
 8893:     if (!$symb) {return '';}
 8894:     my $cid = $env{'request.course.id'};
 8895:     my %lettdig = &letter_to_digits();
 8896:     my $numletts = scalar(keys(%lettdig));
 8897:     my $cnum = $env{'course.'.$cid.'.num'};
 8898:     my $cdom = $env{'course.'.$cid.'.domain'};
 8899:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8900:     my %record;
 8901:     my %scantron_config =
 8902:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8903:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8904:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8905:     my $classlist=&Apache::loncoursedata::get_classlist();
 8906:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8907:     my $navmap=Apache::lonnavmaps::navmap->new();
 8908:     unless (ref($navmap)) {
 8909:         $r->print(&navmap_errormsg());
 8910:         return '';
 8911:     }
 8912:     my $map=$navmap->getResourceByUrl($sequence);
 8913:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8914:         %grader_randomlists_by_symb,%orderedforcode);
 8915:     if (ref($map)) { 
 8916:         $randomorder=$map->randomorder();
 8917:         $randompick=$map->randompick();
 8918:     }
 8919:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8920:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8921:     if ($nav_error) {
 8922:         $r->print(&navmap_errormsg());
 8923:         return '';
 8924:     }
 8925:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8926:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8927:     my ($uname,$udom);
 8928:     my (%scandata,%lastname,%bylast);
 8929:     $r->print('
 8930: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8931: 
 8932:     my @delayqueue;
 8933:     my %completedstudents;
 8934: 
 8935:     my $count=&get_todo_count($scanlines,$scan_data);
 8936:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8937:     my ($username,$domain,$started);
 8938:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8939:     if ($nav_error) {
 8940:         $r->print(&navmap_errormsg());
 8941:         return '';
 8942:     }
 8943: 
 8944:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8945:     my $start=&Time::HiRes::time();
 8946:     my $i=-1;
 8947: 
 8948:     while ($i<$scanlines->{'count'}) {
 8949:         ($username,$domain,$uname)=('','','');
 8950:         $i++;
 8951:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8952:         if ($line=~/^[\s\cz]*$/) { next; }
 8953:         if ($started) {
 8954:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8955:         }
 8956:         $started=1;
 8957:         my $scan_record=
 8958:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8959:                                                      $scan_data);
 8960:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8961:                                               \%idmap,$i)) {
 8962:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8963:                                 'Unable to find a student that matches',1);
 8964:             next;
 8965:         }
 8966:         if (exists $completedstudents{$uname}) {
 8967:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8968:                                 'Student '.$uname.' has multiple sheets',2);
 8969:             next;
 8970:         }
 8971:         my $pid = $scan_record->{'scantron.ID'};
 8972:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8973:         push(@{$bylast{$lastname{$pid}}},$pid);
 8974:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8975:         my $user = $uname.':'.$usec;
 8976:         ($username,$domain)=split(/:/,$uname);
 8977: 
 8978:         my $scancode;
 8979:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8980:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8981:             $scancode = $scan_record->{'scantron.CODE'};
 8982:         } else {
 8983:             $scancode = '';
 8984:         }
 8985: 
 8986:         my @mapresources = @resources;
 8987:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8988:         my %respnumlookup=();
 8989:         my %startline=();
 8990:         if ($randomorder || $randompick) {
 8991:             @mapresources =
 8992:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8993:                              \%orderedforcode);
 8994:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 8995:                                              $scan_record,\@master_seq,\%symb_to_resource,
 8996:                                              \%grader_partids_by_symb,\%orderedforcode,
 8997:                                              \%respnumlookup,\%startline);
 8998:             if ($randompick && $total) {
 8999:                 $lastpos = $total*$scantron_config{'Qlength'};
 9000:             }
 9001:         }
 9002:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9003:         chomp($scandata{$pid});
 9004:         $scandata{$pid} =~ s/\r$//;
 9005: 
 9006:         my $counter = -1;
 9007:         foreach my $resource (@mapresources) {
 9008:             my $parts;
 9009:             my $ressymb = $resource->symb();
 9010:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9011:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9012:                 (my $analysis,$parts) =
 9013:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9014:                                               $username,$domain,undef,
 9015:                                               $bubbles_per_row);
 9016:             } else {
 9017:                 $parts = $grader_partids_by_symb{$ressymb};
 9018:             }
 9019:             ($counter,my $recording) =
 9020:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9021:                                          $scandata{$pid},$parts,
 9022:                                          \%scantron_config,\%lettdig,$numletts,
 9023:                                          $randomorder,$randompick,
 9024:                                          \%respnumlookup,\%startline);
 9025:             $record{$pid} .= $recording;
 9026:         }
 9027:     }
 9028:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9029:     $r->print('<br />');
 9030:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9031:     $passed = 0;
 9032:     $failed = 0;
 9033:     $numstudents = 0;
 9034:     foreach my $last (sort(keys(%bylast))) {
 9035:         if (ref($bylast{$last}) eq 'ARRAY') {
 9036:             foreach my $pid (sort(@{$bylast{$last}})) {
 9037:                 my $showscandata = $scandata{$pid};
 9038:                 my $showrecord = $record{$pid};
 9039:                 $showscandata =~ s/\s/&nbsp;/g;
 9040:                 $showrecord =~ s/\s/&nbsp;/g;
 9041:                 if ($scandata{$pid} eq $record{$pid}) {
 9042:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9043:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9044: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9045: '</tr>'."\n".
 9046: '<tr class="'.$css_class.'">'."\n".
 9047: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 9048:                     $passed ++;
 9049:                 } else {
 9050:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9051:                     $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".
 9052: '</tr>'."\n".
 9053: '<tr class="'.$css_class.'">'."\n".
 9054: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9055: '</tr>'."\n";
 9056:                     $failed ++;
 9057:                 }
 9058:                 $numstudents ++;
 9059:             }
 9060:         }
 9061:     }
 9062:     $r->print(
 9063:         '<p>'
 9064:        .&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).',
 9065:             '<b>',
 9066:             $numstudents,
 9067:             '</b>',
 9068:             $env{'form.scantron_maxbubble'})
 9069:        .'</p>'
 9070:     );
 9071:     $r->print('<p>'
 9072:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9073:              .'<br />'
 9074:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9075:              .'</p>'
 9076:     );
 9077:     if ($passed) {
 9078:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9079:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9080:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9081:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9082:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9083:                  $okstudents."\n".
 9084:                  &Apache::loncommon::end_data_table().'<br />');
 9085:     }
 9086:     if ($failed) {
 9087:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9088:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9089:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9090:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9091:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9092:                  $badstudents."\n".
 9093:                  &Apache::loncommon::end_data_table()).'<br />'.
 9094:                  &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.');  
 9095:     }
 9096:     $r->print('</form><br />');
 9097:     return;
 9098: }
 9099: 
 9100: sub verify_scantron_grading {
 9101:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9102:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9103:         $respnumlookup,$startline) = @_;
 9104:     my ($record,%expected,%startpos);
 9105:     return ($counter,$record) if (!ref($resource));
 9106:     return ($counter,$record) if (!$resource->is_problem());
 9107:     my $symb = $resource->symb();
 9108:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9109:     foreach my $part_id (@{$partids}) {
 9110:         $counter ++;
 9111:         $expected{$part_id} = 0;
 9112:         my $respnum = $counter;
 9113:         if ($randomorder || $randompick) {
 9114:             $respnum = $respnumlookup->{$counter};
 9115:             $startpos{$part_id} = $startline->{$counter} + 1;
 9116:         } else {
 9117:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9118:         }
 9119:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9120:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9121:             foreach my $item (@sub_lines) {
 9122:                 $expected{$part_id} += $item;
 9123:             }
 9124:         } else {
 9125:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9126:         }
 9127:     }
 9128:     if ($symb) {
 9129:         my %recorded;
 9130:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9131:         if ($returnhash{'version'}) {
 9132:             my %lasthash=();
 9133:             my $version;
 9134:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9135:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9136:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9137:                 }
 9138:             }
 9139:             foreach my $key (keys(%lasthash)) {
 9140:                 if ($key =~ /\.scantron$/) {
 9141:                     my $value = &unescape($lasthash{$key});
 9142:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9143:                     if ($value eq '') {
 9144:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9145:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9146:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9147:                             }
 9148:                         }
 9149:                     } else {
 9150:                         my @tocheck;
 9151:                         my @items = split(//,$value);
 9152:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9153:                             ($scantron_config->{'Qon'} eq 'number')) {
 9154:                             if (@items < $expected{$part_id}) {
 9155:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9156:                                 my @singles = split(//,$fragment);
 9157:                                 foreach my $pos (@singles) {
 9158:                                     if ($pos eq ' ') {
 9159:                                         push(@tocheck,$pos);
 9160:                                     } else {
 9161:                                         my $next = shift(@items);
 9162:                                         push(@tocheck,$next);
 9163:                                     }
 9164:                                 }
 9165:                             } else {
 9166:                                 @tocheck = @items;
 9167:                             }
 9168:                             foreach my $letter (@tocheck) {
 9169:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9170:                                     if ($letter !~ /^[A-J]$/) {
 9171:                                         $letter = $scantron_config->{'Qoff'};
 9172:                                     }
 9173:                                     $recorded{$part_id} .= $letter;
 9174:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9175:                                     my $digit;
 9176:                                     if ($letter !~ /^[A-J]$/) {
 9177:                                         $digit = $scantron_config->{'Qoff'};
 9178:                                     } else {
 9179:                                         $digit = $lettdig->{$letter};
 9180:                                     }
 9181:                                     $recorded{$part_id} .= $digit;
 9182:                                 }
 9183:                             }
 9184:                         } else {
 9185:                             @tocheck = @items;
 9186:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9187:                                 my $curr_sub = shift(@tocheck);
 9188:                                 my $digit;
 9189:                                 if ($curr_sub =~ /^[A-J]$/) {
 9190:                                     $digit = $lettdig->{$curr_sub}-1;
 9191:                                 }
 9192:                                 if ($curr_sub eq 'J') {
 9193:                                     $digit += scalar($numletts);
 9194:                                 }
 9195:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9196:                                     if ($j == $digit) {
 9197:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9198:                                     } else {
 9199:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9200:                                     }
 9201:                                 }
 9202:                             }
 9203:                         }
 9204:                     }
 9205:                 }
 9206:             }
 9207:         }
 9208:         foreach my $part_id (@{$partids}) {
 9209:             if ($recorded{$part_id} eq '') {
 9210:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9211:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9212:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9213:                     }
 9214:                 }
 9215:             }
 9216:             $record .= $recorded{$part_id};
 9217:         }
 9218:     }
 9219:     return ($counter,$record);
 9220: }
 9221: 
 9222: sub letter_to_digits {
 9223:     my %lettdig = (
 9224:                     A => 1,
 9225:                     B => 2,
 9226:                     C => 3,
 9227:                     D => 4,
 9228:                     E => 5,
 9229:                     F => 6,
 9230:                     G => 7,
 9231:                     H => 8,
 9232:                     I => 9,
 9233:                     J => 0,
 9234:                   );
 9235:     return %lettdig;
 9236: }
 9237: 
 9238: 
 9239: #-------- end of section for handling grading scantron forms -------
 9240: #
 9241: #-------------------------------------------------------------------
 9242: 
 9243: #-------------------------- Menu interface -------------------------
 9244: #
 9245: #--- Href with symb and command ---
 9246: 
 9247: sub href_symb_cmd {
 9248:     my ($symb,$cmd)=@_;
 9249:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9250: }
 9251: 
 9252: sub grading_menu {
 9253:     my ($request,$symb) = @_;
 9254:     if (!$symb) {return '';}
 9255: 
 9256:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9257:                   'command'=>'individual');
 9258:     
 9259:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9260: 
 9261:     $fields{'command'}='ungraded';
 9262:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9263: 
 9264:     $fields{'command'}='table';
 9265:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9266: 
 9267:     $fields{'command'}='all_for_one';
 9268:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9269: 
 9270:     $fields{'command'}='downloadfilesselect';
 9271:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9272: 
 9273:     $fields{'command'} = 'csvform';
 9274:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9275:     
 9276:     $fields{'command'} = 'processclicker';
 9277:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9278:     
 9279:     $fields{'command'} = 'scantron_selectphase';
 9280:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9281: 
 9282:     $fields{'command'} = 'initialverifyreceipt';
 9283:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9284:     
 9285:     my @menu = ({	categorytitle=>'Hand Grading',
 9286:             items =>[
 9287:                         {	linktext => 'Select individual students to grade',
 9288:                     		url => $url1a,
 9289:                     		permission => 'F',
 9290:                     		icon => 'grade_students.png',
 9291:                     		linktitle => 'Grade current resource for a selection of students.'
 9292:                         }, 
 9293:                         {       linktext => 'Grade ungraded submissions.',
 9294:                                 url => $url1b,
 9295:                                 permission => 'F',
 9296:                                 icon => 'ungrade_sub.png',
 9297:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9298:                         },
 9299: 
 9300:                         {       linktext => 'Grading table',
 9301:                                 url => $url1c,
 9302:                                 permission => 'F',
 9303:                                 icon => 'grading_table.png',
 9304:                                 linktitle => 'Grade current resource for all students.'
 9305:                         },
 9306:                         {       linktext => 'Grade page/folder for one student',
 9307:                                 url => $url1d,
 9308:                                 permission => 'F',
 9309:                                 icon => 'grade_PageFolder.png',
 9310:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9311:                         },
 9312:                         {       linktext => 'Download submissions',
 9313:                                 url => $url1e,
 9314:                                 permission => 'F',
 9315:                                 icon => 'download_sub.png',
 9316:                                 linktitle => 'Download all students submissions.'
 9317:                         }]},
 9318:                          { categorytitle=>'Automated Grading',
 9319:                items =>[
 9320: 
 9321:                 	    {	linktext => 'Upload Scores',
 9322:                     		url => $url2,
 9323:                     		permission => 'F',
 9324:                     		icon => 'uploadscores.png',
 9325:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9326:                 	    },
 9327:                 	    {	linktext => 'Process Clicker',
 9328:                     		url => $url3,
 9329:                     		permission => 'F',
 9330:                     		icon => 'addClickerInfoFile.png',
 9331:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9332:                 	    },
 9333:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9334:                     		url => $url4,
 9335:                     		permission => 'F',
 9336:                     		icon => 'bubblesheet.png',
 9337:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9338:                 	    },
 9339:                             {   linktext => 'Verify Receipt Number',
 9340:                                 url => $url5,
 9341:                                 permission => 'F',
 9342:                                 icon => 'receipt_number.png',
 9343:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9344:                             }
 9345: 
 9346:                     ]
 9347:             });
 9348: 
 9349:     # Create the menu
 9350:     my $Str;
 9351:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9352:     $Str .= '<input type="hidden" name="command" value="" />'.
 9353:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9354: 
 9355:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9356:     return $Str;    
 9357: }
 9358: 
 9359: 
 9360: sub ungraded {
 9361:     my ($request)=@_;
 9362:     &submit_options($request);
 9363: }
 9364: 
 9365: sub submit_options_sequence {
 9366:     my ($request,$symb) = @_;
 9367:     if (!$symb) {return '';}
 9368:     &commonJSfunctions($request);
 9369:     my $result;
 9370: 
 9371:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9372:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9373:     $result.=&selectfield(0).
 9374:             '<input type="hidden" name="command" value="pickStudentPage" />
 9375:             <div>
 9376:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9377:             </div>
 9378:         </div>
 9379:   </form>';
 9380:     return $result;
 9381: }
 9382: 
 9383: sub submit_options_table {
 9384:     my ($request,$symb) = @_;
 9385:     if (!$symb) {return '';}
 9386:     &commonJSfunctions($request);
 9387:     my $result;
 9388: 
 9389:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9390:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9391: 
 9392:     $result.=&selectfield(0).
 9393:             '<input type="hidden" name="command" value="viewgrades" />
 9394:             <div>
 9395:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9396:             </div>
 9397:         </div>
 9398:   </form>';
 9399:     return $result;
 9400: }
 9401: 
 9402: sub submit_options_download {
 9403:     my ($request,$symb) = @_;
 9404:     if (!$symb) {return '';}
 9405: 
 9406:     &commonJSfunctions($request);
 9407: 
 9408:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9409:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9410:     $result.='
 9411: <h2>
 9412:   '.&mt('Select Students for Which to Download Submissions').'
 9413: </h2>'.&selectfield(1).'
 9414:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9415:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9416:             </div>
 9417:           </div>
 9418: 
 9419: 
 9420:   </form>';
 9421:     return $result;
 9422: }
 9423: 
 9424: #--- Displays the submissions first page -------
 9425: sub submit_options {
 9426:     my ($request,$symb) = @_;
 9427:     if (!$symb) {return '';}
 9428: 
 9429:     &commonJSfunctions($request);
 9430:     my $result;
 9431: 
 9432:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9433: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9434:     $result.=&selectfield(1).'
 9435:                 <input type="hidden" name="command" value="submission" /> 
 9436: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9437:             </div>
 9438:           </div>
 9439: 
 9440: 
 9441:   </form>';
 9442:     return $result;
 9443: }
 9444: 
 9445: sub selectfield {
 9446:    my ($full)=@_;
 9447:    my %options = 
 9448:           (&Apache::lonlocal::texthash(
 9449:              'yes'       => 'with submissions',
 9450:              'queued'    => 'in grading queue',
 9451:              'graded'    => 'with ungraded submissions',
 9452:              'incorrect' => 'with incorrect submissions',
 9453:              'all'       => 'with any status'),
 9454:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9455:    my $result='<div class="LC_columnSection">
 9456:   
 9457:     <fieldset>
 9458:       <legend>
 9459:        '.&mt('Sections').'
 9460:       </legend>
 9461:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9462:     </fieldset>
 9463:   
 9464:     <fieldset>
 9465:       <legend>
 9466:         '.&mt('Groups').'
 9467:       </legend>
 9468:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9469:     </fieldset>
 9470:   
 9471:     <fieldset>
 9472:       <legend>
 9473:         '.&mt('Access Status').'
 9474:       </legend>
 9475:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9476:     </fieldset>';
 9477:     if ($full) {
 9478:        $result.='
 9479:     <fieldset>
 9480:       <legend>
 9481:         '.&mt('Submission Status').'
 9482:       </legend>'.
 9483:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9484:    '</fieldset>';
 9485:     }
 9486:     $result.='</div><br />';
 9487:     return $result;
 9488: }
 9489: 
 9490: sub reset_perm {
 9491:     undef(%perm);
 9492: }
 9493: 
 9494: sub init_perm {
 9495:     &reset_perm();
 9496:     foreach my $test_perm ('vgr','mgr','opa') {
 9497: 
 9498: 	my $scope = $env{'request.course.id'};
 9499: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9500: 
 9501: 	    $scope .= '/'.$env{'request.course.sec'};
 9502: 	    if ( $perm{$test_perm}=
 9503: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9504: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9505: 	    } else {
 9506: 		delete($perm{$test_perm});
 9507: 	    }
 9508: 	}
 9509:     }
 9510: }
 9511: 
 9512: sub init_old_essays {
 9513:     my ($symb,$apath,$adom,$aname) = @_;
 9514:     if ($symb ne '') {
 9515:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9516:         if (keys(%essays) > 0) {
 9517:             $old_essays{$symb} = \%essays;
 9518:         }
 9519:     }
 9520:     return;
 9521: }
 9522: 
 9523: sub reset_old_essays {
 9524:     undef(%old_essays);
 9525: }
 9526: 
 9527: sub gather_clicker_ids {
 9528:     my %clicker_ids;
 9529: 
 9530:     my $classlist = &Apache::loncoursedata::get_classlist();
 9531: 
 9532:     # Set up a couple variables.
 9533:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9534:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9535:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9536: 
 9537:     foreach my $student (keys(%$classlist)) {
 9538:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9539:         my $username = $classlist->{$student}->[$username_idx];
 9540:         my $domain   = $classlist->{$student}->[$domain_idx];
 9541:         my $clickers =
 9542: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9543:         foreach my $id (split(/\,/,$clickers)) {
 9544:             $id=~s/^[\#0]+//;
 9545:             $id=~s/[\-\:]//g;
 9546:             if (exists($clicker_ids{$id})) {
 9547: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9548:             } else {
 9549: 		$clicker_ids{$id}=$username.':'.$domain;
 9550:             }
 9551:         }
 9552:     }
 9553:     return %clicker_ids;
 9554: }
 9555: 
 9556: sub gather_adv_clicker_ids {
 9557:     my %clicker_ids;
 9558:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9559:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9560:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9561:     foreach my $element (sort(keys(%coursepersonnel))) {
 9562:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9563:             my ($puname,$pudom)=split(/\:/,$person);
 9564:             my $clickers =
 9565: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9566:             foreach my $id (split(/\,/,$clickers)) {
 9567: 		$id=~s/^[\#0]+//;
 9568:                 $id=~s/[\-\:]//g;
 9569: 		if (exists($clicker_ids{$id})) {
 9570: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9571: 		} else {
 9572: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9573: 		}
 9574:             }
 9575:         }
 9576:     }
 9577:     return %clicker_ids;
 9578: }
 9579: 
 9580: sub clicker_grading_parameters {
 9581:     return ('gradingmechanism' => 'scalar',
 9582:             'upfiletype' => 'scalar',
 9583:             'specificid' => 'scalar',
 9584:             'pcorrect' => 'scalar',
 9585:             'pincorrect' => 'scalar');
 9586: }
 9587: 
 9588: sub process_clicker {
 9589:     my ($r,$symb)=@_;
 9590:     if (!$symb) {return '';}
 9591:     my $result=&checkforfile_js();
 9592:     $result.=&Apache::loncommon::start_data_table().
 9593:              &Apache::loncommon::start_data_table_header_row().
 9594:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9595:              &Apache::loncommon::end_data_table_header_row().
 9596:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9597: # Attempt to restore parameters from last session, set defaults if not present
 9598:     my %Saveable_Parameters=&clicker_grading_parameters();
 9599:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9600:                                                  \%Saveable_Parameters);
 9601:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9602:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9603:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9604:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9605: 
 9606:     my %checked;
 9607:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9608:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9609:           $checked{$gradingmechanism}=' checked="checked"';
 9610:        }
 9611:     }
 9612: 
 9613:     my $upload=&mt("Evaluate File");
 9614:     my $type=&mt("Type");
 9615:     my $attendance=&mt("Award points just for participation");
 9616:     my $personnel=&mt("Correctness determined from response by course personnel");
 9617:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9618:     my $given=&mt("Correctness determined from given list of answers").' '.
 9619:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9620:     my $pcorrect=&mt("Percentage points for correct solution");
 9621:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9622:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9623: 						   {'iclicker' => 'i>clicker',
 9624:                                                     'interwrite' => 'interwrite PRS',
 9625:                                                     'turning' => 'Turning Technologies'});
 9626:     $symb = &Apache::lonenc::check_encrypt($symb);
 9627:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9628: function sanitycheck() {
 9629: // Accept only integer percentages
 9630:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9631:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9632: // Find out grading choice
 9633:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9634:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9635:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9636:       }
 9637:    }
 9638: // By default, new choice equals user selection
 9639:    newgradingchoice=gradingchoice;
 9640: // Not good to give more points for false answers than correct ones
 9641:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9642:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9643:    }
 9644: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9645:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9646:       document.forms.gradesupload.pcorrect.value=100;
 9647:       document.forms.gradesupload.pincorrect.value=100;
 9648:    }
 9649: // If the values are different, cannot be attendance only
 9650:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9651:        (gradingchoice=='attendance')) {
 9652:        newgradingchoice='personnel';
 9653:    }
 9654: // Change grading choice to new one
 9655:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9656:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9657:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9658:       } else {
 9659:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9660:       }
 9661:    }
 9662: // Remember the old state
 9663:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9664: }
 9665: ENDUPFORM
 9666:     $result.= <<ENDUPFORM;
 9667: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9668: <input type="hidden" name="symb" value="$symb" />
 9669: <input type="hidden" name="command" value="processclickerfile" />
 9670: <input type="file" name="upfile" size="50" />
 9671: <br /><label>$type: $selectform</label>
 9672: ENDUPFORM
 9673:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9674:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9675:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9676: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9677: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9678: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9679: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9680: <br />&nbsp;&nbsp;&nbsp;
 9681: <input type="text" name="givenanswer" size="50" />
 9682: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9683: ENDGRADINGFORM
 9684:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9685:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9686:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9687: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9688: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9689: </form>'
 9690: ENDPERCFORM
 9691:     $result.='</td>'.
 9692:              &Apache::loncommon::end_data_table_row().
 9693:              &Apache::loncommon::end_data_table();
 9694:     return $result;
 9695: }
 9696: 
 9697: sub process_clicker_file {
 9698:     my ($r,$symb)=@_;
 9699:     if (!$symb) {return '';}
 9700: 
 9701:     my %Saveable_Parameters=&clicker_grading_parameters();
 9702:     &Apache::loncommon::store_course_settings('grades_clicker',
 9703:                                               \%Saveable_Parameters);
 9704:     my $result='';
 9705:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9706: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9707: 	return $result;
 9708:     }
 9709:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9710:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9711:         return $result;
 9712:     }
 9713:     my $foundgiven=0;
 9714:     if ($env{'form.gradingmechanism'} eq 'given') {
 9715:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9716:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9717:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9718:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9719:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9720:         $foundgiven=$#answers+1;
 9721:     }
 9722:     my %clicker_ids=&gather_clicker_ids();
 9723:     my %correct_ids;
 9724:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9725: 	%correct_ids=&gather_adv_clicker_ids();
 9726:     }
 9727:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9728: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9729: 	   $correct_id=~tr/a-z/A-Z/;
 9730: 	   $correct_id=~s/\s//gs;
 9731: 	   $correct_id=~s/^[\#0]+//;
 9732:            $correct_id=~s/[\-\:]//g;
 9733:            if ($correct_id) {
 9734: 	      $correct_ids{$correct_id}='specified';
 9735:            }
 9736:         }
 9737:     }
 9738:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9739: 	$result.=&mt('Score based on attendance only');
 9740:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9741:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9742:     } else {
 9743: 	my $number=0;
 9744: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9745: 	foreach my $id (sort(keys(%correct_ids))) {
 9746: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9747: 	    if ($correct_ids{$id} eq 'specified') {
 9748: 		$result.=&mt('specified');
 9749: 	    } else {
 9750: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9751: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9752: 	    }
 9753: 	    $number++;
 9754: 	}
 9755:         $result.="</p>\n";
 9756:         if ($number==0) {
 9757:             $result .=
 9758:                  &Apache::lonhtmlcommon::confirm_success(
 9759:                      &mt('No IDs found to determine correct answer'),1);
 9760:             return $result;
 9761:         }
 9762:     }
 9763:     if (length($env{'form.upfile'}) < 2) {
 9764:         $result .=
 9765:             &Apache::lonhtmlcommon::confirm_success(
 9766:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9767:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
 9768:         return $result;
 9769:     }
 9770: 
 9771: # Were able to get all the info needed, now analyze the file
 9772: 
 9773:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9774:     $symb = &Apache::lonenc::check_encrypt($symb);
 9775:     $result.=&Apache::loncommon::start_data_table().
 9776:              &Apache::loncommon::start_data_table_header_row().
 9777:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9778:              &Apache::loncommon::end_data_table_header_row().
 9779:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9780: <td>
 9781: <form method="post" action="/adm/grades" name="clickeranalysis">
 9782: <input type="hidden" name="symb" value="$symb" />
 9783: <input type="hidden" name="command" value="assignclickergrades" />
 9784: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9785: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9786: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9787: ENDHEADER
 9788:     if ($env{'form.gradingmechanism'} eq 'given') {
 9789:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9790:     } 
 9791:     my %responses;
 9792:     my @questiontitles;
 9793:     my $errormsg='';
 9794:     my $number=0;
 9795:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9796: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9797:     }
 9798:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9799:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9800:     }
 9801:     if ($env{'form.upfiletype'} eq 'turning') {
 9802:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9803:     }
 9804:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9805:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9806:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9807:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9808:              '<br />';
 9809:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9810:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9811:        return $result;
 9812:     } 
 9813: # Remember Question Titles
 9814: # FIXME: Possibly need delimiter other than ":"
 9815:     for (my $i=0;$i<$number;$i++) {
 9816:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9817:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9818:     }
 9819:     my $correct_count=0;
 9820:     my $student_count=0;
 9821:     my $unknown_count=0;
 9822: # Match answers with usernames
 9823: # FIXME: Possibly need delimiter other than ":"
 9824:     foreach my $id (keys(%responses)) {
 9825:        if ($correct_ids{$id}) {
 9826:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9827:           $correct_count++;
 9828:        } elsif ($clicker_ids{$id}) {
 9829:           if ($clicker_ids{$id}=~/\,/) {
 9830: # More than one user with the same clicker!
 9831:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9832:                            &Apache::loncommon::start_data_table_row()."<td>".
 9833:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9834:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9835:                            "<select name='multi".$id."'>";
 9836:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9837:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9838:              }
 9839:              $result.='</select>';
 9840:              $unknown_count++;
 9841:           } else {
 9842: # Good: found one and only one user with the right clicker
 9843:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9844:              $student_count++;
 9845:           }
 9846:        } else {
 9847:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9848:                            &Apache::loncommon::start_data_table_row()."<td>".
 9849:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9850:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9851:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9852:                    "\n".&mt("Domain").": ".
 9853:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9854:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9855:           $unknown_count++;
 9856:        }
 9857:     }
 9858:     $result.='<hr />'.
 9859:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9860:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9861:        if ($correct_count==0) {
 9862:           $errormsg.="Found no correct answers for grading!";
 9863:        } elsif ($correct_count>1) {
 9864:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9865:        }
 9866:     }
 9867:     if ($number<1) {
 9868:        $errormsg.="Found no questions.";
 9869:     }
 9870:     if ($errormsg) {
 9871:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9872:     } else {
 9873:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9874:     }
 9875:     $result.='</form></td>'.
 9876:              &Apache::loncommon::end_data_table_row().
 9877:              &Apache::loncommon::end_data_table();
 9878:     return $result;
 9879: }
 9880: 
 9881: sub iclicker_eval {
 9882:     my ($questiontitles,$responses)=@_;
 9883:     my $number=0;
 9884:     my $errormsg='';
 9885:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9886:         my %components=&Apache::loncommon::record_sep($line);
 9887:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9888: 	if ($entries[0] eq 'Question') {
 9889: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9890: 		$$questiontitles[$number]=$entries[$i];
 9891: 		$number++;
 9892: 	    }
 9893: 	}
 9894: 	if ($entries[0]=~/^\#/) {
 9895: 	    my $id=$entries[0];
 9896: 	    my @idresponses;
 9897: 	    $id=~s/^[\#0]+//;
 9898: 	    for (my $i=0;$i<$number;$i++) {
 9899: 		my $idx=3+$i*6;
 9900:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9901: 		push(@idresponses,$entries[$idx]);
 9902: 	    }
 9903: 	    $$responses{$id}=join(',',@idresponses);
 9904: 	}
 9905:     }
 9906:     return ($errormsg,$number);
 9907: }
 9908: 
 9909: sub interwrite_eval {
 9910:     my ($questiontitles,$responses)=@_;
 9911:     my $number=0;
 9912:     my $errormsg='';
 9913:     my $skipline=1;
 9914:     my $questionnumber=0;
 9915:     my %idresponses=();
 9916:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9917:         my %components=&Apache::loncommon::record_sep($line);
 9918:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9919:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9920:         if ($entries[1] eq 'Response') { $skipline=1; }
 9921:         next if $skipline;
 9922:         if ($entries[0]!=$questionnumber) {
 9923:            $questionnumber=$entries[0];
 9924:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9925:            $number++;
 9926:         }
 9927:         my $id=$entries[4];
 9928:         $id=~s/^[\#0]+//;
 9929:         $id=~s/^v\d*\://i;
 9930:         $id=~s/[\-\:]//g;
 9931:         $idresponses{$id}[$number]=$entries[6];
 9932:     }
 9933:     foreach my $id (keys(%idresponses)) {
 9934:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9935:        $$responses{$id}=~s/^\s*\,//;
 9936:     }
 9937:     return ($errormsg,$number);
 9938: }
 9939: 
 9940: sub turning_eval {
 9941:     my ($questiontitles,$responses)=@_;
 9942:     my $number=0;
 9943:     my $errormsg='';
 9944:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9945:         my %components=&Apache::loncommon::record_sep($line);
 9946:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9947:         if ($#entries>$number) { $number=$#entries; }
 9948:         my $id=$entries[0];
 9949:         my @idresponses;
 9950:         $id=~s/^[\#0]+//;
 9951:         unless ($id) { next; }
 9952:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9953:             $entries[$idx]=~s/\,/\;/g;
 9954:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
 9955:             push(@idresponses,$entries[$idx]);
 9956:         }
 9957:         $$responses{$id}=join(',',@idresponses);
 9958:     }
 9959:     for (my $i=1; $i<=$number; $i++) {
 9960:         $$questiontitles[$i]=&mt('Question [_1]',$i);
 9961:     }
 9962:     return ($errormsg,$number);
 9963: }
 9964: 
 9965: 
 9966: sub assign_clicker_grades {
 9967:     my ($r,$symb)=@_;
 9968:     if (!$symb) {return '';}
 9969: # See which part we are saving to
 9970:     my $res_error;
 9971:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9972:     if ($res_error) {
 9973:         return &navmap_errormsg();
 9974:     }
 9975: # FIXME: This should probably look for the first handgradeable part
 9976:     my $part=$$partlist[0];
 9977: # Start screen output
 9978:     my $result=&Apache::loncommon::start_data_table().
 9979:              &Apache::loncommon::start_data_table_header_row().
 9980:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9981:              &Apache::loncommon::end_data_table_header_row().
 9982:              &Apache::loncommon::start_data_table_row().'<td>';
 9983: # Get correct result
 9984: # FIXME: Possibly need delimiter other than ":"
 9985:     my @correct=();
 9986:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9987:     my $number=$env{'form.number'};
 9988:     if ($gradingmechanism ne 'attendance') {
 9989:        foreach my $key (keys(%env)) {
 9990:           if ($key=~/^form\.correct\:/) {
 9991:              my @input=split(/\,/,$env{$key});
 9992:              for (my $i=0;$i<=$#input;$i++) {
 9993:                  if (($correct[$i]) && ($input[$i]) &&
 9994:                      ($correct[$i] ne $input[$i])) {
 9995:                     $result.='<br /><span class="LC_warning">'.
 9996:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9997:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9998:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9999:                     $correct[$i]=$input[$i];
10000:                  }
10001:              }
10002:           }
10003:        }
10004:        for (my $i=0;$i<$number;$i++) {
10005:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10006:              $result.='<br /><span class="LC_error">'.
10007:                       &mt('No correct result given for question "[_1]"!',
10008:                           $env{'form.question:'.$i}).'</span>';
10009:           }
10010:        }
10011:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10012:     }
10013: # Start grading
10014:     my $pcorrect=$env{'form.pcorrect'};
10015:     my $pincorrect=$env{'form.pincorrect'};
10016:     my $storecount=0;
10017:     my %users=();
10018:     foreach my $key (keys(%env)) {
10019:        my $user='';
10020:        if ($key=~/^form\.student\:(.*)$/) {
10021:           $user=$1;
10022:        }
10023:        if ($key=~/^form\.unknown\:(.*)$/) {
10024:           my $id=$1;
10025:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10026:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10027:           } elsif ($env{'form.multi'.$id}) {
10028:              $user=$env{'form.multi'.$id};
10029:           }
10030:        }
10031:        if ($user) {
10032:           if ($users{$user}) {
10033:              $result.='<br /><span class="LC_warning">'.
10034:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10035:                       '</span><br />';
10036:           }
10037:           $users{$user}=1; 
10038:           my @answer=split(/\,/,$env{$key});
10039:           my $sum=0;
10040:           my $realnumber=$number;
10041:           for (my $i=0;$i<$number;$i++) {
10042:              if  ($correct[$i] eq '-') {
10043:                 $realnumber--;
10044:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10045:                 if ($gradingmechanism eq 'attendance') {
10046:                    $sum+=$pcorrect;
10047:                 } elsif ($correct[$i] eq '*') {
10048:                    $sum+=$pcorrect;
10049:                 } else {
10050: # We actually grade if correct or not
10051:                    my $increment=$pincorrect;
10052: # Special case: numerical answer "0"
10053:                    if ($correct[$i] eq '0') {
10054:                       if ($answer[$i]=~/^[0\.]+$/) {
10055:                          $increment=$pcorrect;
10056:                       }
10057: # General numerical answer, both evaluate to something non-zero
10058:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10059:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10060:                          $increment=$pcorrect;
10061:                       }
10062: # Must be just alphanumeric
10063:                    } elsif ($answer[$i] eq $correct[$i]) {
10064:                       $increment=$pcorrect;
10065:                    }
10066:                    $sum+=$increment;
10067:                 }
10068:              }
10069:           }
10070:           my $ave=$sum/(100*$realnumber);
10071: # Store
10072:           my ($username,$domain)=split(/\:/,$user);
10073:           my %grades=();
10074:           $grades{"resource.$part.solved"}='correct_by_override';
10075:           $grades{"resource.$part.awarded"}=$ave;
10076:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10077:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10078:                                                  $env{'request.course.id'},
10079:                                                  $domain,$username);
10080:           if ($returncode ne 'ok') {
10081:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10082:           } else {
10083:              $storecount++;
10084:           }
10085:        }
10086:     }
10087: # We are done
10088:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10089:              '</td>'.
10090:              &Apache::loncommon::end_data_table_row().
10091:              &Apache::loncommon::end_data_table();
10092:     return $result;
10093: }
10094: 
10095: sub navmap_errormsg {
10096:     return '<div class="LC_error">'.
10097:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10098:            &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>').
10099:            '</div>';
10100: }
10101: 
10102: sub startpage {
10103:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10104:     if ($nomenu) {
10105:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10106:     } else {
10107:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10108:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10109:                                                  {'bread_crumbs' => $crumbs}));
10110:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10111:     }
10112:     unless ($nodisplayflag) {
10113:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10114:     }
10115: }
10116: 
10117: sub select_problem {
10118:     my ($r)=@_;
10119:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10120:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10121:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10122:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10123: }
10124: 
10125: sub handler {
10126:     my $request=$_[0];
10127:     &reset_caches();
10128:     if ($request->header_only) {
10129:         &Apache::loncommon::content_type($request,'text/html');
10130:         $request->send_http_header;
10131:         return OK;
10132:     }
10133:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10134: 
10135: # see what command we need to execute
10136: 
10137:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10138:     my $command=$commands[0];
10139: 
10140:     &init_perm();
10141:     if (!$env{'request.course.id'}) {
10142:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10143:                 ($command =~ /^scantronupload/)) {
10144:             # Not in a course.
10145:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10146:             return HTTP_NOT_ACCEPTABLE;
10147:         }
10148:     } elsif (!%perm) {
10149:         $request->internal_redirect('/adm/quickgrades');
10150:         return OK;
10151:     }
10152:     &Apache::loncommon::content_type($request,'text/html');
10153:     $request->send_http_header;
10154: 
10155:     if ($#commands > 0) {
10156: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10157:     }
10158: 
10159: # see what the symb is
10160: 
10161:     my $symb=$env{'form.symb'};
10162:     unless ($symb) {
10163:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10164:        $symb=&Apache::lonnet::symbread($url);
10165:     }
10166:     &Apache::lonenc::check_decrypt(\$symb);
10167: 
10168:     $ssi_error = 0;
10169:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10170: #
10171: # Not called from a resource, but inside a course
10172: #    
10173:         &startpage($request,undef,[],1,1);
10174:         &select_problem($request);
10175:     } else {
10176: 	if ($command eq 'submission' && $perm{'vgr'}) {
10177:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10178:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10179:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10180:                     &choose_task_version_form($symb,$env{'form.student'},
10181:                                               $env{'form.userdom'});
10182:             }
10183:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10184:             if ($versionform) {
10185:                 $request->print($versionform);
10186:             }
10187:             $request->print('<br clear="all" />');
10188: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10189:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10190:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10191:                 &choose_task_version_form($symb,$env{'form.student'},
10192:                                           $env{'form.userdom'},
10193:                                           $env{'form.inhibitmenu'});
10194:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10195:             if ($versionform) {
10196:                 $request->print($versionform);
10197:             }
10198:             $request->print('<br clear="all" />');
10199:             $request->print(&show_previous_task_version($request,$symb));
10200: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10201:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10202:                                        {href=>'',text=>'Select student'}],1,1);
10203: 	    &pickStudentPage($request,$symb);
10204: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10205:             &startpage($request,$symb,
10206:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10207:                                        {href=>'',text=>'Select student'},
10208:                                        {href=>'',text=>'Grade student'}],1,1);
10209: 	    &displayPage($request,$symb);
10210: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10211:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10212:                                        {href=>'',text=>'Select student'},
10213:                                        {href=>'',text=>'Grade student'},
10214:                                        {href=>'',text=>'Store grades'}],1,1);
10215: 	    &updateGradeByPage($request,$symb);
10216: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10217:             &startpage($request,$symb,[{href=>'',text=>'...'},
10218:                                        {href=>'',text=>'Modify grades'}]);
10219: 	    &processGroup($request,$symb);
10220: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10221:             &startpage($request,$symb);
10222: 	    $request->print(&grading_menu($request,$symb));
10223: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10224:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10225: 	    $request->print(&submit_options($request,$symb));
10226:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10227:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10228:             $request->print(&listStudents($request,$symb,'graded'));
10229:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10230:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10231:             $request->print(&submit_options_table($request,$symb));
10232:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10233:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10234:             $request->print(&submit_options_sequence($request,$symb));
10235: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10236:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10237: 	    $request->print(&viewgrades($request,$symb));
10238: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10239:             &startpage($request,$symb,[{href=>'',text=>'...'},
10240:                                        {href=>'',text=>'Store grades'}]);
10241: 	    $request->print(&processHandGrade($request,$symb));
10242: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10243:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10244:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10245:                                                                              text=>"Modify grades"},
10246:                                        {href=>'', text=>"Store grades"}]);
10247: 	    $request->print(&editgrades($request,$symb));
10248:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10249:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10250:             $request->print(&initialverifyreceipt($request,$symb));
10251: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10252:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10253:                                        {href=>'',text=>'Verification Result'}]);
10254: 	    $request->print(&verifyreceipt($request,$symb));
10255:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10256:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10257:             $request->print(&process_clicker($request,$symb));
10258:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10260:                                        {href=>'', text=>'Process clicker file'}]);
10261:             $request->print(&process_clicker_file($request,$symb));
10262:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10263:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10264:                                        {href=>'', text=>'Process clicker file'},
10265:                                        {href=>'', text=>'Store grades'}]);
10266:             $request->print(&assign_clicker_grades($request,$symb));
10267: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10268:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10269: 	    $request->print(&upcsvScores_form($request,$symb));
10270: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10271:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10272: 	    $request->print(&csvupload($request,$symb));
10273: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10274:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10275: 	    $request->print(&csvuploadmap($request,$symb));
10276: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10277: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10278:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10279: 		$request->print(&csvuploadoptions($request,$symb));
10280: 	    } else {
10281: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10282: 		    $env{'form.upfile_associate'} = 'reverse';
10283: 		} else {
10284: 		    $env{'form.upfile_associate'} = 'forward';
10285: 		}
10286:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10287: 		$request->print(&csvuploadmap($request,$symb));
10288: 	    }
10289: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10290:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10291: 	    $request->print(&csvuploadassign($request,$symb));
10292: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10293:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10294: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10295:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10296:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10297:  	    $request->print(&scantron_do_warning($request,$symb));
10298: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10299:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10300: 	    $request->print(&scantron_validate_file($request,$symb));
10301: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10302:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10303: 	    $request->print(&scantron_process_students($request,$symb));
10304:  	} elsif ($command eq 'scantronupload' && 
10305:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10306: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10307:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10308:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10309:  	} elsif ($command eq 'scantronupload_save' &&
10310:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10311: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10313:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10314:  	} elsif ($command eq 'scantron_download' &&
10315: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10316:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10317:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10318:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10319:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10320:             $request->print(&checkscantron_results($request,$symb));
10321:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10322:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10323:             $request->print(&submit_options_download($request,$symb));
10324:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10325:             &startpage($request,$symb,
10326:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10327:     {href=>'', text=>'Download submissions'}]);
10328:             &submit_download_link($request,$symb);
10329: 	} elsif ($command) {
10330:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10331: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10332: 	}
10333:     }
10334:     if ($ssi_error) {
10335: 	&ssi_print_error($request);
10336:     }
10337:     if ($env{'form.inhibitmenu'}) {
10338:         $request->print(&Apache::loncommon::end_page());
10339:     } else {
10340:         &Apache::lonquickgrades::endGradeScreen($request);
10341:     }
10342:     &reset_caches();
10343:     return OK;
10344: }
10345: 
10346: 1;
10347: 
10348: __END__;
10349: 
10350: 
10351: =head1 NAME
10352: 
10353: Apache::grades
10354: 
10355: =head1 SYNOPSIS
10356: 
10357: Handles the viewing of grades.
10358: 
10359: This is part of the LearningOnline Network with CAPA project
10360: described at http://www.lon-capa.org.
10361: 
10362: =head1 OVERVIEW
10363: 
10364: Do an ssi with retries:
10365: While I'd love to factor out this with the version in lonprintout,
10366: 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
10367: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10368: 
10369: At least the logic that drives this has been pulled out into loncommon.
10370: 
10371: 
10372: 
10373: ssi_with_retries - Does the server side include of a resource.
10374:                      if the ssi call returns an error we'll retry it up to
10375:                      the number of times requested by the caller.
10376:                      If we still have a problem, no text is appended to the
10377:                      output and we set some global variables.
10378:                      to indicate to the caller an SSI error occurred.  
10379:                      All of this is supposed to deal with the issues described
10380:                      in LON-CAPA BZ 5631 see:
10381:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10382:                      by informing the user that this happened.
10383: 
10384: Parameters:
10385:   resource   - The resource to include.  This is passed directly, without
10386:                interpretation to lonnet::ssi.
10387:   form       - The form hash parameters that guide the interpretation of the resource
10388:                
10389:   retries    - Number of retries allowed before giving up completely.
10390: Returns:
10391:   On success, returns the rendered resource identified by the resource parameter.
10392: Side Effects:
10393:   The following global variables can be set:
10394:    ssi_error                - If an unrecoverable error occurred this becomes true.
10395:                               It is up to the caller to initialize this to false
10396:                               if desired.
10397:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10398:                               of the resource that could not be rendered by the ssi
10399:                               call.
10400:    ssi_error_message   - The error string fetched from the ssi response
10401:                               in the event of an error.
10402: 
10403: 
10404: =head1 HANDLER SUBROUTINE
10405: 
10406: ssi_with_retries()
10407: 
10408: =head1 SUBROUTINES
10409: 
10410: =over
10411: 
10412: =head1 Routines to display previous version of a Task for a specific student
10413: 
10414: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10415: can receive another opportunity. Access to tasks is slot-based. If a slot
10416: requires a proctor to check-in the student, a new version of the Task will
10417: be created when the student is checked in to the new opportunity.
10418: 
10419: If a particular student has tried two or more versions of a particular task,
10420: the submission screen provides a user with vgr privileges (e.g., a Course
10421: Coordinator) the ability to display a previous version worked on by the
10422: student.  By default, the current version is displayed. If a previous version
10423: has been selected for display, submission data are only shown that pertain
10424: to that particular version, and the interface to submit grades is not shown.
10425: 
10426: =over 4
10427: 
10428: =item show_previous_task_version()
10429: 
10430: Displays a specified version of a student's Task, as the student sees it.
10431: 
10432: Inputs: 2
10433:         request - request object
10434:         symb    - unique symb for current instance of resource
10435: 
10436: Output: None.
10437: 
10438: Side Effects: calls &show_problem() to print version of Task, with
10439:               version contained in form item: $env{'form.previousversion'}
10440: 
10441: =item choose_task_version_form()
10442: 
10443: Displays a web form used to select which version of a student's view of a
10444: Task should be displayed.  Either launches a pop-up window, or replaces
10445: content in existing pop-up, or replaces page in main window.
10446: 
10447: Inputs: 4
10448:         symb    - unique symb for current instance of resource
10449:         uname   - username of student
10450:         udom    - domain of student
10451:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10452:                   breadcrumbs etc., are displayed
10453: 
10454: Output: 4
10455:         current   - student's current version
10456:         displayed - student's version being displayed
10457:         result    - scalar containing HTML for web form used to switch to
10458:                     a different version (or a link to close window, if pop-up).
10459:         js        - javascript for processing selection in versions web form
10460: 
10461: Side Effects: None.
10462: 
10463: =item previous_display_javascript()
10464: 
10465: Inputs: 2
10466:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10467:                   breadcrumbs etc., are displayed.
10468:         current - student's current version number.
10469: 
10470: Output: 1
10471:         js      - javascript for processing selection in versions web form.
10472: 
10473: Side Effects: None.
10474: 
10475: =back
10476: 
10477: =head1 Routines to process bubblesheet data.
10478: 
10479: =over 4
10480: 
10481: =item scantron_get_correction() : 
10482: 
10483:    Builds the interface screen to interact with the operator to fix a
10484:    specific error condition in a specific scanline
10485: 
10486:  Arguments:
10487:     $r           - Apache request object
10488:     $i           - number of the current scanline
10489:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10490:     $scan_config - hash ref as returned from &get_scantron_config()
10491:     $line        - full contents of the current scanline
10492:     $error       - error condition, valid values are
10493:                    'incorrectCODE', 'duplicateCODE',
10494:                    'doublebubble', 'missingbubble',
10495:                    'duplicateID', 'incorrectID'
10496:     $arg         - extra information needed
10497:        For errors:
10498:          - duplicateID   - paper number that this studentID was seen before on
10499:          - duplicateCODE - array ref of the paper numbers this CODE was
10500:                            seen on before
10501:          - incorrectCODE - current incorrect CODE 
10502:          - doublebubble  - array ref of the bubble lines that have double
10503:                            bubble errors
10504:          - missingbubble - array ref of the bubble lines that have missing
10505:                            bubble errors
10506: 
10507:    $randomorder - True if exam folder has randomorder set
10508:    $randompick  - True if exam folder has randompick set
10509:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10510:                      for current line to question number used for same question
10511:                      in "Master Seqence" (as seen by Course Coordinator).
10512:    $startline   - Reference to hash where key is question number (0 is first)
10513:                   and value is number of first bubble line for current student
10514:                   or code-based randompick and/or randomorder.
10515: 
10516: 
10517: 
10518: =item  scantron_get_maxbubble() : 
10519: 
10520:    Arguments:
10521:        $nav_error  - Reference to scalar which is a flag to indicate a
10522:                       failure to retrieve a navmap object.
10523:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10524:        calling routine should trap the error condition and display the warning
10525:        found in &navmap_errormsg().
10526: 
10527:        $scantron_config - Reference to bubblesheet format configuration hash.
10528: 
10529:    Returns the maximum number of bubble lines that are expected to
10530:    occur. Does this by walking the selected sequence rendering the
10531:    resource and then checking &Apache::lonxml::get_problem_counter()
10532:    for what the current value of the problem counter is.
10533: 
10534:    Caches the results to $env{'form.scantron_maxbubble'},
10535:    $env{'form.scantron.bubble_lines.n'}, 
10536:    $env{'form.scantron.first_bubble_line.n'} and
10537:    $env{"form.scantron.sub_bubblelines.n"}
10538:    which are the total number of bubble lines, the number of bubble
10539:    lines for response n and number of the first bubble line for response n,
10540:    and a comma separated list of numbers of bubble lines for sub-questions
10541:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10542: 
10543: 
10544: =item  scantron_validate_missingbubbles() : 
10545: 
10546:    Validates all scanlines in the selected file to not have any
10547:     answers that don't have bubbles that have not been verified
10548:     to be bubble free.
10549: 
10550: =item  scantron_process_students() : 
10551: 
10552:    Routine that does the actual grading of the bubblesheet information.
10553: 
10554:    The parsed scanline hash is added to %env 
10555: 
10556:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10557:    foreach resource , with the form data of
10558: 
10559: 	'submitted'     =>'scantron' 
10560: 	'grade_target'  =>'grade',
10561: 	'grade_username'=> username of student
10562: 	'grade_domain'  => domain of student
10563: 	'grade_courseid'=> of course
10564: 	'grade_symb'    => symb of resource to grade
10565: 
10566:     This triggers a grading pass. The problem grading code takes care
10567:     of converting the bubbled letter information (now in %env) into a
10568:     valid submission.
10569: 
10570: =item  scantron_upload_scantron_data() :
10571: 
10572:     Creates the screen for adding a new bubblesheet data file to a course.
10573: 
10574: =item  scantron_upload_scantron_data_save() : 
10575: 
10576:    Adds a provided bubble information data file to the course if user
10577:    has the correct privileges to do so. 
10578: 
10579: =item  valid_file() :
10580: 
10581:    Validates that the requested bubble data file exists in the course.
10582: 
10583: =item  scantron_download_scantron_data() : 
10584: 
10585:    Shows a list of the three internal files (original, corrected,
10586:    skipped) for a specific bubblesheet data file that exists in the
10587:    course.
10588: 
10589: =item  scantron_validate_ID() : 
10590: 
10591:    Validates all scanlines in the selected file to not have any
10592:    invalid or underspecified student/employee IDs
10593: 
10594: =item navmap_errormsg() :
10595: 
10596:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10597:    Should be called whenever the request to instantiate a navmap object fails.
10598: 
10599: =back
10600: 
10601: =back
10602: 
10603: =cut

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