File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.743: download - view: text, annotated - select for diffs
Thu Dec 14 17:37:07 2017 UTC (6 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5977.
  - Score upload form support for identification of a user based on clicker ID,
    for Course Coordinators who prefer not to use LON-CAPA's in-built
    "Process Clicker" utility.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.743 2017/12/14 17:37:07 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: my %old_essays=();
   58: 
   59: #  These variables are used to recover from ssi errors
   60: 
   61: my $ssi_retries = 5;
   62: my $ssi_error;
   63: my $ssi_error_resource;
   64: my $ssi_error_message;
   65: 
   66: 
   67: sub ssi_with_retries {
   68:     my ($resource, $retries, %form) = @_;
   69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   70:     if ($response->is_error) {
   71: 	$ssi_error          = 1;
   72: 	$ssi_error_resource = $resource;
   73: 	$ssi_error_message  = $response->code . " " . $response->message;
   74:     }
   75: 
   76:     return $content;
   77: 
   78: }
   79: #
   80: #  Prodcuces an ssi retry failure error message to the user:
   81: #
   82: 
   83: sub ssi_print_error {
   84:     my ($r) = @_;
   85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   86:     $r->print('
   87: <br />
   88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   89: <p>
   90: '.&mt('Unable to retrieve a resource from a server:').'<br />
   91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   92: '.&mt('Error:').' '.$ssi_error_message.'
   93: </p>
   94: <p>'.
   95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   97: '</p>');
   98:     return;
   99: }
  100: 
  101: #
  102: # --- Retrieve the parts from the metadata file.---
  103: # Returns an array of everything that the resources stores away
  104: #
  105: 
  106: sub getpartlist {
  107:     my ($symb,$errorref) = @_;
  108: 
  109:     my $navmap   = Apache::lonnavmaps::navmap->new();
  110:     unless (ref($navmap)) {
  111:         if (ref($errorref)) { 
  112:             $$errorref = 'navmap';
  113:             return;
  114:         }
  115:     }
  116:     my $res      = $navmap->getBySymb($symb);
  117:     my $partlist = $res->parts();
  118:     my $url      = $res->src();
  119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  120: 
  121:     my @stores;
  122:     foreach my $part (@{ $partlist }) {
  123: 	foreach my $key (@metakeys) {
  124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  125: 	}
  126:     }
  127:     return @stores;
  128: }
  129: 
  130: #--- Format fullname, username:domain if different for display
  131: #--- Use anywhere where the student names are listed
  132: sub nameUserString {
  133:     my ($type,$fullname,$uname,$udom) = @_;
  134:     if ($type eq 'header') {
  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  136:     } else {
  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  139:     }
  140: }
  141: 
  142: #--- Get the partlist and the response type for a given problem. ---
  143: #--- Indicate if a response type is coded handgraded or not. ---
  144: #--- Sets response_error pointer to "1" if navmaps object broken ---
  145: sub response_type {
  146:     my ($symb,$response_error) = @_;
  147: 
  148:     my $navmap = Apache::lonnavmaps::navmap->new();
  149:     unless (ref($navmap)) {
  150:         if (ref($response_error)) {
  151:             $$response_error = 1;
  152:         }
  153:         return;
  154:     }
  155:     my $res = $navmap->getBySymb($symb);
  156:     unless (ref($res)) {
  157:         $$response_error = 1;
  158:         return;
  159:     }
  160:     my $partlist = $res->parts();
  161:     my %vPart = 
  162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  163:     my (%response_types,%handgrade);
  164:     foreach my $part (@{ $partlist }) {
  165: 	next if (%vPart && !exists($vPart{$part}));
  166: 
  167: 	my @types = $res->responseType($part);
  168: 	my @ids = $res->responseIds($part);
  169: 	for (my $i=0; $i < scalar(@ids); $i++) {
  170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  171: 	    $handgrade{$part.'_'.$ids[$i]} = 
  172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  173: 				     '.handgrade',$symb);
  174: 	}
  175:     }
  176:     return ($partlist,\%handgrade,\%response_types);
  177: }
  178: 
  179: sub flatten_responseType {
  180:     my ($responseType) = @_;
  181:     my @part_response_id =
  182: 	map { 
  183: 	    my $part = $_;
  184: 	    map {
  185: 		[$part,$_]
  186: 		} sort(keys(%{ $responseType->{$part} }));
  187: 	} sort(keys(%$responseType));
  188:     return @part_response_id;
  189: }
  190: 
  191: sub get_display_part {
  192:     my ($partID,$symb)=@_;
  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  194:     if (defined($display) and $display ne '') {
  195:         $display.= ' (<span class="LC_internal_info">'
  196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  197:     } else {
  198: 	$display=$partID;
  199:     }
  200:     return $display;
  201: }
  202: 
  203: sub reset_caches {
  204:     &reset_analyze_cache();
  205:     &reset_perm();
  206:     &reset_old_essays();
  207: }
  208: 
  209: {
  210:     my %analyze_cache;
  211:     my %analyze_cache_formkeys;
  212: 
  213:     sub reset_analyze_cache {
  214: 	undef(%analyze_cache);
  215:         undef(%analyze_cache_formkeys);
  216:     }
  217: 
  218:     sub get_analyze {
  219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  220: 	my $key = "$symb\0$uname\0$udom";
  221:         if ($type eq 'randomizetry') {
  222:             if ($trial ne '') {
  223:                 $key .= "\0".$trial;
  224:             }
  225:         }
  226: 	if (exists($analyze_cache{$key})) {
  227:             my $getupdate = 0;
  228:             if (ref($add_to_hash) eq 'HASH') {
  229:                 foreach my $item (keys(%{$add_to_hash})) {
  230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  232:                             $getupdate = 1;
  233:                             last;
  234:                         }
  235:                     } else {
  236:                         $getupdate = 1;
  237:                     }
  238:                 }
  239:             }
  240:             if (!$getupdate) {
  241:                 return $analyze_cache{$key};
  242:             }
  243:         }
  244: 
  245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  246: 	$url=&Apache::lonnet::clutter($url);
  247:         my %form = ('grade_target'      => 'analyze',
  248:                     'grade_domain'      => $udom,
  249:                     'grade_symb'        => $symb,
  250:                     'grade_courseid'    =>  $env{'request.course.id'},
  251:                     'grade_username'    => $uname,
  252:                     'grade_noincrement' => $no_increment);
  253:         if ($bubbles_per_row ne '') {
  254:             $form{'bubbles_per_row'} = $bubbles_per_row;
  255:         }
  256:         if ($type eq 'randomizetry') {
  257:             $form{'grade_questiontype'} = $type;
  258:             if ($rndseed ne '') {
  259:                 $form{'grade_rndseed'} = $rndseed;
  260:             }
  261:         }
  262:         if (ref($add_to_hash)) {
  263:             %form = (%form,%{$add_to_hash});
  264:         }
  265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  268:         if (ref($add_to_hash) eq 'HASH') {
  269:             $analyze_cache_formkeys{$key} = $add_to_hash;
  270:         } else {
  271:             $analyze_cache_formkeys{$key} = {};
  272:         }
  273: 	return $analyze_cache{$key} = \%analyze;
  274:     }
  275: 
  276:     sub get_order {
  277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  279: 	return $analyze->{"$partid.$respid.shown"};
  280:     }
  281: 
  282:     sub get_radiobutton_correct_foil {
  283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  286:         if (ref($foils) eq 'ARRAY') {
  287: 	    foreach my $foil (@{$foils}) {
  288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  289: 		    return $foil;
  290: 	        }
  291: 	    }
  292: 	}
  293:     }
  294: 
  295:     sub scantron_partids_tograde {
  296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  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:             if ($scancode) {
  305:                 if (ref($add_to_form) eq 'HASH') {
  306:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  307:                 } else {
  308:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  309:                 }
  310:             }
  311:             my $analyze = 
  312:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  313:                              undef,undef,undef,$bubbles_per_row);
  314:             if (ref($analyze) eq 'HASH') {
  315:                 %analysis = %{$analyze};
  316:             }
  317:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  318:                 foreach my $part (@{$analysis{'parts'}}) {
  319:                     my ($id,$respid) = split(/\./,$part);
  320:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  321:                         push(@parts,$part);
  322:                     }
  323:                 }
  324:             }
  325:         }
  326:         return (\%analysis,\@parts);
  327:     }
  328: 
  329: }
  330: 
  331: #--- Clean response type for display
  332: #--- Currently filters option/rank/radiobutton/match/essay/Task
  333: #        response types only.
  334: sub cleanRecord {
  335:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  336: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  337:     my $grayFont = '<span class="LC_internal_info">';
  338:     if ($response =~ /^(option|rank)$/) {
  339: 	my %answer=&Apache::lonnet::str2hash($answer);
  340:         my @answer = %answer;
  341:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  342: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  343: 	my ($toprow,$bottomrow);
  344: 	foreach my $foil (@$order) {
  345: 	    if ($grading{$foil} == 1) {
  346: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  347: 	    } else {
  348: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  349: 	    }
  350: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  351: 	}
  352: 	return '<blockquote><table border="1">'.
  353: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  354: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  355: 	    $bottomrow.'</tr></table></blockquote>';
  356:     } elsif ($response eq 'match') {
  357: 	my %answer=&Apache::lonnet::str2hash($answer);
  358:         my @answer = %answer;
  359:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  360: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  361: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  362: 	my ($toprow,$middlerow,$bottomrow);
  363: 	foreach my $foil (@$order) {
  364: 	    my $item=shift(@items);
  365: 	    if ($grading{$foil} == 1) {
  366: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  367: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  368: 	    } else {
  369: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  370: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  371: 	    }
  372: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  373: 	}
  374: 	return '<blockquote><table border="1">'.
  375: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  376: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  377: 	    $middlerow.'</tr>'.
  378: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  379: 	    $bottomrow.'</tr></table></blockquote>';
  380:     } elsif ($response eq 'radiobutton') {
  381: 	my %answer=&Apache::lonnet::str2hash($answer);
  382:         my @answer = %answer;
  383:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  384: 	my ($toprow,$bottomrow);
  385: 	my $correct = 
  386: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  387: 	foreach my $foil (@$order) {
  388: 	    if (exists($answer{$foil})) {
  389: 		if ($foil eq $correct) {
  390: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  391: 		} else {
  392: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  393: 		}
  394: 	    } else {
  395: 		$toprow.='<td>'.&mt('false').'</td>';
  396: 	    }
  397: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  398: 	}
  399: 	return '<blockquote><table border="1">'.
  400: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  401: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  402: 	    $bottomrow.'</tr></table></blockquote>';
  403:     } elsif ($response eq 'essay') {
  404: 	if (! exists ($env{'form.'.$symb})) {
  405: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  406: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  407: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  408: 
  409: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  410: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  411: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  412: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  413: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  414: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  415: 	}
  416: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  417: 
  418:     } elsif ( $response eq 'organic') {
  419:         my $result=&mt('Smile representation: [_1]',
  420:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  421: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  422: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  423: 	return $result;
  424:     } elsif ( $response eq 'Task') {
  425: 	if ( $answer eq 'SUBMITTED') {
  426: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  427: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  428: 	    return $result;
  429: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  430: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  431: 			       keys(%{$record}));
  432: 	    return join('<br />',($version,@matches));
  433: 			       
  434: 			       
  435: 	} else {
  436: 	    my $result =
  437: 		'<p>'
  438: 		.&mt('Overall result: [_1]',
  439: 		     $record->{$version."resource.$respid.$partid.status"})
  440: 		.'</p>';
  441: 	    
  442: 	    $result .= '<ul>';
  443: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  444: 			     keys(%{$record}));
  445: 	    foreach my $grade (sort(@grade)) {
  446: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  447: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  448: 				     $dim, $record->{$grade}).
  449: 			  '</li>';
  450: 	    }
  451: 	    $result.='</ul>';
  452: 	    return $result;
  453: 	}
  454:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  455:         # Respect multiple input fields, see Bug #5409
  456: 	$answer = 
  457: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  458: 							      $answer);
  459: 	return $answer;
  460:     }
  461:     return &HTML::Entities::encode($answer, '"<>&');
  462: }
  463: 
  464: #-- A couple of common js functions
  465: sub commonJSfunctions {
  466:     my $request = shift;
  467:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  468:     function radioSelection(radioButton) {
  469: 	var selection=null;
  470: 	if (radioButton.length > 1) {
  471: 	    for (var i=0; i<radioButton.length; i++) {
  472: 		if (radioButton[i].checked) {
  473: 		    return radioButton[i].value;
  474: 		}
  475: 	    }
  476: 	} else {
  477: 	    if (radioButton.checked) return radioButton.value;
  478: 	}
  479: 	return selection;
  480:     }
  481: 
  482:     function pullDownSelection(selectOne) {
  483: 	var selection="";
  484: 	if (selectOne.length > 1) {
  485: 	    for (var i=0; i<selectOne.length; i++) {
  486: 		if (selectOne[i].selected) {
  487: 		    return selectOne[i].value;
  488: 		}
  489: 	    }
  490: 	} else {
  491:             // only one value it must be the selected one
  492: 	    return selectOne.value;
  493: 	}
  494:     }
  495: COMMONJSFUNCTIONS
  496: }
  497: 
  498: #--- Dumps the class list with usernames,list of sections,
  499: #--- section, ids and fullnames for each user.
  500: sub getclasslist {
  501:     my ($getsec,$filterlist,$getgroup) = @_;
  502:     my @getsec;
  503:     my @getgroup;
  504:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  505:     if (!ref($getsec)) {
  506: 	if ($getsec ne '' && $getsec ne 'all') {
  507: 	    @getsec=($getsec);
  508: 	}
  509:     } else {
  510: 	@getsec=@{$getsec};
  511:     }
  512:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  513:     if (!ref($getgroup)) {
  514: 	if ($getgroup ne '' && $getgroup ne 'all') {
  515: 	    @getgroup=($getgroup);
  516: 	}
  517:     } else {
  518: 	@getgroup=@{$getgroup};
  519:     }
  520:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  521: 
  522:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  523:     # Bail out if we were unable to get the classlist
  524:     return if (! defined($classlist));
  525:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  526:     #
  527:     my %sections;
  528:     my %fullnames;
  529:     foreach my $student (keys(%$classlist)) {
  530:         my $end      = 
  531:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  532:         my $start    = 
  533:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  534:         my $id       = 
  535:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  536:         my $section  = 
  537:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  538:         my $fullname = 
  539:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  540:         my $status   = 
  541:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  542:         my $group   = 
  543:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  544: 	# filter students according to status selected
  545: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  546: 	    if (!($stu_status =~ $status)) {
  547: 		delete($classlist->{$student});
  548: 		next;
  549: 	    }
  550: 	}
  551: 	# filter students according to groups selected
  552: 	my @stu_groups = split(/,/,$group);
  553: 	if (@getgroup) {
  554: 	    my $exclude = 1;
  555: 	    foreach my $grp (@getgroup) {
  556: 	        foreach my $stu_group (@stu_groups) {
  557: 	            if ($stu_group eq $grp) {
  558: 	                $exclude = 0;
  559:     	            } 
  560: 	        }
  561:     	        if (($grp eq 'none') && !$group) {
  562:         	        $exclude = 0;
  563:         	}
  564: 	    }
  565: 	    if ($exclude) {
  566: 	        delete($classlist->{$student});
  567: 	    }
  568: 	}
  569: 	$section = ($section ne '' ? $section : 'none');
  570: 	if (&canview($section)) {
  571: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  572: 		$sections{$section}++;
  573: 		if ($classlist->{$student}) {
  574: 		    $fullnames{$student}=$fullname;
  575: 		}
  576: 	    } else {
  577: 		delete($classlist->{$student});
  578: 	    }
  579: 	} else {
  580: 	    delete($classlist->{$student});
  581: 	}
  582:     }
  583:     my %seen = ();
  584:     my @sections = sort(keys(%sections));
  585:     return ($classlist,\@sections,\%fullnames);
  586: }
  587: 
  588: sub canmodify {
  589:     my ($sec)=@_;
  590:     if ($perm{'mgr'}) {
  591: 	if (!defined($perm{'mgr_section'})) {
  592: 	    # can modify whole class
  593: 	    return 1;
  594: 	} else {
  595: 	    if ($sec eq $perm{'mgr_section'}) {
  596: 		#can modify the requested section
  597: 		return 1;
  598: 	    } else {
  599: 		# can't modify the request section
  600: 		return 0;
  601: 	    }
  602: 	}
  603:     }
  604:     #can't modify
  605:     return 0;
  606: }
  607: 
  608: sub canview {
  609:     my ($sec)=@_;
  610:     if ($perm{'vgr'}) {
  611: 	if (!defined($perm{'vgr_section'})) {
  612: 	    # can modify whole class
  613: 	    return 1;
  614: 	} else {
  615: 	    if ($sec eq $perm{'vgr_section'}) {
  616: 		#can modify the requested section
  617: 		return 1;
  618: 	    } else {
  619: 		# can't modify the request section
  620: 		return 0;
  621: 	    }
  622: 	}
  623:     }
  624:     #can't modify
  625:     return 0;
  626: }
  627: 
  628: #--- Retrieve the grade status of a student for all the parts
  629: sub student_gradeStatus {
  630:     my ($symb,$udom,$uname,$partlist) = @_;
  631:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  632:     my %partstatus = ();
  633:     foreach (@$partlist) {
  634: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  635: 	$status              = 'nothing' if ($status eq '');
  636: 	$partstatus{$_}      = $status;
  637: 	my $subkey           = "resource.$_.submitted_by";
  638: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  639:     }
  640:     return %partstatus;
  641: }
  642: 
  643: # hidden form and javascript that calls the form
  644: # Use by verifyscript and viewgrades
  645: # Shows a student's view of problem and submission
  646: sub jscriptNform {
  647:     my ($symb) = @_;
  648:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  649:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  650: 	'    function viewOneStudent(user,domain) {'."\n".
  651: 	'	document.onestudent.student.value = user;'."\n".
  652: 	'	document.onestudent.userdom.value = domain;'."\n".
  653: 	'	document.onestudent.submit();'."\n".
  654: 	'    }'."\n".
  655: 	"\n");
  656:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  657: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  658: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  659: 	'<input type="hidden" name="command" value="submission" />'."\n".
  660: 	'<input type="hidden" name="student" value="" />'."\n".
  661: 	'<input type="hidden" name="userdom" value="" />'."\n".
  662: 	'</form>'."\n";
  663:     return $jscript;
  664: }
  665: 
  666: 
  667: 
  668: # Given the score (as a number [0-1] and the weight) what is the final
  669: # point value? This function will round to the nearest tenth, third,
  670: # or quarter if one of those is within the tolerance of .00001.
  671: sub compute_points {
  672:     my ($score, $weight) = @_;
  673:     
  674:     my $tolerance = .00001;
  675:     my $points = $score * $weight;
  676: 
  677:     # Check for nearness to 1/x.
  678:     my $check_for_nearness = sub {
  679:         my ($factor) = @_;
  680:         my $num = ($points * $factor) + $tolerance;
  681:         my $floored_num = floor($num);
  682:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  683:             return $floored_num / $factor;
  684:         }
  685:         return $points;
  686:     };
  687: 
  688:     $points = $check_for_nearness->(10);
  689:     $points = $check_for_nearness->(3);
  690:     $points = $check_for_nearness->(4);
  691:     
  692:     return $points;
  693: }
  694: 
  695: #------------------ End of general use routines --------------------
  696: 
  697: #
  698: # Find most similar essay
  699: #
  700: 
  701: sub most_similar {
  702:     my ($uname,$udom,$symb,$uessay)=@_;
  703: 
  704:     unless ($symb) { return ''; }
  705: 
  706:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  707: 
  708: # ignore spaces and punctuation
  709: 
  710:     $uessay=~s/\W+/ /gs;
  711: 
  712: # ignore empty submissions (occuring when only files are sent)
  713: 
  714:     unless ($uessay=~/\w+/s) { return ''; }
  715: 
  716: # these will be returned. Do not care if not at least 50 percent similar
  717:     my $limit=0.6;
  718:     my $sname='';
  719:     my $sdom='';
  720:     my $scrsid='';
  721:     my $sessay='';
  722: # go through all essays ...
  723:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  724: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  725: # ... except the same student
  726:         next if (($tname eq $uname) && ($tdom eq $udom));
  727: 	my $tessay=$old_essays{$symb}{$tkey};
  728: 	$tessay=~s/\W+/ /gs;
  729: # String similarity gives up if not even limit
  730: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  731: # Found one
  732: 	if ($tsimilar>$limit) {
  733: 	    $limit=$tsimilar;
  734: 	    $sname=$tname;
  735: 	    $sdom=$tdom;
  736: 	    $scrsid=$tcrsid;
  737: 	    $sessay=$old_essays{$symb}{$tkey};
  738: 	}
  739:     }
  740:     if ($limit>0.6) {
  741:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  742:     } else {
  743:        return ('','','','',0);
  744:     }
  745: }
  746: 
  747: #-------------------------------------------------------------------
  748: 
  749: #------------------------------------ Receipt Verification Routines
  750: #
  751: 
  752: sub initialverifyreceipt {
  753:    my ($request,$symb) = @_;
  754:    &commonJSfunctions($request);
  755:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  756:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  757:         '-<input type="text" name="receipt" size="4" />'.
  758:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  759:         '<input type="hidden" name="command" value="verify" />'.
  760:         "</form>\n";
  761: }
  762: 
  763: #--- Check whether a receipt number is valid.---
  764: sub verifyreceipt {
  765:     my ($request,$symb)  = @_;
  766: 
  767:     my $courseid = $env{'request.course.id'};
  768:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  769: 	$env{'form.receipt'};
  770:     $receipt     =~ s/[^\-\d]//g;
  771: 
  772:     my $title.=
  773: 	'<h3><span class="LC_info">'.
  774: 	&mt('Verifying Receipt Number [_1]',$receipt).
  775: 	'</span></h3>'."\n";
  776: 
  777:     my ($string,$contents,$matches) = ('','',0);
  778:     my (undef,undef,$fullname) = &getclasslist('all','0');
  779:     
  780:     my $receiptparts=0;
  781:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  782: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  783:     my $parts=['0'];
  784:     if ($receiptparts) {
  785:         my $res_error; 
  786:         ($parts)=&response_type($symb,\$res_error);
  787:         if ($res_error) {
  788:             return &navmap_errormsg();
  789:         } 
  790:     }
  791:     
  792:     my $header = 
  793: 	&Apache::loncommon::start_data_table().
  794: 	&Apache::loncommon::start_data_table_header_row().
  795: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  796: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  797: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  798:     if ($receiptparts) {
  799: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  800:     }
  801:     $header.=
  802: 	&Apache::loncommon::end_data_table_header_row();
  803: 
  804:     foreach (sort 
  805: 	     {
  806: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  807: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  808: 		 }
  809: 		 return $a cmp $b;
  810: 	     } (keys(%$fullname))) {
  811: 	my ($uname,$udom)=split(/\:/);
  812: 	foreach my $part (@$parts) {
  813: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  814: 		$contents.=
  815: 		    &Apache::loncommon::start_data_table_row().
  816: 		    '<td>&nbsp;'."\n".
  817: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  818: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  819: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  820: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  821: 		if ($receiptparts) {
  822: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  823: 		}
  824: 		$contents.= 
  825: 		    &Apache::loncommon::end_data_table_row()."\n";
  826: 		
  827: 		$matches++;
  828: 	    }
  829: 	}
  830:     }
  831:     if ($matches == 0) {
  832:         $string = $title
  833:                  .'<p class="LC_warning">'
  834:                  .&mt('No match found for the above receipt number.')
  835:                  .'</p>';
  836:     } else {
  837: 	$string = &jscriptNform($symb).$title.
  838: 	    '<p>'.
  839: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  840: 	    '</p>'.
  841: 	    $header.
  842: 	    $contents.
  843: 	    &Apache::loncommon::end_data_table()."\n";
  844:     }
  845:     return $string;
  846: }
  847: 
  848: #--- This is called by a number of programs.
  849: #--- Called from the Grading Menu - View/Grade an individual student
  850: #--- Also called directly when one clicks on the subm button 
  851: #    on the problem page.
  852: sub listStudents {
  853:     my ($request,$symb,$submitonly) = @_;
  854: 
  855:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  856:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  857:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  858:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  859:     unless ($submitonly) {
  860:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  861:     }
  862: 
  863:     my $result='';
  864:     my $res_error;
  865:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  866: 
  867:     my %js_lt = &Apache::lonlocal::texthash (
  868: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  869: 		'single'   => 'Please select the student before clicking on the Next button.',
  870: 	     );
  871:     &js_escape(\%js_lt);
  872:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  873:     function checkSelect(checkBox) {
  874: 	var ctr=0;
  875: 	var sense="";
  876: 	if (checkBox.length > 1) {
  877: 	    for (var i=0; i<checkBox.length; i++) {
  878: 		if (checkBox[i].checked) {
  879: 		    ctr++;
  880: 		}
  881: 	    }
  882: 	    sense = '$js_lt{'multiple'}';
  883: 	} else {
  884: 	    if (checkBox.checked) {
  885: 		ctr = 1;
  886: 	    }
  887: 	    sense = '$js_lt{'single'}';
  888: 	}
  889: 	if (ctr == 0) {
  890: 	    alert(sense);
  891: 	    return false;
  892: 	}
  893: 	document.gradesub.submit();
  894:     }
  895: 
  896:     function reLoadList(formname) {
  897: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  898: 	formname.command.value = 'submission';
  899: 	formname.submit();
  900:     }
  901: LISTJAVASCRIPT
  902: 
  903:     &commonJSfunctions($request);
  904:     $request->print($result);
  905: 
  906:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  907: 	"\n";
  908: 	
  909:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  910:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  911:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  912:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  913:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  914:                   .&Apache::lonhtmlcommon::row_closure();
  915:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  916:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  917:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  918:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  919:                   .&Apache::lonhtmlcommon::row_closure();
  920: 
  921:     my $submission_options;
  922:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  923:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  924:     $env{'form.Status'} = $saveStatus;
  925:     $submission_options.=
  926:         '<span class="LC_nobreak">'.
  927:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  928:         &mt('last submission').' </label></span>'."\n".
  929:         '<span class="LC_nobreak">'.
  930:         '<label><input type="radio" name="lastSub" value="last" /> '.
  931:         &mt('last submission with details').' </label></span>'."\n".
  932:         '<span class="LC_nobreak">'.
  933:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  934:         &mt('all submissions').'</label></span>'."\n".
  935:         '<span class="LC_nobreak">'.
  936:         '<label><input type="radio" name="lastSub" value="all" /> '.
  937:         &mt('all submissions with details').'</label></span>';
  938:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
  939:                   .$submission_options
  940:                   .&Apache::lonhtmlcommon::row_closure();
  941: 
  942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  943:                   .'<select name="increment">'
  944:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  945:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  946:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  947:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  948:                   .'</select>'
  949:                   .&Apache::lonhtmlcommon::row_closure();
  950: 
  951:     $gradeTable .= 
  952:         &build_section_inputs().
  953: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  954: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  955: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  956: 
  957:     if (exists($env{'form.Status'})) {
  958: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  959:     } else {
  960:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  961:                       .&Apache::lonhtmlcommon::StatusOptions(
  962:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  963:                       .&Apache::lonhtmlcommon::row_closure();
  964:     }
  965: 
  966:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  967:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  968:                   .&Apache::lonhtmlcommon::row_closure(1)
  969:                   .&Apache::lonhtmlcommon::end_pick_box();
  970: 
  971:     $gradeTable .= '<p>'
  972:                   .&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"
  973:                   .'<input type="hidden" name="command" value="processGroup" />'
  974:                   .'</p>';
  975: 
  976: # checkall buttons
  977:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  978:     $gradeTable.='<input type="button" '."\n".
  979:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  980:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  981:     $gradeTable.=&check_buttons();
  982:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  983:     $gradeTable.= &Apache::loncommon::start_data_table().
  984: 	&Apache::loncommon::start_data_table_header_row();
  985:     my $loop = 0;
  986:     while ($loop < 2) {
  987: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  988: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  989: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  990: 	    foreach my $part (sort(@$partlist)) {
  991: 		my $display_part=
  992: 		    &get_display_part((split(/_/,$part))[0],$symb);
  993: 		$gradeTable.=
  994: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  995: 	    }
  996: 	} elsif ($submitonly eq 'queued') {
  997: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  998: 	}
  999: 	$loop++;
 1000: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1001:     }
 1002:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1003: 
 1004:     my $ctr = 0;
 1005:     foreach my $student (sort 
 1006: 			 {
 1007: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1008: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1009: 			     }
 1010: 			     return $a cmp $b;
 1011: 			 }
 1012: 			 (keys(%$fullname))) {
 1013: 	my ($uname,$udom) = split(/:/,$student);
 1014: 
 1015: 	my %status = ();
 1016: 
 1017: 	if ($submitonly eq 'queued') {
 1018: 	    my %queue_status = 
 1019: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1020: 							$udom,$uname);
 1021: 	    next if (!defined($queue_status{'gradingqueue'}));
 1022: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1023: 	}
 1024: 
 1025: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1026: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1027: 	    my $submitted = 0;
 1028: 	    my $graded = 0;
 1029: 	    my $incorrect = 0;
 1030: 	    foreach (keys(%status)) {
 1031: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1032: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1033: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1034: 		
 1035: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1036: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1037: 		    $submitted = 0;
 1038: 		    my ($part)=split(/\./,$partid);
 1039: 		    $gradeTable.='<input type="hidden" name="'.
 1040: 			$student.':'.$part.':submitted_by" value="'.
 1041: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1042: 		}
 1043: 	    }
 1044: 	    
 1045: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1046: 				     $submitonly eq 'incorrect' ||
 1047: 				     $submitonly eq 'graded'));
 1048: 	    next if (!$graded && ($submitonly eq 'graded'));
 1049: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1050: 	}
 1051: 
 1052: 	$ctr++;
 1053: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1054:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1055: 	if ( $perm{'vgr'} eq 'F' ) {
 1056: 	    if ($ctr%2 ==1) {
 1057: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1058: 	    }
 1059: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1060:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1061:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1062: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1063: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1064: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1065: 
 1066: 	    if ($submitonly ne 'all') {
 1067: 		foreach (sort(keys(%status))) {
 1068: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1069: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1070: 		}
 1071: 	    }
 1072: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1073: 	    if ($ctr%2 ==0) {
 1074: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1075: 	    }
 1076: 	}
 1077:     }
 1078:     if ($ctr%2 ==1) {
 1079: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1080: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1081: 		foreach (@$partlist) {
 1082: 		    $gradeTable.='<td>&nbsp;</td>';
 1083: 		}
 1084: 	    } elsif ($submitonly eq 'queued') {
 1085: 		$gradeTable.='<td>&nbsp;</td>';
 1086: 	    }
 1087: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1088:     }
 1089: 
 1090:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1091:         '<input type="button" '.
 1092:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1093:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1094:     if ($ctr == 0) {
 1095: 	my $num_students=(scalar(keys(%$fullname)));
 1096: 	if ($num_students eq 0) {
 1097: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1098: 	} else {
 1099: 	    my $submissions='submissions';
 1100: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1101: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1102: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1103: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1104: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1105: 		    $num_students).
 1106: 		'</span><br />';
 1107: 	}
 1108:     } elsif ($ctr == 1) {
 1109: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1110:     }
 1111:     $request->print($gradeTable);
 1112:     return '';
 1113: }
 1114: 
 1115: #---- Called from the listStudents routine
 1116: 
 1117: sub check_script {
 1118:     my ($form, $type)=@_;
 1119:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1120:     function checkall() {
 1121:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1122:             ele = document.forms.'.$form.'.elements[i];
 1123:             if (ele.name == "'.$type.'") {
 1124:             document.forms.'.$form.'.elements[i].checked=true;
 1125:                                        }
 1126:         }
 1127:     }
 1128: 
 1129:     function checksec() {
 1130:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1131:             ele = document.forms.'.$form.'.elements[i];
 1132:            string = document.forms.'.$form.'.chksec.value;
 1133:            if
 1134:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1135:               document.forms.'.$form.'.elements[i].checked=true;
 1136:             }
 1137:         }
 1138:     }
 1139: 
 1140: 
 1141:     function uncheckall() {
 1142:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1143:             ele = document.forms.'.$form.'.elements[i];
 1144:             if (ele.name == "'.$type.'") {
 1145:             document.forms.'.$form.'.elements[i].checked=false;
 1146:                                        }
 1147:         }
 1148:     }
 1149: 
 1150: '."\n");
 1151:     return $chkallscript;
 1152: }
 1153: 
 1154: sub check_buttons {
 1155:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1156:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1157:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1158:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1159:     return $buttons;
 1160: }
 1161: 
 1162: #     Displays the submissions for one student or a group of students
 1163: sub processGroup {
 1164:     my ($request,$symb)  = @_;
 1165:     my $ctr        = 0;
 1166:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1167:     my $total      = scalar(@stuchecked)-1;
 1168: 
 1169:     foreach my $student (@stuchecked) {
 1170: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1171: 	$env{'form.student'}        = $uname;
 1172: 	$env{'form.userdom'}        = $udom;
 1173: 	$env{'form.fullname'}       = $fullname;
 1174: 	&submission($request,$ctr,$total,$symb);
 1175: 	$ctr++;
 1176:     }
 1177:     return '';
 1178: }
 1179: 
 1180: #------------------------------------------------------------------------------------
 1181: #
 1182: #-------------------------- Next few routines handles grading by student, essentially
 1183: #                           handles essay response type problem/part
 1184: #
 1185: #--- Javascript to handle the submission page functionality ---
 1186: sub sub_page_js {
 1187:     my $request = shift;
 1188:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1189:     &js_escape(\$alertmsg);
 1190:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1191:     function updateRadio(formname,id,weight) {
 1192: 	var gradeBox = formname["GD_BOX"+id];
 1193: 	var radioButton = formname["RADVAL"+id];
 1194: 	var oldpts = formname["oldpts"+id].value;
 1195: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1196: 	gradeBox.value = pts;
 1197: 	var resetbox = false;
 1198: 	if (isNaN(pts) || pts < 0) {
 1199: 	    alert("$alertmsg"+pts);
 1200: 	    for (var i=0; i<radioButton.length; i++) {
 1201: 		if (radioButton[i].checked) {
 1202: 		    gradeBox.value = i;
 1203: 		    resetbox = true;
 1204: 		}
 1205: 	    }
 1206: 	    if (!resetbox) {
 1207: 		formtextbox.value = "";
 1208: 	    }
 1209: 	    return;
 1210: 	}
 1211: 
 1212: 	if (pts > weight) {
 1213: 	    var resp = confirm("You entered a value ("+pts+
 1214: 			       ") greater than the weight for the part. Accept?");
 1215: 	    if (resp == false) {
 1216: 		gradeBox.value = oldpts;
 1217: 		return;
 1218: 	    }
 1219: 	}
 1220: 
 1221: 	for (var i=0; i<radioButton.length; i++) {
 1222: 	    radioButton[i].checked=false;
 1223: 	    if (pts == i && pts != "") {
 1224: 		radioButton[i].checked=true;
 1225: 	    }
 1226: 	}
 1227: 	updateSelect(formname,id);
 1228: 	formname["stores"+id].value = "0";
 1229:     }
 1230: 
 1231:     function writeBox(formname,id,pts) {
 1232: 	var gradeBox = formname["GD_BOX"+id];
 1233: 	if (checkSolved(formname,id) == 'update') {
 1234: 	    gradeBox.value = pts;
 1235: 	} else {
 1236: 	    var oldpts = formname["oldpts"+id].value;
 1237: 	    gradeBox.value = oldpts;
 1238: 	    var radioButton = formname["RADVAL"+id];
 1239: 	    for (var i=0; i<radioButton.length; i++) {
 1240: 		radioButton[i].checked=false;
 1241: 		if (i == oldpts) {
 1242: 		    radioButton[i].checked=true;
 1243: 		}
 1244: 	    }
 1245: 	}
 1246: 	formname["stores"+id].value = "0";
 1247: 	updateSelect(formname,id);
 1248: 	return;
 1249:     }
 1250: 
 1251:     function clearRadBox(formname,id) {
 1252: 	if (checkSolved(formname,id) == 'noupdate') {
 1253: 	    updateSelect(formname,id);
 1254: 	    return;
 1255: 	}
 1256: 	gradeSelect = formname["GD_SEL"+id];
 1257: 	for (var i=0; i<gradeSelect.length; i++) {
 1258: 	    if (gradeSelect[i].selected) {
 1259: 		var selectx=i;
 1260: 	    }
 1261: 	}
 1262: 	var stores = formname["stores"+id];
 1263: 	if (selectx == stores.value) { return };
 1264: 	var gradeBox = formname["GD_BOX"+id];
 1265: 	gradeBox.value = "";
 1266: 	var radioButton = formname["RADVAL"+id];
 1267: 	for (var i=0; i<radioButton.length; i++) {
 1268: 	    radioButton[i].checked=false;
 1269: 	}
 1270: 	stores.value = selectx;
 1271:     }
 1272: 
 1273:     function checkSolved(formname,id) {
 1274: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1275: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1276: 	    if (!reply) {return "noupdate";}
 1277: 	    formname.overRideScore.value = 'yes';
 1278: 	}
 1279: 	return "update";
 1280:     }
 1281: 
 1282:     function updateSelect(formname,id) {
 1283: 	formname["GD_SEL"+id][0].selected = true;
 1284: 	return;
 1285:     }
 1286: 
 1287: //=========== Check that a point is assigned for all the parts  ============
 1288:     function checksubmit(formname,val,total,parttot) {
 1289: 	formname.gradeOpt.value = val;
 1290: 	if (val == "Save & Next") {
 1291: 	    for (i=0;i<=total;i++) {
 1292: 		for (j=0;j<parttot;j++) {
 1293: 		    var partid = formname["partid"+i+"_"+j].value;
 1294: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1295: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1296: 			if (points == "") {
 1297: 			    var name = formname["name"+i].value;
 1298: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1299: 			    var resp = confirm("You did not assign a score for "+studentID+
 1300: 					       ", part "+partid+". Continue?");
 1301: 			    if (resp == false) {
 1302: 				formname["GD_BOX"+i+"_"+partid].focus();
 1303: 				return false;
 1304: 			    }
 1305: 			}
 1306: 		    }
 1307: 		}
 1308: 	    }
 1309: 	}
 1310: 	formname.submit();
 1311:     }
 1312: 
 1313: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1314:     function checkSubmitPage(formname,total) {
 1315: 	noscore = new Array(100);
 1316: 	var ptr = 0;
 1317: 	for (i=1;i<total;i++) {
 1318: 	    var partid = formname["q_"+i].value;
 1319: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1320: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1321: 		var status = formname["solved"+i+"_"+partid].value;
 1322: 		if (points == "" && status != "correct_by_student") {
 1323: 		    noscore[ptr] = i;
 1324: 		    ptr++;
 1325: 		}
 1326: 	    }
 1327: 	}
 1328: 	if (ptr != 0) {
 1329: 	    var sense = ptr == 1 ? ": " : "s: ";
 1330: 	    var prolist = "";
 1331: 	    if (ptr == 1) {
 1332: 		prolist = noscore[0];
 1333: 	    } else {
 1334: 		var i = 0;
 1335: 		while (i < ptr-1) {
 1336: 		    prolist += noscore[i]+", ";
 1337: 		    i++;
 1338: 		}
 1339: 		prolist += "and "+noscore[i];
 1340: 	    }
 1341: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1342: 	    if (resp == false) {
 1343: 		return false;
 1344: 	    }
 1345: 	}
 1346: 
 1347: 	formname.submit();
 1348:     }
 1349: SUBJAVASCRIPT
 1350: }
 1351: 
 1352: #--- javascript for essay type problem --
 1353: sub sub_page_kw_js {
 1354:     my $request = shift;
 1355:     my $iconpath = $request->dir_config('lonIconsURL');
 1356:     &commonJSfunctions($request);
 1357: 
 1358:     my $inner_js_msg_central= (<<INNERJS);
 1359: <script type="text/javascript">
 1360:     function checkInput() {
 1361:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1362:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1363:       var usrctr = document.msgcenter.usrctr.value;
 1364:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1365:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1366: 
 1367:       var msgchk = "";
 1368:       if (document.msgcenter.subchk.checked) {
 1369:          msgchk = "msgsub,";
 1370:       }
 1371:       var includemsg = 0;
 1372:       for (var i=1; i<=nmsg; i++) {
 1373:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1374:           var frmmsg = document.msgcenter["msg"+i];
 1375:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1376:           var showflg = opener.document.SCORE["shownOnce"+i];
 1377:           showflg.value = "1";
 1378:           var chkbox = document.msgcenter["msgn"+i];
 1379:           if (chkbox.checked) {
 1380:              msgchk += "savemsg"+i+",";
 1381:              includemsg = 1;
 1382:           }
 1383:       }
 1384:       if (document.msgcenter.newmsgchk.checked) {
 1385:          msgchk += "newmsg"+usrctr;
 1386:          includemsg = 1;
 1387:       }
 1388:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1389:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1390:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1391:       includemsg.value = msgchk;
 1392: 
 1393:       self.close()
 1394: 
 1395:     }
 1396: </script>
 1397: INNERJS
 1398: 
 1399:     my $inner_js_highlight_central= (<<INNERJS);
 1400: <script type="text/javascript">
 1401:     function updateChoice(flag) {
 1402:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1403:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1404:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1405:       opener.document.SCORE.refresh.value = "on";
 1406:       if (opener.document.SCORE.keywords.value!=""){
 1407:          opener.document.SCORE.submit();
 1408:       }
 1409:       self.close()
 1410:     }
 1411: </script>
 1412: INNERJS
 1413: 
 1414:     my $start_page_msg_central = 
 1415:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1416: 				       {'js_ready'  => 1,
 1417: 					'only_body' => 1,
 1418: 					'bgcolor'   =>'#FFFFFF',});
 1419:     my $end_page_msg_central = 
 1420: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1421: 
 1422: 
 1423:     my $start_page_highlight_central = 
 1424:         &Apache::loncommon::start_page('Highlight Central',
 1425: 				       $inner_js_highlight_central,
 1426: 				       {'js_ready'  => 1,
 1427: 					'only_body' => 1,
 1428: 					'bgcolor'   =>'#FFFFFF',});
 1429:     my $end_page_highlight_central = 
 1430: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1431: 
 1432:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1433:     $docopen=~s/^document\.//;
 1434:     my %js_lt = &Apache::lonlocal::texthash(
 1435:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1436:                 plse => 'Please select a word or group of words from document and then click this link.',
 1437:                 adds => 'Add selection to keyword list? Edit if desired.',
 1438:                 col1 => 'red',
 1439:                 col2 => 'green',
 1440:                 col3 => 'blue',
 1441:                 siz1 => 'normal',
 1442:                 siz2 => '+1',
 1443:                 siz3 => '+2',
 1444:                 sty1 => 'normal',
 1445:                 sty2 => 'italic',
 1446:                 sty3 => 'bold',
 1447:              );
 1448:     my %html_js_lt = &Apache::lonlocal::texthash(
 1449:                 comp => 'Compose Message for: ',
 1450:                 incl => 'Include',
 1451:                 type => 'Type',
 1452:                 subj => 'Subject',
 1453:                 mesa => 'Message',
 1454:                 new  => 'New',
 1455:                 save => 'Save',
 1456:                 canc => 'Cancel',
 1457:                 kehi => 'Keyword Highlight Options',
 1458:                 txtc => 'Text Color',
 1459:                 font => 'Font Size',
 1460:                 fnst => 'Font Style',
 1461:              );
 1462:     &js_escape(\%js_lt);
 1463:     &html_escape(\%html_js_lt);
 1464:     &js_escape(\%html_js_lt);
 1465:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1466: 
 1467: //===================== Show list of keywords ====================
 1468:   function keywords(formname) {
 1469:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1470:     if (nret==null) return;
 1471:     formname.keywords.value = nret;
 1472: 
 1473:     if (formname.keywords.value != "") {
 1474: 	formname.refresh.value = "on";
 1475: 	formname.submit();
 1476:     }
 1477:     return;
 1478:   }
 1479: 
 1480: //===================== Script to view submitted by ==================
 1481:   function viewSubmitter(submitter) {
 1482:     document.SCORE.refresh.value = "on";
 1483:     document.SCORE.NCT.value = "1";
 1484:     document.SCORE.unamedom0.value = submitter;
 1485:     document.SCORE.submit();
 1486:     return;
 1487:   }
 1488: 
 1489: //===================== Script to add keyword(s) ==================
 1490:   function getSel() {
 1491:     if (document.getSelection) txt = document.getSelection();
 1492:     else if (document.selection) txt = document.selection.createRange().text;
 1493:     else return;
 1494:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1495:     if (cleantxt=="") {
 1496: 	alert("$js_lt{'plse'}");
 1497: 	return;
 1498:     }
 1499:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1500:     if (nret==null) return;
 1501:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1502:     if (document.SCORE.keywords.value != "") {
 1503: 	document.SCORE.refresh.value = "on";
 1504: 	document.SCORE.submit();
 1505:     }
 1506:     return;
 1507:   }
 1508: 
 1509: //====================== Script for composing message ==============
 1510:    // preload images
 1511:    img1 = new Image();
 1512:    img1.src = "$iconpath/mailbkgrd.gif";
 1513:    img2 = new Image();
 1514:    img2.src = "$iconpath/mailto.gif";
 1515: 
 1516:   function msgCenter(msgform,usrctr,fullname) {
 1517:     var Nmsg  = msgform.savemsgN.value;
 1518:     savedMsgHeader(Nmsg,usrctr,fullname);
 1519:     var subject = msgform.msgsub.value;
 1520:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1521:     re = /msgsub/;
 1522:     var shwsel = "";
 1523:     if (re.test(msgchk)) { shwsel = "checked" }
 1524:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1525:     displaySubject(checkEntities(subject),shwsel);
 1526:     for (var i=1; i<=Nmsg; i++) {
 1527: 	var testmsg = "savemsg"+i+",";
 1528: 	re = new RegExp(testmsg,"g");
 1529: 	shwsel = "";
 1530: 	if (re.test(msgchk)) { shwsel = "checked" }
 1531: 	var message = document.SCORE["savemsg"+i].value;
 1532: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1533: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1534: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1535:     }
 1536:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1537:     shwsel = "";
 1538:     re = /newmsg/;
 1539:     if (re.test(msgchk)) { shwsel = "checked" }
 1540:     newMsg(newmsg,shwsel);
 1541:     msgTail(); 
 1542:     return;
 1543:   }
 1544: 
 1545:   function checkEntities(strx) {
 1546:     if (strx.length == 0) return strx;
 1547:     var orgStr = ["&", "<", ">", '"']; 
 1548:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1549:     var counter = 0;
 1550:     while (counter < 4) {
 1551: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1552: 	counter++;
 1553:     }
 1554:     return strx;
 1555:   }
 1556: 
 1557:   function strReplace(strx, orgStr, newStr) {
 1558:     return strx.split(orgStr).join(newStr);
 1559:   }
 1560: 
 1561:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1562:     var height = 70*Nmsg+250;
 1563:     if (height > 600) {
 1564: 	height = 600;
 1565:     }
 1566:     var xpos = (screen.width-600)/2;
 1567:     xpos = (xpos < 0) ? '0' : xpos;
 1568:     var ypos = (screen.height-height)/2-30;
 1569:     ypos = (ypos < 0) ? '0' : ypos;
 1570: 
 1571:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1572:     pWin.focus();
 1573:     pDoc = pWin.document;
 1574:     pDoc.$docopen;
 1575:     pDoc.write('$start_page_msg_central');
 1576: 
 1577:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1578:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1579:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1580: 
 1581:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1582:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1583: }
 1584:     function displaySubject(msg,shwsel) {
 1585:     pDoc = pWin.document;
 1586:     pDoc.write("<tr>");
 1587:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1588:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1589:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1590: }
 1591: 
 1592:   function displaySavedMsg(ctr,msg,shwsel) {
 1593:     pDoc = pWin.document;
 1594:     pDoc.write("<tr>");
 1595:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1596:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1597:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1598: }
 1599: 
 1600:   function newMsg(newmsg,shwsel) {
 1601:     pDoc = pWin.document;
 1602:     pDoc.write("<tr>");
 1603:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1604:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1605:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1606: }
 1607: 
 1608:   function msgTail() {
 1609:     pDoc = pWin.document;
 1610:     //pDoc.write("<\\/table>");
 1611:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1612:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1613:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1614:     pDoc.write("<\\/form>");
 1615:     pDoc.write('$end_page_msg_central');
 1616:     pDoc.close();
 1617: }
 1618: 
 1619: //====================== Script for keyword highlight options ==============
 1620:   function kwhighlight() {
 1621:     var kwclr    = document.SCORE.kwclr.value;
 1622:     var kwsize   = document.SCORE.kwsize.value;
 1623:     var kwstyle  = document.SCORE.kwstyle.value;
 1624:     var redsel = "";
 1625:     var grnsel = "";
 1626:     var blusel = "";
 1627:     var txtcol1 = "$js_lt{'col1'}";
 1628:     var txtcol2 = "$js_lt{'col2'}";
 1629:     var txtcol3 = "$js_lt{'col3'}";
 1630:     var txtsiz1 = "$js_lt{'siz1'}";
 1631:     var txtsiz2 = "$js_lt{'siz2'}";
 1632:     var txtsiz3 = "$js_lt{'siz3'}";
 1633:     var txtsty1 = "$js_lt{'sty1'}";
 1634:     var txtsty2 = "$js_lt{'sty2'}";
 1635:     var txtsty3 = "$js_lt{'sty3'}";
 1636:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1637:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1638:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1639:     var sznsel = "";
 1640:     var sz1sel = "";
 1641:     var sz2sel = "";
 1642:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1643:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1644:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1645:     var synsel = "";
 1646:     var syisel = "";
 1647:     var sybsel = "";
 1648:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1649:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1650:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1651:     highlightCentral();
 1652:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1653:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1654:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1655:     highlightend();
 1656:     return;
 1657:   }
 1658: 
 1659:   function highlightCentral() {
 1660: //    if (window.hwdWin) window.hwdWin.close();
 1661:     var xpos = (screen.width-400)/2;
 1662:     xpos = (xpos < 0) ? '0' : xpos;
 1663:     var ypos = (screen.height-330)/2-30;
 1664:     ypos = (ypos < 0) ? '0' : ypos;
 1665: 
 1666:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1667:     hwdWin.focus();
 1668:     var hDoc = hwdWin.document;
 1669:     hDoc.$docopen;
 1670:     hDoc.write('$start_page_highlight_central');
 1671:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1672:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1673: 
 1674:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1675:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1676:   }
 1677: 
 1678:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1679:     var hDoc = hwdWin.document;
 1680:     hDoc.write("<tr>");
 1681:     hDoc.write("<td align=\\"left\\">");
 1682:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1683:     hDoc.write("<td align=\\"left\\">");
 1684:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1685:     hDoc.write("<td align=\\"left\\">");
 1686:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1687:     hDoc.write("<\\/tr>");
 1688:   }
 1689: 
 1690:   function highlightend() { 
 1691:     var hDoc = hwdWin.document;
 1692:     hDoc.write("<\\/table><br \\/>");
 1693:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1694:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1695:     hDoc.write("<\\/form>");
 1696:     hDoc.write('$end_page_highlight_central');
 1697:     hDoc.close();
 1698:   }
 1699: 
 1700: SUBJAVASCRIPT
 1701: }
 1702: 
 1703: sub get_increment {
 1704:     my $increment = $env{'form.increment'};
 1705:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1706:         $increment != .1) {
 1707:         $increment = 1;
 1708:     }
 1709:     return $increment;
 1710: }
 1711: 
 1712: sub gradeBox_start {
 1713:     return (
 1714:         &Apache::loncommon::start_data_table()
 1715:        .&Apache::loncommon::start_data_table_header_row()
 1716:        .'<th>'.&mt('Part').'</th>'
 1717:        .'<th>'.&mt('Points').'</th>'
 1718:        .'<th>&nbsp;</th>'
 1719:        .'<th>'.&mt('Assign Grade').'</th>'
 1720:        .'<th>'.&mt('Weight').'</th>'
 1721:        .'<th>'.&mt('Grade Status').'</th>'
 1722:        .&Apache::loncommon::end_data_table_header_row()
 1723:     );
 1724: }
 1725: 
 1726: sub gradeBox_end {
 1727:     return (
 1728:         &Apache::loncommon::end_data_table()
 1729:     );
 1730: }
 1731: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1732: sub gradeBox {
 1733:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1734:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1735: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1736:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1737:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1738:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1739:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1740:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1741: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1742:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1743:     my $display_part= &get_display_part($partid,$symb);
 1744:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1745: 				       [$partid]);
 1746:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1747:     if ($last_resets{$partid}) {
 1748:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1749:     }
 1750:     my $result=&Apache::loncommon::start_data_table_row();
 1751:     my $ctr = 0;
 1752:     my $thisweight = 0;
 1753:     my $increment = &get_increment();
 1754: 
 1755:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1756:     while ($thisweight<=$wgt) {
 1757: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1758:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1759: 	    $thisweight.')" value="'.$thisweight.'" '.
 1760: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1761: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1762:         $thisweight += $increment;
 1763: 	$ctr++;
 1764:     }
 1765:     $radio.='</tr></table>';
 1766: 
 1767:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1768: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1769: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1770: 	$wgt.')" /></td>'."\n";
 1771:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1772: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1773: 	' </td>'."\n";
 1774:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1775: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1776:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1777: 	$line.='<option></option>'.
 1778: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1779:     } else {
 1780: 	$line.='<option selected="selected"></option>'.
 1781: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1782:     }
 1783:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1784: 
 1785: 
 1786:     $result .= 
 1787: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1788:     $result.=&Apache::loncommon::end_data_table_row();
 1789:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1790:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1791: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1792: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1793: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1794:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1795:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1796:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1797:         $aggtries.'" />'."\n";
 1798:     my $res_error;
 1799:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1800:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1801:     if ($res_error) {
 1802:         return &navmap_errormsg();
 1803:     }
 1804:     return $result;
 1805: }
 1806: 
 1807: sub handback_box {
 1808:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1809:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1810:     my (@respids);
 1811:     my @part_response_id = &flatten_responseType($responseType);
 1812:     foreach my $part_response_id (@part_response_id) {
 1813:     	my ($part,$resp) = @{ $part_response_id };
 1814:         if ($part eq $partid) {
 1815:             push(@respids,$resp);
 1816:         }
 1817:     }
 1818:     my $result;
 1819:     foreach my $respid (@respids) {
 1820: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1821: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1822: 	next if (!@$files);
 1823: 	my $file_counter = 0;
 1824: 	foreach my $file (@$files) {
 1825: 	    if ($file =~ /\/portfolio\//) {
 1826:                 $file_counter++;
 1827:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1828:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1829:     	        $file_disp = "$name.$ext";
 1830:     	        $file = $file_path.$file_disp;
 1831:     	        $result.=&mt('Return commented version of [_1] to student.',
 1832:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1833:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1834:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1835: 	    }
 1836: 	}
 1837:         if ($file_counter) {
 1838:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1839:                        '<span class="LC_info">'.
 1840:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1841:         }
 1842:     }
 1843:     return $result;    
 1844: }
 1845: 
 1846: sub show_problem {
 1847:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1848:     my $rendered;
 1849:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1850:     &Apache::lonxml::remember_problem_counter();
 1851:     if ($mode eq 'both' or $mode eq 'text') {
 1852: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1853: 						       $env{'request.course.id'},
 1854: 						       undef,\%form);
 1855:     }
 1856:     if ($removeform) {
 1857: 	$rendered=~s|<form(.*?)>||g;
 1858: 	$rendered=~s|</form>||g;
 1859: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1860:     }
 1861:     my $companswer;
 1862:     if ($mode eq 'both' or $mode eq 'answer') {
 1863: 	&Apache::lonxml::restore_problem_counter();
 1864: 	$companswer=
 1865: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1866: 						    $env{'request.course.id'},
 1867: 						    %form);
 1868:     }
 1869:     if ($removeform) {
 1870: 	$companswer=~s|<form(.*?)>||g;
 1871: 	$companswer=~s|</form>||g;
 1872: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1873:     }
 1874:     my $renderheading = &mt('View of the problem');
 1875:     my $answerheading = &mt('Correct answer');
 1876:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1877:         my $stu_fullname = $env{'form.fullname'};
 1878:         if ($stu_fullname eq '') {
 1879:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1880:         }
 1881:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1882:         if ($forwhom ne '') {
 1883:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1884:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1885:         }
 1886:     }
 1887:     $rendered=
 1888:         '<div class="LC_Box">'
 1889:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1890:        .$rendered
 1891:        .'</div>';
 1892:     $companswer=
 1893:         '<div class="LC_Box">'
 1894:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1895:        .$companswer
 1896:        .'</div>';
 1897:     my $result;
 1898:     if ($mode eq 'both') {
 1899:         $result=$rendered.$companswer;
 1900:     } elsif ($mode eq 'text') {
 1901:         $result=$rendered;
 1902:     } elsif ($mode eq 'answer') {
 1903:         $result=$companswer;
 1904:     }
 1905:     return $result;
 1906: }
 1907: 
 1908: sub files_exist {
 1909:     my ($r, $symb) = @_;
 1910:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1911: 
 1912:     foreach my $student (@students) {
 1913:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1914:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1915: 					      $udom,$uname);
 1916:         my ($string,$timestamp)= &get_last_submission(\%record);
 1917:         foreach my $submission (@$string) {
 1918:             my ($partid,$respid) =
 1919: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1920:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1921: 					   \%record);
 1922:             return 1 if (@$files);
 1923:         }
 1924:     }
 1925:     return 0;
 1926: }
 1927: 
 1928: sub download_all_link {
 1929:     my ($r,$symb) = @_;
 1930:     unless (&files_exist($r, $symb)) {
 1931:        $r->print(&mt('There are currently no submitted documents.'));
 1932:        return;
 1933:     }
 1934: 
 1935:     my $all_students = 
 1936: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1937: 
 1938:     my $parts =
 1939: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1940: 
 1941:     my $identifier = &Apache::loncommon::get_cgi_id();
 1942:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1943:                              'cgi.'.$identifier.'.symb' => $symb,
 1944:                              'cgi.'.$identifier.'.parts' => $parts,});
 1945:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1946: 	      &mt('Download All Submitted Documents').'</a>');
 1947:     return;
 1948: }
 1949: 
 1950: sub submit_download_link {
 1951:     my ($request,$symb) = @_;
 1952:     if (!$symb) { return ''; }
 1953: #FIXME: Figure out which type of problem this is and provide appropriate download
 1954:     &download_all_link($request,$symb);
 1955: }
 1956: 
 1957: sub build_section_inputs {
 1958:     my $section_inputs;
 1959:     if ($env{'form.section'} eq '') {
 1960:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1961:     } else {
 1962:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1963:         foreach my $section (@sections) {
 1964:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1965:         }
 1966:     }
 1967:     return $section_inputs;
 1968: }
 1969: 
 1970: # --------------------------- show submissions of a student, option to grade 
 1971: sub submission {
 1972:     my ($request,$counter,$total,$symb) = @_;
 1973:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1974:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1975:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1976:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1977: 
 1978:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1979:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1980: 
 1981:     if (!&canview($usec)) {
 1982:         $request->print(
 1983:             '<span class="LC_warning">'.
 1984:             &mt('Unable to view requested student.').
 1985:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1986:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1987:             '</span>');
 1988: 	return;
 1989:     }
 1990: 
 1991:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1992:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1993:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1994:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1995:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1996: 	'" src="'.$request->dir_config('lonIconsURL').
 1997: 	'/check.gif" height="16" border="0" />';
 1998: 
 1999:     # header info
 2000:     if ($counter == 0) {
 2001: 	&sub_page_js($request);
 2002: 	&sub_page_kw_js($request);
 2003: 
 2004: 	# option to display problem, only once else it cause problems 
 2005:         # with the form later since the problem has a form.
 2006: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2007: 	    my $mode;
 2008: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2009: 		$mode='both';
 2010: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2011: 		$mode='text';
 2012: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2013: 		$mode='answer';
 2014: 	    }
 2015: 	    &Apache::lonxml::clear_problem_counter();
 2016: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2017: 	}
 2018: 
 2019: 	# kwclr is the only variable that is guaranteed not to be blank 
 2020:         # if this subroutine has been called once.
 2021: 	my %keyhash = ();
 2022: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2023:         if (1) {
 2024: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2025: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2026: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2027: 
 2028: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2029: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2030: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2031: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2032: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2033: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2034: 		$keyhash{$symb.'_subject'} : $probtitle;
 2035: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2036: 	}
 2037: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2038: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2039: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2040: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2041: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2042: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2043: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2044: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2045: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2046: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2047: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2048: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2049: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2050: 			&build_section_inputs().
 2051: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2052: 			'<input type="hidden" name="NCT"'.
 2053: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2054: #	if ($env{'form.handgrade'} eq 'yes') {
 2055:         if (1) {
 2056: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2057: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2058: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2059: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2060: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2061: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2062: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2063: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2064: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2065: 	    }
 2066: 	}
 2067: 	
 2068: 	my ($cts,$prnmsg) = (1,'');
 2069: 	while ($cts <= $env{'form.savemsgN'}) {
 2070: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2071: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2072: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2073: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2074: 		'" />'."\n".
 2075: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2076: 	    $cts++;
 2077: 	}
 2078: 	$request->print($prnmsg);
 2079: 
 2080: #	if ($env{'form.handgrade'} eq 'yes') {
 2081:         if (1) {
 2082: 
 2083:             my %lt = &Apache::lonlocal::texthash(
 2084:                           keyh => 'Keyword Highlighting for Essays',
 2085:                           keyw => 'Keyword Options',
 2086:                           list => 'List',
 2087:                           past => 'Paste Selection to List',
 2088:                           high => 'Highlight Attribute',
 2089:                      );    
 2090: #
 2091: # Print out the keyword options line
 2092: #
 2093: 	    $request->print(
 2094:                 '<div class="LC_columnSection">'
 2095:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2096:                .&Apache::lonhtmlcommon::funclist_from_array(
 2097:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2098:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2099:  class="page">'.$lt{'past'}.'</a>',
 2100:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2101:                     {legend => $lt{'keyw'}})
 2102:                .'</fieldset></div>'
 2103:             );
 2104: 
 2105: #
 2106: # Load the other essays for similarity check
 2107: #
 2108:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2109: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2110: 	    $apath=&escape($apath);
 2111: 	    $apath=~s/\W/\_/gs;
 2112:             &init_old_essays($symb,$apath,$adom,$aname);
 2113:         }
 2114:     }
 2115: 
 2116: # This is where output for one specific student would start
 2117:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2118:     $request->print(
 2119:         "\n\n"
 2120:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2121:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2122:        ."\n"
 2123:     );
 2124: 
 2125:     # Show additional functions if allowed
 2126:     if ($perm{'vgr'}) {
 2127:         $request->print(
 2128:             &Apache::loncommon::track_student_link(
 2129:                 'View recent activity',
 2130:                 $uname,$udom,'check')
 2131:            .' '
 2132:         );
 2133:     }
 2134:     if ($perm{'opa'}) {
 2135:         $request->print(
 2136:             &Apache::loncommon::pprmlink(
 2137:                 &mt('Set/Change parameters'),
 2138:                 $uname,$udom,$symb,'check'));
 2139:     }
 2140: 
 2141:     # Show Problem
 2142:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2143: 	my $mode;
 2144: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2145: 	    $mode='both';
 2146: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2147: 	    $mode='text';
 2148: 	} elsif ($env{'form.vAns'} eq 'all') {
 2149: 	    $mode='answer';
 2150: 	}
 2151: 	&Apache::lonxml::clear_problem_counter();
 2152: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2153:     }
 2154: 
 2155:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2156:     my $res_error;
 2157:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2158:     if ($res_error) {
 2159:         $request->print(&navmap_errormsg());
 2160:         return;
 2161:     }
 2162: 
 2163:     # Display student info
 2164:     $request->print(($counter == 0 ? '' : '<br />'));
 2165: 
 2166:     my $result='<div class="LC_Box">'
 2167:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2168:     $result.='<input type="hidden" name="name'.$counter.
 2169:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2170: #    if ($env{'form.handgrade'} eq 'no') {
 2171:     if (1) {
 2172:         $result.='<p class="LC_info">'
 2173:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2174:                 ."</p>\n";
 2175:     }
 2176: 
 2177:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2178:     my $fullname;
 2179:     my $col_fullnames = [];
 2180: #    if ($env{'form.handgrade'} eq 'yes') {
 2181:     if (1) {
 2182: 	(my $sub_result,$fullname,$col_fullnames)=
 2183: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2184: 				 $counter);
 2185: 	$result.=$sub_result;
 2186:     }
 2187:     $request->print($result."\n");
 2188:     
 2189:     # print student answer/submission
 2190:     # Options are (1) Handgraded submission only
 2191:     #             (2) Last submission, includes submission that is not handgraded 
 2192:     #                  (for multi-response type part)
 2193:     #             (3) Last submission plus the parts info
 2194:     #             (4) The whole record for this student
 2195:     
 2196:     my ($string,$timestamp)= &get_last_submission(\%record);
 2197: 	
 2198:     my $lastsubonly;
 2199: 
 2200:     if ($$timestamp eq '') {
 2201:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2202:     } else {
 2203:         $lastsubonly =
 2204:             '<div class="LC_grade_submissions_body">'
 2205:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2206: 
 2207: 	my %seenparts;
 2208: 	my @part_response_id = &flatten_responseType($responseType);
 2209: 	foreach my $part (@part_response_id) {
 2210: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2211: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2212: 
 2213: 	    my ($partid,$respid) = @{ $part };
 2214: 	    my $display_part=&get_display_part($partid,$symb);
 2215: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2216: 		if (exists($seenparts{$partid})) { next; }
 2217: 		$seenparts{$partid}=1;
 2218:                 $request->print(
 2219:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2220:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2221:                                '<a href="javascript:viewSubmitter(\''.
 2222:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2223:                                '\');" target="_self">'.
 2224:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2225:                     '<br />');
 2226: 		next;
 2227: 		}
 2228: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2229: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2230:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2231:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2232:                     ' <span class="LC_internal_info">'.
 2233:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2234:                     '</span>&nbsp; &nbsp;'.
 2235: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2236: 		next;
 2237: 	    }
 2238: 	    foreach my $submission (@$string) {
 2239: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2240: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2241: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2242: 		# Similarity check
 2243:                 my $similar='';
 2244:                 my ($type,$trial,$rndseed);
 2245:                 if ($hide eq 'rand') {
 2246:                     $type = 'randomizetry';
 2247:                     $trial = $record{"resource.$partid.tries"};
 2248:                     $rndseed = $record{"resource.$partid.rndseed"};
 2249:                 }
 2250: 	        if ($env{'form.checkPlag'}) {
 2251:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2252: 		        &most_similar($uname,$udom,$symb,$subval);
 2253: 		    if ($osim) {
 2254: 			$osim=int($osim*100.0);
 2255: 			my %old_course_desc = 
 2256: 			    &Apache::lonnet::coursedescription($ocrsid,
 2257: 							{'one_time' => 1});
 2258: 
 2259:                         if ($hide eq 'anon') {
 2260:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2261:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2262:                         } else {
 2263: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2264: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2265: 				    $osim,
 2266: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2267: 				        $old_course_desc{'description'},
 2268: 				        $old_course_desc{'num'},
 2269: 				        $old_course_desc{'domain'}).
 2270: 				    '</span></h3><blockquote><i>'.
 2271: 				    &keywords_highlight($oessay).
 2272: 				    '</i></blockquote><hr />';
 2273:                         }
 2274: 	            }
 2275: 		}
 2276: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2277:                                      undef,$type,$trial,$rndseed);
 2278:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2279: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2280: 		    my $display_part=&get_display_part($partid,$symb);
 2281:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2282:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2283:                         ' <span class="LC_internal_info">'.
 2284:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2285:                         '</span>&nbsp; &nbsp;';
 2286: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2287:                         
 2288: 		    if (@$files) {
 2289:                         if ($hide eq 'anon') {
 2290:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2291:                         } else {
 2292:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2293:                                         .'<br /><span class="LC_warning">';
 2294:                             if(@$files == 1) {
 2295:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2296:                             } else {
 2297:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2298:                             }
 2299:                             $lastsubonly .= '</span>';                         
 2300:                             foreach my $file (@$files) {
 2301:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2302:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2303:                             }
 2304:                         }
 2305: 			$lastsubonly.='<br />';
 2306:                     }
 2307:                     if ($hide eq 'anon') {
 2308:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2309:                     } else {
 2310:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2311:                         if ($draft) {
 2312:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2313:                         }
 2314:                         $subval =
 2315: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2316: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2317:                         if ($responsetype eq 'essay') {
 2318:                             $subval =~ s{\n}{<br />}g;
 2319:                         }
 2320:                         $lastsubonly.=$subval."\n";
 2321:                     }
 2322: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2323: 		    $lastsubonly.='</div>';
 2324: 		}
 2325:             }
 2326: 	}
 2327: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2328:     }
 2329:     $request->print($lastsubonly);
 2330:     if ($env{'form.lastSub'} eq 'datesub') {
 2331:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2332: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2333:   
 2334:     } 
 2335:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2336:         my $identifier = (&canmodify($usec)? $counter : '');
 2337:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2338: 								 $env{'request.course.id'},
 2339: 								 $last,'.submission',
 2340: 								 'Apache::grades::keywords_highlight',
 2341:                                                                  $usec,$identifier));
 2342:     }
 2343:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2344: 	.$udom.'" />'."\n");
 2345:     # return if view submission with no grading option
 2346:     if (!&canmodify($usec)) {
 2347: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2348: 	return;
 2349:     } else {
 2350: 	$request->print('</div>'."\n");
 2351:     }
 2352: 
 2353:     # essay grading message center
 2354: #    if ($env{'form.handgrade'} eq 'yes') {
 2355:     if (1) {
 2356: 	my $result='<div class="LC_grade_message_center">';
 2357:     
 2358: 	$result.='<div class="LC_grade_message_center_header">'.
 2359: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2360: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2361: 	my $msgfor = $givenn.' '.$lastname;
 2362: 	if (scalar(@$col_fullnames) > 0) {
 2363: 	    my $lastone = pop(@$col_fullnames);
 2364: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2365: 	}
 2366: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2367: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2368: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2369: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2370: 	    ',\''.$msgfor.'\');" target="_self">'.
 2371: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2372: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2373: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2374: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2375: 	    '<br />&nbsp;('.
 2376: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2377: 	$result.='</div></div>';
 2378: 	$request->print($result);
 2379:     }
 2380: 
 2381:     my %seen = ();
 2382:     my @partlist;
 2383:     my @gradePartRespid;
 2384:     my @part_response_id = &flatten_responseType($responseType);
 2385:     $request->print(
 2386:         '<div class="LC_Box">'
 2387:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2388:     );
 2389:     $request->print(&gradeBox_start());
 2390:     foreach my $part_response_id (@part_response_id) {
 2391:     	my ($partid,$respid) = @{ $part_response_id };
 2392: 	my $part_resp = join('_',@{ $part_response_id });
 2393: 	next if ($seen{$partid} > 0);
 2394: 	$seen{$partid}++;
 2395: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2396: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2397: 	push(@partlist,$partid);
 2398: 	push(@gradePartRespid,$partid.'.'.$respid);
 2399: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2400:     }
 2401:     $request->print(&gradeBox_end()); # </div>
 2402:     $request->print('</div>');
 2403: 
 2404:     $request->print('<div class="LC_grade_info_links">');
 2405:     $request->print('</div>');
 2406: 
 2407:     $result='<input type="hidden" name="partlist'.$counter.
 2408: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2409:     $result.='<input type="hidden" name="gradePartRespid'.
 2410: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2411:     my $ctr = 0;
 2412:     while ($ctr < scalar(@partlist)) {
 2413: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2414: 	    $partlist[$ctr].'" />'."\n";
 2415: 	$ctr++;
 2416:     }
 2417:     $request->print($result.''."\n");
 2418: 
 2419: # Done with printing info for one student
 2420: 
 2421:     $request->print('</div>');#LC_grade_show_user
 2422: 
 2423: 
 2424:     # print end of form
 2425:     if ($counter == $total) {
 2426:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2427: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2428: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2429: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2430: 	my $ntstu ='<select name="NTSTU">'.
 2431: 	    '<option>1</option><option>2</option>'.
 2432: 	    '<option>3</option><option>5</option>'.
 2433: 	    '<option>7</option><option>10</option></select>'."\n";
 2434: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2435: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2436:         $endform.=&mt('[_1]student(s)',$ntstu);
 2437: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2438: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2439: 	    '<input type="button" value="'.&mt('Next').'" '.
 2440: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2441:         $endform.='<span class="LC_warning">'.
 2442:                   &mt('(Next and Previous (student) do not save the scores.)').
 2443:                   '</span>'."\n" ;
 2444:         $endform.="<input type='hidden' value='".&get_increment().
 2445:             "' name='increment' />";
 2446: 	$endform.='</td></tr></table></form>';
 2447: 	$request->print($endform);
 2448:     }
 2449:     return '';
 2450: }
 2451: 
 2452: sub check_collaborators {
 2453:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2454:     my ($result,@col_fullnames);
 2455:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2456:     foreach my $part (keys(%$handgrade)) {
 2457: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2458: 					'.maxcollaborators',
 2459: 					$symb,$udom,$uname);
 2460: 	next if ($ncol <= 0);
 2461: 	$part =~ s/\_/\./g;
 2462: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2463: 	my (@good_collaborators, @bad_collaborators);
 2464: 	foreach my $possible_collaborator
 2465: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2466: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2467: 	    next if ($possible_collaborator eq '');
 2468: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2469: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2470: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2471: 	    # Doing this grep allows 'fuzzy' specification
 2472: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2473: 			       keys(%$classlist));
 2474: 	    if (! scalar(@matches)) {
 2475: 		push(@bad_collaborators, $possible_collaborator);
 2476: 	    } else {
 2477: 		push(@good_collaborators, @matches);
 2478: 	    }
 2479: 	}
 2480: 	if (scalar(@good_collaborators) != 0) {
 2481: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2482: 	    foreach my $name (@good_collaborators) {
 2483: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2484: 		push(@col_fullnames, $givenn.' '.$lastname);
 2485: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2486: 	    }
 2487: 	    $result.='</ol><br />'."\n";
 2488: 	    my ($part)=split(/\./,$part);
 2489: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2490: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2491: 		"\n";
 2492: 	}
 2493: 	if (scalar(@bad_collaborators) > 0) {
 2494: 	    $result.='<div class="LC_warning">';
 2495: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2496: 	    $result .= '</div>';
 2497: 	}         
 2498: 	if (scalar(@bad_collaborators > $ncol)) {
 2499: 	    $result .= '<div class="LC_warning">';
 2500: 	    $result .= &mt('This student has submitted too many '.
 2501: 		'collaborators.  Maximum is [_1].',$ncol);
 2502: 	    $result .= '</div>';
 2503: 	}
 2504:     }
 2505:     return ($result,$fullname,\@col_fullnames);
 2506: }
 2507: 
 2508: #--- Retrieve the last submission for all the parts
 2509: sub get_last_submission {
 2510:     my ($returnhash)=@_;
 2511:     my (@string,$timestamp,%lasthidden);
 2512:     if ($$returnhash{'version'}) {
 2513: 	my %lasthash=();
 2514: 	my ($version);
 2515: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2516: 	    foreach my $key (sort(split(/\:/,
 2517: 					$$returnhash{$version.':keys'}))) {
 2518: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2519: 		$timestamp = 
 2520: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2521: 	    }
 2522: 	}
 2523:         my (%typeparts,%randombytry);
 2524:         my $showsurv = 
 2525:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2526:         foreach my $key (sort(keys(%lasthash))) {
 2527:             if ($key =~ /\.type$/) {
 2528:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2529:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2530:                     ($lasthash{$key} eq 'randomizetry')) {
 2531:                     my ($ign,@parts) = split(/\./,$key);
 2532:                     pop(@parts);
 2533:                     my $id = join('.',@parts);
 2534:                     if ($lasthash{$key} eq 'randomizetry') {
 2535:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2536:                     } else {
 2537:                         unless ($showsurv) {
 2538:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2539:                         }
 2540:                     }
 2541:                     delete($lasthash{$key});
 2542:                 }
 2543:             }
 2544:         }
 2545:         my @hidden = keys(%typeparts);
 2546:         my @randomize = keys(%randombytry);
 2547: 	foreach my $key (keys(%lasthash)) {
 2548: 	    next if ($key !~ /\.submission$/);
 2549:             my $hide;
 2550:             if (@hidden) {
 2551:                 foreach my $id (@hidden) {
 2552:                     if ($key =~ /^\Q$id\E/) {
 2553:                         $hide = 'anon';
 2554:                         last;
 2555:                     }
 2556:                 }
 2557:             }
 2558:             unless ($hide) {
 2559:                 if (@randomize) {
 2560:                     foreach my $id (@randomize) {
 2561:                         if ($key =~ /^\Q$id\E/) {
 2562:                             $hide = 'rand';
 2563:                             last;
 2564:                         }
 2565:                     }
 2566:                 }
 2567:             }
 2568: 	    my ($partid,$foo) = split(/submission$/,$key);
 2569: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2570:             push(@string, join(':', $key, $hide, $draft, (
 2571:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2572:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2573: 	}
 2574:     }
 2575:     if (!@string) {
 2576: 	$string[0] =
 2577: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2578:     }
 2579:     return (\@string,\$timestamp);
 2580: }
 2581: 
 2582: #--- High light keywords, with style choosen by user.
 2583: sub keywords_highlight {
 2584:     my $string    = shift;
 2585:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2586:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2587:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2588:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2589:     foreach my $keyword (@keylist) {
 2590: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2591:     }
 2592:     return $string;
 2593: }
 2594: 
 2595: # For Tasks provide a mechanism to display previous version for one specific student
 2596: 
 2597: sub show_previous_task_version {
 2598:     my ($request,$symb) = @_;
 2599:     if ($symb eq '') {
 2600:         $request->print(
 2601:             '<span class="LC_error">'.
 2602:             &mt('Unable to handle ambiguous references.').
 2603:             '</span>');
 2604:         return '';
 2605:     }
 2606:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2607:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2608:     if (!&canview($usec)) {
 2609:         $request->print(
 2610:             '<span class="LC_warning">'.
 2611:             &mt('Unable to view previous version for requested student.').
 2612:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2613:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2614:             '</span>');
 2615:         return;
 2616:     }
 2617:     my $mode = 'both';
 2618:     my $isTask = ($symb =~/\.task$/);
 2619:     if ($isTask) {
 2620:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2621:             if ($env{'form.fullname'} eq '') {
 2622:                 $env{'form.fullname'} =
 2623:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2624:             }
 2625:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2626:             $request->print("\n\n".
 2627:                             '<div class="LC_grade_show_user">'.
 2628:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2629:                             '</h2>'."\n");
 2630:             &Apache::lonxml::clear_problem_counter();
 2631:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2632:                             {'previousversion' => $env{'form.previousversion'} }));
 2633:             $request->print("\n</div>");
 2634:         }
 2635:     }
 2636:     return;
 2637: }
 2638: 
 2639: sub choose_task_version_form {
 2640:     my ($symb,$uname,$udom,$nomenu) = @_;
 2641:     my $isTask = ($symb =~/\.task$/);
 2642:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2643:     if ($isTask) {
 2644:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2645:                                               $udom,$uname);
 2646:         if (($record{'resource.0.version'} eq '') ||
 2647:             ($record{'resource.0.version'} < 2)) {
 2648:             return ($record{'resource.0.version'},
 2649:                     $record{'resource.0.version'},$result,$js);
 2650:         } else {
 2651:             $current = $record{'resource.0.version'};
 2652:         }
 2653:         if ($env{'form.previousversion'}) {
 2654:             $displayed = $env{'form.previousversion'};
 2655:             $rowtitle = &mt('Choose another version:')
 2656:         } else {
 2657:             $displayed = $current;
 2658:             $rowtitle = &mt('Show earlier version:');
 2659:         }
 2660:         $result = '<div class="LC_left_float">';
 2661:         my $list;
 2662:         my $numversions = 0;
 2663:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2664:             if ($i == $current) {
 2665:                 if (!$env{'form.previousversion'} || $nomenu) {
 2666:                     next;
 2667:                 } else {
 2668:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2669:                     $numversions ++;
 2670:                 }
 2671:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2672:                 unless ($i == $env{'form.previousversion'}) {
 2673:                     $numversions ++;
 2674:                 }
 2675:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2676:             }
 2677:         }
 2678:         if ($numversions) {
 2679:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2680:             $result .=
 2681:                 '<form name="getprev" method="post" action=""'.
 2682:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2683:                 &Apache::loncommon::start_data_table().
 2684:                 &Apache::loncommon::start_data_table_row().
 2685:                 '<th align="left">'.$rowtitle.'</th>'.
 2686:                 '<td><select name="version">'.
 2687:                 '<option>'.&mt('Select').'</option>'.
 2688:                 $list.
 2689:                 '</select></td>'.
 2690:                 &Apache::loncommon::end_data_table_row();
 2691:             unless ($nomenu) {
 2692:                 $result .= &Apache::loncommon::start_data_table_row().
 2693:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2694:                 '<td><span class="LC_nobreak">'.
 2695:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2696:                 &mt('Yes').'</label>'.
 2697:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2698:                 '</span></td>'.
 2699:                 &Apache::loncommon::end_data_table_row();
 2700:             }
 2701:             $result .=
 2702:                 &Apache::loncommon::start_data_table_row().
 2703:                 '<th align="left">&nbsp;</th>'.
 2704:                 '<td>'.
 2705:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2706:                 '</td>'.
 2707:                 &Apache::loncommon::end_data_table_row().
 2708:                 &Apache::loncommon::end_data_table().
 2709:                 '</form>';
 2710:             $js = &previous_display_javascript($nomenu,$current);
 2711:         } elsif ($displayed && $nomenu) {
 2712:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2713:         } else {
 2714:             $result .= &mt('No previous versions to show for this student');
 2715:         }
 2716:         $result .= '</div>';
 2717:     }
 2718:     return ($current,$displayed,$result,$js);
 2719: }
 2720: 
 2721: sub previous_display_javascript {
 2722:     my ($nomenu,$current) = @_;
 2723:     my $js = <<"JSONE";
 2724: <script type="text/javascript">
 2725: // <![CDATA[
 2726: function previousVersion(uname,udom,symb) {
 2727:     var current = '$current';
 2728:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2729:     var prevstr = new RegExp("^\\\\d+\$");
 2730:     if (!prevstr.test(version)) {
 2731:         return false;
 2732:     }
 2733:     var url = '';
 2734:     if (version == current) {
 2735:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2736:     } else {
 2737:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2738:     }
 2739: JSONE
 2740:     if ($nomenu) {
 2741:         $js .= <<"JSTWO";
 2742:     document.location.href = url;
 2743: JSTWO
 2744:     } else {
 2745:         $js .= <<"JSTHREE";
 2746:     var newwin = 0;
 2747:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2748:         if (document.getprev.prevwin[i].checked == true) {
 2749:             newwin = document.getprev.prevwin[i].value;
 2750:         }
 2751:     }
 2752:     if (newwin == 1) {
 2753:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2754:         url = url+'&inhibitmenu=yes';
 2755:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2756:             previousWin = window.open(url,'',options,1);
 2757:         } else {
 2758:             previousWin.location.href = url;
 2759:         }
 2760:         previousWin.focus();
 2761:         return false;
 2762:     } else {
 2763:         document.location.href = url;
 2764:         return false;
 2765:     }
 2766: JSTHREE
 2767:     }
 2768:     $js .= <<"ENDJS";
 2769:     return false;
 2770: }
 2771: // ]]>
 2772: </script>
 2773: ENDJS
 2774: 
 2775: }
 2776: 
 2777: #--- Called from submission routine
 2778: sub processHandGrade {
 2779:     my ($request,$symb) = @_;
 2780:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2781:     my $button = $env{'form.gradeOpt'};
 2782:     my $ngrade = $env{'form.NCT'};
 2783:     my $ntstu  = $env{'form.NTSTU'};
 2784:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2785:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2786: 
 2787:     if ($button eq 'Save & Next') {
 2788: 	my $ctr = 0;
 2789: 	while ($ctr < $ngrade) {
 2790: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2791: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2792:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2793: 	    if ($errorflag eq 'no_score') {
 2794: 		$ctr++;
 2795: 		next;
 2796: 	    }
 2797: 	    if ($errorflag eq 'not_allowed') {
 2798: 		$request->print(
 2799:                     '<span class="LC_error">'
 2800:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2801:                    .'</span>');
 2802: 		$ctr++;
 2803: 		next;
 2804: 	    }
 2805:             if ($numhidden) {
 2806:                 $request->print(
 2807:                     '<span class="LC_info">'
 2808:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2809:                    .'</span><br />');
 2810:             }
 2811: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2812: 	    my ($subject,$message,$msgstatus) = ('','','');
 2813: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2814:             my ($feedurl,$showsymb) =
 2815: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2816: 	    my $messagetail;
 2817: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2818: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2819: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2820: 		$subject.=' ['.$restitle.']';
 2821: 		my (@msgnum) = split(/,/,$includemsg);
 2822: 		foreach (@msgnum) {
 2823: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2824: 		}
 2825: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2826: 		if ($env{'form.withgrades'.$ctr}) {
 2827: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2828: 		    $messagetail = " for <a href=\"".
 2829: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2830: 		}
 2831: 		$msgstatus = 
 2832:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2833: 						     $message.$messagetail,
 2834:                                                      undef,$feedurl,undef,
 2835:                                                      undef,undef,$showsymb,
 2836:                                                      $restitle);
 2837: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2838: 				$msgstatus.'<br />');
 2839: 	    }
 2840: 	    if ($env{'form.collaborator'.$ctr}) {
 2841: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2842: 		foreach my $collabstr (@collabstrs) {
 2843: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2844: 		    foreach my $collaborator (@collaborators) {
 2845: 			my ($errorflag,$pts,$wgt) = 
 2846: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2847: 					   $env{'form.unamedom'.$ctr},$part);
 2848: 			if ($errorflag eq 'not_allowed') {
 2849: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2850: 			    next;
 2851: 			} elsif ($message ne '') {
 2852: 			    my ($baseurl,$showsymb) = 
 2853: 				&get_feedurl_and_symb($symb,$collaborator,
 2854: 						      $udom);
 2855: 			    if ($env{'form.withgrades'.$ctr}) {
 2856: 				$messagetail = " for <a href=\"".
 2857:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2858: 			    }
 2859: 			    $msgstatus = 
 2860: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2861: 			}
 2862: 		    }
 2863: 		}
 2864: 	    }
 2865: 	    $ctr++;
 2866: 	}
 2867:     }
 2868: 
 2869: #    if ($env{'form.handgrade'} eq 'yes') {
 2870:     if (1) {
 2871: 	# Keywords sorted in alphabatical order
 2872: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2873: 	my %keyhash = ();
 2874: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2875: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2876: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2877: 	$env{'form.keywords'} = join(' ',@keywords);
 2878: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2879: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2880: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2881: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2882: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2883: 
 2884: 	# message center - Order of message gets changed. Blank line is eliminated.
 2885: 	# New messages are saved in env for the next student.
 2886: 	# All messages are saved in nohist_handgrade.db
 2887: 	my ($ctr,$idx) = (1,1);
 2888: 	while ($ctr <= $env{'form.savemsgN'}) {
 2889: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2890: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2891: 		$idx++;
 2892: 	    }
 2893: 	    $ctr++;
 2894: 	}
 2895: 	$ctr = 0;
 2896: 	while ($ctr < $ngrade) {
 2897: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2898: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2899: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2900: 		$idx++;
 2901: 	    }
 2902: 	    $ctr++;
 2903: 	}
 2904: 	$env{'form.savemsgN'} = --$idx;
 2905: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2906: 	my $putresult = &Apache::lonnet::put
 2907: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2908:     }
 2909:     # Called by Save & Refresh from Highlight Attribute Window
 2910:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2911:     if ($env{'form.refresh'} eq 'on') {
 2912: 	my ($ctr,$total) = (0,0);
 2913: 	while ($ctr < $ngrade) {
 2914: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2915: 	    $ctr++;
 2916: 	}
 2917: 	$env{'form.NTSTU'}=$ngrade;
 2918: 	$ctr = 0;
 2919: 	while ($ctr < $total) {
 2920: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2921: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2922: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2923: 	    &submission($request,$ctr,$total-1,$symb);
 2924: 	    $ctr++;
 2925: 	}
 2926: 	return '';
 2927:     }
 2928: 
 2929:     # Get the next/previous one or group of students
 2930:     my $firststu = $env{'form.unamedom0'};
 2931:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2932:     my $ctr = 2;
 2933:     while ($laststu eq '') {
 2934: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2935: 	$ctr++;
 2936: 	$laststu = $firststu if ($ctr > $ngrade);
 2937:     }
 2938: 
 2939:     my (@parsedlist,@nextlist);
 2940:     my ($nextflg) = 0;
 2941:     foreach my $item (sort 
 2942: 	     {
 2943: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2944: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2945: 		 }
 2946: 		 return $a cmp $b;
 2947: 	     } (keys(%$fullname))) {
 2948: # FIXME: this is fishy, looks like the button label
 2949: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2950: 	    push(@parsedlist,$item);
 2951: 	}
 2952: 	$nextflg = 1 if ($item eq $laststu);
 2953: 	if ($button eq 'Previous') {
 2954: 	    last if ($item eq $firststu);
 2955: 	    push(@parsedlist,$item);
 2956: 	}
 2957:     }
 2958:     $ctr = 0;
 2959: # FIXME: this is fishy, looks like the button label
 2960:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2961:     my $res_error;
 2962:     my ($partlist) = &response_type($symb,\$res_error);
 2963:     if ($res_error) {
 2964:         $request->print(&navmap_errormsg());
 2965:         return;
 2966:     }
 2967:     foreach my $student (@parsedlist) {
 2968: 	my $submitonly=$env{'form.submitonly'};
 2969: 	my ($uname,$udom) = split(/:/,$student);
 2970: 	
 2971: 	if ($submitonly eq 'queued') {
 2972: 	    my %queue_status = 
 2973: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2974: 							$udom,$uname);
 2975: 	    next if (!defined($queue_status{'gradingqueue'}));
 2976: 	}
 2977: 
 2978: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2979: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2980: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2981: 	    my $submitted = 0;
 2982: 	    my $ungraded = 0;
 2983: 	    my $incorrect = 0;
 2984: 	    foreach my $item (keys(%status)) {
 2985: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2986: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2987: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2988: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2989: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2990: 		    $submitted = 0;
 2991: 		}
 2992: 	    }
 2993: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2994: 				     $submitonly eq 'incorrect' ||
 2995: 				     $submitonly eq 'graded'));
 2996: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2997: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2998: 	}
 2999: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3000: 	last if ($ctr == $ntstu);
 3001: 	$ctr++;
 3002:     }
 3003: 
 3004:     $ctr = 0;
 3005:     my $total = scalar(@nextlist)-1;
 3006: 
 3007:     foreach (sort(@nextlist)) {
 3008: 	my ($uname,$udom,$submitter) = split(/:/);
 3009: 	$env{'form.student'}  = $uname;
 3010: 	$env{'form.userdom'}  = $udom;
 3011: 	$env{'form.fullname'} = $$fullname{$_};
 3012: 	&submission($request,$ctr,$total,$symb);
 3013: 	$ctr++;
 3014:     }
 3015:     if ($total < 0) {
 3016: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3017: 	$request->print($the_end);
 3018:     }
 3019:     return '';
 3020: }
 3021: 
 3022: #---- Save the score and award for each student, if changed
 3023: sub saveHandGrade {
 3024:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3025:     my @version_parts;
 3026:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3027: 					   $env{'request.course.id'});
 3028:     if (!&canmodify($usec)) { return('not_allowed'); }
 3029:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3030:     my @parts_graded;
 3031:     my %newrecord  = ();
 3032:     my ($pts,$wgt,$totchg) = ('','',0);
 3033:     my %aggregate = ();
 3034:     my $aggregateflag = 0;
 3035:     if ($env{'form.HIDE'.$newflg}) {
 3036:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3037:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3038:         $totchg += $numchgs;
 3039:     }
 3040:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3041:     foreach my $new_part (@parts) {
 3042: 	#collaborator ($submi may vary for different parts
 3043: 	if ($submitter && $new_part ne $part) { next; }
 3044: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3045: 	if ($dropMenu eq 'excused') {
 3046: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3047: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3048: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3049: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3050: 		}
 3051: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3052: 	    }
 3053: 	} elsif ($dropMenu eq 'reset status'
 3054: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3055: 	    foreach my $key (keys(%record)) {
 3056: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3057: 	    }
 3058: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3059: 		"$env{'user.name'}:$env{'user.domain'}";
 3060:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3061: 
 3062:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3063: 					       [$new_part]);
 3064:             my $aggtries =$totaltries;
 3065:             if ($last_resets{$new_part}) {
 3066:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3067: 					   $new_part);
 3068:             }
 3069: 
 3070:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3071:             if ($aggtries > 0) {
 3072:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3073:                 $aggregateflag = 1;
 3074:             }
 3075: 	} elsif ($dropMenu eq '') {
 3076: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3077: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3078: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3079: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3080: 		next;
 3081: 	    }
 3082: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3083: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3084: 	    my $partial= $pts/$wgt;
 3085: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3086: 		#do not update score for part if not changed.
 3087:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3088: 		next;
 3089: 	    } else {
 3090: 	        push(@parts_graded,$new_part);
 3091: 	    }
 3092: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3093: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3094: 	    }
 3095: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3096: 	    if ($partial == 0) {
 3097: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3098: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3099: 		}
 3100: 	    } else {
 3101: 		if ($record{$reckey} ne 'correct_by_override') {
 3102: 		    $newrecord{$reckey} = 'correct_by_override';
 3103: 		}
 3104: 	    }	    
 3105: 	    if ($submitter && 
 3106: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3107: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3108: 	    }
 3109: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3110: 		"$env{'user.name'}:$env{'user.domain'}";
 3111: 	}
 3112: 	# unless problem has been graded, set flag to version the submitted files
 3113: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3114: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3115: 	        $dropMenu eq 'reset status')
 3116: 	   {
 3117: 	    push(@version_parts,$new_part);
 3118: 	}
 3119:     }
 3120:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3121:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3122: 
 3123:     if (%newrecord) {
 3124:         if (@version_parts) {
 3125:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3126:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3127: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3128: 	    foreach my $new_part (@version_parts) {
 3129: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3130: 				$new_part,\%newrecord);
 3131: 	    }
 3132:         }
 3133: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3134: 				$env{'request.course.id'},$domain,$stuname);
 3135: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3136: 				     $cdom,$cnum,$domain,$stuname);
 3137:     }
 3138:     if ($aggregateflag) {
 3139:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3140: 			      $cdom,$cnum);
 3141:     }
 3142:     return ('',$pts,$wgt,$totchg);
 3143: }
 3144: 
 3145: sub makehidden {
 3146:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3147:     return unless (ref($record) eq 'HASH');
 3148:     my %modified;
 3149:     my $numchanged = 0;
 3150:     if (exists($record->{$version.':keys'})) {
 3151:         my $partsregexp = $parts;
 3152:         $partsregexp =~ s/,/|/g;
 3153:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3154:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3155:                  my $item = $1;
 3156:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3157:                      $modified{$key} = $record->{$version.':'.$key};
 3158:                  }
 3159:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3160:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3161:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3162:                 $modified{$key} = $record->{$version.':'.$key};
 3163:             }
 3164:         }
 3165:         if (keys(%modified)) {
 3166:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3167:                                           $domain,$stuname,$tolog) eq 'ok') {
 3168:                 $numchanged ++;
 3169:             }
 3170:         }
 3171:     }
 3172:     return $numchanged;
 3173: }
 3174: 
 3175: sub check_and_remove_from_queue {
 3176:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3177:     my @ungraded_parts;
 3178:     foreach my $part (@{$parts}) {
 3179: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3180: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3181: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3182: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3183: 		) {
 3184: 	    push(@ungraded_parts, $part);
 3185: 	}
 3186:     }
 3187:     if ( !@ungraded_parts ) {
 3188: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3189: 					       $cnum,$domain,$stuname);
 3190:     }
 3191: }
 3192: 
 3193: sub handback_files {
 3194:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3195:     my $portfolio_root = '/userfiles/portfolio';
 3196:     my $res_error;
 3197:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3198:     if ($res_error) {
 3199:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3200:         return;
 3201:     }
 3202:     my @handedback;
 3203:     my $file_msg;
 3204:     my @part_response_id = &flatten_responseType($responseType);
 3205:     foreach my $part_response_id (@part_response_id) {
 3206:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3207: 	my $part_resp = join('_',@{ $part_response_id });
 3208:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3209:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3210:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3211:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3212:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3213:                     my ($directory,$answer_file) = 
 3214:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3215:                     my ($answer_name,$answer_ver,$answer_ext) =
 3216: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3217: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3218:                     my $getpropath = 1;
 3219:                     my ($dir_list,$listerror) = 
 3220:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3221:                                                  $domain,$stuname,$getpropath);
 3222: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3223:                     # fix filename
 3224:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3225:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3226:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3227:             	                                $save_file_name);
 3228:                     if ($result !~ m|^/uploaded/|) {
 3229:                         $request->print('<br /><span class="LC_error">'.
 3230:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3231:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3232:                                         '</span>');
 3233:                     } else {
 3234:                         # mark the file as read only
 3235:                         push(@handedback,$save_file_name);
 3236: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3237: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3238: 			}
 3239:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3240: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3241:                     }
 3242:                     $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>'));
 3243:                 }
 3244:             }
 3245:         }
 3246:     }
 3247:     if (@handedback > 0) {
 3248:         $request->print('<br />');
 3249:         my @what = ($symb,$env{'request.course.id'},'handback');
 3250:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3251:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3252:         my ($subject,$message);
 3253:         if (scalar(@handedback) == 1) {
 3254:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3255:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3256:         } else {
 3257:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3258:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3259:         }
 3260:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3261:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3262:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3263:         my ($feedurl,$showsymb) =
 3264:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3265:         my $restitle = &Apache::lonnet::gettitle($symb);
 3266:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3267:         my $msgstatus =
 3268:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3269:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3270:                  $restitle);
 3271:         if ($msgstatus) {
 3272:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3273:         }
 3274:     }
 3275:     return;
 3276: }
 3277: 
 3278: sub get_feedurl_and_symb {
 3279:     my ($symb,$uname,$udom) = @_;
 3280:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3281:     $url = &Apache::lonnet::clutter($url);
 3282:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3283: 					$symb,$udom,$uname);
 3284:     if ($encrypturl =~ /^yes$/i) {
 3285: 	&Apache::lonenc::encrypted(\$url,1);
 3286: 	&Apache::lonenc::encrypted(\$symb,1);
 3287:     }
 3288:     return ($url,$symb);
 3289: }
 3290: 
 3291: sub get_submitted_files {
 3292:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3293:     my @files;
 3294:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3295:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3296:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3297:     	    push(@files,$file_url.$file);
 3298:         }
 3299:     }
 3300:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3301:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3302:     }
 3303:     return (\@files);
 3304: }
 3305: 
 3306: # ----------- Provides number of tries since last reset.
 3307: sub get_num_tries {
 3308:     my ($record,$last_reset,$part) = @_;
 3309:     my $timestamp = '';
 3310:     my $num_tries = 0;
 3311:     if ($$record{'version'}) {
 3312:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3313:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3314:                 $timestamp = $$record{$version.':timestamp'};
 3315:                 if ($timestamp > $last_reset) {
 3316:                     $num_tries ++;
 3317:                 } else {
 3318:                     last;
 3319:                 }
 3320:             }
 3321:         }
 3322:     }
 3323:     return $num_tries;
 3324: }
 3325: 
 3326: # ----------- Determine decrements required in aggregate totals 
 3327: sub decrement_aggs {
 3328:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3329:     my %decrement = (
 3330:                         attempts => 0,
 3331:                         users => 0,
 3332:                         correct => 0
 3333:                     );
 3334:     $decrement{'attempts'} = $aggtries;
 3335:     if ($solvedstatus =~ /^correct/) {
 3336:         $decrement{'correct'} = 1;
 3337:     }
 3338:     if ($aggtries == $totaltries) {
 3339:         $decrement{'users'} = 1;
 3340:     }
 3341:     foreach my $type (keys(%decrement)) {
 3342:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3343:     }
 3344:     return;
 3345: }
 3346: 
 3347: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3348: sub get_last_resets {
 3349:     my ($symb,$courseid,$partids) =@_;
 3350:     my %last_resets;
 3351:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3352:     my $cname = $env{'course.'.$courseid.'.num'};
 3353:     my @keys;
 3354:     foreach my $part (@{$partids}) {
 3355: 	push(@keys,"$symb\0$part\0resettime");
 3356:     }
 3357:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3358: 				     $cdom,$cname);
 3359:     foreach my $part (@{$partids}) {
 3360: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3361:     }
 3362:     return %last_resets;
 3363: }
 3364: 
 3365: # ----------- Handles creating versions for portfolio files as answers
 3366: sub version_portfiles {
 3367:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3368:     my $version_parts = join('|',@$v_flag);
 3369:     my @returned_keys;
 3370:     my $parts = join('|', @$parts_graded);
 3371:     foreach my $key (keys(%$record)) {
 3372:         my $new_portfiles;
 3373:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3374:             my @versioned_portfiles;
 3375:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3376:             if (@portfiles) {
 3377:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3378:                                                       \@versioned_portfiles);
 3379:             }
 3380:             $$record{$key} = join(',',@versioned_portfiles);
 3381:             push(@returned_keys,$key);
 3382:         }
 3383:     } 
 3384:     return (@returned_keys);   
 3385: }
 3386: 
 3387: #--------------------------------------------------------------------------------------
 3388: #
 3389: #-------------------------- Next few routines handles grading by section or whole class
 3390: #
 3391: #--- Javascript to handle grading by section or whole class
 3392: sub viewgrades_js {
 3393:     my ($request) = shift;
 3394: 
 3395:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3396:     &js_escape(\$alertmsg);
 3397:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3398:    function writePoint(partid,weight,point) {
 3399: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3400: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3401: 	if (point == "textval") {
 3402: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3403: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3404: 		alert("$alertmsg"+parseFloat(point));
 3405: 		var resetbox = false;
 3406: 		for (var i=0; i<radioButton.length; i++) {
 3407: 		    if (radioButton[i].checked) {
 3408: 			textbox.value = i;
 3409: 			resetbox = true;
 3410: 		    }
 3411: 		}
 3412: 		if (!resetbox) {
 3413: 		    textbox.value = "";
 3414: 		}
 3415: 		return;
 3416: 	    }
 3417: 	    if (parseFloat(point) > parseFloat(weight)) {
 3418: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3419: 				   ") greater than the weight for the part. Accept?");
 3420: 		if (resp == false) {
 3421: 		    textbox.value = "";
 3422: 		    return;
 3423: 		}
 3424: 	    }
 3425: 	    for (var i=0; i<radioButton.length; i++) {
 3426: 		radioButton[i].checked=false;
 3427: 		if (parseFloat(point) == i) {
 3428: 		    radioButton[i].checked=true;
 3429: 		}
 3430: 	    }
 3431: 
 3432: 	} else {
 3433: 	    textbox.value = parseFloat(point);
 3434: 	}
 3435: 	for (i=0;i<document.classgrade.total.value;i++) {
 3436: 	    var user = document.classgrade["ctr"+i].value;
 3437: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3438: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3439: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3440: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3441: 	    if (saveval != "correct") {
 3442: 		scorename.value = point;
 3443: 		if (selname[0].selected != true) {
 3444: 		    selname[0].selected = true;
 3445: 		}
 3446: 	    }
 3447: 	}
 3448: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3449:     }
 3450: 
 3451:     function writeRadText(partid,weight) {
 3452: 	var selval   = document.classgrade["SELVAL_"+partid];
 3453: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3454:         var override = document.classgrade["FORCE_"+partid].checked;
 3455: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3456: 	if (selval[1].selected || selval[2].selected) {
 3457: 	    for (var i=0; i<radioButton.length; i++) {
 3458: 		radioButton[i].checked=false;
 3459: 
 3460: 	    }
 3461: 	    textbox.value = "";
 3462: 
 3463: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3464: 		var user = document.classgrade["ctr"+i].value;
 3465: 		user = user.replace(new RegExp(':', 'g'),"_");
 3466: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3467: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3468: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3469: 		if ((saveval != "correct") || override) {
 3470: 		    scorename.value = "";
 3471: 		    if (selval[1].selected) {
 3472: 			selname[1].selected = true;
 3473: 		    } else {
 3474: 			selname[2].selected = true;
 3475: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3476: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3477: 		    }
 3478: 		}
 3479: 	    }
 3480: 	} else {
 3481: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3482: 		var user = document.classgrade["ctr"+i].value;
 3483: 		user = user.replace(new RegExp(':', 'g'),"_");
 3484: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3485: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3486: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3487: 		if ((saveval != "correct") || override) {
 3488: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3489: 		    selname[0].selected = true;
 3490: 		}
 3491: 	    }
 3492: 	}	    
 3493:     }
 3494: 
 3495:     function changeSelect(partid,user) {
 3496: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3497: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3498: 	var point  = textbox.value;
 3499: 	var weight = document.classgrade["weight_"+partid].value;
 3500: 
 3501: 	if (isNaN(point) || parseFloat(point) < 0) {
 3502: 	    alert("$alertmsg"+parseFloat(point));
 3503: 	    textbox.value = "";
 3504: 	    return;
 3505: 	}
 3506: 	if (parseFloat(point) > parseFloat(weight)) {
 3507: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3508: 			       ") greater than the weight of the part. Accept?");
 3509: 	    if (resp == false) {
 3510: 		textbox.value = "";
 3511: 		return;
 3512: 	    }
 3513: 	}
 3514: 	selval[0].selected = true;
 3515:     }
 3516: 
 3517:     function changeOneScore(partid,user) {
 3518: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3519: 	if (selval[1].selected || selval[2].selected) {
 3520: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3521: 	    if (selval[2].selected) {
 3522: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3523: 	    }
 3524:         }
 3525:     }
 3526: 
 3527:     function resetEntry(numpart) {
 3528: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3529: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3530: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3531: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3532: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3533: 	    for (var i=0; i<radioButton.length; i++) {
 3534: 		radioButton[i].checked=false;
 3535: 
 3536: 	    }
 3537: 	    textbox.value = "";
 3538: 	    selval[0].selected = true;
 3539: 
 3540: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3541: 		var user = document.classgrade["ctr"+i].value;
 3542: 		user = user.replace(new RegExp(':', 'g'),"_");
 3543: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3544: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3545: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3546: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3547: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3548: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3549: 		if (saveselval == "excused") {
 3550: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3551: 		} else {
 3552: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3553: 		}
 3554: 	    }
 3555: 	}
 3556:     }
 3557: 
 3558: VIEWJAVASCRIPT
 3559: }
 3560: 
 3561: #--- show scores for a section or whole class w/ option to change/update a score
 3562: sub viewgrades {
 3563:     my ($request,$symb) = @_;
 3564:     &viewgrades_js($request);
 3565: 
 3566:     #need to make sure we have the correct data for later EXT calls, 
 3567:     #thus invalidate the cache
 3568:     &Apache::lonnet::devalidatecourseresdata(
 3569:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3570:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3571:     &Apache::lonnet::clear_EXT_cache_status();
 3572: 
 3573:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3574: 
 3575:     #view individual student submission form - called using Javascript viewOneStudent
 3576:     $result.=&jscriptNform($symb);
 3577: 
 3578:     #beginning of class grading form
 3579:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3580:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3581: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3582: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3583: 	&build_section_inputs().
 3584: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3585: 
 3586:     #retrieve selected groups
 3587:     my (@groups,$group_display);
 3588:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3589:     if (grep(/^all$/,@groups)) {
 3590:         @groups = ('all');
 3591:     } elsif (grep(/^none$/,@groups)) {
 3592:         @groups = ('none');
 3593:     } elsif (@groups > 0) {
 3594:         $group_display = join(', ',@groups);
 3595:     }
 3596: 
 3597:     my ($common_header,$specific_header,@sections,$section_display);
 3598:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3599:     if (grep(/^all$/,@sections)) {
 3600:         @sections = ('all');
 3601:         if ($group_display) {
 3602:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3603:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3604:         } elsif (grep(/^none$/,@groups)) {
 3605:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3606:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3607:         } else {
 3608: 	    $common_header = &mt('Assign Common Grade to Class');
 3609:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3610:         }
 3611:     } elsif (grep(/^none$/,@sections)) {
 3612:         @sections = ('none');
 3613:         if ($group_display) {
 3614:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3615:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3616:         } elsif (grep(/^none$/,@groups)) {
 3617:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3618:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3619:         } else {
 3620:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3621: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3622:         }
 3623:     } else {
 3624:         $section_display = join (", ",@sections);
 3625:         if ($group_display) {
 3626:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3627:                                  $section_display,$group_display);
 3628:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3629:                                    $section_display,$group_display);
 3630:         } elsif (grep(/^none$/,@groups)) {
 3631:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3632:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3633:         } else {
 3634:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3635: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3636:         }
 3637:     }
 3638:     my %submit_types = &substatus_options();
 3639:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3640: 
 3641:     if ($env{'form.submitonly'} eq 'all') {
 3642:         $result.= '<h3>'.$common_header.'</h3>';
 3643:     } else {
 3644:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3645:     }
 3646:     $result .= &Apache::loncommon::start_data_table();
 3647:     #radio buttons/text box for assigning points for a section or class.
 3648:     #handles different parts of a problem
 3649:     my $res_error;
 3650:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3651:     if ($res_error) {
 3652:         return &navmap_errormsg();
 3653:     }
 3654:     my %weight = ();
 3655:     my $ctsparts = 0;
 3656:     my %seen = ();
 3657:     my @part_response_id = &flatten_responseType($responseType);
 3658:     foreach my $part_response_id (@part_response_id) {
 3659:     	my ($partid,$respid) = @{ $part_response_id };
 3660: 	my $part_resp = join('_',@{ $part_response_id });
 3661: 	next if $seen{$partid};
 3662: 	$seen{$partid}++;
 3663: 	my $handgrade=$$handgrade{$part_resp};
 3664: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3665: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3666: 
 3667: 	my $display_part=&get_display_part($partid,$symb);
 3668: 	my $radio.='<table border="0"><tr>';  
 3669: 	my $ctr = 0;
 3670: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3671: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3672: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3673: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3674: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3675: 	    $ctr++;
 3676: 	}
 3677: 	$radio.='</tr></table>';
 3678: 	my $line = '<input type="text" name="TEXTVAL_'.
 3679: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3680: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3681: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3682:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3683:             '<select name="SELVAL_'.$partid.'" '.
 3684:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3685:                 $weight{$partid}.')"> '.
 3686: 	    '<option selected="selected"> </option>'.
 3687: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3688: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3689: 	    '</select></td>'.
 3690:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3691: 	$line.='<input type="hidden" name="partid_'.
 3692: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3693: 	$line.='<input type="hidden" name="weight_'.
 3694: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3695: 
 3696: 	$result.=
 3697: 	    &Apache::loncommon::start_data_table_row()."\n".
 3698: 	    '<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>'.
 3699: 	    &Apache::loncommon::end_data_table_row()."\n";
 3700: 	$ctsparts++;
 3701:     }
 3702:     $result.=&Apache::loncommon::end_data_table()."\n".
 3703: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3704:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3705: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3706: 
 3707:     #table listing all the students in a section/class
 3708:     #header of table
 3709:     if ($env{'form.submitonly'} eq 'all') {
 3710:         $result.= '<h3>'.$specific_header.'</h3>';
 3711:     } else {
 3712:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3713:     }
 3714:     $result.= &Apache::loncommon::start_data_table().
 3715: 	      &Apache::loncommon::start_data_table_header_row().
 3716: 	      '<th>'.&mt('No.').'</th>'.
 3717: 	      '<th>'.&nameUserString('header')."</th>\n";
 3718:     my $partserror;
 3719:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3720:     if ($partserror) {
 3721:         return &navmap_errormsg();
 3722:     }
 3723:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3724:     my @partids = ();
 3725:     foreach my $part (@parts) {
 3726: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3727:         my $narrowtext = &mt('Tries');
 3728: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3729: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3730: 	my ($partid) = &split_part_type($part);
 3731:         push(@partids,$partid);
 3732: #
 3733: # FIXME: Looks like $display looks at English text
 3734: #
 3735: 	my $display_part=&get_display_part($partid,$symb);
 3736: 	if ($display =~ /^Partial Credit Factor/) {
 3737: 	    $result.='<th>'.
 3738: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3739: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3740: 	    next;
 3741: 	    
 3742: 	} else {
 3743: 	    if ($display =~ /Problem Status/) {
 3744: 		my $grade_status_mt = &mt('Grade Status');
 3745: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3746: 	    }
 3747: 	    my $part_mt = &mt('Part:');
 3748: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3749: 	}
 3750: 
 3751: 	$result.='<th>'.$display.'</th>'."\n";
 3752:     }
 3753:     $result.=&Apache::loncommon::end_data_table_header_row();
 3754: 
 3755:     my %last_resets = 
 3756: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3757: 
 3758:     #get info for each student
 3759:     #list all the students - with points and grade status
 3760:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3761:     my $ctr = 0;
 3762:     foreach (sort 
 3763: 	     {
 3764: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3765: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3766: 		 }
 3767: 		 return $a cmp $b;
 3768: 	     } (keys(%$fullname))) {
 3769: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3770: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 3771:     }
 3772:     $result.=&Apache::loncommon::end_data_table();
 3773:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3774:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3775: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3776:     if ($ctr == 0) {
 3777:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3778:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3779:                 '<span class="LC_warning">';
 3780:         if ($env{'form.submitonly'} eq 'all') {
 3781:             if (grep(/^all$/,@sections)) {
 3782:                 if (grep(/^all$/,@groups)) {
 3783:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3784:                                    $stu_status);
 3785:                 } elsif (grep(/^none$/,@groups)) {
 3786:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 3787:                                    $stu_status); 
 3788:                 } else {
 3789:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3790:                                    $group_display,$stu_status);
 3791:                 }
 3792:             } elsif (grep(/^none$/,@sections)) {
 3793:                 if (grep(/^all$/,@groups)) {
 3794:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 3795:                                    $stu_status);
 3796:                 } elsif (grep(/^none$/,@groups)) {
 3797:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 3798:                                    $stu_status);
 3799:                 } else {
 3800:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3801:                                    $group_display,$stu_status);
 3802:                 }
 3803:             } else {
 3804:                 if (grep(/^all$/,@groups)) {
 3805:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3806:                                    $section_display,$stu_status);
 3807:                 } elsif (grep(/^none$/,@groups)) {
 3808:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 3809:                                    $section_display,$stu_status);
 3810:                 } else {
 3811:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 3812:                                    $section_display,$group_display,$stu_status);
 3813:                 }
 3814:             }
 3815:         } else {
 3816:             if (grep(/^all$/,@sections)) {
 3817:                 if (grep(/^all$/,@groups)) {
 3818:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3819:                                    $stu_status,$submission_status);
 3820:                 } elsif (grep(/^none$/,@groups)) {
 3821:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3822:                                    $stu_status,$submission_status);
 3823:                 } else {
 3824:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3825:                                    $group_display,$stu_status,$submission_status);
 3826:                 }
 3827:             } elsif (grep(/^none$/,@sections)) {
 3828:                 if (grep(/^all$/,@groups)) {
 3829:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3830:                                    $stu_status,$submission_status);
 3831:                 } elsif (grep(/^none$/,@groups)) {
 3832:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3833:                                    $stu_status,$submission_status);
 3834:                 } else {
 3835:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3836:                                    $group_display,$stu_status,$submission_status);
 3837:                 }
 3838:             } else {
 3839:                 if (grep(/^all$/,@groups)) {
 3840: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3841: 	                           $section_display,$stu_status,$submission_status);
 3842:                 } elsif (grep(/^none$/,@groups)) {
 3843:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3844:                                    $section_display,$stu_status,$submission_status);
 3845:                 } else {
 3846:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
 3847:                                    $section_display,$group_display,$stu_status,$submission_status);
 3848:                 }
 3849:             }
 3850:         }
 3851: 	$result .= '</span><br />';
 3852:     }
 3853:     return $result;
 3854: }
 3855: 
 3856: #--- call by previous routine to display each student who satisfies submission filter. 
 3857: sub viewstudentgrade {
 3858:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3859:     my ($uname,$udom) = split(/:/,$student);
 3860:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3861:     my $submitonly = $env{'form.submitonly'};
 3862:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 3863:         my %partstatus = ();
 3864:         if (ref($parts) eq 'ARRAY') {
 3865:             foreach my $apart (@{$parts}) {
 3866:                 my ($part,$type) = &split_part_type($apart);
 3867:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 3868:                 $status = 'nothing' if ($status eq '');
 3869:                 $partstatus{$part}      = $status;
 3870:                 my $subkey = "resource.$part.submitted_by";
 3871:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 3872:             }
 3873:             my $submitted = 0;
 3874:             my $graded = 0;
 3875:             my $incorrect = 0;
 3876:             foreach my $key (keys(%partstatus)) {
 3877:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 3878:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 3879:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 3880: 
 3881:                 my $partid = (split(/\./,$key))[1];
 3882:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 3883:                     $submitted = 0;
 3884:                 }
 3885:             }
 3886:             return if (!$submitted && ($submitonly eq 'yes' ||
 3887:                                        $submitonly eq 'incorrect' ||
 3888:                                        $submitonly eq 'graded'));
 3889:             return if (!$graded && ($submitonly eq 'graded'));
 3890:             return if (!$incorrect && $submitonly eq 'incorrect');
 3891:         }
 3892:     }
 3893:     if ($submitonly eq 'queued') {
 3894:         my ($cdom,$cnum) = split(/_/,$courseid);
 3895:         my %queue_status =
 3896:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3897:                                                     $udom,$uname);
 3898:         return if (!defined($queue_status{'gradingqueue'}));
 3899:     }
 3900:     $$ctr++;
 3901:     my %aggregates = ();
 3902:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3903: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 3904: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 3905: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3906: 	'\');" target="_self">'.$fullname.'</a> '.
 3907: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3908:     $student=~s/:/_/; # colon doen't work in javascript for names
 3909:     foreach my $apart (@$parts) {
 3910: 	my ($part,$type) = &split_part_type($apart);
 3911: 	my $score=$record{"resource.$part.$type"};
 3912:         $result.='<td align="center">';
 3913:         my ($aggtries,$totaltries);
 3914:         unless (exists($aggregates{$part})) {
 3915: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3916: 	    $aggtries = $totaltries;
 3917:             if ($$last_resets{$part}) {  
 3918:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3919: 					   $part);
 3920:             }
 3921:             $result.='<input type="hidden" name="'.
 3922:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3923:             $result.='<input type="hidden" name="'.
 3924:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3925:             $aggregates{$part} = 1;
 3926:         }
 3927: 	if ($type eq 'awarded') {
 3928: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3929: 	    $result.='<input type="hidden" name="'.
 3930: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3931: 	    $result.='<input type="text" name="'.
 3932: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3933:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3934: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3935: 	} elsif ($type eq 'solved') {
 3936: 	    my ($status,$foo)=split(/_/,$score,2);
 3937: 	    $status = 'nothing' if ($status eq '');
 3938: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3939: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3940: 	    $result.='&nbsp;<select name="'.
 3941: 		'GD_'.$student.'_'.$part.'_solved" '.
 3942:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3943: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3944: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3945: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3946: 	    $result.="</select>&nbsp;</td>\n";
 3947: 	} else {
 3948: 	    $result.='<input type="hidden" name="'.
 3949: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3950: 		    "\n";
 3951: 	    $result.='<input type="text" name="'.
 3952: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3953: 		'value="'.$score.'" size="4" /></td>'."\n";
 3954: 	}
 3955:     }
 3956:     $result.=&Apache::loncommon::end_data_table_row();
 3957:     return $result;
 3958: }
 3959: 
 3960: #--- change scores for all the students in a section/class
 3961: #    record does not get update if unchanged
 3962: sub editgrades {
 3963:     my ($request,$symb) = @_;
 3964: 
 3965:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3966:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3967:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3968: 
 3969:     my $result= &Apache::loncommon::start_data_table().
 3970: 	&Apache::loncommon::start_data_table_header_row().
 3971: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3972: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3973:     my %scoreptr = (
 3974: 		    'correct'  =>'correct_by_override',
 3975: 		    'incorrect'=>'incorrect_by_override',
 3976: 		    'excused'  =>'excused',
 3977: 		    'ungraded' =>'ungraded_attempted',
 3978:                     'credited' =>'credit_attempted',
 3979: 		    'nothing'  => '',
 3980: 		    );
 3981:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3982: 
 3983:     my (@partid);
 3984:     my %weight = ();
 3985:     my %columns = ();
 3986:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3987: 
 3988:     my $partserror;
 3989:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3990:     if ($partserror) {
 3991:         return &navmap_errormsg();
 3992:     }
 3993:     my $header;
 3994:     while ($ctr < $env{'form.totalparts'}) {
 3995: 	my $partid = $env{'form.partid_'.$ctr};
 3996: 	push(@partid,$partid);
 3997: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3998: 	$ctr++;
 3999:     }
 4000:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4001:     foreach my $partid (@partid) {
 4002: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4003: 	    '<th align="center">'.&mt('New Score').'</th>';
 4004: 	$columns{$partid}=2;
 4005: 	foreach my $stores (@parts) {
 4006: 	    my ($part,$type) = &split_part_type($stores);
 4007: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4008: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4009: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4010: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4011:             my $narrowtext = &mt('Tries');
 4012: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4013: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4014: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4015: 	    $columns{$partid}+=2;
 4016: 	}
 4017:     }
 4018:     foreach my $partid (@partid) {
 4019: 	my $display_part=&get_display_part($partid,$symb);
 4020: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4021: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4022: 	    '</th>';
 4023: 
 4024:     }
 4025:     $result .= &Apache::loncommon::end_data_table_header_row().
 4026: 	&Apache::loncommon::start_data_table_header_row().
 4027: 	$header.
 4028: 	&Apache::loncommon::end_data_table_header_row();
 4029:     my @noupdate;
 4030:     my ($updateCtr,$noupdateCtr) = (1,1);
 4031:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4032: 	my $line;
 4033: 	my $user = $env{'form.ctr'.$i};
 4034: 	my ($uname,$udom)=split(/:/,$user);
 4035: 	my %newrecord;
 4036: 	my $updateflag = 0;
 4037: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4038: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4039: 	if (!&canmodify($usec)) {
 4040: 	    my $numcols=scalar(@partid)*4+2;
 4041: 	    push(@noupdate,
 4042: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 4043: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 4044: 	    next;
 4045: 	}
 4046:         my %aggregate = ();
 4047:         my $aggregateflag = 0;
 4048: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4049: 	foreach (@partid) {
 4050: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4051: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4052: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4053: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4054: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4055: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4056: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4057: 	    my $score;
 4058: 	    if ($partial eq '') {
 4059: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4060: 	    } elsif ($partial > 0) {
 4061: 		$score = 'correct_by_override';
 4062: 	    } elsif ($partial == 0) {
 4063: 		$score = 'incorrect_by_override';
 4064: 	    }
 4065: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4066: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4067: 
 4068: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4069: 		"$env{'user.name'}:$env{'user.domain'}";
 4070: 	    if ($dropMenu eq 'reset status' &&
 4071: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4072: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4073: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4074: 		$newrecord{'resource.'.$_.'.award'} = '';
 4075: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4076: 		$updateflag = 1;
 4077:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4078:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4079:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4080:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4081:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4082:                     $aggregateflag = 1;
 4083:                 }
 4084: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4085: 		$updateflag = 1;
 4086: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4087: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4088: 		$rec_update++;
 4089: 	    }
 4090: 
 4091: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4092: 		'<td align="center">'.$awarded.
 4093: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4094: 
 4095: 
 4096: 	    my $partid=$_;
 4097: 	    foreach my $stores (@parts) {
 4098: 		my ($part,$type) = &split_part_type($stores);
 4099: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4100: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4101: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4102: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4103: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4104: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4105: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4106: 		    $updateflag=1;
 4107: 		}
 4108: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4109: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4110: 	    }
 4111: 	}
 4112: 	$line.="\n";
 4113: 
 4114: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4115: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4116: 
 4117: 	if ($updateflag) {
 4118: 	    $count++;
 4119: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4120: 				    $udom,$uname);
 4121: 
 4122: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4123: 					      $cnum,$udom,$uname)) {
 4124: 		# need to figure out if should be in queue.
 4125: 		my %record =  
 4126: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4127: 					     $udom,$uname);
 4128: 		my $all_graded = 1;
 4129: 		my $none_graded = 1;
 4130: 		foreach my $part (@parts) {
 4131: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4132: 			$all_graded = 0;
 4133: 		    } else {
 4134: 			$none_graded = 0;
 4135: 		    }
 4136: 		}
 4137: 
 4138: 		if ($all_graded || $none_graded) {
 4139: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4140: 							   $symb,$cdom,$cnum,
 4141: 							   $udom,$uname);
 4142: 		}
 4143: 	    }
 4144: 
 4145: 	    $result.=&Apache::loncommon::start_data_table_row().
 4146: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4147: 		&Apache::loncommon::end_data_table_row();
 4148: 	    $updateCtr++;
 4149: 	} else {
 4150: 	    push(@noupdate,
 4151: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4152: 	    $noupdateCtr++;
 4153: 	}
 4154:         if ($aggregateflag) {
 4155:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4156: 				  $cdom,$cnum);
 4157:         }
 4158:     }
 4159:     if (@noupdate) {
 4160: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4161: 	my $numcols=scalar(@partid)*4+2;
 4162: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4163: 	    '<td align="center" colspan="'.$numcols.'">'.
 4164: 	    &mt('No Changes Occurred For the Students Below').
 4165: 	    '</td>'.
 4166: 	    &Apache::loncommon::end_data_table_row();
 4167: 	foreach my $line (@noupdate) {
 4168: 	    $result.=
 4169: 		&Apache::loncommon::start_data_table_row().
 4170: 		$line.
 4171: 		&Apache::loncommon::end_data_table_row();
 4172: 	}
 4173:     }
 4174:     $result .= &Apache::loncommon::end_data_table();
 4175:     my $msg = '<p><b>'.
 4176: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4177: 	    $rec_update,$count).'</b><br />'.
 4178: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4179: 	'</b></p>';
 4180:     return $title.$msg.$result;
 4181: }
 4182: 
 4183: sub split_part_type {
 4184:     my ($partstr) = @_;
 4185:     my ($temp,@allparts)=split(/_/,$partstr);
 4186:     my $type=pop(@allparts);
 4187:     my $part=join('_',@allparts);
 4188:     return ($part,$type);
 4189: }
 4190: 
 4191: #------------- end of section for handling grading by section/class ---------
 4192: #
 4193: #----------------------------------------------------------------------------
 4194: 
 4195: 
 4196: #----------------------------------------------------------------------------
 4197: #
 4198: #-------------------------- Next few routines handles grading by csv upload
 4199: #
 4200: #--- Javascript to handle csv upload
 4201: sub csvupload_javascript_reverse_associate {
 4202:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4203:     my $error2=&mt('You need to specify at least one grading field');
 4204:   &js_escape(\$error1);
 4205:   &js_escape(\$error2);
 4206:   return(<<ENDPICK);
 4207:   function verify(vf) {
 4208:     var foundsomething=0;
 4209:     var founduname=0;
 4210:     var foundID=0;
 4211:     var foundclicker=0;
 4212:     for (i=0;i<=vf.nfields.value;i++) {
 4213:       tw=eval('vf.f'+i+'.selectedIndex');
 4214:       if (i==0 && tw!=0) { foundID=1; }
 4215:       if (i==1 && tw!=0) { founduname=1; }
 4216:       if (i==2 && tw!=0) { foundclicker=1; }
 4217:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4218:     }
 4219:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4220: 	alert('$error1');
 4221: 	return;
 4222:     }
 4223:     if (foundsomething==0) {
 4224: 	alert('$error2');
 4225: 	return;
 4226:     }
 4227:     vf.submit();
 4228:   }
 4229:   function flip(vf,tf) {
 4230:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4231:     var i;
 4232:     for (i=0;i<=vf.nfields.value;i++) {
 4233:       //can not pick the same destination field for both name and domain
 4234:       if (((i ==0)||(i ==1)) && 
 4235:           ((tf==0)||(tf==1)) && 
 4236:           (i!=tf) &&
 4237:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4238:         eval('vf.f'+i+'.selectedIndex=0;')
 4239:       }
 4240:     }
 4241:   }
 4242: ENDPICK
 4243: }
 4244: 
 4245: sub csvupload_javascript_forward_associate {
 4246:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4247:     my $error2=&mt('You need to specify at least one grading field');
 4248:   &js_escape(\$error1);
 4249:   &js_escape(\$error2);
 4250:   return(<<ENDPICK);
 4251:   function verify(vf) {
 4252:     var foundsomething=0;
 4253:     var founduname=0;
 4254:     var foundID=0;
 4255:     var foundclicker=0;
 4256:     for (i=0;i<=vf.nfields.value;i++) {
 4257:       tw=eval('vf.f'+i+'.selectedIndex');
 4258:       if (tw==1) { foundID=1; }
 4259:       if (tw==2) { founduname=1; }
 4260:       if (tw==3) { foundclicker=1; } 
 4261:       if (tw>4) { foundsomething=1; }
 4262:     }
 4263:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4264: 	alert('$error1');
 4265: 	return;
 4266:     }
 4267:     if (foundsomething==0) {
 4268: 	alert('$error2');
 4269: 	return;
 4270:     }
 4271:     vf.submit();
 4272:   }
 4273:   function flip(vf,tf) {
 4274:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4275:     var i;
 4276:     //can not pick the same destination field twice
 4277:     for (i=0;i<=vf.nfields.value;i++) {
 4278:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4279:         eval('vf.f'+i+'.selectedIndex=0;')
 4280:       }
 4281:     }
 4282:   }
 4283: ENDPICK
 4284: }
 4285: 
 4286: sub csvuploadmap_header {
 4287:     my ($request,$symb,$datatoken,$distotal)= @_;
 4288:     my $javascript;
 4289:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4290: 	$javascript=&csvupload_javascript_reverse_associate();
 4291:     } else {
 4292: 	$javascript=&csvupload_javascript_forward_associate();
 4293:     }
 4294: 
 4295:     $symb = &Apache::lonenc::check_encrypt($symb);
 4296:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4297:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4298:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4299:     my $reverse=&mt("Reverse Association");
 4300:     $request->print(<<ENDPICK);
 4301: <br />
 4302: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4303: <input type="hidden" name="associate"  value="" />
 4304: <input type="hidden" name="phase"      value="three" />
 4305: <input type="hidden" name="datatoken"  value="$datatoken" />
 4306: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4307: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4308: <input type="hidden" name="upfile_associate" 
 4309:                                        value="$env{'form.upfile_associate'}" />
 4310: <input type="hidden" name="symb"       value="$symb" />
 4311: <input type="hidden" name="command"    value="csvuploadoptions" />
 4312: <hr />
 4313: ENDPICK
 4314:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4315:     return '';
 4316: 
 4317: }
 4318: 
 4319: sub csvupload_fields {
 4320:     my ($symb,$errorref) = @_;
 4321:     my (@parts) = &getpartlist($symb,$errorref);
 4322:     if (ref($errorref)) {
 4323:         if ($$errorref) {
 4324:             return;
 4325:         }
 4326:     }
 4327: 
 4328:     my @fields=(['ID','Student/Employee ID'],
 4329: 		['username','Student Username'],
 4330: 		['clicker','Clicker ID'],
 4331: 		['domain','Student Domain']);
 4332:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4333:     foreach my $part (sort(@parts)) {
 4334: 	my @datum;
 4335: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4336: 	my $name=$part;
 4337: 	if  (!$display) { $display = $name; }
 4338: 	@datum=($name,$display);
 4339: 	if ($name=~/^stores_(.*)_awarded/) {
 4340: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4341: 	}
 4342: 	push(@fields,\@datum);
 4343:     }
 4344:     return (@fields);
 4345: }
 4346: 
 4347: sub csvuploadmap_footer {
 4348:     my ($request,$i,$keyfields) =@_;
 4349:     my $buttontext = &mt('Assign Grades');
 4350:     $request->print(<<ENDPICK);
 4351: </table>
 4352: <input type="hidden" name="nfields" value="$i" />
 4353: <input type="hidden" name="keyfields" value="$keyfields" />
 4354: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4355: </form>
 4356: ENDPICK
 4357: }
 4358: 
 4359: sub checkforfile_js {
 4360:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4361:     &js_escape(\$alertmsg);
 4362:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4363:     function checkUpload(formname) {
 4364: 	if (formname.upfile.value == "") {
 4365: 	    alert("$alertmsg");
 4366: 	    return false;
 4367: 	}
 4368: 	formname.submit();
 4369:     }
 4370: CSVFORMJS
 4371:     return $result;
 4372: }
 4373: 
 4374: sub upcsvScores_form {
 4375:     my ($request,$symb) = @_;
 4376:     if (!$symb) {return '';}
 4377:     my $result=&checkforfile_js();
 4378:     $result.=&Apache::loncommon::start_data_table().
 4379:              &Apache::loncommon::start_data_table_header_row().
 4380:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4381:              &Apache::loncommon::end_data_table_header_row().
 4382:              &Apache::loncommon::start_data_table_row().'<td>';
 4383:     my $upload=&mt("Upload Scores");
 4384:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4385:     my $ignore=&mt('Ignore First Line');
 4386:     $symb = &Apache::lonenc::check_encrypt($symb);
 4387:     $result.=<<ENDUPFORM;
 4388: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4389: <input type="hidden" name="symb" value="$symb" />
 4390: <input type="hidden" name="command" value="csvuploadmap" />
 4391: $upfile_select
 4392: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4393: </form>
 4394: ENDUPFORM
 4395:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4396:                            &mt("How do I create a CSV file from a spreadsheet")).
 4397:              '</td>'.
 4398:             &Apache::loncommon::end_data_table_row().
 4399:             &Apache::loncommon::end_data_table();
 4400:     return $result;
 4401: }
 4402: 
 4403: 
 4404: sub csvuploadmap {
 4405:     my ($request,$symb)= @_;
 4406:     if (!$symb) {return '';}
 4407: 
 4408:     my $datatoken;
 4409:     if (!$env{'form.datatoken'}) {
 4410: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4411:     } else {
 4412: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4413:         if ($datatoken ne '') {
 4414: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4415:         }
 4416:     }
 4417:     my @records=&Apache::loncommon::upfile_record_sep();
 4418:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4419:     my ($i,$keyfields);
 4420:     if (@records) {
 4421:         my $fieldserror;
 4422: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4423:         if ($fieldserror) {
 4424:             $request->print(&navmap_errormsg());
 4425:             return;
 4426:         }
 4427: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4428: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4429: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4430: 							  \@fields);
 4431: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4432: 	    chop($keyfields);
 4433: 	} else {
 4434: 	    unshift(@fields,['none','']);
 4435: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4436: 							    \@fields);
 4437:             foreach my $rec (@records) {
 4438:                 my %temp = &Apache::loncommon::record_sep($rec);
 4439:                 if (%temp) {
 4440:                     $keyfields=join(',',sort(keys(%temp)));
 4441:                     last;
 4442:                 }
 4443:             }
 4444: 	}
 4445:     }
 4446:     &csvuploadmap_footer($request,$i,$keyfields);
 4447: 
 4448:     return '';
 4449: }
 4450: 
 4451: sub csvuploadoptions {
 4452:     my ($request,$symb)= @_;
 4453:     my $overwrite=&mt('Overwrite any existing score');
 4454:     $request->print(<<ENDPICK);
 4455: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4456: <input type="hidden" name="command"    value="csvuploadassign" />
 4457: <p>
 4458: <label>
 4459:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4460:    $overwrite
 4461: </label>
 4462: </p>
 4463: ENDPICK
 4464:     my %fields=&get_fields();
 4465:     if (!defined($fields{'domain'})) {
 4466: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4467: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4468:     }
 4469:     foreach my $key (sort(keys(%env))) {
 4470: 	if ($key !~ /^form\.(.*)$/) { next; }
 4471: 	my $cleankey=$1;
 4472: 	if ($cleankey eq 'command') { next; }
 4473: 	$request->print('<input type="hidden" name="'.$cleankey.
 4474: 			'"  value="'.$env{$key}.'" />'."\n");
 4475:     }
 4476:     # FIXME do a check for any duplicated user ids...
 4477:     # FIXME do a check for any invalid user ids?...
 4478:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4479: <hr /></form>'."\n");
 4480:     return '';
 4481: }
 4482: 
 4483: sub get_fields {
 4484:     my %fields;
 4485:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4486:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4487: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4488: 	    if ($env{'form.f'.$i} ne 'none') {
 4489: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4490: 	    }
 4491: 	} else {
 4492: 	    if ($env{'form.f'.$i} ne 'none') {
 4493: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4494: 	    }
 4495: 	}
 4496:     }
 4497:     return %fields;
 4498: }
 4499: 
 4500: sub csvuploadassign {
 4501:     my ($request,$symb)= @_;
 4502:     if (!$symb) {return '';}
 4503:     my $error_msg = '';
 4504:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4505:     if ($datatoken ne '') { 
 4506:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4507:     }
 4508:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4509:     my %fields=&get_fields();
 4510:     my $courseid=$env{'request.course.id'};
 4511:     my ($classlist) = &getclasslist('all',0);
 4512:     my @notallowed;
 4513:     my @skipped;
 4514:     my @warnings;
 4515:     my $countdone=0;
 4516:     foreach my $grade (@gradedata) {
 4517: 	my %entries=&Apache::loncommon::record_sep($grade);
 4518: 	my $domain;
 4519: 	if ($entries{$fields{'domain'}}) {
 4520: 	    $domain=$entries{$fields{'domain'}};
 4521: 	} else {
 4522: 	    $domain=$env{'form.default_domain'};
 4523: 	}
 4524: 	$domain=~s/\s//g;
 4525: 	my $username=$entries{$fields{'username'}};
 4526: 	$username=~s/\s//g;
 4527: 	if (!$username) {
 4528: 	    my $id=$entries{$fields{'ID'}};
 4529: 	    $id=~s/\s//g;
 4530:             if ($id ne '') {
 4531: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4532: 	        $username=$ids{$id};
 4533:             } else {
 4534:                 if ($entries{$fields{'clicker'}}) {
 4535:                     my $clicker = $entries{$fields{'clicker'}};
 4536:                     $clicker=~s/\s//g;
 4537:                     if ($clicker ne '') {
 4538:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4539:                         if ($clickers{$clicker} ne '') {  
 4540:                             my $match = 0;
 4541:                             my @inclass;
 4542:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4543:                                 if (exists($$classlist{"$poss:$domain"})) {
 4544:                                     $username = $poss;
 4545:                                     push(@inclass,$poss);
 4546:                                     $match ++;
 4547:                                     
 4548:                                 }
 4549:                             }
 4550:                             if ($match > 1) {
 4551:                                 undef($username); 
 4552:                                 $request->print('<p class="LC_warning">'.
 4553:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4554:                                                 $clicker,join(', ',@inclass)).'</p>');
 4555:                             }
 4556:                         }
 4557:                     }
 4558:                 }
 4559:             }
 4560: 	}
 4561: 	if (!exists($$classlist{"$username:$domain"})) {
 4562: 	    my $id=$entries{$fields{'ID'}};
 4563: 	    $id=~s/\s//g;
 4564:             my $clicker = $entries{$fields{'clicker'}};
 4565:             $clicker=~s/\s//g;
 4566:             if ($clicker) {
 4567:                 push(@skipped,"$clicker:$domain");
 4568: 	    } elsif ($id) {
 4569: 		push(@skipped,"$id:$domain");
 4570: 	    } else {
 4571: 		push(@skipped,"$username:$domain");
 4572: 	    }
 4573: 	    next;
 4574: 	}
 4575: 	my $usec=$classlist->{"$username:$domain"}[5];
 4576: 	if (!&canmodify($usec)) {
 4577: 	    push(@notallowed,"$username:$domain");
 4578: 	    next;
 4579: 	}
 4580: 	my %points;
 4581: 	my %grades;
 4582: 	foreach my $dest (keys(%fields)) {
 4583: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4584: 		$dest eq 'domain') { next; }
 4585: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4586: 	    if ($dest=~/stores_(.*)_points/) {
 4587: 		my $part=$1;
 4588: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4589: 					      $symb,$domain,$username);
 4590:                 if ($wgt) {
 4591:                     $entries{$fields{$dest}}=~s/\s//g;
 4592:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4593:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4594:                                           : 'correct_by_override';
 4595:                     if ($pcr>1) {
 4596:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4597:                     }
 4598:                     $grades{"resource.$part.awarded"}=$pcr;
 4599:                     $grades{"resource.$part.solved"}=$award;
 4600:                     $points{$part}=1;
 4601:                 } else {
 4602:                     $error_msg = "<br />" .
 4603:                         &mt("Some point values were assigned"
 4604:                             ." for problems with a weight "
 4605:                             ."of zero. These values were "
 4606:                             ."ignored.");
 4607:                 }
 4608: 	    } else {
 4609: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4610: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4611: 		my $store_key=$dest;
 4612: 		$store_key=~s/^stores/resource/;
 4613: 		$store_key=~s/_/\./g;
 4614: 		$grades{$store_key}=$entries{$fields{$dest}};
 4615: 	    }
 4616: 	}
 4617: 	if (! %grades) { 
 4618:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4619:         } else {
 4620: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4621: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4622: 					   $env{'request.course.id'},
 4623: 					   $domain,$username);
 4624: 	   if ($result eq 'ok') {
 4625: # Successfully stored
 4626: 	      $request->print('.');
 4627: # Remove from grading queue
 4628:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4629:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4630:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4631:                                              $domain,$username);
 4632:               $countdone++;
 4633:            } else {
 4634: 	      $request->print("<p><span class=\"LC_error\">".
 4635:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4636:                                   "$username:$domain",$result)."</span></p>");
 4637: 	   }
 4638: 	   $request->rflush();
 4639:         }
 4640:     }
 4641:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4642:     if (@warnings) {
 4643:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4644:         $request->print(join(', ',@warnings));
 4645:     }
 4646:     if (@skipped) {
 4647: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4648:         $request->print(join(', ',@skipped));
 4649:     }
 4650:     if (@notallowed) {
 4651: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4652: 	$request->print(join(', ',@notallowed));
 4653:     }
 4654:     $request->print("<br />\n");
 4655:     return $error_msg;
 4656: }
 4657: #------------- end of section for handling csv file upload ---------
 4658: #
 4659: #-------------------------------------------------------------------
 4660: #
 4661: #-------------- Next few routines handle grading by page/sequence
 4662: #
 4663: #--- Select a page/sequence and a student to grade
 4664: sub pickStudentPage {
 4665:     my ($request,$symb) = @_;
 4666: 
 4667:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4668:     &js_escape(\$alertmsg);
 4669:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4670: 
 4671: function checkPickOne(formname) {
 4672:     if (radioSelection(formname.student) == null) {
 4673: 	alert("$alertmsg");
 4674: 	return;
 4675:     }
 4676:     ptr = pullDownSelection(formname.selectpage);
 4677:     formname.page.value = formname["page"+ptr].value;
 4678:     formname.title.value = formname["title"+ptr].value;
 4679:     formname.submit();
 4680: }
 4681: 
 4682: LISTJAVASCRIPT
 4683:     &commonJSfunctions($request);
 4684: 
 4685:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4686:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4687:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4688: 
 4689:     my $result='<h3><span class="LC_info">&nbsp;'.
 4690: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4691: 
 4692:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4693:     my $map_error;
 4694:     my ($titles,$symbx) = &getSymbMap($map_error);
 4695:     if ($map_error) {
 4696:         $request->print(&navmap_errormsg());
 4697:         return; 
 4698:     }
 4699:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4700: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4701: #    my $type=($curpage =~ /\.(page|sequence)/);
 4702: 
 4703:     # Collection of hidden fields
 4704:     my $ctr=0;
 4705:     foreach (@$titles) {
 4706:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4707:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4708:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4709:         $ctr++;
 4710:     }
 4711:     $result.='<input type="hidden" name="page" />'."\n".
 4712:         '<input type="hidden" name="title" />'."\n";
 4713: 
 4714:     $result.=&build_section_inputs();
 4715:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4716:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4717: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4718: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4719: 
 4720:     # Show grading options
 4721:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4722:     my $select = '<select name="selectpage">'."\n";
 4723:     $ctr=0;
 4724:     foreach (@$titles) {
 4725: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4726: 	$select.='<option value="'.$ctr.'"'.
 4727: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4728: 	    '>'.$showtitle.'</option>'."\n";
 4729: 	$ctr++;
 4730:     }
 4731:     $select.= '</select>';
 4732: 
 4733:     $result.=
 4734:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4735:        .$select
 4736:        .&Apache::lonhtmlcommon::row_closure();
 4737: 
 4738:     $result.=
 4739:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4740:        .'<label><input type="radio" name="vProb" value="no"'
 4741:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4742:        .'<label><input type="radio" name="vProb" value="yes" />'
 4743:            .&mt('yes').'</label>'."\n"
 4744:        .&Apache::lonhtmlcommon::row_closure();
 4745: 
 4746:     $result.=
 4747:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4748:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4749:            .&mt('none').' </label>'."\n"
 4750:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4751:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4752:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4753:            .&mt('all submissions with details').' </label>'
 4754:        .&Apache::lonhtmlcommon::row_closure();
 4755:     
 4756:     $result.=
 4757:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4758:        .'<input type="text" name="CODE" value="" />'
 4759:        .&Apache::lonhtmlcommon::row_closure(1)
 4760:        .&Apache::lonhtmlcommon::end_pick_box();
 4761: 
 4762:     # Show list of students to select for grading
 4763:     $result.='<br /><input type="button" '.
 4764:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4765: 
 4766:     $request->print($result);
 4767: 
 4768:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4769: 	&Apache::loncommon::start_data_table().
 4770: 	&Apache::loncommon::start_data_table_header_row().
 4771: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4772: 	'<th>'.&nameUserString('header').'</th>'.
 4773: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4774: 	'<th>'.&nameUserString('header').'</th>'.
 4775: 	&Apache::loncommon::end_data_table_header_row();
 4776:  
 4777:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4778:     my $ptr = 1;
 4779:     foreach my $student (sort 
 4780: 			 {
 4781: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4782: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4783: 			     }
 4784: 			     return $a cmp $b;
 4785: 			 } (keys(%$fullname))) {
 4786: 	my ($uname,$udom) = split(/:/,$student);
 4787: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4788:                                   : '</td>');
 4789: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4790: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4791: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4792: 	$studentTable.=
 4793: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4794:                          : '');
 4795: 	$ptr++;
 4796:     }
 4797:     if ($ptr%2 == 0) {
 4798: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4799: 	    &Apache::loncommon::end_data_table_row();
 4800:     }
 4801:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4802:     $studentTable.='<input type="button" '.
 4803:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4804: 
 4805:     $request->print($studentTable);
 4806: 
 4807:     return '';
 4808: }
 4809: 
 4810: sub getSymbMap {
 4811:     my ($map_error) = @_;
 4812:     my $navmap = Apache::lonnavmaps::navmap->new();
 4813:     unless (ref($navmap)) {
 4814:         if (ref($map_error)) {
 4815:             $$map_error = 'navmap';
 4816:         }
 4817:         return;
 4818:     }
 4819:     my %symbx = ();
 4820:     my @titles = ();
 4821:     my $minder = 0;
 4822: 
 4823:     # Gather every sequence that has problems.
 4824:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4825: 					       1,0,1);
 4826:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4827: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4828: 	    my $title = $minder.'.'.
 4829: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4830: 	    push(@titles, $title); # minder in case two titles are identical
 4831: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4832: 	    $minder++;
 4833: 	}
 4834:     }
 4835:     return \@titles,\%symbx;
 4836: }
 4837: 
 4838: #
 4839: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4840: sub displayPage {
 4841:     my ($request,$symb) = @_;
 4842:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4843:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4844:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4845:     my $pageTitle = $env{'form.page'};
 4846:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4847:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4848:     my $usec=$classlist->{$env{'form.student'}}[5];
 4849: 
 4850:     #need to make sure we have the correct data for later EXT calls, 
 4851:     #thus invalidate the cache
 4852:     &Apache::lonnet::devalidatecourseresdata(
 4853:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4854:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4855:     &Apache::lonnet::clear_EXT_cache_status();
 4856: 
 4857:     if (!&canview($usec)) {
 4858:         $request->print(
 4859:             '<span class="LC_warning">'.
 4860:             &mt('Unable to view requested student. ([_1])',
 4861:                     $env{'form.student'}).
 4862:             '</span>');
 4863:         return;
 4864:     }
 4865:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4866:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4867: 	'</h3>'."\n";
 4868:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4869:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4870: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4871:     } else {
 4872: 	delete($env{'form.CODE'});
 4873:     }
 4874:     &sub_page_js($request);
 4875:     $request->print($result);
 4876: 
 4877:     my $navmap = Apache::lonnavmaps::navmap->new();
 4878:     unless (ref($navmap)) {
 4879:         $request->print(&navmap_errormsg());
 4880:         return;
 4881:     }
 4882:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4883:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4884:     if (!$map) {
 4885: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4886: 	return; 
 4887:     }
 4888:     my $iterator = $navmap->getIterator($map->map_start(),
 4889: 					$map->map_finish());
 4890: 
 4891:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4892: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4893: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4894: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4895: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4896: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4897: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4898: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4899: 
 4900:     if (defined($env{'form.CODE'})) {
 4901: 	$studentTable.=
 4902: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4903:     }
 4904:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4905: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4906: 
 4907:     $studentTable.='&nbsp;<span class="LC_info">'.
 4908:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4909:         '</span>'."\n".
 4910: 	&Apache::loncommon::start_data_table().
 4911: 	&Apache::loncommon::start_data_table_header_row().
 4912: 	'<th>'.&mt('Prob.').'</th>'.
 4913: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4914: 	&Apache::loncommon::end_data_table_header_row();
 4915: 
 4916:     &Apache::lonxml::clear_problem_counter();
 4917:     my ($depth,$question,$prob) = (1,1,1);
 4918:     $iterator->next(); # skip the first BEGIN_MAP
 4919:     my $curRes = $iterator->next(); # for "current resource"
 4920:     while ($depth > 0) {
 4921:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4922:         if($curRes == $iterator->END_MAP) { $depth--; }
 4923: 
 4924:         if (ref($curRes) && $curRes->is_problem()) {
 4925: 	    my $parts = $curRes->parts();
 4926:             my $title = $curRes->compTitle();
 4927: 	    my $symbx = $curRes->symb();
 4928: 	    $studentTable.=
 4929: 		&Apache::loncommon::start_data_table_row().
 4930: 		'<td align="center" valign="top" >'.$prob.
 4931: 		(scalar(@{$parts}) == 1 ? '' 
 4932: 		                        : '<br />('.&mt('[_1]parts',
 4933: 							scalar(@{$parts}).'&nbsp;').')'
 4934: 		 ).
 4935: 		 '</td>';
 4936: 	    $studentTable.='<td valign="top">';
 4937: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4938: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4939: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4940: 					     undef,'both',\%form);
 4941: 	    } else {
 4942: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4943: 		$companswer =~ s|<form(.*?)>||g;
 4944: 		$companswer =~ s|</form>||g;
 4945: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4946: #		    $companswer =~ s/$1/ /ms;
 4947: #		    $request->print('match='.$1."<br />\n");
 4948: #		}
 4949: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4950: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4951: 	    }
 4952: 
 4953: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4954: 
 4955: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4956: 		if ($record{'version'} eq '') {
 4957: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4958: 		} else {
 4959: 		    my %responseType = ();
 4960: 		    foreach my $partid (@{$parts}) {
 4961: 			my @responseIds =$curRes->responseIds($partid);
 4962: 			my @responseType =$curRes->responseType($partid);
 4963: 			my %responseIds;
 4964: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4965: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4966: 			}
 4967: 			$responseType{$partid} = \%responseIds;
 4968: 		    }
 4969: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4970: 
 4971: 		}
 4972: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4973: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4974:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 4975: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4976: 									$env{'request.course.id'},
 4977: 									'','.submission',undef,
 4978:                                                                         $usec,$identifier);
 4979:  
 4980: 	    }
 4981: 	    if (&canmodify($usec)) {
 4982:             $studentTable.=&gradeBox_start();
 4983: 		foreach my $partid (@{$parts}) {
 4984: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4985: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4986: 		    $question++;
 4987: 		}
 4988:             $studentTable.=&gradeBox_end();
 4989: 		$prob++;
 4990: 	    }
 4991: 	    $studentTable.='</td></tr>';
 4992: 
 4993: 	}
 4994:         $curRes = $iterator->next();
 4995:     }
 4996: 
 4997:     $studentTable.=
 4998:         '</table>'."\n".
 4999:         '<input type="button" value="'.&mt('Save').'" '.
 5000:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5001:         '</form>'."\n";
 5002:     $request->print($studentTable);
 5003: 
 5004:     return '';
 5005: }
 5006: 
 5007: sub displaySubByDates {
 5008:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5009:     my $isCODE=0;
 5010:     my $isTask = ($symb =~/\.task$/);
 5011:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5012:     my $studentTable=&Apache::loncommon::start_data_table().
 5013: 	&Apache::loncommon::start_data_table_header_row().
 5014: 	'<th>'.&mt('Date/Time').'</th>'.
 5015: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5016:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5017: 	'<th>'.&mt('Submission').'</th>'.
 5018: 	'<th>'.&mt('Status').'</th>'.
 5019: 	&Apache::loncommon::end_data_table_header_row();
 5020:     my ($version);
 5021:     my %mark;
 5022:     my %orders;
 5023:     $mark{'correct_by_student'} = $checkIcon;
 5024:     if (!exists($$record{'1:timestamp'})) {
 5025: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5026:     }
 5027: 
 5028:     my $interaction;
 5029:     my $no_increment = 1;
 5030:     my (%lastrndseed,%lasttype);
 5031:     for ($version=1;$version<=$$record{'version'};$version++) {
 5032: 	my $timestamp = 
 5033: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5034: 	if (exists($$record{$version.':resource.0.version'})) {
 5035: 	    $interaction = $$record{$version.':resource.0.version'};
 5036: 	}
 5037:         if ($isTask && $env{'form.previousversion'}) {
 5038:             next unless ($interaction == $env{'form.previousversion'});
 5039:         }
 5040: 	my $where = ($isTask ? "$version:resource.$interaction"
 5041: 		             : "$version:resource");
 5042: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5043: 	    '<td>'.$timestamp.'</td>';
 5044: 	if ($isCODE) {
 5045: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5046: 	}
 5047:         if ($isTask) {
 5048:             $studentTable.='<td>'.$interaction.'</td>';
 5049:         }
 5050: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5051: 	my @displaySub = ();
 5052: 	foreach my $partid (@{$parts}) {
 5053:             my ($hidden,$type);
 5054:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5055:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5056:                 $hidden = 1;
 5057:             }
 5058: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5059: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5060: 	    
 5061: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5062: 	    my $display_part=&get_display_part($partid,$symb);
 5063: 	    foreach my $matchKey (@matchKey) {
 5064: 		if (exists($$record{$version.':'.$matchKey}) &&
 5065: 		    $$record{$version.':'.$matchKey} ne '') {
 5066:                     
 5067: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5068: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5069:                     $displaySub[0].='<span class="LC_nobreak">';
 5070:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5071:                                    .' <span class="LC_internal_info">'
 5072:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5073:                                    .'</span>'
 5074:                                    .' <b>';
 5075:                     if ($hidden) {
 5076:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5077:                     } else {
 5078:                         my ($trial,$rndseed,$newvariation);
 5079:                         if ($type eq 'randomizetry') {
 5080:                             $trial = $$record{"$where.$partid.tries"};
 5081:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5082:                         }
 5083: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5084: 			    $displaySub[0].=&mt('Trial not counted');
 5085: 		        } else {
 5086: 			    $displaySub[0].=&mt('Trial: [_1]',
 5087: 					    $$record{"$where.$partid.tries"});
 5088:                             if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5089:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5090:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5091:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5092:                                 }
 5093:                             }
 5094:                             $lastrndseed{$partid} = $rndseed;
 5095:                             $lasttype{$partid} = $type;
 5096: 		        }
 5097: 		        my $responseType=($isTask ? 'Task'
 5098:                                               : $responseType->{$partid}->{$responseId});
 5099: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5100: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5101: 			    $orders{$partid}->{$responseId}=
 5102: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5103:                                            $no_increment,$type,$trial,$rndseed);
 5104: 		        }
 5105: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5106: 		        $displaySub[0].='&nbsp; '.
 5107: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5108:                     }
 5109: 		}
 5110: 	    }
 5111: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5112: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5113: 				    $$record{"$where.$partid.checkedin"},
 5114: 				    $$record{"$where.$partid.checkedin.slot"}).
 5115: 					'<br />';
 5116: 	    }
 5117: 	    if (exists $$record{"$where.$partid.award"}) {
 5118: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5119: 		    lc($$record{"$where.$partid.award"}).' '.
 5120: 		    $mark{$$record{"$where.$partid.solved"}}.
 5121: 		    '<br />';
 5122: 	    }
 5123: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5124: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5125: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5126: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5127: 		$displaySub[2].=
 5128: 		    $$record{"$version:resource.$partid.regrader"}.
 5129: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5130: 	    }
 5131: 	}
 5132: 	# needed because old essay regrader has not parts info
 5133: 	if (exists $$record{"$version:resource.regrader"}) {
 5134: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5135: 	}
 5136: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5137: 	if ($displaySub[2]) {
 5138: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5139: 	}
 5140: 	$studentTable.='&nbsp;</td>'.
 5141: 	    &Apache::loncommon::end_data_table_row();
 5142:     }
 5143:     $studentTable.=&Apache::loncommon::end_data_table();
 5144:     return $studentTable;
 5145: }
 5146: 
 5147: sub updateGradeByPage {
 5148:     my ($request,$symb) = @_;
 5149: 
 5150:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5151:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5152:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5153:     my $pageTitle = $env{'form.page'};
 5154:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5155:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5156:     my $usec=$classlist->{$env{'form.student'}}[5];
 5157:     if (!&canmodify($usec)) {
 5158: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5159: 	return;
 5160:     }
 5161:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5162:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5163: 	'</h3>'."\n";
 5164: 
 5165:     $request->print($result);
 5166: 
 5167: 
 5168:     my $navmap = Apache::lonnavmaps::navmap->new();
 5169:     unless (ref($navmap)) {
 5170:         $request->print(&navmap_errormsg());
 5171:         return;
 5172:     }
 5173:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5174:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5175:     if (!$map) {
 5176: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5177: 	return; 
 5178:     }
 5179:     my $iterator = $navmap->getIterator($map->map_start(),
 5180: 					$map->map_finish());
 5181: 
 5182:     my $studentTable=
 5183: 	&Apache::loncommon::start_data_table().
 5184: 	&Apache::loncommon::start_data_table_header_row().
 5185: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5186: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5187: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5188: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5189: 	&Apache::loncommon::end_data_table_header_row();
 5190: 
 5191:     $iterator->next(); # skip the first BEGIN_MAP
 5192:     my $curRes = $iterator->next(); # for "current resource"
 5193:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5194:     while ($depth > 0) {
 5195:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5196:         if($curRes == $iterator->END_MAP) { $depth--; }
 5197: 
 5198:         if (ref($curRes) && $curRes->is_problem()) {
 5199: 	    my $parts = $curRes->parts();
 5200:             my $title = $curRes->compTitle();
 5201: 	    my $symbx = $curRes->symb();
 5202: 	    $studentTable.=
 5203: 		&Apache::loncommon::start_data_table_row().
 5204: 		'<td align="center" valign="top" >'.$prob.
 5205: 		(scalar(@{$parts}) == 1 ? '' 
 5206:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5207: 		.')').'</td>';
 5208: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5209: 
 5210: 	    my %newrecord=();
 5211: 	    my @displayPts=();
 5212:             my %aggregate = ();
 5213:             my $aggregateflag = 0;
 5214:             if ($env{'form.HIDE'.$prob}) {
 5215:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5216:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5217:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5218:                 $hideflag += $numchgs;
 5219:             }
 5220: 	    foreach my $partid (@{$parts}) {
 5221: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5222: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5223: 
 5224: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5225: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5226: 		my $partial = $newpts/$wgt;
 5227: 		my $score;
 5228: 		if ($partial > 0) {
 5229: 		    $score = 'correct_by_override';
 5230: 		} elsif ($newpts ne '') { #empty is taken as 0
 5231: 		    $score = 'incorrect_by_override';
 5232: 		}
 5233: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5234: 		if ($dropMenu eq 'excused') {
 5235: 		    $partial = '';
 5236: 		    $score = 'excused';
 5237: 		} elsif ($dropMenu eq 'reset status'
 5238: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5239: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5240: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5241: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5242: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5243: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5244: 		    $changeflag++;
 5245: 		    $newpts = '';
 5246:                     
 5247:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5248:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5249:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5250:                     if ($aggtries > 0) {
 5251:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5252:                         $aggregateflag = 1;
 5253:                     }
 5254: 		}
 5255: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5256: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5257: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5258: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5259: 		    '&nbsp;<br />';
 5260: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5261: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5262: 		    '&nbsp;<br />';
 5263: 		$question++;
 5264: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5265: 
 5266: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5267: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5268: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5269: 		    if (scalar(keys(%newrecord)) > 0);
 5270: 
 5271: 		$changeflag++;
 5272: 	    }
 5273: 	    if (scalar(keys(%newrecord)) > 0) {
 5274: 		my %record = 
 5275: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5276: 					     $udom,$uname);
 5277: 
 5278: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5279: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5280: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5281: 		    $newrecord{'resource.CODE'} = '';
 5282: 		}
 5283: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5284: 					$udom,$uname);
 5285: 		%record = &Apache::lonnet::restore($symbx,
 5286: 						   $env{'request.course.id'},
 5287: 						   $udom,$uname);
 5288: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5289: 					     $cdom,$cnum,$udom,$uname);
 5290: 	    }
 5291: 	    
 5292:             if ($aggregateflag) {
 5293:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5294:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5295:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5296:             }
 5297: 
 5298: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5299: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5300: 		&Apache::loncommon::end_data_table_row();
 5301: 
 5302: 	    $prob++;
 5303: 	}
 5304:         $curRes = $iterator->next();
 5305:     }
 5306: 
 5307:     $studentTable.=&Apache::loncommon::end_data_table();
 5308:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5309: 		  &mt('The scores were changed for [quant,_1,problem].',
 5310: 		  $changeflag).'<br />');
 5311:     my $hidemsg=($hideflag == 0 ? '' :
 5312:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5313:                      $hideflag).'<br />');
 5314:     $request->print($hidemsg.$grademsg.$studentTable);
 5315: 
 5316:     return '';
 5317: }
 5318: 
 5319: #-------- end of section for handling grading by page/sequence ---------
 5320: #
 5321: #-------------------------------------------------------------------
 5322: 
 5323: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5324: #
 5325: #------ start of section for handling grading by page/sequence ---------
 5326: 
 5327: =pod
 5328: 
 5329: =head1 Bubble sheet grading routines
 5330: 
 5331:   For this documentation:
 5332: 
 5333:    'scanline' refers to the full line of characters
 5334:    from the file that we are parsing that represents one entire sheet
 5335: 
 5336:    'bubble line' refers to the data
 5337:    representing the line of bubbles that are on the physical bubblesheet
 5338: 
 5339: 
 5340: The overall process is that a scanned in bubblesheet data is uploaded
 5341: into a course. When a user wants to grade, they select a
 5342: sequence/folder of resources, a file of bubblesheet info, and pick
 5343: one of the predefined configurations for what each scanline looks
 5344: like.
 5345: 
 5346: Next each scanline is checked for any errors of either 'missing
 5347: bubbles' (it's an error because it may have been mis-scanned
 5348: because too light bubbling), 'double bubble' (each bubble line should
 5349: have no more than one letter picked), invalid or duplicated CODE,
 5350: invalid student/employee ID
 5351: 
 5352: If the CODE option is used that determines the randomization of the
 5353: homework problems, either way the student/employee ID is looked up into a
 5354: username:domain.
 5355: 
 5356: During the validation phase the instructor can choose to skip scanlines. 
 5357: 
 5358: After the validation phase, there are now 3 bubblesheet files
 5359: 
 5360:   scantron_original_filename (unmodified original file)
 5361:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5362:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5363: 
 5364: Also there is a separate hash nohist_scantrondata that contains extra
 5365: correction information that isn't representable in the bubblesheet
 5366: file (see &scantron_getfile() for more information)
 5367: 
 5368: After all scanlines are either valid, marked as valid or skipped, then
 5369: foreach line foreach problem in the picked sequence, an ssi request is
 5370: made that simulates a user submitting their selected letter(s) against
 5371: the homework problem.
 5372: 
 5373: =over 4
 5374: 
 5375: 
 5376: 
 5377: =item defaultFormData
 5378: 
 5379:   Returns html hidden inputs used to hold context/default values.
 5380: 
 5381:  Arguments:
 5382:   $symb - $symb of the current resource 
 5383: 
 5384: =cut
 5385: 
 5386: sub defaultFormData {
 5387:     my ($symb)=@_;
 5388:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5389: }
 5390: 
 5391: 
 5392: =pod 
 5393: 
 5394: =item getSequenceDropDown
 5395: 
 5396:    Return html dropdown of possible sequences to grade
 5397:  
 5398:  Arguments:
 5399:    $symb - $symb of the current resource
 5400:    $map_error - ref to scalar which will container error if
 5401:                 $navmap object is unavailable in &getSymbMap().
 5402: 
 5403: =cut
 5404: 
 5405: sub getSequenceDropDown {
 5406:     my ($symb,$map_error)=@_;
 5407:     my $result='<select name="selectpage">'."\n";
 5408:     my ($titles,$symbx) = &getSymbMap($map_error);
 5409:     if (ref($map_error)) {
 5410:         return if ($$map_error);
 5411:     }
 5412:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5413:     my $ctr=0;
 5414:     foreach (@$titles) {
 5415: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5416: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5417: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5418: 	    '>'.$showtitle.'</option>'."\n";
 5419: 	$ctr++;
 5420:     }
 5421:     $result.= '</select>';
 5422:     return $result;
 5423: }
 5424: 
 5425: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5426:                                    # key is zero-based index - 0, 1, 2 ...
 5427: 
 5428: my %first_bubble_line;             # First bubble line no. for each bubble.
 5429: 
 5430: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5431:                                    # matchresponse or rankresponse, where 
 5432:                                    # an individual response can have multiple 
 5433:                                    # lines
 5434: 
 5435: my %responsetype_per_response;     # responsetype for each response
 5436: 
 5437: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5438:                                    # numbered response. Needed when randomorder
 5439:                                    # or randompick are in use. Key is ID, value 
 5440:                                    # is response number.
 5441: 
 5442: # Save and restore the bubble lines array to the form env.
 5443: 
 5444: 
 5445: sub save_bubble_lines {
 5446:     foreach my $line (keys(%bubble_lines_per_response)) {
 5447: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5448: 	$env{"form.scantron.first_bubble_line.$line"} =
 5449: 	    $first_bubble_line{$line};
 5450:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5451:             $subdivided_bubble_lines{$line};
 5452:         $env{"form.scantron.responsetype.$line"} =
 5453:             $responsetype_per_response{$line};
 5454:     }
 5455:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5456:         my $line = $masterseq_id_responsenum{$resid};
 5457:         $env{"form.scantron.residpart.$line"} = $resid;
 5458:     }
 5459: }
 5460: 
 5461: 
 5462: sub restore_bubble_lines {
 5463:     my $line = 0;
 5464:     %bubble_lines_per_response = ();
 5465:     %masterseq_id_responsenum = ();
 5466:     while ($env{"form.scantron.bubblelines.$line"}) {
 5467: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5468: 	$bubble_lines_per_response{$line} = $value;
 5469: 	$first_bubble_line{$line}  =
 5470: 	    $env{"form.scantron.first_bubble_line.$line"};
 5471:         $subdivided_bubble_lines{$line} =
 5472:             $env{"form.scantron.sub_bubblelines.$line"};
 5473:         $responsetype_per_response{$line} =
 5474:             $env{"form.scantron.responsetype.$line"};
 5475:         my $id = $env{"form.scantron.residpart.$line"};
 5476:         $masterseq_id_responsenum{$id} = $line;
 5477: 	$line++;
 5478:     }
 5479: }
 5480: 
 5481: =pod 
 5482: 
 5483: =item scantron_filenames
 5484: 
 5485:    Returns a list of the scantron files in the current course 
 5486: 
 5487: =cut
 5488: 
 5489: sub scantron_filenames {
 5490:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5491:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5492:     my $getpropath = 1;
 5493:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5494:                                                         $cname,$getpropath);
 5495:     my @possiblenames;
 5496:     if (ref($dirlist) eq 'ARRAY') {
 5497:         foreach my $filename (sort(@{$dirlist})) {
 5498: 	    ($filename)=split(/&/,$filename);
 5499: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5500: 	    $filename=~s/^scantron_orig_//;
 5501: 	    push(@possiblenames,$filename);
 5502:         }
 5503:     }
 5504:     return @possiblenames;
 5505: }
 5506: 
 5507: =pod 
 5508: 
 5509: =item scantron_uploads
 5510: 
 5511:    Returns  html drop-down list of scantron files in current course.
 5512: 
 5513:  Arguments:
 5514:    $file2grade - filename to set as selected in the dropdown
 5515: 
 5516: =cut
 5517: 
 5518: sub scantron_uploads {
 5519:     my ($file2grade) = @_;
 5520:     my $result=	'<select name="scantron_selectfile">';
 5521:     $result.="<option></option>";
 5522:     foreach my $filename (sort(&scantron_filenames())) {
 5523: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5524:     }
 5525:     $result.="</select>";
 5526:     return $result;
 5527: }
 5528: 
 5529: =pod 
 5530: 
 5531: =item scantron_scantab
 5532: 
 5533:   Returns html drop down of the scantron formats in the scantronformat.tab
 5534:   file.
 5535: 
 5536: =cut
 5537: 
 5538: sub scantron_scantab {
 5539:     my $result='<select name="scantron_format">'."\n";
 5540:     $result.='<option></option>'."\n";
 5541:     my @lines = &get_scantronformat_file();
 5542:     if (@lines > 0) {
 5543:         foreach my $line (@lines) {
 5544:             next if (($line =~ /^\#/) || ($line eq ''));
 5545: 	    my ($name,$descrip)=split(/:/,$line);
 5546: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5547:         }
 5548:     }
 5549:     $result.='</select>'."\n";
 5550:     return $result;
 5551: }
 5552: 
 5553: =pod
 5554: 
 5555: =item get_scantronformat_file
 5556: 
 5557:   Returns an array containing lines from the scantron format file for
 5558:   the domain of the course.
 5559: 
 5560:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5561:   lines are from this file.
 5562: 
 5563:   Otherwise, if a default.tab has been published in RES space by the 
 5564:   domainconfig user, lines are from this file.
 5565: 
 5566:   Otherwise, fall back to getting lines from the legacy file on the
 5567:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5568: 
 5569: =cut
 5570: 
 5571: sub get_scantronformat_file {
 5572:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5573:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5574:     my $gottab = 0;
 5575:     my @lines;
 5576:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5577:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5578:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5579:             if ($formatfile ne '-1') {
 5580:                 @lines = split("\n",$formatfile,-1);
 5581:                 $gottab = 1;
 5582:             }
 5583:         }
 5584:     }
 5585:     if (!$gottab) {
 5586:         my $confname = $cdom.'-domainconfig';
 5587:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5588:         my $formatfile =  &Apache::lonnet::getfile($default);
 5589:         if ($formatfile ne '-1') {
 5590:             @lines = split("\n",$formatfile,-1);
 5591:             $gottab = 1;
 5592:         }
 5593:     }
 5594:     if (!$gottab) {
 5595:         my @domains = &Apache::lonnet::current_machine_domains();
 5596:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5597:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5598:             @lines = <$fh>;
 5599:             close($fh);
 5600:         } else {
 5601:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5602:             @lines = <$fh>;
 5603:             close($fh);
 5604:         }
 5605:     }
 5606:     return @lines;
 5607: }
 5608: 
 5609: =pod 
 5610: 
 5611: =item scantron_CODElist
 5612: 
 5613:   Returns html drop down of the saved CODE lists from current course,
 5614:   generated from earlier printings.
 5615: 
 5616: =cut
 5617: 
 5618: sub scantron_CODElist {
 5619:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5620:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5621:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5622:     my $namechoice='<option></option>';
 5623:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5624: 	if ($name =~ /^error: 2 /) { next; }
 5625: 	if ($name =~ /^type\0/) { next; }
 5626: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5627:     }
 5628:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5629:     return $namechoice;
 5630: }
 5631: 
 5632: =pod 
 5633: 
 5634: =item scantron_CODEunique
 5635: 
 5636:   Returns the html for "Each CODE to be used once" radio.
 5637: 
 5638: =cut
 5639: 
 5640: sub scantron_CODEunique {
 5641:     my $result='<span class="LC_nobreak">
 5642:                  <label><input type="radio" name="scantron_CODEunique"
 5643:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5644:                 </span>
 5645:                 <span class="LC_nobreak">
 5646:                  <label><input type="radio" name="scantron_CODEunique"
 5647:                         value="no" />'.&mt('No').' </label>
 5648:                 </span>';
 5649:     return $result;
 5650: }
 5651: 
 5652: =pod 
 5653: 
 5654: =item scantron_selectphase
 5655: 
 5656:   Generates the initial screen to start the bubblesheet process.
 5657:   Allows for - starting a grading run.
 5658:              - downloading existing scan data (original, corrected
 5659:                                                 or skipped info)
 5660: 
 5661:              - uploading new scan data
 5662: 
 5663:  Arguments:
 5664:   $r          - The Apache request object
 5665:   $file2grade - name of the file that contain the scanned data to score
 5666: 
 5667: =cut
 5668: 
 5669: sub scantron_selectphase {
 5670:     my ($r,$file2grade,$symb) = @_;
 5671:     if (!$symb) {return '';}
 5672:     my $map_error;
 5673:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5674:     if ($map_error) {
 5675:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5676:         return;
 5677:     }
 5678:     my $default_form_data=&defaultFormData($symb);
 5679:     my $file_selector=&scantron_uploads($file2grade);
 5680:     my $format_selector=&scantron_scantab();
 5681:     my $CODE_selector=&scantron_CODElist();
 5682:     my $CODE_unique=&scantron_CODEunique();
 5683:     my $result;
 5684: 
 5685:     $ssi_error = 0;
 5686: 
 5687:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5688:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5689: 
 5690: 	# Chunk of form to prompt for a scantron file upload.
 5691: 
 5692:         $r->print('
 5693:     <br />
 5694:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5695:        '.&Apache::loncommon::start_data_table_header_row().'
 5696:             <th>
 5697:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5698:             </th>
 5699:        '.&Apache::loncommon::end_data_table_header_row().'
 5700:        '.&Apache::loncommon::start_data_table_row().'
 5701:             <td>
 5702: ');
 5703:     my $default_form_data=&defaultFormData($symb);
 5704:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5705:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5706:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5707:     &js_escape(\$alertmsg);
 5708:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5709:     function checkUpload(formname) {
 5710: 	if (formname.upfile.value == "") {
 5711: 	    alert("'.$alertmsg.'");
 5712: 	    return false;
 5713: 	}
 5714: 	formname.submit();
 5715:     }'));
 5716:     $r->print('
 5717:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5718:                 '.$default_form_data.'
 5719:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5720:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5721:                 <input name="command" value="scantronupload_save" type="hidden" />
 5722:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5723:                 <br />
 5724:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5725:               </form>
 5726: ');
 5727: 
 5728:         $r->print('
 5729:             </td>
 5730:        '.&Apache::loncommon::end_data_table_row().'
 5731:        '.&Apache::loncommon::end_data_table().'
 5732: ');
 5733:     }
 5734: 
 5735:     # Chunk of form to prompt for a file to grade and how:
 5736: 
 5737:     $result.= '
 5738:     <br />
 5739:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5740:     <input type="hidden" name="command" value="scantron_warning" />
 5741:     '.$default_form_data.'
 5742:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5743:        '.&Apache::loncommon::start_data_table_header_row().'
 5744:             <th colspan="2">
 5745:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5746:             </th>
 5747:        '.&Apache::loncommon::end_data_table_header_row().'
 5748:        '.&Apache::loncommon::start_data_table_row().'
 5749:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5750:        '.&Apache::loncommon::end_data_table_row().'
 5751:        '.&Apache::loncommon::start_data_table_row().'
 5752:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5753:        '.&Apache::loncommon::end_data_table_row().'
 5754:        '.&Apache::loncommon::start_data_table_row().'
 5755:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5756:        '.&Apache::loncommon::end_data_table_row().'
 5757:        '.&Apache::loncommon::start_data_table_row().'
 5758:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5759:        '.&Apache::loncommon::end_data_table_row().'
 5760:        '.&Apache::loncommon::start_data_table_row().'
 5761:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5762:        '.&Apache::loncommon::end_data_table_row().'
 5763:        '.&Apache::loncommon::start_data_table_row().'
 5764: 	    <td> '.&mt('Options:').' </td>
 5765:             <td>
 5766: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5767:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5768:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5769: 	    </td>
 5770:        '.&Apache::loncommon::end_data_table_row().'
 5771:        '.&Apache::loncommon::start_data_table_row().'
 5772:             <td colspan="2">
 5773:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5774:             </td>
 5775:        '.&Apache::loncommon::end_data_table_row().'
 5776:     '.&Apache::loncommon::end_data_table().'
 5777:     </form>
 5778: ';
 5779:    
 5780:     $r->print($result);
 5781: 
 5782: 
 5783: 
 5784:     # Chunk of the form that prompts to view a scoring office file,
 5785:     # corrected file, skipped records in a file.
 5786: 
 5787:     $r->print('
 5788:    <br />
 5789:    <form action="/adm/grades" name="scantron_download">
 5790:      '.$default_form_data.'
 5791:      <input type="hidden" name="command" value="scantron_download" />
 5792:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5793:        '.&Apache::loncommon::start_data_table_header_row().'
 5794:               <th>
 5795:                 &nbsp;'.&mt('Download a scoring office file').'
 5796:               </th>
 5797:        '.&Apache::loncommon::end_data_table_header_row().'
 5798:        '.&Apache::loncommon::start_data_table_row().'
 5799:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5800:                 <br />
 5801:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5802:        '.&Apache::loncommon::end_data_table_row().'
 5803:      '.&Apache::loncommon::end_data_table().'
 5804:    </form>
 5805:    <br />
 5806: ');
 5807: 
 5808:     &Apache::lonpickcode::code_list($r,2);
 5809: 
 5810:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5811:              $default_form_data."\n".
 5812:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5813:              &Apache::loncommon::start_data_table_header_row()."\n".
 5814:              '<th colspan="2">
 5815:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5816:              '</th>'."\n".
 5817:               &Apache::loncommon::end_data_table_header_row()."\n".
 5818:               &Apache::loncommon::start_data_table_row()."\n".
 5819:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5820:               '<td> '.$sequence_selector.' </td>'.
 5821:               &Apache::loncommon::end_data_table_row()."\n".
 5822:               &Apache::loncommon::start_data_table_row()."\n".
 5823:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5824:               '<td> '.$file_selector.' </td>'."\n".
 5825:               &Apache::loncommon::end_data_table_row()."\n".
 5826:               &Apache::loncommon::start_data_table_row()."\n".
 5827:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5828:               '<td> '.$format_selector.' </td>'."\n".
 5829:               &Apache::loncommon::end_data_table_row()."\n".
 5830:               &Apache::loncommon::start_data_table_row()."\n".
 5831:               '<td> '.&mt('Options').' </td>'."\n".
 5832:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5833:               &Apache::loncommon::end_data_table_row()."\n".
 5834:               &Apache::loncommon::start_data_table_row()."\n".
 5835:               '<td colspan="2">'."\n".
 5836:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5837:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5838:               '</td>'."\n".
 5839:               &Apache::loncommon::end_data_table_row()."\n".
 5840:               &Apache::loncommon::end_data_table()."\n".
 5841:               '</form><br />');
 5842:     return;
 5843: }
 5844: 
 5845: =pod
 5846: 
 5847: =item get_scantron_config
 5848: 
 5849:    Parse and return the bubblesheet configuration line selected as a
 5850:    hash of configuration file fields.
 5851: 
 5852:  Arguments:
 5853:     which - the name of the configuration to parse from the file.
 5854: 
 5855: 
 5856:  Returns:
 5857:             If the named configuration is not in the file, an empty
 5858:             hash is returned.
 5859:     a hash with the fields
 5860:       name         - internal name for the this configuration setup
 5861:       description  - text to display to operator that describes this config
 5862:       CODElocation - if 0 or the string 'none'
 5863:                           - no CODE exists for this config
 5864:                      if -1 || the string 'letter'
 5865:                           - a CODE exists for this config and is
 5866:                             a string of letters
 5867:                      Unsupported value (but planned for future support)
 5868:                           if a positive integer
 5869:                                - The CODE exists as the first n items from
 5870:                                  the question section of the form
 5871:                           if the string 'number'
 5872:                                - The CODE exists for this config and is
 5873:                                  a string of numbers
 5874:       CODEstart   - (only matter if a CODE exists) column in the line where
 5875:                      the CODE starts
 5876:       CODElength  - length of the CODE
 5877:       IDstart     - column where the student/employee ID starts
 5878:       IDlength    - length of the student/employee ID info
 5879:       Qstart      - column where the information from the bubbled
 5880:                     'questions' start
 5881:       Qlength     - number of columns comprising a single bubble line from
 5882:                     the sheet. (usually either 1 or 10)
 5883:       Qon         - either a single character representing the character used
 5884:                     to signal a bubble was chosen in the positional setup, or
 5885:                     the string 'letter' if the letter of the chosen bubble is
 5886:                     in the final, or 'number' if a number representing the
 5887:                     chosen bubble is in the file (1->A 0->J)
 5888:       Qoff        - the character used to represent that a bubble was
 5889:                     left blank
 5890:       PaperID     - if the scanning process generates a unique number for each
 5891:                     sheet scanned the column that this ID number starts in
 5892:       PaperIDlength - number of columns that comprise the unique ID number
 5893:                       for the sheet of paper
 5894:       FirstName   - column that the first name starts in
 5895:       FirstNameLength - number of columns that the first name spans
 5896:  
 5897:       LastName    - column that the last name starts in
 5898:       LastNameLength - number of columns that the last name spans
 5899:       BubblesPerRow - number of bubbles available in each row used to 
 5900:                       bubble an answer. (If not specified, 10 assumed).
 5901: 
 5902: =cut
 5903: 
 5904: sub get_scantron_config {
 5905:     my ($which) = @_;
 5906:     my @lines = &get_scantronformat_file();
 5907:     my %config;
 5908:     #FIXME probably should move to XML it has already gotten a bit much now
 5909:     foreach my $line (@lines) {
 5910: 	my ($name,$descrip)=split(/:/,$line);
 5911: 	if ($name ne $which ) { next; }
 5912: 	chomp($line);
 5913: 	my @config=split(/:/,$line);
 5914: 	$config{'name'}=$config[0];
 5915: 	$config{'description'}=$config[1];
 5916: 	$config{'CODElocation'}=$config[2];
 5917: 	$config{'CODEstart'}=$config[3];
 5918: 	$config{'CODElength'}=$config[4];
 5919: 	$config{'IDstart'}=$config[5];
 5920: 	$config{'IDlength'}=$config[6];
 5921: 	$config{'Qstart'}=$config[7];
 5922:  	$config{'Qlength'}=$config[8];
 5923: 	$config{'Qoff'}=$config[9];
 5924: 	$config{'Qon'}=$config[10];
 5925: 	$config{'PaperID'}=$config[11];
 5926: 	$config{'PaperIDlength'}=$config[12];
 5927: 	$config{'FirstName'}=$config[13];
 5928: 	$config{'FirstNamelength'}=$config[14];
 5929: 	$config{'LastName'}=$config[15];
 5930: 	$config{'LastNamelength'}=$config[16];
 5931:         $config{'BubblesPerRow'}=$config[17];
 5932: 	last;
 5933:     }
 5934:     return %config;
 5935: }
 5936: 
 5937: =pod 
 5938: 
 5939: =item username_to_idmap
 5940: 
 5941:     creates a hash keyed by student/employee ID with values of the corresponding
 5942:     student username:domain. If a single ID occurs for more than one student,
 5943:     the status of the student is checked, and if Active, the value in the hash
 5944:     will be set to the Active student.
 5945: 
 5946:   Arguments:
 5947: 
 5948:     $classlist - reference to the class list hash. This is a hash
 5949:                  keyed by student name:domain  whose elements are references
 5950:                  to arrays containing various chunks of information
 5951:                  about the student. (See loncoursedata for more info).
 5952: 
 5953:   Returns
 5954:     %idmap - the constructed hash
 5955: 
 5956: =cut
 5957: 
 5958: sub username_to_idmap {
 5959:     my ($classlist)= @_;
 5960:     my %idmap;
 5961:     foreach my $student (keys(%$classlist)) {
 5962:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 5963:         unless ($id eq '') {
 5964:             if (!exists($idmap{$id})) {
 5965:                 $idmap{$id} = $student;
 5966:             } else {
 5967:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 5968:                 if ($status eq 'Active') {
 5969:                     $idmap{$id} = $student;
 5970:                 }
 5971:             }
 5972:         }
 5973:     }
 5974:     return %idmap;
 5975: }
 5976: 
 5977: =pod
 5978: 
 5979: =item scantron_fixup_scanline
 5980: 
 5981:    Process a requested correction to a scanline.
 5982: 
 5983:   Arguments:
 5984:     $scantron_config   - hash from &get_scantron_config()
 5985:     $scan_data         - hash of correction information 
 5986:                           (see &scantron_getfile())
 5987:     $line              - existing scanline
 5988:     $whichline         - line number of the passed in scanline
 5989:     $field             - type of change to process 
 5990:                          (either 
 5991:                           'ID'     -> correct the student/employee ID
 5992:                           'CODE'   -> correct the CODE
 5993:                           'answer' -> fixup the submitted answers)
 5994:     
 5995:    $args               - hash of additional info,
 5996:                           - 'ID' 
 5997:                                'newid' -> studentID to use in replacement
 5998:                                           of existing one
 5999:                           - 'CODE' 
 6000:                                'CODE_ignore_dup' - set to true if duplicates
 6001:                                                    should be ignored.
 6002: 	                       'CODE' - is new code or 'use_unfound'
 6003:                                         if the existing unfound code should
 6004:                                         be used as is
 6005:                           - 'answer'
 6006:                                'response' - new answer or 'none' if blank
 6007:                                'question' - the bubble line to change
 6008:                                'questionnum' - the question identifier,
 6009:                                                may include subquestion. 
 6010: 
 6011:   Returns:
 6012:     $line - the modified scanline
 6013: 
 6014:   Side effects: 
 6015:     $scan_data - may be updated
 6016: 
 6017: =cut
 6018: 
 6019: 
 6020: sub scantron_fixup_scanline {
 6021:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6022:     if ($field eq 'ID') {
 6023: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6024: 	    return ($line,1,'New value too large');
 6025: 	}
 6026: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6027: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6028: 				     $args->{'newid'});
 6029: 	}
 6030: 	substr($line,$$scantron_config{'IDstart'}-1,
 6031: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6032: 	if ($args->{'newid'}=~/^\s*$/) {
 6033: 	    &scan_data($scan_data,"$whichline.user",
 6034: 		       $args->{'username'}.':'.$args->{'domain'});
 6035: 	}
 6036:     } elsif ($field eq 'CODE') {
 6037: 	if ($args->{'CODE_ignore_dup'}) {
 6038: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6039: 	}
 6040: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6041: 	if ($args->{'CODE'} ne 'use_unfound') {
 6042: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6043: 		return ($line,1,'New CODE value too large');
 6044: 	    }
 6045: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6046: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6047: 	    }
 6048: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6049: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6050: 	}
 6051:     } elsif ($field eq 'answer') {
 6052: 	my $length=$scantron_config->{'Qlength'};
 6053: 	my $off=$scantron_config->{'Qoff'};
 6054: 	my $on=$scantron_config->{'Qon'};
 6055: 	my $answer=${off}x$length;
 6056: 	if ($args->{'response'} eq 'none') {
 6057: 	    &scan_data($scan_data,
 6058: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6059: 	} else {
 6060: 	    if ($on eq 'letter') {
 6061: 		my @alphabet=('A'..'Z');
 6062: 		$answer=$alphabet[$args->{'response'}];
 6063: 	    } elsif ($on eq 'number') {
 6064: 		$answer=$args->{'response'}+1;
 6065: 		if ($answer == 10) { $answer = '0'; }
 6066: 	    } else {
 6067: 		substr($answer,$args->{'response'},1)=$on;
 6068: 	    }
 6069: 	    &scan_data($scan_data,
 6070: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6071: 	}
 6072: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6073: 	substr($line,$where-1,$length)=$answer;
 6074:     }
 6075:     return $line;
 6076: }
 6077: 
 6078: =pod
 6079: 
 6080: =item scan_data
 6081: 
 6082:     Edit or look up  an item in the scan_data hash.
 6083: 
 6084:   Arguments:
 6085:     $scan_data  - The hash (see scantron_getfile)
 6086:     $key        - shorthand of the key to edit (actual key is
 6087:                   scantronfilename_key).
 6088:     $data        - New value of the hash entry.
 6089:     $delete      - If true, the entry is removed from the hash.
 6090: 
 6091:   Returns:
 6092:     The new value of the hash table field (undefined if deleted).
 6093: 
 6094: =cut
 6095: 
 6096: 
 6097: sub scan_data {
 6098:     my ($scan_data,$key,$value,$delete)=@_;
 6099:     my $filename=$env{'form.scantron_selectfile'};
 6100:     if (defined($value)) {
 6101: 	$scan_data->{$filename.'_'.$key} = $value;
 6102:     }
 6103:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6104:     return $scan_data->{$filename.'_'.$key};
 6105: }
 6106: 
 6107: # ----- These first few routines are general use routines.----
 6108: 
 6109: # Return the number of occurences of a pattern in a string.
 6110: 
 6111: sub occurence_count {
 6112:     my ($string, $pattern) = @_;
 6113: 
 6114:     my @matches = ($string =~ /$pattern/g);
 6115: 
 6116:     return scalar(@matches);
 6117: }
 6118: 
 6119: 
 6120: # Take a string known to have digits and convert all the
 6121: # digits into letters in the range J,A..I.
 6122: 
 6123: sub digits_to_letters {
 6124:     my ($input) = @_;
 6125: 
 6126:     my @alphabet = ('J', 'A'..'I');
 6127: 
 6128:     my @input    = split(//, $input);
 6129:     my $output ='';
 6130:     for (my $i = 0; $i < scalar(@input); $i++) {
 6131: 	if ($input[$i] =~ /\d/) {
 6132: 	    $output .= $alphabet[$input[$i]];
 6133: 	} else {
 6134: 	    $output .= $input[$i];
 6135: 	}
 6136:     }
 6137:     return $output;
 6138: }
 6139: 
 6140: =pod 
 6141: 
 6142: =item scantron_parse_scanline
 6143: 
 6144:   Decodes a scanline from the selected bubblesheet file
 6145: 
 6146:  Arguments:
 6147:     line             - The text of the bubblesheet file line to process
 6148:     whichline        - Line number
 6149:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6150:     scan_data        - Hash of extra information about the scanline
 6151:                        (see scantron_getfile for more information)
 6152:     just_header      - True if should not process question answers but only
 6153:                        the stuff to the left of the answers.
 6154:     randomorder      - True if randomorder in use
 6155:     randompick       - True if randompick in use
 6156:     sequence         - Exam folder URL
 6157:     master_seq       - Ref to array containing symbs in exam folder
 6158:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6159:                        (corresponding values are resource objects)
 6160:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6161:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6162:                        are refs to an array of resource objects, ordered
 6163:                        according to order used for CODE, when randomorder
 6164:                        and or randompick are in use.
 6165:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6166:                        for current line to question number used for same question
 6167:                         in "Master Sequence" (as seen by Course Coordinator).
 6168:     startline        - Ref to hash where key is question number (0 is first)
 6169:                        and value is number of first bubble line for current 
 6170:                        student or code-based randompick and/or randomorder.
 6171:     totalref         - Ref of scalar used to score total number of bubble
 6172:                        lines needed for responses in a scan line (used when
 6173:                        randompick in use. 
 6174:     
 6175:  Returns:
 6176:    Hash containing the result of parsing the scanline
 6177: 
 6178:    Keys are all proceeded by the string 'scantron.'
 6179: 
 6180:        CODE    - the CODE in use for this scanline
 6181:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6182:                  by the operator
 6183:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6184:                             CODEs were selected, but the usage has been
 6185:                             forced by the operator
 6186:        ID  - student/employee ID
 6187:        PaperID - if used, the ID number printed on the sheet when the 
 6188:                  paper was scanned
 6189:        FirstName - first name from the sheet
 6190:        LastName  - last name from the sheet
 6191: 
 6192:      if just_header was not true these key may also exist
 6193: 
 6194:        missingerror - a list of bubble ranges that are considered to be answers
 6195:                       to a single question that don't have any bubbles filled in.
 6196:                       Of the form questionnumber:firstbubblenumber:count.
 6197:        doubleerror  - a list of bubble ranges that are considered to be answers
 6198:                       to a single question that have more than one bubble filled in.
 6199:                       Of the form questionnumber::firstbubblenumber:count
 6200:    
 6201:                 In the above, count is the number of bubble responses in the
 6202:                 input line needed to represent the possible answers to the question.
 6203:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6204:                 per line would have count = 2.
 6205: 
 6206:        maxquest     - the number of the last bubble line that was parsed
 6207: 
 6208:        (<number> starts at 1)
 6209:        <number>.answer - zero or more letters representing the selected
 6210:                          letters from the scanline for the bubble line 
 6211:                          <number>.
 6212:                          if blank there was either no bubble or there where
 6213:                          multiple bubbles, (consult the keys missingerror and
 6214:                          doubleerror if this is an error condition)
 6215: 
 6216: =cut
 6217: 
 6218: sub scantron_parse_scanline {
 6219:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6220:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6221:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6222: 
 6223:     my %record;
 6224:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6225:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6226: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6227: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6228: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6229: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6230: 	    $record{'scantron.CODE'}=substr($data,
 6231: 					    $$scantron_config{'CODEstart'}-1,
 6232: 					    $$scantron_config{'CODElength'});
 6233: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6234: 		$record{'scantron.useCODE'}=1;
 6235: 	    }
 6236: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6237: 		$record{'scantron.CODE_ignore_dup'}=1;
 6238: 	    }
 6239: 	} else {
 6240: 	    #FIXME interpret first N questions
 6241: 	}
 6242:     }
 6243:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6244: 				  $$scantron_config{'IDlength'});
 6245:     $record{'scantron.PaperID'}=
 6246: 	substr($data,$$scantron_config{'PaperID'}-1,
 6247: 	       $$scantron_config{'PaperIDlength'});
 6248:     $record{'scantron.FirstName'}=
 6249: 	substr($data,$$scantron_config{'FirstName'}-1,
 6250: 	       $$scantron_config{'FirstNamelength'});
 6251:     $record{'scantron.LastName'}=
 6252: 	substr($data,$$scantron_config{'LastName'}-1,
 6253: 	       $$scantron_config{'LastNamelength'});
 6254:     if ($just_header) { return \%record; }
 6255: 
 6256:     my @alphabet=('A'..'Z');
 6257:     my $questnum=0;
 6258:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6259: 
 6260:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6261:     if ($randompick || $randomorder) {
 6262:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6263:                                          $master_seq,$symb_to_resource,
 6264:                                          $partids_by_symb,$orderedforcode,
 6265:                                          $respnumlookup,$startline);
 6266:         if ($total) {
 6267:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6268:         }
 6269:         if (ref($totalref)) {
 6270:             $$totalref = $total;
 6271:         }
 6272:     }
 6273:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6274:     chomp($questions);		# Get rid of any trailing \n.
 6275:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6276:     while (length($questions)) {
 6277:         my $answers_needed;
 6278:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6279:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6280:         } else {
 6281: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6282:         }
 6283:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6284:                              || 1;
 6285:         $questnum++;
 6286:         my $quest_id = $questnum;
 6287:         my $currentquest = substr($questions,0,$answer_length);
 6288:         $questions       = substr($questions,$answer_length);
 6289:         if (length($currentquest) < $answer_length) { next; }
 6290: 
 6291:         my $subdivided;
 6292:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6293:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6294:         } else {
 6295:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6296:         }
 6297:         if ($subdivided =~ /,/) {
 6298:             my $subquestnum = 1;
 6299:             my $subquestions = $currentquest;
 6300:             my @subanswers_needed = split(/,/,$subdivided);
 6301:             foreach my $subans (@subanswers_needed) {
 6302:                 my $subans_length =
 6303:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6304:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6305:                 $subquestions   = substr($subquestions,$subans_length);
 6306:                 $quest_id = "$questnum.$subquestnum";
 6307:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6308:                     ($$scantron_config{'Qon'} eq 'number')) {
 6309:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6310:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6311:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6312:                         $randomorder,$randompick,$respnumlookup);
 6313:                 } else {
 6314:                     $ansnum = &scantron_validator_positional($ansnum,
 6315:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6316:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6317:                         $randomorder,$randompick,$respnumlookup);
 6318:                 }
 6319:                 $subquestnum ++;
 6320:             }
 6321:         } else {
 6322:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6323:                 ($$scantron_config{'Qon'} eq 'number')) {
 6324:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6325:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6326:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6327:                     $randomorder,$randompick,$respnumlookup);
 6328:             } else {
 6329:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6330:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6331:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6332:                     $randomorder,$randompick,$respnumlookup);
 6333:             }
 6334:         }
 6335:     }
 6336:     $record{'scantron.maxquest'}=$questnum;
 6337:     return \%record;
 6338: }
 6339: 
 6340: sub get_master_seq {
 6341:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6342:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6343:                    (ref($symb_to_resource) eq 'HASH'));
 6344:     my $resource_error;
 6345:     foreach my $resource (@{$resources}) {
 6346:         my $ressymb;
 6347:         if (ref($resource)) {
 6348:             $ressymb = $resource->symb();
 6349:             push(@{$master_seq},$ressymb);
 6350:             $symb_to_resource->{$ressymb} = $resource;
 6351:         } else {
 6352:             $resource_error = 1;
 6353:             last;
 6354:         }
 6355:     }
 6356:     return $resource_error;
 6357: }
 6358: 
 6359: sub get_respnum_lookups {
 6360:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6361:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6362:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6363:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6364:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6365:                    (ref($startline) eq 'HASH'));
 6366:     my ($user,$scancode);
 6367:     if ((exists($record->{'scantron.CODE'})) &&
 6368:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6369:         $scancode = $record->{'scantron.CODE'};
 6370:     } else {
 6371:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6372:     }
 6373:     my @mapresources =
 6374:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6375:                      $orderedforcode);
 6376:     my $total = 0;
 6377:     my $count = 0;
 6378:     foreach my $resource (@mapresources) {
 6379:         my $id = $resource->id();
 6380:         my $symb = $resource->symb();
 6381:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6382:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6383:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6384:                 if ($respnum ne '') {
 6385:                     $respnumlookup->{$count} = $respnum;
 6386:                     $startline->{$count} = $total;
 6387:                     $total += $bubble_lines_per_response{$respnum};
 6388:                     $count ++;
 6389:                 }
 6390:             }
 6391:         }
 6392:     }
 6393:     return $total;
 6394: }
 6395: 
 6396: sub scantron_validator_lettnum {
 6397:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6398:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6399:         $randompick,$respnumlookup) = @_;
 6400: 
 6401:     # Qon 'letter' implies for each slot in currquest we have:
 6402:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6403:     #    about anything else (esp. a value of Qoff) for missing
 6404:     #    bubbles.
 6405:     #
 6406:     # Qon 'number' implies each slot gives a digit that indexes the
 6407:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6408:     #    and * or ? for double bubbles on a single line.
 6409:     #
 6410: 
 6411:     my $matchon;
 6412:     if ($$scantron_config{'Qon'} eq 'letter') {
 6413:         $matchon = '[A-Z]';
 6414:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6415:         $matchon = '\d';
 6416:     }
 6417:     my $occurrences = 0;
 6418:     my $responsenum = $questnum-1;
 6419:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6420:        $responsenum = $respnumlookup->{$questnum-1} 
 6421:     }
 6422:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6423:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6424:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6425:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6426:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6427:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6428:         my @singlelines = split('',$currquest);
 6429:         foreach my $entry (@singlelines) {
 6430:             $occurrences = &occurence_count($entry,$matchon);
 6431:             if ($occurrences > 1) {
 6432:                 last;
 6433:             }
 6434:         }
 6435:     } else {
 6436:         $occurrences = &occurence_count($currquest,$matchon); 
 6437:     }
 6438:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6439:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6440:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6441:             my $bubble = substr($currquest,$ans,1);
 6442:             if ($bubble =~ /$matchon/ ) {
 6443:                 if ($$scantron_config{'Qon'} eq 'number') {
 6444:                     if ($bubble == 0) {
 6445:                         $bubble = 10; 
 6446:                     }
 6447:                     $record->{"scantron.$ansnum.answer"} = 
 6448:                         $alphabet->[$bubble-1];
 6449:                 } else {
 6450:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6451:                 }
 6452:             } else {
 6453:                 $record->{"scantron.$ansnum.answer"}='';
 6454:             }
 6455:             $ansnum++;
 6456:         }
 6457:     } elsif (!defined($currquest)
 6458:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6459:             || (&occurence_count($currquest,$matchon) == 0)) {
 6460:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6461:             $record->{"scantron.$ansnum.answer"}='';
 6462:             $ansnum++;
 6463:         }
 6464:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6465:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6466:         }
 6467:     } else {
 6468:         if ($$scantron_config{'Qon'} eq 'number') {
 6469:             $currquest = &digits_to_letters($currquest);            
 6470:         }
 6471:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6472:             my $bubble = substr($currquest,$ans,1);
 6473:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6474:             $ansnum++;
 6475:         }
 6476:     }
 6477:     return $ansnum;
 6478: }
 6479: 
 6480: sub scantron_validator_positional {
 6481:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6482:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6483:         $randomorder,$randompick,$respnumlookup) = @_;
 6484: 
 6485:     # Otherwise there's a positional notation;
 6486:     # each bubble line requires Qlength items, and there are filled in
 6487:     # bubbles for each case where there 'Qon' characters.
 6488:     #
 6489: 
 6490:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6491: 
 6492:     # If the split only gives us one element.. the full length of the
 6493:     # answer string, no bubbles are filled in:
 6494: 
 6495:     if ($answers_needed eq '') {
 6496:         return;
 6497:     }
 6498: 
 6499:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6500:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6501:             $record->{"scantron.$ansnum.answer"}='';
 6502:             $ansnum++;
 6503:         }
 6504:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6505:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6506:         }
 6507:     } elsif (scalar(@array) == 2) {
 6508:         my $location = length($array[0]);
 6509:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6510:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6511:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6512:             if ($ans eq $line_num) {
 6513:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6514:             } else {
 6515:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6516:             }
 6517:             $ansnum++;
 6518:          }
 6519:     } else {
 6520:         #  If there's more than one instance of a bubble character
 6521:         #  That's a double bubble; with positional notation we can
 6522:         #  record all the bubbles filled in as well as the
 6523:         #  fact this response consists of multiple bubbles.
 6524:         #
 6525:         my $responsenum = $questnum-1;
 6526:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6527:             $responsenum = $respnumlookup->{$questnum-1}
 6528:         }
 6529:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6530:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6531:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6532:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6533:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6534:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6535:             my $doubleerror = 0;
 6536:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6537:                    (!$doubleerror)) {
 6538:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6539:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6540:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6541:                if (length(@currarray) > 2) {
 6542:                    $doubleerror = 1;
 6543:                } 
 6544:             }
 6545:             if ($doubleerror) {
 6546:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6547:             }
 6548:         } else {
 6549:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6550:         }
 6551:         my $item = $ansnum;
 6552:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6553:             $record->{"scantron.$item.answer"} = '';
 6554:             $item ++;
 6555:         }
 6556: 
 6557:         my @ans=@array;
 6558:         my $i=0;
 6559:         my $increment = 0;
 6560:         while ($#ans) {
 6561:             $i+=length($ans[0]) + $increment;
 6562:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6563:             my $bubble = $i%$$scantron_config{'Qlength'};
 6564:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6565:             shift(@ans);
 6566:             $increment = 1;
 6567:         }
 6568:         $ansnum += $answers_needed;
 6569:     }
 6570:     return $ansnum;
 6571: }
 6572: 
 6573: =pod
 6574: 
 6575: =item scantron_add_delay
 6576: 
 6577:    Adds an error message that occurred during the grading phase to a
 6578:    queue of messages to be shown after grading pass is complete
 6579: 
 6580:  Arguments:
 6581:    $delayqueue  - arrary ref of hash ref of error messages
 6582:    $scanline    - the scanline that caused the error
 6583:    $errormesage - the error message
 6584:    $errorcode   - a numeric code for the error
 6585: 
 6586:  Side Effects:
 6587:    updates the $delayqueue to have a new hash ref of the error
 6588: 
 6589: =cut
 6590: 
 6591: sub scantron_add_delay {
 6592:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6593:     push(@$delayqueue,
 6594: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6595: 	  'ecode' => $errorcode }
 6596: 	 );
 6597: }
 6598: 
 6599: =pod
 6600: 
 6601: =item scantron_find_student
 6602: 
 6603:    Finds the username for the current scanline
 6604: 
 6605:   Arguments:
 6606:    $scantron_record - hash result from scantron_parse_scanline
 6607:    $scan_data       - hash of correction information 
 6608:                       (see &scantron_getfile() form more information)
 6609:    $idmap           - hash from &username_to_idmap()
 6610:    $line            - number of current scanline
 6611:  
 6612:   Returns:
 6613:    Either 'username:domain' or undef if unknown
 6614: 
 6615: =cut
 6616: 
 6617: sub scantron_find_student {
 6618:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6619:     my $scanID=$$scantron_record{'scantron.ID'};
 6620:     if ($scanID =~ /^\s*$/) {
 6621:  	return &scan_data($scan_data,"$line.user");
 6622:     }
 6623:     foreach my $id (keys(%$idmap)) {
 6624:  	if (lc($id) eq lc($scanID)) {
 6625:  	    return $$idmap{$id};
 6626:  	}
 6627:     }
 6628:     return undef;
 6629: }
 6630: 
 6631: =pod
 6632: 
 6633: =item scantron_filter
 6634: 
 6635:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6636:    hidden resources was selected
 6637: 
 6638: =cut
 6639: 
 6640: sub scantron_filter {
 6641:     my ($curres)=@_;
 6642: 
 6643:     if (ref($curres) && $curres->is_problem()) {
 6644: 	# if the user has asked to not have either hidden
 6645: 	# or 'randomout' controlled resources to be graded
 6646: 	# don't include them
 6647: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6648: 	    && $curres->randomout) {
 6649: 	    return 0;
 6650: 	}
 6651: 	return 1;
 6652:     }
 6653:     return 0;
 6654: }
 6655: 
 6656: =pod
 6657: 
 6658: =item scantron_process_corrections
 6659: 
 6660:    Gets correction information out of submitted form data and corrects
 6661:    the scanline
 6662: 
 6663: =cut
 6664: 
 6665: sub scantron_process_corrections {
 6666:     my ($r) = @_;
 6667:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6668:     my ($scanlines,$scan_data)=&scantron_getfile();
 6669:     my $classlist=&Apache::loncoursedata::get_classlist();
 6670:     my $which=$env{'form.scantron_line'};
 6671:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6672:     my ($skip,$err,$errmsg);
 6673:     if ($env{'form.scantron_skip_record'}) {
 6674: 	$skip=1;
 6675:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6676: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6677: 	    $env{'form.scantron_domain'};
 6678: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6679: 	($line,$err,$errmsg)=
 6680: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6681: 				     'ID',{'newid'=>$newid,
 6682: 				    'username'=>$env{'form.scantron_username'},
 6683: 				    'domain'=>$env{'form.scantron_domain'}});
 6684:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6685: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6686: 	my $newCODE;
 6687: 	my %args;
 6688: 	if      ($resolution eq 'use_unfound') {
 6689: 	    $newCODE='use_unfound';
 6690: 	} elsif ($resolution eq 'use_found') {
 6691: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6692: 	} elsif ($resolution eq 'use_typed') {
 6693: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6694: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6695: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6696: 	}
 6697: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6698: 	    $args{'CODE_ignore_dup'}=1;
 6699: 	}
 6700: 	$args{'CODE'}=$newCODE;
 6701: 	($line,$err,$errmsg)=
 6702: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6703: 				     'CODE',\%args);
 6704:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6705: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6706: 	    ($line,$err,$errmsg)=
 6707: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6708: 					 $which,'answer',
 6709: 					 { 'question'=>$question,
 6710: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6711:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6712: 	    if ($err) { last; }
 6713: 	}
 6714:     }
 6715:     if ($err) {
 6716:         $r->print(
 6717:             '<p class="LC_error">'
 6718:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6719:                 $errmsg)
 6720:            .'</p>');
 6721:     } else {
 6722: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6723: 	&scantron_putfile($scanlines,$scan_data);
 6724:     }
 6725: }
 6726: 
 6727: =pod
 6728: 
 6729: =item reset_skipping_status
 6730: 
 6731:    Forgets the current set of remember skipped scanlines (and thus
 6732:    reverts back to considering all lines in the
 6733:    scantron_skipped_<filename> file)
 6734: 
 6735: =cut
 6736: 
 6737: sub reset_skipping_status {
 6738:     my ($scanlines,$scan_data)=&scantron_getfile();
 6739:     &scan_data($scan_data,'remember_skipping',undef,1);
 6740:     &scantron_putfile(undef,$scan_data);
 6741: }
 6742: 
 6743: =pod
 6744: 
 6745: =item start_skipping
 6746: 
 6747:    Marks a scanline to be skipped. 
 6748: 
 6749: =cut
 6750: 
 6751: sub start_skipping {
 6752:     my ($scan_data,$i)=@_;
 6753:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6754:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6755: 	$remembered{$i}=2;
 6756:     } else {
 6757: 	$remembered{$i}=1;
 6758:     }
 6759:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6760: }
 6761: 
 6762: =pod
 6763: 
 6764: =item should_be_skipped
 6765: 
 6766:    Checks whether a scanline should be skipped.
 6767: 
 6768: =cut
 6769: 
 6770: sub should_be_skipped {
 6771:     my ($scanlines,$scan_data,$i)=@_;
 6772:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6773: 	# not redoing old skips
 6774: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6775: 	return 0;
 6776:     }
 6777:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6778: 
 6779:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6780: 	return 0;
 6781:     }
 6782:     return 1;
 6783: }
 6784: 
 6785: =pod
 6786: 
 6787: =item remember_current_skipped
 6788: 
 6789:    Discovers what scanlines are in the scantron_skipped_<filename>
 6790:    file and remembers them into scan_data for later use.
 6791: 
 6792: =cut
 6793: 
 6794: sub remember_current_skipped {
 6795:     my ($scanlines,$scan_data)=&scantron_getfile();
 6796:     my %to_remember;
 6797:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6798: 	if ($scanlines->{'skipped'}[$i]) {
 6799: 	    $to_remember{$i}=1;
 6800: 	}
 6801:     }
 6802: 
 6803:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6804:     &scantron_putfile(undef,$scan_data);
 6805: }
 6806: 
 6807: =pod
 6808: 
 6809: =item check_for_error
 6810: 
 6811:     Checks if there was an error when attempting to remove a specific
 6812:     scantron_.. bubblesheet data file. Prints out an error if
 6813:     something went wrong.
 6814: 
 6815: =cut
 6816: 
 6817: sub check_for_error {
 6818:     my ($r,$result)=@_;
 6819:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6820: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6821:     }
 6822: }
 6823: 
 6824: =pod
 6825: 
 6826: =item scantron_warning_screen
 6827: 
 6828:    Interstitial screen to make sure the operator has selected the
 6829:    correct options before we start the validation phase.
 6830: 
 6831: =cut
 6832: 
 6833: sub scantron_warning_screen {
 6834:     my ($button_text,$symb)=@_;
 6835:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6836:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6837:     my $CODElist;
 6838:     if ($scantron_config{'CODElocation'} &&
 6839: 	$scantron_config{'CODEstart'} &&
 6840: 	$scantron_config{'CODElength'}) {
 6841: 	$CODElist=$env{'form.scantron_CODElist'};
 6842: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6843: 	$CODElist=
 6844: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6845: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6846:     }
 6847:     my $lastbubblepoints;
 6848:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6849:         $lastbubblepoints =
 6850:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6851:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6852:     }
 6853:     return ('
 6854: <p>
 6855: <span class="LC_warning">
 6856: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6857: </p>
 6858: <table>
 6859: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6860: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6861: '.$CODElist.$lastbubblepoints.'
 6862: </table>
 6863: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6864: '.&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>
 6865: 
 6866: <br />
 6867: ');
 6868: }
 6869: 
 6870: =pod
 6871: 
 6872: =item scantron_do_warning
 6873: 
 6874:    Check if the operator has picked something for all required
 6875:    fields. Error out if something is missing.
 6876: 
 6877: =cut
 6878: 
 6879: sub scantron_do_warning {
 6880:     my ($r,$symb)=@_;
 6881:     if (!$symb) {return '';}
 6882:     my $default_form_data=&defaultFormData($symb);
 6883:     $r->print(&scantron_form_start().$default_form_data);
 6884:     if ( $env{'form.selectpage'} eq '' ||
 6885: 	 $env{'form.scantron_selectfile'} eq '' ||
 6886: 	 $env{'form.scantron_format'} eq '' ) {
 6887: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6888: 	if ( $env{'form.selectpage'} eq '') {
 6889: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6890: 	} 
 6891: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6892: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6893: 	} 
 6894: 	if ( $env{'form.scantron_format'} eq '') {
 6895: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6896: 	} 
 6897:     } else {
 6898: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6899:         my $bubbledbyhand=&hand_bubble_option();
 6900: 	$r->print('
 6901: '.$warning.$bubbledbyhand.'
 6902: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6903: <input type="hidden" name="command" value="scantron_validate" />
 6904: ');
 6905:     }
 6906:     $r->print("</form><br />");
 6907:     return '';
 6908: }
 6909: 
 6910: =pod
 6911: 
 6912: =item scantron_form_start
 6913: 
 6914:     html hidden input for remembering all selected grading options
 6915: 
 6916: =cut
 6917: 
 6918: sub scantron_form_start {
 6919:     my ($max_bubble)=@_;
 6920:     my $result= <<SCANTRONFORM;
 6921: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6922:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6923:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6924:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6925:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6926:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6927:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6928:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6929:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6930:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6931: SCANTRONFORM
 6932: 
 6933:   my $line = 0;
 6934:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6935:        my $chunk =
 6936: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6937:        $chunk .=
 6938: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6939:        $chunk .= 
 6940:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6941:        $chunk .=
 6942:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6943:        $chunk .=
 6944:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6945:        $result .= $chunk;
 6946:        $line++;
 6947:     }
 6948:     return $result;
 6949: }
 6950: 
 6951: =pod
 6952: 
 6953: =item scantron_validate_file
 6954: 
 6955:     Dispatch routine for doing validation of a bubblesheet data file.
 6956: 
 6957:     Also processes any necessary information resets that need to
 6958:     occur before validation begins (ignore previous corrections,
 6959:     restarting the skipped records processing)
 6960: 
 6961: =cut
 6962: 
 6963: sub scantron_validate_file {
 6964:     my ($r,$symb) = @_;
 6965:     if (!$symb) {return '';}
 6966:     my $default_form_data=&defaultFormData($symb);
 6967:     
 6968:     # do the detection of only doing skipped records first before we delete
 6969:     # them when doing the corrections reset
 6970:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6971: 	&reset_skipping_status();
 6972:     }
 6973:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6974: 	&remember_current_skipped();
 6975: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6976:     }
 6977: 
 6978:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6979: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6980: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6981: 	&check_for_error($r,&scantron_remove_scan_data());
 6982: 	$env{'form.scantron_options_ignore'}='done';
 6983:     }
 6984: 
 6985:     if ($env{'form.scantron_corrections'}) {
 6986: 	&scantron_process_corrections($r);
 6987:     }
 6988:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6989:     #get the student pick code ready
 6990:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6991:     my $nav_error;
 6992:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6993:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6994:     if ($nav_error) {
 6995:         $r->print(&navmap_errormsg());
 6996:         return '';
 6997:     }
 6998:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6999:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7000:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7001:     }
 7002:     $r->print($result);
 7003:     
 7004:     my @validate_phases=( 'sequence',
 7005: 			  'ID',
 7006: 			  'CODE',
 7007: 			  'doublebubble',
 7008: 			  'missingbubbles');
 7009:     if (!$env{'form.validatepass'}) {
 7010: 	$env{'form.validatepass'} = 0;
 7011:     }
 7012:     my $currentphase=$env{'form.validatepass'};
 7013: 
 7014: 
 7015:     my $stop=0;
 7016:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7017: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7018: 	$r->rflush();
 7019:      
 7020: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7021: 	{
 7022: 	    no strict 'refs';
 7023: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7024: 	}
 7025:     }
 7026:     if (!$stop) {
 7027: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7028: 	$r->print(&mt('Validation process complete.').'<br />'.
 7029:                   $warning.
 7030:                   &mt('Perform verification for each student after storage of submissions?').
 7031:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7032:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7033:                   ('&nbsp;'x3).'<label>'.
 7034:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7035:                   '</label></span><br />'.
 7036:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7037:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7038:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7039:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7040:     } else {
 7041: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7042: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7043:     }
 7044:     if ($stop) {
 7045: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7046: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7047: 	    $r->print(' '.&mt('this error').' <br />');
 7048: 
 7049: 	    $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>');
 7050: 	} else {
 7051:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7052: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7053:             } else {
 7054:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7055:             }
 7056: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7057: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7058: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7059: 	}
 7060:     }
 7061:     $r->print(" </form><br />");
 7062:     return '';
 7063: }
 7064: 
 7065: 
 7066: =pod
 7067: 
 7068: =item scantron_remove_file
 7069: 
 7070:    Removes the requested bubblesheet data file, makes sure that
 7071:    scantron_original_<filename> is never removed
 7072: 
 7073: 
 7074: =cut
 7075: 
 7076: sub scantron_remove_file {
 7077:     my ($which)=@_;
 7078:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7079:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7080:     my $file='scantron_';
 7081:     if ($which eq 'corrected' || $which eq 'skipped') {
 7082: 	$file.=$which.'_';
 7083:     } else {
 7084: 	return 'refused';
 7085:     }
 7086:     $file.=$env{'form.scantron_selectfile'};
 7087:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7088: }
 7089: 
 7090: 
 7091: =pod
 7092: 
 7093: =item scantron_remove_scan_data
 7094: 
 7095:    Removes all scan_data correction for the requested bubblesheet
 7096:    data file.  (In the case that both the are doing skipped records we need
 7097:    to remember the old skipped lines for the time being so that element
 7098:    persists for a while.)
 7099: 
 7100: =cut
 7101: 
 7102: sub scantron_remove_scan_data {
 7103:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7104:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7105:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7106:     my @todelete;
 7107:     my $filename=$env{'form.scantron_selectfile'};
 7108:     foreach my $key (@keys) {
 7109: 	if ($key=~/^\Q$filename\E_/) {
 7110: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7111: 		$key=~/remember_skipping/) {
 7112: 		next;
 7113: 	    }
 7114: 	    push(@todelete,$key);
 7115: 	}
 7116:     }
 7117:     my $result;
 7118:     if (@todelete) {
 7119: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7120: 				       \@todelete,$cdom,$cname);
 7121:     } else {
 7122: 	$result = 'ok';
 7123:     }
 7124:     return $result;
 7125: }
 7126: 
 7127: 
 7128: =pod
 7129: 
 7130: =item scantron_getfile
 7131: 
 7132:     Fetches the requested bubblesheet data file (all 3 versions), and
 7133:     the scan_data hash
 7134:   
 7135:   Arguments:
 7136:     None
 7137: 
 7138:   Returns:
 7139:     2 hash references
 7140: 
 7141:      - first one has 
 7142:          orig      -
 7143:          corrected -
 7144:          skipped   -  each of which points to an array ref of the specified
 7145:                       file broken up into individual lines
 7146:          count     - number of scanlines
 7147:  
 7148:      - second is the scan_data hash possible keys are
 7149:        ($number refers to scanline numbered $number and thus the key affects
 7150:         only that scanline
 7151:         $bubline refers to the specific bubble line element and the aspects
 7152:         refers to that specific bubble line element)
 7153: 
 7154:        $number.user - username:domain to use
 7155:        $number.CODE_ignore_dup 
 7156:                     - ignore the duplicate CODE error 
 7157:        $number.useCODE
 7158:                     - use the CODE in the scanline as is
 7159:        $number.no_bubble.$bubline
 7160:                     - it is valid that there is no bubbled in bubble
 7161:                       at $number $bubline
 7162:        remember_skipping
 7163:                     - a frozen hash containing keys of $number and values
 7164:                       of either 
 7165:                         1 - we are on a 'do skipped records pass' and plan
 7166:                             on processing this line
 7167:                         2 - we are on a 'do skipped records pass' and this
 7168:                             scanline has been marked to skip yet again
 7169: 
 7170: =cut
 7171: 
 7172: sub scantron_getfile {
 7173:     #FIXME really would prefer a scantron directory
 7174:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7175:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7176:     my $lines;
 7177:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7178: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7179:     my %scanlines;
 7180:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7181:     my $temp=$scanlines{'orig'};
 7182:     $scanlines{'count'}=$#$temp;
 7183: 
 7184:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7185: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7186:     if ($lines eq '-1') {
 7187: 	$scanlines{'corrected'}=[];
 7188:     } else {
 7189: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7190:     }
 7191:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7192: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7193:     if ($lines eq '-1') {
 7194: 	$scanlines{'skipped'}=[];
 7195:     } else {
 7196: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7197:     }
 7198:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7199:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7200:     my %scan_data = @tmp;
 7201:     return (\%scanlines,\%scan_data);
 7202: }
 7203: 
 7204: =pod
 7205: 
 7206: =item lonnet_putfile
 7207: 
 7208:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7209: 
 7210:  Arguments:
 7211:    $contents - data to store
 7212:    $filename - filename to store $contents into
 7213: 
 7214:  Returns:
 7215:    result value from &Apache::lonnet::finishuserfileupload
 7216: 
 7217: =cut
 7218: 
 7219: sub lonnet_putfile {
 7220:     my ($contents,$filename)=@_;
 7221:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7222:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7223:     $env{'form.sillywaytopassafilearound'}=$contents;
 7224:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7225: 
 7226: }
 7227: 
 7228: =pod
 7229: 
 7230: =item scantron_putfile
 7231: 
 7232:     Stores the current version of the bubblesheet data files, and the
 7233:     scan_data hash. (Does not modify the original version only the
 7234:     corrected and skipped versions.
 7235: 
 7236:  Arguments:
 7237:     $scanlines - hash ref that looks like the first return value from
 7238:                  &scantron_getfile()
 7239:     $scan_data - hash ref that looks like the second return value from
 7240:                  &scantron_getfile()
 7241: 
 7242: =cut
 7243: 
 7244: sub scantron_putfile {
 7245:     my ($scanlines,$scan_data) = @_;
 7246:     #FIXME really would prefer a scantron directory
 7247:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7248:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7249:     if ($scanlines) {
 7250: 	my $prefix='scantron_';
 7251: # no need to update orig, shouldn't change
 7252: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7253: #		    $env{'form.scantron_selectfile'});
 7254: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7255: 			$prefix.'corrected_'.
 7256: 			$env{'form.scantron_selectfile'});
 7257: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7258: 			$prefix.'skipped_'.
 7259: 			$env{'form.scantron_selectfile'});
 7260:     }
 7261:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7262: }
 7263: 
 7264: =pod
 7265: 
 7266: =item scantron_get_line
 7267: 
 7268:    Returns the correct version of the scanline
 7269: 
 7270:  Arguments:
 7271:     $scanlines - hash ref that looks like the first return value from
 7272:                  &scantron_getfile()
 7273:     $scan_data - hash ref that looks like the second return value from
 7274:                  &scantron_getfile()
 7275:     $i         - number of the requested line (starts at 0)
 7276: 
 7277:  Returns:
 7278:    A scanline, (either the original or the corrected one if it
 7279:    exists), or undef if the requested scanline should be
 7280:    skipped. (Either because it's an skipped scanline, or it's an
 7281:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7282:    pass.
 7283: 
 7284: =cut
 7285: 
 7286: sub scantron_get_line {
 7287:     my ($scanlines,$scan_data,$i)=@_;
 7288:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7289:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7290:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7291:     return $scanlines->{'orig'}[$i]; 
 7292: }
 7293: 
 7294: =pod
 7295: 
 7296: =item scantron_todo_count
 7297: 
 7298:     Counts the number of scanlines that need processing.
 7299: 
 7300:  Arguments:
 7301:     $scanlines - hash ref that looks like the first return value from
 7302:                  &scantron_getfile()
 7303:     $scan_data - hash ref that looks like the second return value from
 7304:                  &scantron_getfile()
 7305: 
 7306:  Returns:
 7307:     $count - number of scanlines to process
 7308: 
 7309: =cut
 7310: 
 7311: sub get_todo_count {
 7312:     my ($scanlines,$scan_data)=@_;
 7313:     my $count=0;
 7314:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7315: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7316: 	if ($line=~/^[\s\cz]*$/) { next; }
 7317: 	$count++;
 7318:     }
 7319:     return $count;
 7320: }
 7321: 
 7322: =pod
 7323: 
 7324: =item scantron_put_line
 7325: 
 7326:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7327:     data file.
 7328: 
 7329:  Arguments:
 7330:     $scanlines - hash ref that looks like the first return value from
 7331:                  &scantron_getfile()
 7332:     $scan_data - hash ref that looks like the second return value from
 7333:                  &scantron_getfile()
 7334:     $i         - line number to update
 7335:     $newline   - contents of the updated scanline
 7336:     $skip      - if true make the line for skipping and update the
 7337:                  'skipped' file
 7338: 
 7339: =cut
 7340: 
 7341: sub scantron_put_line {
 7342:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7343:     if ($skip) {
 7344: 	$scanlines->{'skipped'}[$i]=$newline;
 7345: 	&start_skipping($scan_data,$i);
 7346: 	return;
 7347:     }
 7348:     $scanlines->{'corrected'}[$i]=$newline;
 7349: }
 7350: 
 7351: =pod
 7352: 
 7353: =item scantron_clear_skip
 7354: 
 7355:    Remove a line from the 'skipped' file
 7356: 
 7357:  Arguments:
 7358:     $scanlines - hash ref that looks like the first return value from
 7359:                  &scantron_getfile()
 7360:     $scan_data - hash ref that looks like the second return value from
 7361:                  &scantron_getfile()
 7362:     $i         - line number to update
 7363: 
 7364: =cut
 7365: 
 7366: sub scantron_clear_skip {
 7367:     my ($scanlines,$scan_data,$i)=@_;
 7368:     if (exists($scanlines->{'skipped'}[$i])) {
 7369: 	undef($scanlines->{'skipped'}[$i]);
 7370: 	return 1;
 7371:     }
 7372:     return 0;
 7373: }
 7374: 
 7375: =pod
 7376: 
 7377: =item scantron_filter_not_exam
 7378: 
 7379:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7380:    filter out resources that are not marked as 'exam' mode
 7381: 
 7382: =cut
 7383: 
 7384: sub scantron_filter_not_exam {
 7385:     my ($curres)=@_;
 7386:     
 7387:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7388: 	# if the user has asked to not have either hidden
 7389: 	# or 'randomout' controlled resources to be graded
 7390: 	# don't include them
 7391: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7392: 	    && $curres->randomout) {
 7393: 	    return 0;
 7394: 	}
 7395: 	return 1;
 7396:     }
 7397:     return 0;
 7398: }
 7399: 
 7400: =pod
 7401: 
 7402: =item scantron_validate_sequence
 7403: 
 7404:     Validates the selected sequence, checking for resource that are
 7405:     not set to exam mode.
 7406: 
 7407: =cut
 7408: 
 7409: sub scantron_validate_sequence {
 7410:     my ($r,$currentphase) = @_;
 7411: 
 7412:     my $navmap=Apache::lonnavmaps::navmap->new();
 7413:     unless (ref($navmap)) {
 7414:         $r->print(&navmap_errormsg());
 7415:         return (1,$currentphase);
 7416:     }
 7417:     my (undef,undef,$sequence)=
 7418: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7419: 
 7420:     my $map=$navmap->getResourceByUrl($sequence);
 7421: 
 7422:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7423:                                     value="ignore" />');
 7424:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7425: 	my @resources=
 7426: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7427: 	if (@resources) {
 7428: 	    $r->print(
 7429:                 '<p class="LC_warning">'
 7430:                .&mt('Some resources in the sequence currently are not set to'
 7431:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7432:                    .' work correctly.')
 7433:                .'</p>'
 7434:             );
 7435: 	    return (1,$currentphase);
 7436: 	}
 7437:     }
 7438: 
 7439:     return (0,$currentphase+1);
 7440: }
 7441: 
 7442: 
 7443: 
 7444: sub scantron_validate_ID {
 7445:     my ($r,$currentphase) = @_;
 7446:     
 7447:     #get student info
 7448:     my $classlist=&Apache::loncoursedata::get_classlist();
 7449:     my %idmap=&username_to_idmap($classlist);
 7450: 
 7451:     #get scantron line setup
 7452:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7453:     my ($scanlines,$scan_data)=&scantron_getfile();
 7454: 
 7455:     my $nav_error;
 7456:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7457:     if ($nav_error) {
 7458:         $r->print(&navmap_errormsg());
 7459:         return(1,$currentphase);
 7460:     }
 7461: 
 7462:     my %found=('ids'=>{},'usernames'=>{});
 7463:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7464: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7465: 	if ($line=~/^[\s\cz]*$/) { next; }
 7466: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7467: 						 $scan_data);
 7468: 	my $id=$$scan_record{'scantron.ID'};
 7469: 	my $found;
 7470: 	foreach my $checkid (keys(%idmap)) {
 7471: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7472: 	}
 7473: 	if ($found) {
 7474: 	    my $username=$idmap{$found};
 7475: 	    if ($found{'ids'}{$found}) {
 7476: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7477: 					 $line,'duplicateID',$found);
 7478: 		return(1,$currentphase);
 7479: 	    } elsif ($found{'usernames'}{$username}) {
 7480: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7481: 					 $line,'duplicateID',$username);
 7482: 		return(1,$currentphase);
 7483: 	    }
 7484: 	    #FIXME store away line we previously saw the ID on to use above
 7485: 	    $found{'ids'}{$found}++;
 7486: 	    $found{'usernames'}{$username}++;
 7487: 	} else {
 7488: 	    if ($id =~ /^\s*$/) {
 7489: 		my $username=&scan_data($scan_data,"$i.user");
 7490: 		if (defined($username) && $found{'usernames'}{$username}) {
 7491: 		    &scantron_get_correction($r,$i,$scan_record,
 7492: 					     \%scantron_config,
 7493: 					     $line,'duplicateID',$username);
 7494: 		    return(1,$currentphase);
 7495: 		} elsif (!defined($username)) {
 7496: 		    &scantron_get_correction($r,$i,$scan_record,
 7497: 					     \%scantron_config,
 7498: 					     $line,'incorrectID');
 7499: 		    return(1,$currentphase);
 7500: 		}
 7501: 		$found{'usernames'}{$username}++;
 7502: 	    } else {
 7503: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7504: 					 $line,'incorrectID');
 7505: 		return(1,$currentphase);
 7506: 	    }
 7507: 	}
 7508:     }
 7509: 
 7510:     return (0,$currentphase+1);
 7511: }
 7512: 
 7513: 
 7514: sub scantron_get_correction {
 7515:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7516:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7517: #FIXME in the case of a duplicated ID the previous line, probably need
 7518: #to show both the current line and the previous one and allow skipping
 7519: #the previous one or the current one
 7520: 
 7521:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7522:         $r->print(
 7523:             '<p class="LC_warning">'
 7524:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7525:                 "<b>$error</b>",
 7526:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7527:            ."</p> \n");
 7528:     } else {
 7529:         $r->print(
 7530:             '<p class="LC_warning">'
 7531:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7532:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7533:            ."</p> \n");
 7534:     }
 7535:     my $message =
 7536:         '<p>'
 7537:        .&mt('The ID on the form is [_1]',
 7538:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7539:        .'<br />'
 7540:        .&mt('The name on the paper is [_1], [_2]',
 7541:             $$scan_record{'scantron.LastName'},
 7542:             $$scan_record{'scantron.FirstName'})
 7543:        .'</p>';
 7544: 
 7545:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7546:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7547:                            # Array populated for doublebubble or
 7548:     my @lines_to_correct;  # missingbubble errors to build javascript
 7549:                            # to validate radio button checking   
 7550: 
 7551:     if ($error =~ /ID$/) {
 7552: 	if ($error eq 'incorrectID') {
 7553:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7554: 		      "</p>\n");
 7555: 	} elsif ($error eq 'duplicateID') {
 7556:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7557: 	}
 7558: 	$r->print($message);
 7559: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7560: 	$r->print("\n<ul><li> ");
 7561: 	#FIXME it would be nice if this sent back the user ID and
 7562: 	#could do partial userID matches
 7563: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7564: 				       'scantron_username','scantron_domain'));
 7565: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7566: 	$r->print("\n:\n".
 7567: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7568: 
 7569: 	$r->print('</li>');
 7570:     } elsif ($error =~ /CODE$/) {
 7571: 	if ($error eq 'incorrectCODE') {
 7572: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7573: 	} elsif ($error eq 'duplicateCODE') {
 7574: 	    $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");
 7575: 	}
 7576: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7577: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7578:                  ."</p>\n");
 7579: 	$r->print($message);
 7580: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7581: 	$r->print("\n<br /> ");
 7582: 	my $i=0;
 7583: 	if ($error eq 'incorrectCODE' 
 7584: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7585: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7586: 	    if ($closest > 0) {
 7587: 		foreach my $testcode (@{$closest}) {
 7588: 		    my $checked='';
 7589: 		    if (!$i) { $checked=' checked="checked"'; }
 7590: 		    $r->print("
 7591:    <label>
 7592:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7593:        ".&mt("Use the similar CODE [_1] instead.",
 7594: 	    "<b><tt>".$testcode."</tt></b>")."
 7595:     </label>
 7596:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7597: 		    $r->print("\n<br />");
 7598: 		    $i++;
 7599: 		}
 7600: 	    }
 7601: 	}
 7602: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7603: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7604: 	    $r->print("
 7605:     <label>
 7606:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7607:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7608: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7609:     </label>");
 7610: 	    $r->print("\n<br />");
 7611: 	}
 7612: 
 7613: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7614: function change_radio(field) {
 7615:     var slct=document.scantronupload.scantron_CODE_resolution;
 7616:     var i;
 7617:     for (i=0;i<slct.length;i++) {
 7618:         if (slct[i].value==field) { slct[i].checked=true; }
 7619:     }
 7620: }
 7621: ENDSCRIPT
 7622: 	my $href="/adm/pickcode?".
 7623: 	   "form=".&escape("scantronupload").
 7624: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7625: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7626: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7627: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7628: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7629: 	    $r->print("
 7630:     <label>
 7631:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7632:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7633: 	     "<a target='_blank' href='$href'>","</a>")."
 7634:     </label> 
 7635:     ".&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\')" />'));
 7636: 	    $r->print("\n<br />");
 7637: 	}
 7638: 	$r->print("
 7639:     <label>
 7640:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7641:        ".&mt("Use [_1] as the CODE.",
 7642: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7643: 	$r->print("\n<br /><br />");
 7644:     } elsif ($error eq 'doublebubble') {
 7645: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7646: 
 7647: 	# The form field scantron_questions is acutally a list of line numbers.
 7648: 	# represented by this form so:
 7649: 
 7650: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7651:                                                 $respnumlookup,$startline);
 7652: 
 7653: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7654: 		  $line_list.'" />');
 7655: 	$r->print($message);
 7656: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7657: 	foreach my $question (@{$arg}) {
 7658: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7659:                                                    $scan_record, $error,
 7660:                                                    $randomorder,$randompick,
 7661:                                                    $respnumlookup,$startline);
 7662:             push(@lines_to_correct,@linenums);
 7663: 	}
 7664:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7665:     } elsif ($error eq 'missingbubble') {
 7666: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7667: 	$r->print($message);
 7668: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7669: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7670: 
 7671: 	# The form field scantron_questions is actually a list of line numbers not
 7672: 	# a list of question numbers. Therefore:
 7673: 	#
 7674: 
 7675: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7676:                                                 $respnumlookup,$startline);
 7677: 
 7678: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7679: 		  $line_list.'" />');
 7680: 	foreach my $question (@{$arg}) {
 7681: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7682:                                                    $scan_record, $error,
 7683:                                                    $randomorder,$randompick,
 7684:                                                    $respnumlookup,$startline);
 7685:             push(@lines_to_correct,@linenums);
 7686: 	}
 7687:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7688:     } else {
 7689: 	$r->print("\n<ul>");
 7690:     }
 7691:     $r->print("\n</li></ul>");
 7692: }
 7693: 
 7694: sub verify_bubbles_checked {
 7695:     my (@ansnums) = @_;
 7696:     my $ansnumstr = join('","',@ansnums);
 7697:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7698:     &js_escape(\$warning);
 7699:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7700: function verify_bubble_radio(form) {
 7701:     var ansnumArray = new Array ("$ansnumstr");
 7702:     var need_bubble_count = 0;
 7703:     for (var i=0; i<ansnumArray.length; i++) {
 7704:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7705:             var bubble_picked = 0; 
 7706:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7707:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7708:                     bubble_picked = 1;
 7709:                 }
 7710:             }
 7711:             if (bubble_picked == 0) {
 7712:                 need_bubble_count ++;
 7713:             }
 7714:         }
 7715:     }
 7716:     if (need_bubble_count) {
 7717:         alert("$warning");
 7718:         return;
 7719:     }
 7720:     form.submit(); 
 7721: }
 7722: ENDSCRIPT
 7723:     return $output;
 7724: }
 7725: 
 7726: =pod
 7727: 
 7728: =item  questions_to_line_list
 7729: 
 7730: Converts a list of questions into a string of comma separated
 7731: line numbers in the answer sheet used by the questions.  This is
 7732: used to fill in the scantron_questions form field.
 7733: 
 7734:   Arguments:
 7735:      questions    - Reference to an array of questions.
 7736:      randomorder  - True if randomorder in use.
 7737:      randompick   - True if randompick in use.
 7738:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7739:                      for current line to question number used for same question
 7740:                      in "Master Seqence" (as seen by Course Coordinator).
 7741:      startline    - Reference to hash where key is question number (0 is first)
 7742:                     and key is number of first bubble line for current student
 7743:                     or code-based randompick and/or randomorder.
 7744: 
 7745: =cut
 7746: 
 7747: 
 7748: sub questions_to_line_list {
 7749:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7750:     my @lines;
 7751: 
 7752:     foreach my $item (@{$questions}) {
 7753:         my $question = $item;
 7754:         my ($first,$count,$last);
 7755:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7756:             $question = $1;
 7757:             my $subquestion = $2;
 7758:             my $responsenum = $question-1;
 7759:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7760:                 $responsenum = $respnumlookup->{$question-1};
 7761:                 if (ref($startline) eq 'HASH') {
 7762:                     $first = $startline->{$question-1} + 1;
 7763:                 }
 7764:             } else {
 7765:                 $first = $first_bubble_line{$responsenum} + 1;
 7766:             }
 7767:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7768:             my $subcount = 1;
 7769:             while ($subcount<$subquestion) {
 7770:                 $first += $subans[$subcount-1];
 7771:                 $subcount ++;
 7772:             }
 7773:             $count = $subans[$subquestion-1];
 7774:         } else {
 7775:             my $responsenum = $question-1;
 7776:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7777:                 $responsenum = $respnumlookup->{$question-1};
 7778:                 if (ref($startline) eq 'HASH') {
 7779:                     $first = $startline->{$question-1} + 1;
 7780:                 }
 7781:             } else {
 7782:                 $first = $first_bubble_line{$responsenum} + 1;
 7783:             }
 7784: 	    $count   = $bubble_lines_per_response{$responsenum};
 7785:         }
 7786:         $last = $first+$count-1;
 7787:         push(@lines, ($first..$last));
 7788:     }
 7789:     return join(',', @lines);
 7790: }
 7791: 
 7792: =pod 
 7793: 
 7794: =item prompt_for_corrections
 7795: 
 7796: Prompts for a potentially multiline correction to the
 7797: user's bubbling (factors out common code from scantron_get_correction
 7798: for multi and missing bubble cases).
 7799: 
 7800:  Arguments:
 7801:    $r           - Apache request object.
 7802:    $question    - The question number to prompt for.
 7803:    $scan_config - The scantron file configuration hash.
 7804:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7805:    $error       - Type of error
 7806:    $randomorder - True if randomorder in use.
 7807:    $randompick  - True if randompick in use.
 7808:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7809:                     for current line to question number used for same question
 7810:                     in "Master Seqence" (as seen by Course Coordinator).
 7811:    $startline   - Reference to hash where key is question number (0 is first)
 7812:                   and value is number of first bubble line for current student
 7813:                   or code-based randompick and/or randomorder.
 7814: 
 7815: 
 7816:  Implicit inputs:
 7817:    %bubble_lines_per_response   - Starting line numbers for each question.
 7818:                                   Numbered from 0 (but question numbers are from
 7819:                                   1.
 7820:    %first_bubble_line           - Starting bubble line for each question.
 7821:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7822:                                   type problems render as separate sub-questions, 
 7823:                                   in exam mode. This hash contains a 
 7824:                                   comma-separated list of the lines per 
 7825:                                   sub-question.
 7826:    %responsetype_per_response   - essayresponse, formularesponse,
 7827:                                   stringresponse, imageresponse, reactionresponse,
 7828:                                   and organicresponse type problem parts can have
 7829:                                   multiple lines per response if the weight
 7830:                                   assigned exceeds 10.  In this case, only
 7831:                                   one bubble per line is permitted, but more 
 7832:                                   than one line might contain bubbles, e.g.
 7833:                                   bubbling of: line 1 - J, line 2 - J, 
 7834:                                   line 3 - B would assign 22 points.  
 7835: 
 7836: =cut
 7837: 
 7838: sub prompt_for_corrections {
 7839:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7840:         $randompick, $respnumlookup, $startline) = @_;
 7841:     my ($current_line,$lines);
 7842:     my @linenums;
 7843:     my $questionnum = $question;
 7844:     my ($first,$responsenum);
 7845:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7846:         $question = $1;
 7847:         my $subquestion = $2;
 7848:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7849:             $responsenum = $respnumlookup->{$question-1};
 7850:             if (ref($startline) eq 'HASH') {
 7851:                 $first = $startline->{$question-1};
 7852:             }
 7853:         } else {
 7854:             $responsenum = $question-1;
 7855:             $first = $first_bubble_line{$responsenum};
 7856:         }
 7857:         $current_line = $first + 1 ;
 7858:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7859:         my $subcount = 1;
 7860:         while ($subcount<$subquestion) {
 7861:             $current_line += $subans[$subcount-1];
 7862:             $subcount ++;
 7863:         }
 7864:         $lines = $subans[$subquestion-1];
 7865:     } else {
 7866:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7867:             $responsenum = $respnumlookup->{$question-1};
 7868:             if (ref($startline) eq 'HASH') { 
 7869:                 $first = $startline->{$question-1};
 7870:             }
 7871:         } else {
 7872:             $responsenum = $question-1;
 7873:             $first = $first_bubble_line{$responsenum};
 7874:         }
 7875:         $current_line = $first + 1;
 7876:         $lines        = $bubble_lines_per_response{$responsenum};
 7877:     }
 7878:     if ($lines > 1) {
 7879:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7880:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7881:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7882:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7883:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7884:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7885:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7886:             $r->print(
 7887:                 &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)
 7888:                .'<br /><br />'
 7889:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7890:                .'<br />'
 7891:                .&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.')
 7892:                .'<br />'
 7893:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7894:                .'<br /><br />'
 7895:             );
 7896:         } else {
 7897:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7898:         }
 7899:     }
 7900:     for (my $i =0; $i < $lines; $i++) {
 7901:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7902: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7903: 	        		  $questionnum,$error,split('', $selected));
 7904:         push(@linenums,$current_line);
 7905: 	$current_line++;
 7906:     }
 7907:     if ($lines > 1) {
 7908: 	$r->print("<hr /><br />");
 7909:     }
 7910:     return @linenums;
 7911: }
 7912: 
 7913: =pod
 7914: 
 7915: =item scantron_bubble_selector
 7916:   
 7917:    Generates the html radiobuttons to correct a single bubble line
 7918:    possibly showing the existing the selected bubbles if known
 7919: 
 7920:  Arguments:
 7921:     $r           - Apache request object
 7922:     $scan_config - hash from &get_scantron_config()
 7923:     $line        - Number of the line being displayed.
 7924:     $questionnum - Question number (may include subquestion)
 7925:     $error       - Type of error.
 7926:     @selected    - Array of bubbles picked on this line.
 7927: 
 7928: =cut
 7929: 
 7930: sub scantron_bubble_selector {
 7931:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7932:     my $max=$$scan_config{'Qlength'};
 7933: 
 7934:     my $scmode=$$scan_config{'Qon'};
 7935:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7936:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7937:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7938:             $max=$$scan_config{'BubblesPerRow'};
 7939:             if (($scmode eq 'number') && ($max > 10)) {
 7940:                 $max = 10;
 7941:             } elsif (($scmode eq 'letter') && $max > 26) {
 7942:                 $max = 26;
 7943:             }
 7944:         } else {
 7945:             $max = 10;
 7946:         }
 7947:     }
 7948: 
 7949:     my @alphabet=('A'..'Z');
 7950:     $r->print(&Apache::loncommon::start_data_table().
 7951:               &Apache::loncommon::start_data_table_row());
 7952:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7953:     for (my $i=0;$i<$max+1;$i++) {
 7954: 	$r->print("\n".'<td align="center">');
 7955: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7956: 	else { $r->print('&nbsp;'); }
 7957: 	$r->print('</td>');
 7958:     }
 7959:     $r->print(&Apache::loncommon::end_data_table_row().
 7960:               &Apache::loncommon::start_data_table_row());
 7961:     for (my $i=0;$i<$max;$i++) {
 7962: 	$r->print("\n".
 7963: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7964: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7965:     }
 7966:     my $nobub_checked = ' ';
 7967:     if ($error eq 'missingbubble') {
 7968:         $nobub_checked = ' checked = "checked" ';
 7969:     }
 7970:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7971: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7972:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7973:               $line.'" value="'.$questionnum.'" /></td>');
 7974:     $r->print(&Apache::loncommon::end_data_table_row().
 7975:               &Apache::loncommon::end_data_table());
 7976: }
 7977: 
 7978: =pod
 7979: 
 7980: =item num_matches
 7981: 
 7982:    Counts the number of characters that are the same between the two arguments.
 7983: 
 7984:  Arguments:
 7985:    $orig - CODE from the scanline
 7986:    $code - CODE to match against
 7987: 
 7988:  Returns:
 7989:    $count - integer count of the number of same characters between the
 7990:             two arguments
 7991: 
 7992: =cut
 7993: 
 7994: sub num_matches {
 7995:     my ($orig,$code) = @_;
 7996:     my @code=split(//,$code);
 7997:     my @orig=split(//,$orig);
 7998:     my $same=0;
 7999:     for (my $i=0;$i<scalar(@code);$i++) {
 8000: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8001:     }
 8002:     return $same;
 8003: }
 8004: 
 8005: =pod
 8006: 
 8007: =item scantron_get_closely_matching_CODEs
 8008: 
 8009:    Cycles through all CODEs and finds the set that has the greatest
 8010:    number of same characters as the provided CODE
 8011: 
 8012:  Arguments:
 8013:    $allcodes - hash ref returned by &get_codes()
 8014:    $CODE     - CODE from the current scanline
 8015: 
 8016:  Returns:
 8017:    2 element list
 8018:     - first elements is number of how closely matching the best fit is 
 8019:       (5 means best set has 5 matching characters)
 8020:     - second element is an arrary ref containing the set of valid CODEs
 8021:       that best fit the passed in CODE
 8022: 
 8023: =cut
 8024: 
 8025: sub scantron_get_closely_matching_CODEs {
 8026:     my ($allcodes,$CODE)=@_;
 8027:     my @CODEs;
 8028:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8029: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8030:     }
 8031: 
 8032:     return ($#CODEs,$CODEs[-1]);
 8033: }
 8034: 
 8035: =pod
 8036: 
 8037: =item get_codes
 8038: 
 8039:    Builds a hash which has keys of all of the valid CODEs from the selected
 8040:    set of remembered CODEs.
 8041: 
 8042:  Arguments:
 8043:   $old_name - name of the set of remembered CODEs
 8044:   $cdom     - domain of the course
 8045:   $cnum     - internal course name
 8046: 
 8047:  Returns:
 8048:   %allcodes - keys are the valid CODEs, values are all 1
 8049: 
 8050: =cut
 8051: 
 8052: sub get_codes {
 8053:     my ($old_name, $cdom, $cnum) = @_;
 8054:     if (!$old_name) {
 8055: 	$old_name=$env{'form.scantron_CODElist'};
 8056:     }
 8057:     if (!$cdom) {
 8058: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8059:     }
 8060:     if (!$cnum) {
 8061: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8062:     }
 8063:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8064: 				    $cdom,$cnum);
 8065:     my %allcodes;
 8066:     if ($result{"type\0$old_name"} eq 'number') {
 8067: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8068:     } else {
 8069: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8070:     }
 8071:     return %allcodes;
 8072: }
 8073: 
 8074: =pod
 8075: 
 8076: =item scantron_validate_CODE
 8077: 
 8078:    Validates all scanlines in the selected file to not have any
 8079:    invalid or underspecified CODEs and that none of the codes are
 8080:    duplicated if this was requested.
 8081: 
 8082: =cut
 8083: 
 8084: sub scantron_validate_CODE {
 8085:     my ($r,$currentphase) = @_;
 8086:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8087:     if ($scantron_config{'CODElocation'} &&
 8088: 	$scantron_config{'CODEstart'} &&
 8089: 	$scantron_config{'CODElength'}) {
 8090: 	if (!defined($env{'form.scantron_CODElist'})) {
 8091: 	    &FIXME_blow_up()
 8092: 	}
 8093:     } else {
 8094: 	return (0,$currentphase+1);
 8095:     }
 8096:     
 8097:     my %usedCODEs;
 8098: 
 8099:     my %allcodes=&get_codes();
 8100: 
 8101:     my $nav_error;
 8102:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8103:     if ($nav_error) {
 8104:         $r->print(&navmap_errormsg());
 8105:         return(1,$currentphase);
 8106:     }
 8107: 
 8108:     my ($scanlines,$scan_data)=&scantron_getfile();
 8109:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8110: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8111: 	if ($line=~/^[\s\cz]*$/) { next; }
 8112: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8113: 						 $scan_data);
 8114: 	my $CODE=$$scan_record{'scantron.CODE'};
 8115: 	my $error=0;
 8116: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8117: 	    &scantron_get_correction($r,$i,$scan_record,
 8118: 				     \%scantron_config,
 8119: 				     $line,'incorrectCODE',\%allcodes);
 8120: 	    return(1,$currentphase);
 8121: 	}
 8122: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8123: 	    && !$$scan_record{'scantron.useCODE'}) {
 8124: 	    &scantron_get_correction($r,$i,$scan_record,
 8125: 				     \%scantron_config,
 8126: 				     $line,'incorrectCODE',\%allcodes);
 8127: 	    return(1,$currentphase);
 8128: 	}
 8129: 	if (exists($usedCODEs{$CODE}) 
 8130: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8131: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8132: 	    &scantron_get_correction($r,$i,$scan_record,
 8133: 				     \%scantron_config,
 8134: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8135: 	    return(1,$currentphase);
 8136: 	}
 8137: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8138:     }
 8139:     return (0,$currentphase+1);
 8140: }
 8141: 
 8142: =pod
 8143: 
 8144: =item scantron_validate_doublebubble
 8145: 
 8146:    Validates all scanlines in the selected file to not have any
 8147:    bubble lines with multiple bubbles marked.
 8148: 
 8149: =cut
 8150: 
 8151: sub scantron_validate_doublebubble {
 8152:     my ($r,$currentphase) = @_;
 8153:     #get student info
 8154:     my $classlist=&Apache::loncoursedata::get_classlist();
 8155:     my %idmap=&username_to_idmap($classlist);
 8156:     my (undef,undef,$sequence)=
 8157:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8158: 
 8159:     #get scantron line setup
 8160:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8161:     my ($scanlines,$scan_data)=&scantron_getfile();
 8162: 
 8163:     my $navmap = Apache::lonnavmaps::navmap->new();
 8164:     unless (ref($navmap)) {
 8165:         $r->print(&navmap_errormsg());
 8166:         return(1,$currentphase);
 8167:     }
 8168:     my $map=$navmap->getResourceByUrl($sequence);
 8169:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8170:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8171:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8172:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8173: 
 8174:     my $nav_error;
 8175:     if (ref($map)) {
 8176:         $randomorder = $map->randomorder();
 8177:         $randompick = $map->randompick();
 8178:         if ($randomorder || $randompick) {
 8179:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8180:             if ($nav_error) {
 8181:                 $r->print(&navmap_errormsg());
 8182:                 return(1,$currentphase);
 8183:             }
 8184:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8185:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8186:         }
 8187:     } else {
 8188:         $r->print(&navmap_errormsg());
 8189:         return(1,$currentphase);
 8190:     }
 8191: 
 8192:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8193:     if ($nav_error) {
 8194:         $r->print(&navmap_errormsg());
 8195:         return(1,$currentphase);
 8196:     }
 8197: 
 8198:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8199: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8200: 	if ($line=~/^[\s\cz]*$/) { next; }
 8201: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8202: 						 $scan_data,undef,\%idmap,$randomorder,
 8203:                                                  $randompick,$sequence,\@master_seq,
 8204:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8205:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8206: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8207: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8208: 				 'doublebubble',
 8209: 				 $$scan_record{'scantron.doubleerror'},
 8210:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8211:     	return (1,$currentphase);
 8212:     }
 8213:     return (0,$currentphase+1);
 8214: }
 8215: 
 8216: 
 8217: sub scantron_get_maxbubble {
 8218:     my ($nav_error,$scantron_config) = @_;
 8219:     if (defined($env{'form.scantron_maxbubble'}) &&
 8220: 	$env{'form.scantron_maxbubble'}) {
 8221: 	&restore_bubble_lines();
 8222: 	return $env{'form.scantron_maxbubble'};
 8223:     }
 8224: 
 8225:     my (undef, undef, $sequence) =
 8226: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8227: 
 8228:     my $navmap=Apache::lonnavmaps::navmap->new();
 8229:     unless (ref($navmap)) {
 8230:         if (ref($nav_error)) {
 8231:             $$nav_error = 1;
 8232:         }
 8233:         return;
 8234:     }
 8235:     my $map=$navmap->getResourceByUrl($sequence);
 8236:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8237:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8238: 
 8239:     &Apache::lonxml::clear_problem_counter();
 8240: 
 8241:     my $uname       = $env{'user.name'};
 8242:     my $udom        = $env{'user.domain'};
 8243:     my $cid         = $env{'request.course.id'};
 8244:     my $total_lines = 0;
 8245:     %bubble_lines_per_response = ();
 8246:     %first_bubble_line         = ();
 8247:     %subdivided_bubble_lines   = ();
 8248:     %responsetype_per_response = ();
 8249:     %masterseq_id_responsenum  = ();
 8250: 
 8251:     my $response_number = 0;
 8252:     my $bubble_line     = 0;
 8253:     foreach my $resource (@resources) {
 8254:         my $resid = $resource->id(); 
 8255:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8256:                                                           $udom,undef,$bubbles_per_row);
 8257:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8258: 	    foreach my $part_id (@{$parts}) {
 8259:                 my $lines;
 8260: 
 8261: 	        # TODO - make this a persistent hash not an array.
 8262: 
 8263:                 # optionresponse, matchresponse and rankresponse type items 
 8264:                 # render as separate sub-questions in exam mode.
 8265:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8266:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8267:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8268:                     my ($numbub,$numshown);
 8269:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8270:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8271:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8272:                         }
 8273:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8274:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8275:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8276:                         }
 8277:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8278:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8279:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8280:                         }
 8281:                     }
 8282:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8283:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8284:                     }
 8285:                     my $bubbles_per_row =
 8286:                         &bubblesheet_bubbles_per_row($scantron_config);
 8287:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8288:                     if (($numbub % $bubbles_per_row) != 0) {
 8289:                         $inner_bubble_lines++;
 8290:                     }
 8291:                     for (my $i=0; $i<$numshown; $i++) {
 8292:                         $subdivided_bubble_lines{$response_number} .= 
 8293:                             $inner_bubble_lines.',';
 8294:                     }
 8295:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8296:                     $lines = $numshown * $inner_bubble_lines;
 8297:                 } else {
 8298:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8299:                 }
 8300: 
 8301:                 $first_bubble_line{$response_number} = $bubble_line;
 8302: 	        $bubble_lines_per_response{$response_number} = $lines;
 8303:                 $responsetype_per_response{$response_number} = 
 8304:                     $analysis->{$part_id.'.type'};
 8305:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8306: 	        $response_number++;
 8307: 
 8308: 	        $bubble_line +=  $lines;
 8309: 	        $total_lines +=  $lines;
 8310: 	    }
 8311:         }
 8312:     }
 8313:     &Apache::lonnet::delenv('scantron.');
 8314: 
 8315:     &save_bubble_lines();
 8316:     $env{'form.scantron_maxbubble'} =
 8317: 	$total_lines;
 8318:     return $env{'form.scantron_maxbubble'};
 8319: }
 8320: 
 8321: sub bubblesheet_bubbles_per_row {
 8322:     my ($scantron_config) = @_;
 8323:     my $bubbles_per_row;
 8324:     if (ref($scantron_config) eq 'HASH') {
 8325:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8326:     }
 8327:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8328:         $bubbles_per_row = 10;
 8329:     }
 8330:     return $bubbles_per_row;
 8331: }
 8332: 
 8333: sub scantron_validate_missingbubbles {
 8334:     my ($r,$currentphase) = @_;
 8335:     #get student info
 8336:     my $classlist=&Apache::loncoursedata::get_classlist();
 8337:     my %idmap=&username_to_idmap($classlist);
 8338:     my (undef,undef,$sequence)=
 8339:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8340: 
 8341:     #get scantron line setup
 8342:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8343:     my ($scanlines,$scan_data)=&scantron_getfile();
 8344: 
 8345:     my $navmap = Apache::lonnavmaps::navmap->new();
 8346:     unless (ref($navmap)) {
 8347:         $r->print(&navmap_errormsg());
 8348:         return(1,$currentphase);
 8349:     }
 8350: 
 8351:     my $map=$navmap->getResourceByUrl($sequence);
 8352:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8353:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8354:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8355:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8356: 
 8357:     my $nav_error;
 8358:     if (ref($map)) {
 8359:         $randomorder = $map->randomorder();
 8360:         $randompick = $map->randompick();
 8361:         if ($randomorder || $randompick) {
 8362:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8363:             if ($nav_error) {
 8364:                 $r->print(&navmap_errormsg());
 8365:                 return(1,$currentphase);
 8366:             }
 8367:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8368:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8369:         }
 8370:     } else {
 8371:         $r->print(&navmap_errormsg());
 8372:         return(1,$currentphase);
 8373:     }
 8374: 
 8375: 
 8376:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8377:     if ($nav_error) {
 8378:         $r->print(&navmap_errormsg());
 8379:         return(1,$currentphase);
 8380:     }
 8381: 
 8382:     if (!$max_bubble) { $max_bubble=2**31; }
 8383:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8384: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8385: 	if ($line=~/^[\s\cz]*$/) { next; }
 8386: 	my $scan_record =
 8387:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8388: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8389:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8390:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8391: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8392: 	my @to_correct;
 8393: 	
 8394: 	# Probably here's where the error is...
 8395: 
 8396: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8397:             my $lastbubble;
 8398:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8399:                my $question = $1;
 8400:                my $subquestion = $2;
 8401:                my ($first,$responsenum);
 8402:                if ($randomorder || $randompick) {
 8403:                    $responsenum = $respnumlookup{$question-1};
 8404:                    $first = $startline{$question-1};
 8405:                } else {
 8406:                    $responsenum = $question-1; 
 8407:                    $first = $first_bubble_line{$responsenum};
 8408:                }
 8409:                if (!defined($first)) { next; }
 8410:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8411:                my $subcount = 1;
 8412:                while ($subcount<$subquestion) {
 8413:                    $first += $subans[$subcount-1];
 8414:                    $subcount ++;
 8415:                }
 8416:                my $count = $subans[$subquestion-1];
 8417:                $lastbubble = $first + $count;
 8418:             } else {
 8419:                my ($first,$responsenum);
 8420:                if ($randomorder || $randompick) {
 8421:                    $responsenum = $respnumlookup{$missing-1};
 8422:                    $first = $startline{$missing-1};
 8423:                } else {
 8424:                    $responsenum = $missing-1;
 8425:                    $first = $first_bubble_line{$responsenum};
 8426:                }
 8427:                if (!defined($first)) { next; }
 8428:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8429:             }
 8430:             if ($lastbubble > $max_bubble) { next; }
 8431: 	    push(@to_correct,$missing);
 8432: 	}
 8433: 	if (@to_correct) {
 8434: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8435: 				     $line,'missingbubble',\@to_correct,
 8436:                                      $randomorder,$randompick,\%respnumlookup,
 8437:                                      \%startline);
 8438: 	    return (1,$currentphase);
 8439: 	}
 8440: 
 8441:     }
 8442:     return (0,$currentphase+1);
 8443: }
 8444: 
 8445: sub hand_bubble_option {
 8446:     my (undef, undef, $sequence) =
 8447:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8448:     return if ($sequence eq '');
 8449:     my $navmap = Apache::lonnavmaps::navmap->new();
 8450:     unless (ref($navmap)) {
 8451:         return;
 8452:     }
 8453:     my $needs_hand_bubbles;
 8454:     my $map=$navmap->getResourceByUrl($sequence);
 8455:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8456:     foreach my $res (@resources) {
 8457:         if (ref($res)) {
 8458:             if ($res->is_problem()) {
 8459:                 my $partlist = $res->parts();
 8460:                 foreach my $part (@{ $partlist }) {
 8461:                     my @types = $res->responseType($part);
 8462:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8463:                         $needs_hand_bubbles = 1;
 8464:                         last;
 8465:                     }
 8466:                 }
 8467:             }
 8468:         }
 8469:     }
 8470:     if ($needs_hand_bubbles) {
 8471:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8472:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8473:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8474:                &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 />').
 8475:                '<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;'.
 8476:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8477:     }
 8478:     return;
 8479: }
 8480: 
 8481: sub scantron_process_students {
 8482:     my ($r,$symb) = @_;
 8483: 
 8484:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8485:     if (!$symb) {
 8486: 	return '';
 8487:     }
 8488:     my $default_form_data=&defaultFormData($symb);
 8489: 
 8490:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8491:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8492:     my ($scanlines,$scan_data)=&scantron_getfile();
 8493:     my $classlist=&Apache::loncoursedata::get_classlist();
 8494:     my %idmap=&username_to_idmap($classlist);
 8495:     my $navmap=Apache::lonnavmaps::navmap->new();
 8496:     unless (ref($navmap)) {
 8497:         $r->print(&navmap_errormsg());
 8498:         return '';
 8499:     }
 8500:     my $map=$navmap->getResourceByUrl($sequence);
 8501:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8502:         %grader_randomlists_by_symb);
 8503:     if (ref($map)) {
 8504:         $randomorder = $map->randomorder();
 8505:         $randompick = $map->randompick();
 8506:     } else {
 8507:         $r->print(&navmap_errormsg());
 8508:         return '';
 8509:     }
 8510:     my $nav_error;
 8511:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8512:     if ($randomorder || $randompick) {
 8513:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8514:         if ($nav_error) {
 8515:             $r->print(&navmap_errormsg());
 8516:             return '';
 8517:         }
 8518:     }
 8519:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8520:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8521: 
 8522:     my ($uname,$udom);
 8523:     my $result= <<SCANTRONFORM;
 8524: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8525:   <input type="hidden" name="command" value="scantron_configphase" />
 8526:   $default_form_data
 8527: SCANTRONFORM
 8528:     $r->print($result);
 8529: 
 8530:     my @delayqueue;
 8531:     my (%completedstudents,%scandata);
 8532:     
 8533:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8534:     my $count=&get_todo_count($scanlines,$scan_data);
 8535:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8536:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8537:     $r->print('<br />');
 8538:     my $start=&Time::HiRes::time();
 8539:     my $i=-1;
 8540:     my $started;
 8541: 
 8542:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8543:     if ($nav_error) {
 8544:         $r->print(&navmap_errormsg());
 8545:         return '';
 8546:     }
 8547: 
 8548:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8549:     # the user and return.
 8550: 
 8551:     if ($ssi_error) {
 8552: 	$r->print("</form>");
 8553: 	&ssi_print_error($r);
 8554:         &Apache::lonnet::remove_lock($lock);
 8555: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8556:     }
 8557: 
 8558:     my %lettdig = &letter_to_digits();
 8559:     my $numletts = scalar(keys(%lettdig));
 8560:     my %orderedforcode;
 8561: 
 8562:     while ($i<$scanlines->{'count'}) {
 8563:  	($uname,$udom)=('','');
 8564:  	$i++;
 8565:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8566:  	if ($line=~/^[\s\cz]*$/) { next; }
 8567: 	if ($started) {
 8568: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8569: 	}
 8570: 	$started=1;
 8571:         my %respnumlookup = ();
 8572:         my %startline = ();
 8573:         my $total;
 8574:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8575:                                                  $scan_data,undef,\%idmap,$randomorder,
 8576:                                                  $randompick,$sequence,\@master_seq,
 8577:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8578:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8579:                                                  \$total);
 8580:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8581:  					      \%idmap,$i)) {
 8582:   	    &scantron_add_delay(\@delayqueue,$line,
 8583:  				'Unable to find a student that matches',1);
 8584:  	    next;
 8585:   	}
 8586:  	if (exists $completedstudents{$uname}) {
 8587:  	    &scantron_add_delay(\@delayqueue,$line,
 8588:  				'Student '.$uname.' has multiple sheets',2);
 8589:  	    next;
 8590:  	}
 8591:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8592:         my $user = $uname.':'.$usec;
 8593:   	($uname,$udom)=split(/:/,$uname);
 8594: 
 8595:         my $scancode;
 8596:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8597:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8598:             $scancode = $scan_record->{'scantron.CODE'};
 8599:         } else {
 8600:             $scancode = '';
 8601:         }
 8602: 
 8603:         my @mapresources = @resources;
 8604:         if ($randomorder || $randompick) {
 8605:             @mapresources = 
 8606:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8607:                              \%orderedforcode);
 8608:         }
 8609:         my (%partids_by_symb,$res_error);
 8610:         foreach my $resource (@mapresources) {
 8611:             my $ressymb;
 8612:             if (ref($resource)) {
 8613:                 $ressymb = $resource->symb();
 8614:             } else {
 8615:                 $res_error = 1;
 8616:                 last;
 8617:             }
 8618:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8619:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8620:                 my $currcode;
 8621:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8622:                     $currcode = $scancode;
 8623:                 }
 8624:                 my ($analysis,$parts) =
 8625:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8626:                                               $uname,$udom,undef,$bubbles_per_row,
 8627:                                               $currcode);
 8628:                 $partids_by_symb{$ressymb} = $parts;
 8629:             } else {
 8630:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8631:             }
 8632:         }
 8633: 
 8634:         if ($res_error) {
 8635:             &scantron_add_delay(\@delayqueue,$line,
 8636:                                 'An error occurred while grading student '.$uname,2);
 8637:             next;
 8638:         }
 8639: 
 8640: 	&Apache::lonxml::clear_problem_counter();
 8641:   	&Apache::lonnet::appenv($scan_record);
 8642: 
 8643: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8644: 	    &scantron_putfile($scanlines,$scan_data);
 8645: 	}
 8646: 	
 8647:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8648:                                    \@mapresources,\%partids_by_symb,
 8649:                                    $bubbles_per_row,$randomorder,$randompick,
 8650:                                    \%respnumlookup,\%startline) 
 8651:             eq 'ssi_error') {
 8652:             $ssi_error = 0; # So end of handler error message does not trigger.
 8653:             $r->print("</form>");
 8654:             &ssi_print_error($r);
 8655:             &Apache::lonnet::remove_lock($lock);
 8656:             return '';      # Why return ''?  Beats me.
 8657:         }
 8658: 
 8659:         if (($scancode) && ($randomorder || $randompick)) {
 8660:             my $parmresult =
 8661:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8662:                                                        '0_examcode',2,$scancode,
 8663:                                                        'string_examcode',$uname,
 8664:                                                        $udom);
 8665:         }
 8666: 	$completedstudents{$uname}={'line'=>$line};
 8667:         if ($env{'form.verifyrecord'}) {
 8668:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8669:             if ($randompick) {
 8670:                 if ($total) {
 8671:                     $lastpos = $total*$scantron_config{'Qlength'};
 8672:                 }
 8673:             }
 8674: 
 8675:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8676:             chomp($studentdata);
 8677:             $studentdata =~ s/\r$//;
 8678:             my $studentrecord = '';
 8679:             my $counter = -1;
 8680:             foreach my $resource (@mapresources) {
 8681:                 my $ressymb = $resource->symb();
 8682:                 ($counter,my $recording) =
 8683:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8684:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8685:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8686:                                              $randompick,\%respnumlookup,\%startline);
 8687:                 $studentrecord .= $recording;
 8688:             }
 8689:             if ($studentrecord ne $studentdata) {
 8690:                 &Apache::lonxml::clear_problem_counter();
 8691:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8692:                                            \@mapresources,\%partids_by_symb,
 8693:                                            $bubbles_per_row,$randomorder,$randompick,
 8694:                                            \%respnumlookup,\%startline) 
 8695:                     eq 'ssi_error') {
 8696:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8697:                     $r->print("</form>");
 8698:                     &ssi_print_error($r);
 8699:                     &Apache::lonnet::remove_lock($lock);
 8700:                     delete($completedstudents{$uname});
 8701:                     return '';
 8702:                 }
 8703:                 $counter = -1;
 8704:                 $studentrecord = '';
 8705:                 foreach my $resource (@mapresources) {
 8706:                     my $ressymb = $resource->symb();
 8707:                     ($counter,my $recording) =
 8708:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8709:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8710:                                                  \%scantron_config,\%lettdig,$numletts,
 8711:                                                  $randomorder,$randompick,\%respnumlookup,
 8712:                                                  \%startline);
 8713:                     $studentrecord .= $recording;
 8714:                 }
 8715:                 if ($studentrecord ne $studentdata) {
 8716:                     $r->print('<p><span class="LC_warning">');
 8717:                     if ($scancode eq '') {
 8718:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8719:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8720:                     } else {
 8721:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8722:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8723:                     }
 8724:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8725:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8726:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8727:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8728:                               &Apache::loncommon::start_data_table_row().
 8729:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8730:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8731:                               &Apache::loncommon::end_data_table_row().
 8732:                               &Apache::loncommon::start_data_table_row().
 8733:                               '<td>'.&mt('Stored submissions').'</td>'.
 8734:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8735:                               &Apache::loncommon::end_data_table_row().
 8736:                               &Apache::loncommon::end_data_table().'</p>');
 8737:                 } else {
 8738:                     $r->print('<br /><span class="LC_warning">'.
 8739:                              &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 />'.
 8740:                              &mt("As a consequence, this user's submission history records two tries.").
 8741:                                  '</span><br />');
 8742:                 }
 8743:             }
 8744:         }
 8745:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8746:     } continue {
 8747: 	&Apache::lonxml::clear_problem_counter();
 8748: 	&Apache::lonnet::delenv('scantron.');
 8749:     }
 8750:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8751:     &Apache::lonnet::remove_lock($lock);
 8752: #    my $lasttime = &Time::HiRes::time()-$start;
 8753: #    $r->print("<p>took $lasttime</p>");
 8754: 
 8755:     $r->print("</form>");
 8756:     return '';
 8757: }
 8758: 
 8759: sub graders_resources_pass {
 8760:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8761:         $bubbles_per_row) = @_;
 8762:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8763:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8764:         foreach my $resource (@{$resources}) {
 8765:             my $ressymb = $resource->symb();
 8766:             my ($analysis,$parts) =
 8767:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8768:                                           $env{'user.name'},$env{'user.domain'},
 8769:                                           1,$bubbles_per_row);
 8770:             $grader_partids_by_symb->{$ressymb} = $parts;
 8771:             if (ref($analysis) eq 'HASH') {
 8772:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8773:                     $grader_randomlists_by_symb->{$ressymb} =
 8774:                         $analysis->{'parts_withrandomlist'};
 8775:                 }
 8776:             }
 8777:         }
 8778:     }
 8779:     return;
 8780: }
 8781: 
 8782: =pod
 8783: 
 8784: =item users_order
 8785: 
 8786:   Returns array of resources in current map, ordered based on either CODE,
 8787:   if this is a CODEd exam, or based on student's identity if this is a 
 8788:   "NAMEd" exam.
 8789: 
 8790:   Should be used when randomorder and/or randompick applied when the 
 8791:   corresponding exam was printed, prior to students completing bubblesheets 
 8792:   for the version of the exam the student received.
 8793: 
 8794: =cut
 8795: 
 8796: sub users_order  {
 8797:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8798:     my @mapresources;
 8799:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8800:         return @mapresources;
 8801:     }
 8802:     if ($scancode) {
 8803:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8804:             @mapresources = @{$orderedforcode->{$scancode}};
 8805:         } else {
 8806:             $env{'form.CODE'} = $scancode;
 8807:             my $actual_seq =
 8808:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8809:                                                                $master_seq,
 8810:                                                                $user,$scancode,1);
 8811:             if (ref($actual_seq) eq 'ARRAY') {
 8812:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8813:                 if (ref($orderedforcode) eq 'HASH') {
 8814:                     if (@mapresources > 0) { 
 8815:                         $orderedforcode->{$scancode} = \@mapresources;
 8816:                     }
 8817:                 }
 8818:             }
 8819:             delete($env{'form.CODE'});
 8820:         }
 8821:     } else {
 8822:         my $actual_seq =
 8823:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8824:                                                            $master_seq,
 8825:                                                            $user,undef,1);
 8826:         if (ref($actual_seq) eq 'ARRAY') {
 8827:             @mapresources = 
 8828:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8829:         }
 8830:     }
 8831:     return @mapresources;
 8832: }
 8833: 
 8834: sub grade_student_bubbles {
 8835:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8836:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8837:     my $uselookup = 0;
 8838:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8839:         (ref($startline) eq 'HASH')) {
 8840:         $uselookup = 1;
 8841:     }
 8842: 
 8843:     if (ref($resources) eq 'ARRAY') {
 8844:         my $count = 0;
 8845:         foreach my $resource (@{$resources}) {
 8846:             my $ressymb = $resource->symb();
 8847:             my %form = ('submitted'      => 'scantron',
 8848:                         'grade_target'   => 'grade',
 8849:                         'grade_username' => $uname,
 8850:                         'grade_domain'   => $udom,
 8851:                         'grade_courseid' => $env{'request.course.id'},
 8852:                         'grade_symb'     => $ressymb,
 8853:                         'CODE'           => $scancode
 8854:                        );
 8855:             if ($bubbles_per_row ne '') {
 8856:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8857:             }
 8858:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8859:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8860:             }
 8861:             if (ref($parts) eq 'HASH') {
 8862:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8863:                     foreach my $part (@{$parts->{$ressymb}}) {
 8864:                         if ($uselookup) {
 8865:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8866:                         } else {
 8867:                             $form{'scantron_questnum_start.'.$part} =
 8868:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8869:                         }
 8870:                         $count++;
 8871:                     }
 8872:                 }
 8873:             }
 8874:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8875:             return 'ssi_error' if ($ssi_error);
 8876:             last if (&Apache::loncommon::connection_aborted($r));
 8877:         }
 8878:     }
 8879:     return;
 8880: }
 8881: 
 8882: sub scantron_upload_scantron_data {
 8883:     my ($r,$symb)=@_;
 8884:     my $dom = $env{'request.role.domain'};
 8885:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8886:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8887:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8888: 							  'domainid',
 8889: 							  'coursename',$dom);
 8890:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8891:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8892:     my $default_form_data=&defaultFormData($symb);
 8893:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8894:     &js_escape(\$nofile_alert);
 8895:     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.");
 8896:     &js_escape(\$nocourseid_alert);
 8897:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8898:     function checkUpload(formname) {
 8899: 	if (formname.upfile.value == "") {
 8900: 	    alert("'.$nofile_alert.'");
 8901: 	    return false;
 8902: 	}
 8903:         if (formname.courseid.value == "") {
 8904:             alert("'.$nocourseid_alert.'");
 8905:             return false;
 8906:         }
 8907: 	formname.submit();
 8908:     }
 8909: 
 8910:     function ToSyllabus() {
 8911:         var cdom = '."'$dom'".';
 8912:         var cnum = document.rules.courseid.value;
 8913:         if (cdom == "" || cdom == null) {
 8914:             return;
 8915:         }
 8916:         if (cnum == "" || cnum == null) {
 8917:            return;
 8918:         }
 8919:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8920:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8921:         return;
 8922:     }
 8923: 
 8924: '));
 8925:     $r->print('
 8926: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8927: 
 8928: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8929: '.$default_form_data.
 8930:   &Apache::lonhtmlcommon::start_pick_box().
 8931:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8932:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8933:   &Apache::lonhtmlcommon::row_closure().
 8934:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8935:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8936:   &Apache::lonhtmlcommon::row_closure().
 8937:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8938:   '<input name="domainid" type="hidden" />'.$domdesc.
 8939:   &Apache::lonhtmlcommon::row_closure().
 8940:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8941:   '<input type="file" name="upfile" size="50" />'.
 8942:   &Apache::lonhtmlcommon::row_closure(1).
 8943:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8944: 
 8945: <input name="command" value="scantronupload_save" type="hidden" />
 8946: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8947: </form>
 8948: ');
 8949:     return '';
 8950: }
 8951: 
 8952: 
 8953: sub scantron_upload_scantron_data_save {
 8954:     my($r,$symb)=@_;
 8955:     my $doanotherupload=
 8956: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8957: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8958: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8959: 	'</form>'."\n";
 8960:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8961: 	!&Apache::lonnet::allowed('usc',
 8962: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8963: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8964: 	unless ($symb) {
 8965: 	    $r->print($doanotherupload);
 8966: 	}
 8967: 	return '';
 8968:     }
 8969:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8970:     my $uploadedfile;
 8971:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8972:     if (length($env{'form.upfile'}) < 2) {
 8973:         $r->print(
 8974:             &Apache::lonhtmlcommon::confirm_success(
 8975:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8976:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8977:     } else {
 8978:         my $result = 
 8979:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8980:                                             $env{'form.courseid'},$env{'form.domainid'});
 8981:         if ($result =~ m{^/uploaded/}) {
 8982:             $r->print(
 8983:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8984:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8985:                         (length($env{'form.upfile'})-1),
 8986:                         '<span class="LC_filename">'.$result.'</span>'));
 8987:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8988:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8989:                                                        $env{'form.courseid'},$uploadedfile));
 8990:         } else {
 8991:             $r->print(
 8992:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8993:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8994:                           $result,
 8995: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8996: 	}
 8997:     }
 8998:     if ($symb) {
 8999: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9000:     } else {
 9001: 	$r->print($doanotherupload);
 9002:     }
 9003:     return '';
 9004: }
 9005: 
 9006: sub validate_uploaded_scantron_file {
 9007:     my ($cdom,$cname,$fname) = @_;
 9008:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9009:     my @lines;
 9010:     if ($scanlines ne '-1') {
 9011:         @lines=split("\n",$scanlines,-1);
 9012:     }
 9013:     my $output;
 9014:     if (@lines) {
 9015:         my (%counts,$max_match_format);
 9016:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9017:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9018:         my %idmap = &username_to_idmap($classlist);
 9019:         foreach my $key (keys(%idmap)) {
 9020:             my $lckey = lc($key);
 9021:             $idmap{$lckey} = $idmap{$key};
 9022:         }
 9023:         my %unique_formats;
 9024:         my @formatlines = &get_scantronformat_file();
 9025:         foreach my $line (@formatlines) {
 9026:             chomp($line);
 9027:             my @config = split(/:/,$line);
 9028:             my $idstart = $config[5];
 9029:             my $idlength = $config[6];
 9030:             if (($idstart ne '') && ($idlength > 0)) {
 9031:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9032:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9033:                 } else {
 9034:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9035:                 }
 9036:             }
 9037:         }
 9038:         foreach my $key (keys(%unique_formats)) {
 9039:             my ($idstart,$idlength) = split(':',$key);
 9040:             %{$counts{$key}} = (
 9041:                                'found'   => 0,
 9042:                                'total'   => 0,
 9043:                               );
 9044:             foreach my $line (@lines) {
 9045:                 next if ($line =~ /^#/);
 9046:                 next if ($line =~ /^[\s\cz]*$/);
 9047:                 my $id = substr($line,$idstart-1,$idlength);
 9048:                 $id = lc($id);
 9049:                 if (exists($idmap{$id})) {
 9050:                     $counts{$key}{'found'} ++;
 9051:                 }
 9052:                 $counts{$key}{'total'} ++;
 9053:             }
 9054:             if ($counts{$key}{'total'}) {
 9055:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9056:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9057:                     $max_match_pct = $percent_match;
 9058:                     $max_match_format = $key;
 9059:                     $found_match_count = $counts{$key}{'found'};
 9060:                     $max_match_count = $counts{$key}{'total'};
 9061:                 }
 9062:             }
 9063:         }
 9064:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9065:             my $format_descs;
 9066:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9067:             for (my $i=0; $i<$numwithformat; $i++) {
 9068:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9069:                 if ($i<$numwithformat-2) {
 9070:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9071:                 } elsif ($i==$numwithformat-2) {
 9072:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9073:                 } elsif ($i==$numwithformat-1) {
 9074:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9075:                 }
 9076:             }
 9077:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9078:             $output .= '<br />';
 9079:             if ($found_match_count == $max_match_count) {
 9080:                 # 100% matching entries
 9081:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9082:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9083:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9084:                 &mt('Comparison of student IDs in the uploaded file with'.
 9085:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9086:                     ' in the file (for the format defined for [_3]).',
 9087:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9088:             } else {
 9089:                 # Not all entries matching? -> Show warning and additional info
 9090:                 $output .=
 9091:                     &Apache::lonhtmlcommon::confirm_success(
 9092:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9093:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9094:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9095:                     &mt('Comparison of student IDs in the uploaded file with'.
 9096:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9097:                         ' in the file (for the format defined for [_3]).',
 9098:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9099:                     '<p class="LC_info">'.
 9100:                     &mt('A low percentage of matches results from one of the following:').
 9101:                     '</p><ul>'.
 9102:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9103:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9104:                                '<i>'.$cdom.'</i>').'</li>'.
 9105:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9106:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9107:                     '</ul>';
 9108:             }
 9109:         }
 9110:     } else {
 9111:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9112:     }
 9113:     return $output;
 9114: }
 9115: 
 9116: sub valid_file {
 9117:     my ($requested_file)=@_;
 9118:     foreach my $filename (sort(&scantron_filenames())) {
 9119: 	if ($requested_file eq $filename) { return 1; }
 9120:     }
 9121:     return 0;
 9122: }
 9123: 
 9124: sub scantron_download_scantron_data {
 9125:     my ($r,$symb)=@_;
 9126:     my $default_form_data=&defaultFormData($symb);
 9127:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9128:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9129:     my $file=$env{'form.scantron_selectfile'};
 9130:     if (! &valid_file($file)) {
 9131: 	$r->print('
 9132: 	<p>
 9133: 	    '.&mt('The requested filename was invalid.').'
 9134:         </p>
 9135: ');
 9136: 	return;
 9137:     }
 9138:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9139:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9140:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9141:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9142:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9143:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9144:     $r->print('
 9145:     <p>
 9146: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9147: 	      '<a href="'.$orig.'">','</a>').'
 9148:     </p>
 9149:     <p>
 9150: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9151: 	      '<a href="'.$corrected.'">','</a>').'
 9152:     </p>
 9153:     <p>
 9154: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9155: 	      '<a href="'.$skipped.'">','</a>').'
 9156:     </p>
 9157: ');
 9158:     return '';
 9159: }
 9160: 
 9161: sub checkscantron_results {
 9162:     my ($r,$symb) = @_;
 9163:     if (!$symb) {return '';}
 9164:     my $cid = $env{'request.course.id'};
 9165:     my %lettdig = &letter_to_digits();
 9166:     my $numletts = scalar(keys(%lettdig));
 9167:     my $cnum = $env{'course.'.$cid.'.num'};
 9168:     my $cdom = $env{'course.'.$cid.'.domain'};
 9169:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9170:     my %record;
 9171:     my %scantron_config =
 9172:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9173:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9174:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9175:     my $classlist=&Apache::loncoursedata::get_classlist();
 9176:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9177:     my $navmap=Apache::lonnavmaps::navmap->new();
 9178:     unless (ref($navmap)) {
 9179:         $r->print(&navmap_errormsg());
 9180:         return '';
 9181:     }
 9182:     my $map=$navmap->getResourceByUrl($sequence);
 9183:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9184:         %grader_randomlists_by_symb,%orderedforcode);
 9185:     if (ref($map)) { 
 9186:         $randomorder=$map->randomorder();
 9187:         $randompick=$map->randompick();
 9188:     }
 9189:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9190:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9191:     if ($nav_error) {
 9192:         $r->print(&navmap_errormsg());
 9193:         return '';
 9194:     }
 9195:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9196:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9197:     my ($uname,$udom);
 9198:     my (%scandata,%lastname,%bylast);
 9199:     $r->print('
 9200: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9201: 
 9202:     my @delayqueue;
 9203:     my %completedstudents;
 9204: 
 9205:     my $count=&get_todo_count($scanlines,$scan_data);
 9206:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9207:     my ($username,$domain,$started);
 9208:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9209:     if ($nav_error) {
 9210:         $r->print(&navmap_errormsg());
 9211:         return '';
 9212:     }
 9213: 
 9214:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9215:     my $start=&Time::HiRes::time();
 9216:     my $i=-1;
 9217: 
 9218:     while ($i<$scanlines->{'count'}) {
 9219:         ($username,$domain,$uname)=('','','');
 9220:         $i++;
 9221:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9222:         if ($line=~/^[\s\cz]*$/) { next; }
 9223:         if ($started) {
 9224:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9225:         }
 9226:         $started=1;
 9227:         my $scan_record=
 9228:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9229:                                                      $scan_data);
 9230:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9231:                                               \%idmap,$i)) {
 9232:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9233:                                 'Unable to find a student that matches',1);
 9234:             next;
 9235:         }
 9236:         if (exists $completedstudents{$uname}) {
 9237:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9238:                                 'Student '.$uname.' has multiple sheets',2);
 9239:             next;
 9240:         }
 9241:         my $pid = $scan_record->{'scantron.ID'};
 9242:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9243:         push(@{$bylast{$lastname{$pid}}},$pid);
 9244:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9245:         my $user = $uname.':'.$usec;
 9246:         ($username,$domain)=split(/:/,$uname);
 9247: 
 9248:         my $scancode;
 9249:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9250:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9251:             $scancode = $scan_record->{'scantron.CODE'};
 9252:         } else {
 9253:             $scancode = '';
 9254:         }
 9255: 
 9256:         my @mapresources = @resources;
 9257:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9258:         my %respnumlookup=();
 9259:         my %startline=();
 9260:         if ($randomorder || $randompick) {
 9261:             @mapresources =
 9262:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9263:                              \%orderedforcode);
 9264:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9265:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9266:                                              \%grader_partids_by_symb,\%orderedforcode,
 9267:                                              \%respnumlookup,\%startline);
 9268:             if ($randompick && $total) {
 9269:                 $lastpos = $total*$scantron_config{'Qlength'};
 9270:             }
 9271:         }
 9272:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9273:         chomp($scandata{$pid});
 9274:         $scandata{$pid} =~ s/\r$//;
 9275: 
 9276:         my $counter = -1;
 9277:         foreach my $resource (@mapresources) {
 9278:             my $parts;
 9279:             my $ressymb = $resource->symb();
 9280:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9281:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9282:                 my $currcode;
 9283:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9284:                     $currcode = $scancode;
 9285:                 }
 9286:                 (my $analysis,$parts) =
 9287:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9288:                                               $username,$domain,undef,
 9289:                                               $bubbles_per_row,$currcode);
 9290:             } else {
 9291:                 $parts = $grader_partids_by_symb{$ressymb};
 9292:             }
 9293:             ($counter,my $recording) =
 9294:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9295:                                          $scandata{$pid},$parts,
 9296:                                          \%scantron_config,\%lettdig,$numletts,
 9297:                                          $randomorder,$randompick,
 9298:                                          \%respnumlookup,\%startline);
 9299:             $record{$pid} .= $recording;
 9300:         }
 9301:     }
 9302:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9303:     $r->print('<br />');
 9304:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9305:     $passed = 0;
 9306:     $failed = 0;
 9307:     $numstudents = 0;
 9308:     foreach my $last (sort(keys(%bylast))) {
 9309:         if (ref($bylast{$last}) eq 'ARRAY') {
 9310:             foreach my $pid (sort(@{$bylast{$last}})) {
 9311:                 my $showscandata = $scandata{$pid};
 9312:                 my $showrecord = $record{$pid};
 9313:                 $showscandata =~ s/\s/&nbsp;/g;
 9314:                 $showrecord =~ s/\s/&nbsp;/g;
 9315:                 if ($scandata{$pid} eq $record{$pid}) {
 9316:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9317:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9318: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9319: '</tr>'."\n".
 9320: '<tr class="'.$css_class.'">'."\n".
 9321: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9322:                     $passed ++;
 9323:                 } else {
 9324:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9325:                     $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".
 9326: '</tr>'."\n".
 9327: '<tr class="'.$css_class.'">'."\n".
 9328: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9329: '</tr>'."\n";
 9330:                     $failed ++;
 9331:                 }
 9332:                 $numstudents ++;
 9333:             }
 9334:         }
 9335:     }
 9336:     $r->print(
 9337:         '<p>'
 9338:        .&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).',
 9339:             '<b>',
 9340:             $numstudents,
 9341:             '</b>',
 9342:             $env{'form.scantron_maxbubble'})
 9343:        .'</p>'
 9344:     );
 9345:     $r->print('<p>'
 9346:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9347:              .'<br />'
 9348:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9349:              .'</p>'
 9350:     );
 9351:     if ($passed) {
 9352:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9353:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9354:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9355:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9356:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9357:                  $okstudents."\n".
 9358:                  &Apache::loncommon::end_data_table().'<br />');
 9359:     }
 9360:     if ($failed) {
 9361:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9362:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9363:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9364:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9365:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9366:                  $badstudents."\n".
 9367:                  &Apache::loncommon::end_data_table()).'<br />'.
 9368:                  &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.');  
 9369:     }
 9370:     $r->print('</form><br />');
 9371:     return;
 9372: }
 9373: 
 9374: sub verify_scantron_grading {
 9375:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9376:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9377:         $respnumlookup,$startline) = @_;
 9378:     my ($record,%expected,%startpos);
 9379:     return ($counter,$record) if (!ref($resource));
 9380:     return ($counter,$record) if (!$resource->is_problem());
 9381:     my $symb = $resource->symb();
 9382:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9383:     foreach my $part_id (@{$partids}) {
 9384:         $counter ++;
 9385:         $expected{$part_id} = 0;
 9386:         my $respnum = $counter;
 9387:         if ($randomorder || $randompick) {
 9388:             $respnum = $respnumlookup->{$counter};
 9389:             $startpos{$part_id} = $startline->{$counter} + 1;
 9390:         } else {
 9391:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9392:         }
 9393:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9394:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9395:             foreach my $item (@sub_lines) {
 9396:                 $expected{$part_id} += $item;
 9397:             }
 9398:         } else {
 9399:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9400:         }
 9401:     }
 9402:     if ($symb) {
 9403:         my %recorded;
 9404:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9405:         if ($returnhash{'version'}) {
 9406:             my %lasthash=();
 9407:             my $version;
 9408:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9409:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9410:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9411:                 }
 9412:             }
 9413:             foreach my $key (keys(%lasthash)) {
 9414:                 if ($key =~ /\.scantron$/) {
 9415:                     my $value = &unescape($lasthash{$key});
 9416:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9417:                     if ($value eq '') {
 9418:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9419:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9420:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9421:                             }
 9422:                         }
 9423:                     } else {
 9424:                         my @tocheck;
 9425:                         my @items = split(//,$value);
 9426:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9427:                             ($scantron_config->{'Qon'} eq 'number')) {
 9428:                             if (@items < $expected{$part_id}) {
 9429:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9430:                                 my @singles = split(//,$fragment);
 9431:                                 foreach my $pos (@singles) {
 9432:                                     if ($pos eq ' ') {
 9433:                                         push(@tocheck,$pos);
 9434:                                     } else {
 9435:                                         my $next = shift(@items);
 9436:                                         push(@tocheck,$next);
 9437:                                     }
 9438:                                 }
 9439:                             } else {
 9440:                                 @tocheck = @items;
 9441:                             }
 9442:                             foreach my $letter (@tocheck) {
 9443:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9444:                                     if ($letter !~ /^[A-J]$/) {
 9445:                                         $letter = $scantron_config->{'Qoff'};
 9446:                                     }
 9447:                                     $recorded{$part_id} .= $letter;
 9448:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9449:                                     my $digit;
 9450:                                     if ($letter !~ /^[A-J]$/) {
 9451:                                         $digit = $scantron_config->{'Qoff'};
 9452:                                     } else {
 9453:                                         $digit = $lettdig->{$letter};
 9454:                                     }
 9455:                                     $recorded{$part_id} .= $digit;
 9456:                                 }
 9457:                             }
 9458:                         } else {
 9459:                             @tocheck = @items;
 9460:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9461:                                 my $curr_sub = shift(@tocheck);
 9462:                                 my $digit;
 9463:                                 if ($curr_sub =~ /^[A-J]$/) {
 9464:                                     $digit = $lettdig->{$curr_sub}-1;
 9465:                                 }
 9466:                                 if ($curr_sub eq 'J') {
 9467:                                     $digit += scalar($numletts);
 9468:                                 }
 9469:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9470:                                     if ($j == $digit) {
 9471:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9472:                                     } else {
 9473:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9474:                                     }
 9475:                                 }
 9476:                             }
 9477:                         }
 9478:                     }
 9479:                 }
 9480:             }
 9481:         }
 9482:         foreach my $part_id (@{$partids}) {
 9483:             if ($recorded{$part_id} eq '') {
 9484:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9485:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9486:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9487:                     }
 9488:                 }
 9489:             }
 9490:             $record .= $recorded{$part_id};
 9491:         }
 9492:     }
 9493:     return ($counter,$record);
 9494: }
 9495: 
 9496: sub letter_to_digits {
 9497:     my %lettdig = (
 9498:                     A => 1,
 9499:                     B => 2,
 9500:                     C => 3,
 9501:                     D => 4,
 9502:                     E => 5,
 9503:                     F => 6,
 9504:                     G => 7,
 9505:                     H => 8,
 9506:                     I => 9,
 9507:                     J => 0,
 9508:                   );
 9509:     return %lettdig;
 9510: }
 9511: 
 9512: 
 9513: #-------- end of section for handling grading scantron forms -------
 9514: #
 9515: #-------------------------------------------------------------------
 9516: 
 9517: #-------------------------- Menu interface -------------------------
 9518: #
 9519: #--- Href with symb and command ---
 9520: 
 9521: sub href_symb_cmd {
 9522:     my ($symb,$cmd)=@_;
 9523:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9524: }
 9525: 
 9526: sub grading_menu {
 9527:     my ($request,$symb) = @_;
 9528:     if (!$symb) {return '';}
 9529: 
 9530:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9531:                   'command'=>'individual');
 9532:     
 9533:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9534: 
 9535:     $fields{'command'}='ungraded';
 9536:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9537: 
 9538:     $fields{'command'}='table';
 9539:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9540: 
 9541:     $fields{'command'}='all_for_one';
 9542:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9543: 
 9544:     $fields{'command'}='downloadfilesselect';
 9545:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9546: 
 9547:     $fields{'command'} = 'csvform';
 9548:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9549:     
 9550:     $fields{'command'} = 'processclicker';
 9551:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9552:     
 9553:     $fields{'command'} = 'scantron_selectphase';
 9554:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9555: 
 9556:     $fields{'command'} = 'initialverifyreceipt';
 9557:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9558:     
 9559:     my @menu = ({	categorytitle=>'Hand Grading',
 9560:             items =>[
 9561:                         {	linktext => 'Select individual students to grade',
 9562:                     		url => $url1a,
 9563:                     		permission => 'F',
 9564:                     		icon => 'grade_students.png',
 9565:                     		linktitle => 'Grade current resource for a selection of students.'
 9566:                         }, 
 9567:                         {       linktext => 'Grade ungraded submissions.',
 9568:                                 url => $url1b,
 9569:                                 permission => 'F',
 9570:                                 icon => 'ungrade_sub.png',
 9571:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9572:                         },
 9573: 
 9574:                         {       linktext => 'Grading table',
 9575:                                 url => $url1c,
 9576:                                 permission => 'F',
 9577:                                 icon => 'grading_table.png',
 9578:                                 linktitle => 'Grade current resource for all students.'
 9579:                         },
 9580:                         {       linktext => 'Grade page/folder for one student',
 9581:                                 url => $url1d,
 9582:                                 permission => 'F',
 9583:                                 icon => 'grade_PageFolder.png',
 9584:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9585:                         },
 9586:                         {       linktext => 'Download submissions',
 9587:                                 url => $url1e,
 9588:                                 permission => 'F',
 9589:                                 icon => 'download_sub.png',
 9590:                                 linktitle => 'Download all students submissions.'
 9591:                         }]},
 9592:                          { categorytitle=>'Automated Grading',
 9593:                items =>[
 9594: 
 9595:                 	    {	linktext => 'Upload Scores',
 9596:                     		url => $url2,
 9597:                     		permission => 'F',
 9598:                     		icon => 'uploadscores.png',
 9599:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9600:                 	    },
 9601:                 	    {	linktext => 'Process Clicker',
 9602:                     		url => $url3,
 9603:                     		permission => 'F',
 9604:                     		icon => 'addClickerInfoFile.png',
 9605:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9606:                 	    },
 9607:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9608:                     		url => $url4,
 9609:                     		permission => 'F',
 9610:                     		icon => 'bubblesheet.png',
 9611:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9612:                 	    },
 9613:                             {   linktext => 'Verify Receipt Number',
 9614:                                 url => $url5,
 9615:                                 permission => 'F',
 9616:                                 icon => 'receipt_number.png',
 9617:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9618:                             }
 9619: 
 9620:                     ]
 9621:             });
 9622: 
 9623:     # Create the menu
 9624:     my $Str;
 9625:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9626:     $Str .= '<input type="hidden" name="command" value="" />'.
 9627:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9628: 
 9629:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9630:     return $Str;    
 9631: }
 9632: 
 9633: 
 9634: sub ungraded {
 9635:     my ($request)=@_;
 9636:     &submit_options($request);
 9637: }
 9638: 
 9639: sub submit_options_sequence {
 9640:     my ($request,$symb) = @_;
 9641:     if (!$symb) {return '';}
 9642:     &commonJSfunctions($request);
 9643:     my $result;
 9644: 
 9645:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9646:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9647:     $result.=&selectfield(0).
 9648:             '<input type="hidden" name="command" value="pickStudentPage" />
 9649:             <div>
 9650:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9651:             </div>
 9652:         </div>
 9653:   </form>';
 9654:     return $result;
 9655: }
 9656: 
 9657: sub submit_options_table {
 9658:     my ($request,$symb) = @_;
 9659:     if (!$symb) {return '';}
 9660:     &commonJSfunctions($request);
 9661:     my $result;
 9662: 
 9663:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9664:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9665: 
 9666:     $result.=&selectfield(1).
 9667:             '<input type="hidden" name="command" value="viewgrades" />
 9668:             <div>
 9669:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9670:             </div>
 9671:         </div>
 9672:   </form>';
 9673:     return $result;
 9674: }
 9675: 
 9676: sub submit_options_download {
 9677:     my ($request,$symb) = @_;
 9678:     if (!$symb) {return '';}
 9679: 
 9680:     &commonJSfunctions($request);
 9681: 
 9682:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9683:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9684:     $result.='
 9685: <h2>
 9686:   '.&mt('Select Students for Which to Download Submissions').'
 9687: </h2>'.&selectfield(1).'
 9688:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9689:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9690:             </div>
 9691:           </div>
 9692: 
 9693: 
 9694:   </form>';
 9695:     return $result;
 9696: }
 9697: 
 9698: #--- Displays the submissions first page -------
 9699: sub submit_options {
 9700:     my ($request,$symb) = @_;
 9701:     if (!$symb) {return '';}
 9702: 
 9703:     &commonJSfunctions($request);
 9704:     my $result;
 9705: 
 9706:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9707: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9708:     $result.=&selectfield(1).'
 9709:                 <input type="hidden" name="command" value="submission" /> 
 9710: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9711:             </div>
 9712:           </div>
 9713: 
 9714: 
 9715:   </form>';
 9716:     return $result;
 9717: }
 9718: 
 9719: sub selectfield {
 9720:    my ($full)=@_;
 9721:    my %options = 
 9722:           (&substatus_options,
 9723:            'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9724:    my $result='<div class="LC_columnSection">
 9725:   
 9726:     <fieldset>
 9727:       <legend>
 9728:        '.&mt('Sections').'
 9729:       </legend>
 9730:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9731:     </fieldset>
 9732:   
 9733:     <fieldset>
 9734:       <legend>
 9735:         '.&mt('Groups').'
 9736:       </legend>
 9737:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9738:     </fieldset>
 9739:   
 9740:     <fieldset>
 9741:       <legend>
 9742:         '.&mt('Access Status').'
 9743:       </legend>
 9744:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9745:     </fieldset>';
 9746:     if ($full) {
 9747:        $result.='
 9748:     <fieldset>
 9749:       <legend>
 9750:         '.&mt('Submission Status').'
 9751:       </legend>'.
 9752:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9753:    '</fieldset>';
 9754:     }
 9755:     $result.='</div><br />';
 9756:     return $result;
 9757: }
 9758: 
 9759: sub substatus_options {
 9760:     return &Apache::lonlocal::texthash(
 9761:                                       'yes'       => 'with submissions',
 9762:                                       'queued'    => 'in grading queue',
 9763:                                       'graded'    => 'with ungraded submissions',
 9764:                                       'incorrect' => 'with incorrect submissions',
 9765:                                       'all'       => 'with any status',
 9766:                                       );
 9767: }
 9768: 
 9769: sub reset_perm {
 9770:     undef(%perm);
 9771: }
 9772: 
 9773: sub init_perm {
 9774:     &reset_perm();
 9775:     foreach my $test_perm ('vgr','mgr','opa') {
 9776: 
 9777: 	my $scope = $env{'request.course.id'};
 9778: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9779: 
 9780: 	    $scope .= '/'.$env{'request.course.sec'};
 9781: 	    if ( $perm{$test_perm}=
 9782: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9783: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9784: 	    } else {
 9785: 		delete($perm{$test_perm});
 9786: 	    }
 9787: 	}
 9788:     }
 9789: }
 9790: 
 9791: sub init_old_essays {
 9792:     my ($symb,$apath,$adom,$aname) = @_;
 9793:     if ($symb ne '') {
 9794:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9795:         if (keys(%essays) > 0) {
 9796:             $old_essays{$symb} = \%essays;
 9797:         }
 9798:     }
 9799:     return;
 9800: }
 9801: 
 9802: sub reset_old_essays {
 9803:     undef(%old_essays);
 9804: }
 9805: 
 9806: sub gather_clicker_ids {
 9807:     my %clicker_ids;
 9808: 
 9809:     my $classlist = &Apache::loncoursedata::get_classlist();
 9810: 
 9811:     # Set up a couple variables.
 9812:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9813:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9814:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9815: 
 9816:     foreach my $student (keys(%$classlist)) {
 9817:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9818:         my $username = $classlist->{$student}->[$username_idx];
 9819:         my $domain   = $classlist->{$student}->[$domain_idx];
 9820:         my $clickers =
 9821: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9822:         foreach my $id (split(/\,/,$clickers)) {
 9823:             $id=~s/^[\#0]+//;
 9824:             $id=~s/[\-\:]//g;
 9825:             if (exists($clicker_ids{$id})) {
 9826: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9827:             } else {
 9828: 		$clicker_ids{$id}=$username.':'.$domain;
 9829:             }
 9830:         }
 9831:     }
 9832:     return %clicker_ids;
 9833: }
 9834: 
 9835: sub gather_adv_clicker_ids {
 9836:     my %clicker_ids;
 9837:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9838:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9839:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9840:     foreach my $element (sort(keys(%coursepersonnel))) {
 9841:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9842:             my ($puname,$pudom)=split(/\:/,$person);
 9843:             my $clickers =
 9844: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9845:             foreach my $id (split(/\,/,$clickers)) {
 9846: 		$id=~s/^[\#0]+//;
 9847:                 $id=~s/[\-\:]//g;
 9848: 		if (exists($clicker_ids{$id})) {
 9849: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9850: 		} else {
 9851: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9852: 		}
 9853:             }
 9854:         }
 9855:     }
 9856:     return %clicker_ids;
 9857: }
 9858: 
 9859: sub clicker_grading_parameters {
 9860:     return ('gradingmechanism' => 'scalar',
 9861:             'upfiletype' => 'scalar',
 9862:             'specificid' => 'scalar',
 9863:             'pcorrect' => 'scalar',
 9864:             'pincorrect' => 'scalar');
 9865: }
 9866: 
 9867: sub process_clicker {
 9868:     my ($r,$symb)=@_;
 9869:     if (!$symb) {return '';}
 9870:     my $result=&checkforfile_js();
 9871:     $result.=&Apache::loncommon::start_data_table().
 9872:              &Apache::loncommon::start_data_table_header_row().
 9873:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9874:              &Apache::loncommon::end_data_table_header_row().
 9875:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9876: # Attempt to restore parameters from last session, set defaults if not present
 9877:     my %Saveable_Parameters=&clicker_grading_parameters();
 9878:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9879:                                                  \%Saveable_Parameters);
 9880:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9881:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9882:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9883:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9884: 
 9885:     my %checked;
 9886:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9887:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9888:           $checked{$gradingmechanism}=' checked="checked"';
 9889:        }
 9890:     }
 9891: 
 9892:     my $upload=&mt("Evaluate File");
 9893:     my $type=&mt("Type");
 9894:     my $attendance=&mt("Award points just for participation");
 9895:     my $personnel=&mt("Correctness determined from response by course personnel");
 9896:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9897:     my $given=&mt("Correctness determined from given list of answers").' '.
 9898:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9899:     my $pcorrect=&mt("Percentage points for correct solution");
 9900:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9901:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9902: 						   {'iclicker' => 'i>clicker',
 9903:                                                     'interwrite' => 'interwrite PRS',
 9904:                                                     'turning' => 'Turning Technologies'});
 9905:     $symb = &Apache::lonenc::check_encrypt($symb);
 9906:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9907: function sanitycheck() {
 9908: // Accept only integer percentages
 9909:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9910:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9911: // Find out grading choice
 9912:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9913:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9914:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9915:       }
 9916:    }
 9917: // By default, new choice equals user selection
 9918:    newgradingchoice=gradingchoice;
 9919: // Not good to give more points for false answers than correct ones
 9920:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9921:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9922:    }
 9923: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9924:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9925:       document.forms.gradesupload.pcorrect.value=100;
 9926:       document.forms.gradesupload.pincorrect.value=100;
 9927:    }
 9928: // If the values are different, cannot be attendance only
 9929:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9930:        (gradingchoice=='attendance')) {
 9931:        newgradingchoice='personnel';
 9932:    }
 9933: // Change grading choice to new one
 9934:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9935:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9936:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9937:       } else {
 9938:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9939:       }
 9940:    }
 9941: // Remember the old state
 9942:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9943: }
 9944: ENDUPFORM
 9945:     $result.= <<ENDUPFORM;
 9946: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9947: <input type="hidden" name="symb" value="$symb" />
 9948: <input type="hidden" name="command" value="processclickerfile" />
 9949: <input type="file" name="upfile" size="50" />
 9950: <br /><label>$type: $selectform</label>
 9951: ENDUPFORM
 9952:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9953:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9954:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9955: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9956: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9957: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9958: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9959: <br />&nbsp;&nbsp;&nbsp;
 9960: <input type="text" name="givenanswer" size="50" />
 9961: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9962: ENDGRADINGFORM
 9963:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9964:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9965:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9966: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9967: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9968: </form>'
 9969: ENDPERCFORM
 9970:     $result.='</td>'.
 9971:              &Apache::loncommon::end_data_table_row().
 9972:              &Apache::loncommon::end_data_table();
 9973:     return $result;
 9974: }
 9975: 
 9976: sub process_clicker_file {
 9977:     my ($r,$symb)=@_;
 9978:     if (!$symb) {return '';}
 9979: 
 9980:     my %Saveable_Parameters=&clicker_grading_parameters();
 9981:     &Apache::loncommon::store_course_settings('grades_clicker',
 9982:                                               \%Saveable_Parameters);
 9983:     my $result='';
 9984:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9985: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9986: 	return $result;
 9987:     }
 9988:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9989:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9990:         return $result;
 9991:     }
 9992:     my $foundgiven=0;
 9993:     if ($env{'form.gradingmechanism'} eq 'given') {
 9994:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9995:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9996:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9997:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9998:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9999:         $foundgiven=$#answers+1;
10000:     }
10001:     my %clicker_ids=&gather_clicker_ids();
10002:     my %correct_ids;
10003:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10004: 	%correct_ids=&gather_adv_clicker_ids();
10005:     }
10006:     if ($env{'form.gradingmechanism'} eq 'specific') {
10007: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10008: 	   $correct_id=~tr/a-z/A-Z/;
10009: 	   $correct_id=~s/\s//gs;
10010: 	   $correct_id=~s/^[\#0]+//;
10011:            $correct_id=~s/[\-\:]//g;
10012:            if ($correct_id) {
10013: 	      $correct_ids{$correct_id}='specified';
10014:            }
10015:         }
10016:     }
10017:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10018: 	$result.=&mt('Score based on attendance only');
10019:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10020:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10021:     } else {
10022: 	my $number=0;
10023: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10024: 	foreach my $id (sort(keys(%correct_ids))) {
10025: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10026: 	    if ($correct_ids{$id} eq 'specified') {
10027: 		$result.=&mt('specified');
10028: 	    } else {
10029: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10030: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10031: 	    }
10032: 	    $number++;
10033: 	}
10034:         $result.="</p>\n";
10035:         if ($number==0) {
10036:             $result .=
10037:                  &Apache::lonhtmlcommon::confirm_success(
10038:                      &mt('No IDs found to determine correct answer'),1);
10039:             return $result;
10040:         }
10041:     }
10042:     if (length($env{'form.upfile'}) < 2) {
10043:         $result .=
10044:             &Apache::lonhtmlcommon::confirm_success(
10045:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10046:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10047:         return $result;
10048:     }
10049: 
10050: # Were able to get all the info needed, now analyze the file
10051: 
10052:     $result.=&Apache::loncommon::studentbrowser_javascript();
10053:     $symb = &Apache::lonenc::check_encrypt($symb);
10054:     $result.=&Apache::loncommon::start_data_table().
10055:              &Apache::loncommon::start_data_table_header_row().
10056:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10057:              &Apache::loncommon::end_data_table_header_row().
10058:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10059: <td>
10060: <form method="post" action="/adm/grades" name="clickeranalysis">
10061: <input type="hidden" name="symb" value="$symb" />
10062: <input type="hidden" name="command" value="assignclickergrades" />
10063: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10064: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10065: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10066: ENDHEADER
10067:     if ($env{'form.gradingmechanism'} eq 'given') {
10068:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10069:     } 
10070:     my %responses;
10071:     my @questiontitles;
10072:     my $errormsg='';
10073:     my $number=0;
10074:     if ($env{'form.upfiletype'} eq 'iclicker') {
10075: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10076:     }
10077:     if ($env{'form.upfiletype'} eq 'interwrite') {
10078:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10079:     }
10080:     if ($env{'form.upfiletype'} eq 'turning') {
10081:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10082:     }
10083:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10084:              '<input type="hidden" name="number" value="'.$number.'" />'.
10085:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10086:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10087:              '<br />';
10088:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10089:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10090:        return $result;
10091:     } 
10092: # Remember Question Titles
10093: # FIXME: Possibly need delimiter other than ":"
10094:     for (my $i=0;$i<$number;$i++) {
10095:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10096:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10097:     }
10098:     my $correct_count=0;
10099:     my $student_count=0;
10100:     my $unknown_count=0;
10101: # Match answers with usernames
10102: # FIXME: Possibly need delimiter other than ":"
10103:     foreach my $id (keys(%responses)) {
10104:        if ($correct_ids{$id}) {
10105:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10106:           $correct_count++;
10107:        } elsif ($clicker_ids{$id}) {
10108:           if ($clicker_ids{$id}=~/\,/) {
10109: # More than one user with the same clicker!
10110:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10111:                            &Apache::loncommon::start_data_table_row()."<td>".
10112:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10113:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10114:                            "<select name='multi".$id."'>";
10115:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10116:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10117:              }
10118:              $result.='</select>';
10119:              $unknown_count++;
10120:           } else {
10121: # Good: found one and only one user with the right clicker
10122:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10123:              $student_count++;
10124:           }
10125:        } else {
10126:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10127:                            &Apache::loncommon::start_data_table_row()."<td>".
10128:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10129:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10130:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10131:                    "\n".&mt("Domain").": ".
10132:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10133:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10134:           $unknown_count++;
10135:        }
10136:     }
10137:     $result.='<hr />'.
10138:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10139:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10140:        if ($correct_count==0) {
10141:           $errormsg.="Found no correct answers for grading!";
10142:        } elsif ($correct_count>1) {
10143:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10144:        }
10145:     }
10146:     if ($number<1) {
10147:        $errormsg.="Found no questions.";
10148:     }
10149:     if ($errormsg) {
10150:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10151:     } else {
10152:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10153:     }
10154:     $result.='</form></td>'.
10155:              &Apache::loncommon::end_data_table_row().
10156:              &Apache::loncommon::end_data_table();
10157:     return $result;
10158: }
10159: 
10160: sub iclicker_eval {
10161:     my ($questiontitles,$responses)=@_;
10162:     my $number=0;
10163:     my $errormsg='';
10164:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10165:         my %components=&Apache::loncommon::record_sep($line);
10166:         my @entries=map {$components{$_}} (sort(keys(%components)));
10167: 	if ($entries[0] eq 'Question') {
10168: 	    for (my $i=3;$i<$#entries;$i+=6) {
10169: 		$$questiontitles[$number]=$entries[$i];
10170: 		$number++;
10171: 	    }
10172: 	}
10173: 	if ($entries[0]=~/^\#/) {
10174: 	    my $id=$entries[0];
10175: 	    my @idresponses;
10176: 	    $id=~s/^[\#0]+//;
10177: 	    for (my $i=0;$i<$number;$i++) {
10178: 		my $idx=3+$i*6;
10179:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10180: 		push(@idresponses,$entries[$idx]);
10181: 	    }
10182: 	    $$responses{$id}=join(',',@idresponses);
10183: 	}
10184:     }
10185:     return ($errormsg,$number);
10186: }
10187: 
10188: sub interwrite_eval {
10189:     my ($questiontitles,$responses)=@_;
10190:     my $number=0;
10191:     my $errormsg='';
10192:     my $skipline=1;
10193:     my $questionnumber=0;
10194:     my %idresponses=();
10195:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10196:         my %components=&Apache::loncommon::record_sep($line);
10197:         my @entries=map {$components{$_}} (sort(keys(%components)));
10198:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10199:         if ($entries[1] eq 'Response') { $skipline=1; }
10200:         next if $skipline;
10201:         if ($entries[0]!=$questionnumber) {
10202:            $questionnumber=$entries[0];
10203:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10204:            $number++;
10205:         }
10206:         my $id=$entries[4];
10207:         $id=~s/^[\#0]+//;
10208:         $id=~s/^v\d*\://i;
10209:         $id=~s/[\-\:]//g;
10210:         $idresponses{$id}[$number]=$entries[6];
10211:     }
10212:     foreach my $id (keys(%idresponses)) {
10213:        $$responses{$id}=join(',',@{$idresponses{$id}});
10214:        $$responses{$id}=~s/^\s*\,//;
10215:     }
10216:     return ($errormsg,$number);
10217: }
10218: 
10219: sub turning_eval {
10220:     my ($questiontitles,$responses)=@_;
10221:     my $number=0;
10222:     my $errormsg='';
10223:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10224:         my %components=&Apache::loncommon::record_sep($line);
10225:         my @entries=map {$components{$_}} (sort(keys(%components)));
10226:         if ($#entries>$number) { $number=$#entries; }
10227:         my $id=$entries[0];
10228:         my @idresponses;
10229:         $id=~s/^[\#0]+//;
10230:         unless ($id) { next; }
10231:         for (my $idx=1;$idx<=$#entries;$idx++) {
10232:             $entries[$idx]=~s/\,/\;/g;
10233:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10234:             push(@idresponses,$entries[$idx]);
10235:         }
10236:         $$responses{$id}=join(',',@idresponses);
10237:     }
10238:     for (my $i=1; $i<=$number; $i++) {
10239:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10240:     }
10241:     return ($errormsg,$number);
10242: }
10243: 
10244: 
10245: sub assign_clicker_grades {
10246:     my ($r,$symb)=@_;
10247:     if (!$symb) {return '';}
10248: # See which part we are saving to
10249:     my $res_error;
10250:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10251:     if ($res_error) {
10252:         return &navmap_errormsg();
10253:     }
10254: # FIXME: This should probably look for the first handgradeable part
10255:     my $part=$$partlist[0];
10256: # Start screen output
10257:     my $result=&Apache::loncommon::start_data_table().
10258:              &Apache::loncommon::start_data_table_header_row().
10259:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10260:              &Apache::loncommon::end_data_table_header_row().
10261:              &Apache::loncommon::start_data_table_row().'<td>';
10262: # Get correct result
10263: # FIXME: Possibly need delimiter other than ":"
10264:     my @correct=();
10265:     my $gradingmechanism=$env{'form.gradingmechanism'};
10266:     my $number=$env{'form.number'};
10267:     if ($gradingmechanism ne 'attendance') {
10268:        foreach my $key (keys(%env)) {
10269:           if ($key=~/^form\.correct\:/) {
10270:              my @input=split(/\,/,$env{$key});
10271:              for (my $i=0;$i<=$#input;$i++) {
10272:                  if (($correct[$i]) && ($input[$i]) &&
10273:                      ($correct[$i] ne $input[$i])) {
10274:                     $result.='<br /><span class="LC_warning">'.
10275:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10276:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10277:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10278:                     $correct[$i]=$input[$i];
10279:                  }
10280:              }
10281:           }
10282:        }
10283:        for (my $i=0;$i<$number;$i++) {
10284:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10285:              $result.='<br /><span class="LC_error">'.
10286:                       &mt('No correct result given for question "[_1]"!',
10287:                           $env{'form.question:'.$i}).'</span>';
10288:           }
10289:        }
10290:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10291:     }
10292: # Start grading
10293:     my $pcorrect=$env{'form.pcorrect'};
10294:     my $pincorrect=$env{'form.pincorrect'};
10295:     my $storecount=0;
10296:     my %users=();
10297:     foreach my $key (keys(%env)) {
10298:        my $user='';
10299:        if ($key=~/^form\.student\:(.*)$/) {
10300:           $user=$1;
10301:        }
10302:        if ($key=~/^form\.unknown\:(.*)$/) {
10303:           my $id=$1;
10304:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10305:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10306:           } elsif ($env{'form.multi'.$id}) {
10307:              $user=$env{'form.multi'.$id};
10308:           }
10309:        }
10310:        if ($user) {
10311:           if ($users{$user}) {
10312:              $result.='<br /><span class="LC_warning">'.
10313:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10314:                       '</span><br />';
10315:           }
10316:           $users{$user}=1; 
10317:           my @answer=split(/\,/,$env{$key});
10318:           my $sum=0;
10319:           my $realnumber=$number;
10320:           for (my $i=0;$i<$number;$i++) {
10321:              if  ($correct[$i] eq '-') {
10322:                 $realnumber--;
10323:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10324:                 if ($gradingmechanism eq 'attendance') {
10325:                    $sum+=$pcorrect;
10326:                 } elsif ($correct[$i] eq '*') {
10327:                    $sum+=$pcorrect;
10328:                 } else {
10329: # We actually grade if correct or not
10330:                    my $increment=$pincorrect;
10331: # Special case: numerical answer "0"
10332:                    if ($correct[$i] eq '0') {
10333:                       if ($answer[$i]=~/^[0\.]+$/) {
10334:                          $increment=$pcorrect;
10335:                       }
10336: # General numerical answer, both evaluate to something non-zero
10337:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10338:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10339:                          $increment=$pcorrect;
10340:                       }
10341: # Must be just alphanumeric
10342:                    } elsif ($answer[$i] eq $correct[$i]) {
10343:                       $increment=$pcorrect;
10344:                    }
10345:                    $sum+=$increment;
10346:                 }
10347:              }
10348:           }
10349:           my $ave=$sum/(100*$realnumber);
10350: # Store
10351:           my ($username,$domain)=split(/\:/,$user);
10352:           my %grades=();
10353:           $grades{"resource.$part.solved"}='correct_by_override';
10354:           $grades{"resource.$part.awarded"}=$ave;
10355:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10356:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10357:                                                  $env{'request.course.id'},
10358:                                                  $domain,$username);
10359:           if ($returncode ne 'ok') {
10360:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10361:           } else {
10362:              $storecount++;
10363:           }
10364:        }
10365:     }
10366: # We are done
10367:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10368:              '</td>'.
10369:              &Apache::loncommon::end_data_table_row().
10370:              &Apache::loncommon::end_data_table();
10371:     return $result;
10372: }
10373: 
10374: sub navmap_errormsg {
10375:     return '<div class="LC_error">'.
10376:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10377:            &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>').
10378:            '</div>';
10379: }
10380: 
10381: sub startpage {
10382:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10383:     if ($nomenu) {
10384:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10385:     } else {
10386:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10387:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10388:                                                  {'bread_crumbs' => $crumbs}));
10389:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10390:     }
10391:     unless ($nodisplayflag) {
10392:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10393:     }
10394: }
10395: 
10396: sub select_problem {
10397:     my ($r)=@_;
10398:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10399:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10400:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10401:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10402: }
10403: 
10404: sub handler {
10405:     my $request=$_[0];
10406:     &reset_caches();
10407:     if ($request->header_only) {
10408:         &Apache::loncommon::content_type($request,'text/html');
10409:         $request->send_http_header;
10410:         return OK;
10411:     }
10412:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10413: 
10414: # see what command we need to execute
10415: 
10416:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10417:     my $command=$commands[0];
10418: 
10419:     &init_perm();
10420:     if (!$env{'request.course.id'}) {
10421:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10422:                 ($command =~ /^scantronupload/)) {
10423:             # Not in a course.
10424:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10425:             return HTTP_NOT_ACCEPTABLE;
10426:         }
10427:     } elsif (!%perm) {
10428:         $request->internal_redirect('/adm/quickgrades');
10429:         return OK;
10430:     }
10431:     &Apache::loncommon::content_type($request,'text/html');
10432:     $request->send_http_header;
10433: 
10434:     if ($#commands > 0) {
10435: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10436:     }
10437: 
10438: # see what the symb is
10439: 
10440:     my $symb=$env{'form.symb'};
10441:     unless ($symb) {
10442:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10443:        $symb=&Apache::lonnet::symbread($url);
10444:     }
10445:     &Apache::lonenc::check_decrypt(\$symb);
10446: 
10447:     $ssi_error = 0;
10448:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10449: #
10450: # Not called from a resource, but inside a course
10451: #    
10452:         &startpage($request,undef,[],1,1);
10453:         &select_problem($request);
10454:     } else {
10455: 	if ($command eq 'submission' && $perm{'vgr'}) {
10456:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10457:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10458:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10459:                     &choose_task_version_form($symb,$env{'form.student'},
10460:                                               $env{'form.userdom'});
10461:             }
10462:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10463:             if ($versionform) {
10464:                 $request->print($versionform);
10465:             }
10466:             $request->print('<br clear="all" />');
10467: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10468:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10469:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10470:                 &choose_task_version_form($symb,$env{'form.student'},
10471:                                           $env{'form.userdom'},
10472:                                           $env{'form.inhibitmenu'});
10473:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10474:             if ($versionform) {
10475:                 $request->print($versionform);
10476:             }
10477:             $request->print('<br clear="all" />');
10478:             $request->print(&show_previous_task_version($request,$symb));
10479: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10480:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10481:                                        {href=>'',text=>'Select student'}],1,1);
10482: 	    &pickStudentPage($request,$symb);
10483: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10484:             &startpage($request,$symb,
10485:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10486:                                        {href=>'',text=>'Select student'},
10487:                                        {href=>'',text=>'Grade student'}],1,1);
10488: 	    &displayPage($request,$symb);
10489: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10490:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10491:                                        {href=>'',text=>'Select student'},
10492:                                        {href=>'',text=>'Grade student'},
10493:                                        {href=>'',text=>'Store grades'}],1,1);
10494: 	    &updateGradeByPage($request,$symb);
10495: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10496:             &startpage($request,$symb,[{href=>'',text=>'...'},
10497:                                        {href=>'',text=>'Modify grades'}]);
10498: 	    &processGroup($request,$symb);
10499: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10500:             &startpage($request,$symb);
10501: 	    $request->print(&grading_menu($request,$symb));
10502: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10503:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10504: 	    $request->print(&submit_options($request,$symb));
10505:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10506:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10507:             $request->print(&listStudents($request,$symb,'graded'));
10508:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10509:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10510:             $request->print(&submit_options_table($request,$symb));
10511:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10512:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10513:             $request->print(&submit_options_sequence($request,$symb));
10514: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10515:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10516: 	    $request->print(&viewgrades($request,$symb));
10517: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10518:             &startpage($request,$symb,[{href=>'',text=>'...'},
10519:                                        {href=>'',text=>'Store grades'}]);
10520: 	    $request->print(&processHandGrade($request,$symb));
10521: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10522:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10523:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10524:                                                                              text=>"Modify grades"},
10525:                                        {href=>'', text=>"Store grades"}]);
10526: 	    $request->print(&editgrades($request,$symb));
10527:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10528:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10529:             $request->print(&initialverifyreceipt($request,$symb));
10530: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10531:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10532:                                        {href=>'',text=>'Verification Result'}]);
10533: 	    $request->print(&verifyreceipt($request,$symb));
10534:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10535:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10536:             $request->print(&process_clicker($request,$symb));
10537:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10538:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10539:                                        {href=>'', text=>'Process clicker file'}]);
10540:             $request->print(&process_clicker_file($request,$symb));
10541:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10542:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10543:                                        {href=>'', text=>'Process clicker file'},
10544:                                        {href=>'', text=>'Store grades'}]);
10545:             $request->print(&assign_clicker_grades($request,$symb));
10546: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10547:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10548: 	    $request->print(&upcsvScores_form($request,$symb));
10549: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10550:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10551: 	    $request->print(&csvupload($request,$symb));
10552: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10553:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10554: 	    $request->print(&csvuploadmap($request,$symb));
10555: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10556: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10557:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10558: 		$request->print(&csvuploadoptions($request,$symb));
10559: 	    } else {
10560: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10561: 		    $env{'form.upfile_associate'} = 'reverse';
10562: 		} else {
10563: 		    $env{'form.upfile_associate'} = 'forward';
10564: 		}
10565:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10566: 		$request->print(&csvuploadmap($request,$symb));
10567: 	    }
10568: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10569:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10570: 	    $request->print(&csvuploadassign($request,$symb));
10571: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10572:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10573: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10574:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10575:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10576:  	    $request->print(&scantron_do_warning($request,$symb));
10577: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10578:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10579: 	    $request->print(&scantron_validate_file($request,$symb));
10580: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10581:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10582: 	    $request->print(&scantron_process_students($request,$symb));
10583:  	} elsif ($command eq 'scantronupload' && 
10584:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10585: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10586:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10587:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10588:  	} elsif ($command eq 'scantronupload_save' &&
10589:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10590: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10591:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10592:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10593:  	} elsif ($command eq 'scantron_download' &&
10594: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10595:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10596:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10597:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10598:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10599:             $request->print(&checkscantron_results($request,$symb));
10600:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10601:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10602:             $request->print(&submit_options_download($request,$symb));
10603:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10604:             &startpage($request,$symb,
10605:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10606:     {href=>'', text=>'Download submissions'}]);
10607:             &submit_download_link($request,$symb);
10608: 	} elsif ($command) {
10609:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10610: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10611: 	}
10612:     }
10613:     if ($ssi_error) {
10614: 	&ssi_print_error($request);
10615:     }
10616:     if ($env{'form.inhibitmenu'}) {
10617:         $request->print(&Apache::loncommon::end_page());
10618:     } else {
10619:         &Apache::lonquickgrades::endGradeScreen($request);
10620:     }
10621:     &reset_caches();
10622:     return OK;
10623: }
10624: 
10625: 1;
10626: 
10627: __END__;
10628: 
10629: 
10630: =head1 NAME
10631: 
10632: Apache::grades
10633: 
10634: =head1 SYNOPSIS
10635: 
10636: Handles the viewing of grades.
10637: 
10638: This is part of the LearningOnline Network with CAPA project
10639: described at http://www.lon-capa.org.
10640: 
10641: =head1 OVERVIEW
10642: 
10643: Do an ssi with retries:
10644: While I'd love to factor out this with the version in lonprintout,
10645: 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
10646: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10647: 
10648: At least the logic that drives this has been pulled out into loncommon.
10649: 
10650: 
10651: 
10652: ssi_with_retries - Does the server side include of a resource.
10653:                      if the ssi call returns an error we'll retry it up to
10654:                      the number of times requested by the caller.
10655:                      If we still have a problem, no text is appended to the
10656:                      output and we set some global variables.
10657:                      to indicate to the caller an SSI error occurred.  
10658:                      All of this is supposed to deal with the issues described
10659:                      in LON-CAPA BZ 5631 see:
10660:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10661:                      by informing the user that this happened.
10662: 
10663: Parameters:
10664:   resource   - The resource to include.  This is passed directly, without
10665:                interpretation to lonnet::ssi.
10666:   form       - The form hash parameters that guide the interpretation of the resource
10667:                
10668:   retries    - Number of retries allowed before giving up completely.
10669: Returns:
10670:   On success, returns the rendered resource identified by the resource parameter.
10671: Side Effects:
10672:   The following global variables can be set:
10673:    ssi_error                - If an unrecoverable error occurred this becomes true.
10674:                               It is up to the caller to initialize this to false
10675:                               if desired.
10676:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10677:                               of the resource that could not be rendered by the ssi
10678:                               call.
10679:    ssi_error_message   - The error string fetched from the ssi response
10680:                               in the event of an error.
10681: 
10682: 
10683: =head1 HANDLER SUBROUTINE
10684: 
10685: ssi_with_retries()
10686: 
10687: =head1 SUBROUTINES
10688: 
10689: =over
10690: 
10691: =head1 Routines to display previous version of a Task for a specific student
10692: 
10693: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10694: can receive another opportunity. Access to tasks is slot-based. If a slot
10695: requires a proctor to check-in the student, a new version of the Task will
10696: be created when the student is checked in to the new opportunity.
10697: 
10698: If a particular student has tried two or more versions of a particular task,
10699: the submission screen provides a user with vgr privileges (e.g., a Course
10700: Coordinator) the ability to display a previous version worked on by the
10701: student.  By default, the current version is displayed. If a previous version
10702: has been selected for display, submission data are only shown that pertain
10703: to that particular version, and the interface to submit grades is not shown.
10704: 
10705: =over 4
10706: 
10707: =item show_previous_task_version()
10708: 
10709: Displays a specified version of a student's Task, as the student sees it.
10710: 
10711: Inputs: 2
10712:         request - request object
10713:         symb    - unique symb for current instance of resource
10714: 
10715: Output: None.
10716: 
10717: Side Effects: calls &show_problem() to print version of Task, with
10718:               version contained in form item: $env{'form.previousversion'}
10719: 
10720: =item choose_task_version_form()
10721: 
10722: Displays a web form used to select which version of a student's view of a
10723: Task should be displayed.  Either launches a pop-up window, or replaces
10724: content in existing pop-up, or replaces page in main window.
10725: 
10726: Inputs: 4
10727:         symb    - unique symb for current instance of resource
10728:         uname   - username of student
10729:         udom    - domain of student
10730:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10731:                   breadcrumbs etc., are displayed
10732: 
10733: Output: 4
10734:         current   - student's current version
10735:         displayed - student's version being displayed
10736:         result    - scalar containing HTML for web form used to switch to
10737:                     a different version (or a link to close window, if pop-up).
10738:         js        - javascript for processing selection in versions web form
10739: 
10740: Side Effects: None.
10741: 
10742: =item previous_display_javascript()
10743: 
10744: Inputs: 2
10745:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10746:                   breadcrumbs etc., are displayed.
10747:         current - student's current version number.
10748: 
10749: Output: 1
10750:         js      - javascript for processing selection in versions web form.
10751: 
10752: Side Effects: None.
10753: 
10754: =back
10755: 
10756: =head1 Routines to process bubblesheet data.
10757: 
10758: =over 4
10759: 
10760: =item scantron_get_correction() : 
10761: 
10762:    Builds the interface screen to interact with the operator to fix a
10763:    specific error condition in a specific scanline
10764: 
10765:  Arguments:
10766:     $r           - Apache request object
10767:     $i           - number of the current scanline
10768:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10769:     $scan_config - hash ref as returned from &get_scantron_config()
10770:     $line        - full contents of the current scanline
10771:     $error       - error condition, valid values are
10772:                    'incorrectCODE', 'duplicateCODE',
10773:                    'doublebubble', 'missingbubble',
10774:                    'duplicateID', 'incorrectID'
10775:     $arg         - extra information needed
10776:        For errors:
10777:          - duplicateID   - paper number that this studentID was seen before on
10778:          - duplicateCODE - array ref of the paper numbers this CODE was
10779:                            seen on before
10780:          - incorrectCODE - current incorrect CODE 
10781:          - doublebubble  - array ref of the bubble lines that have double
10782:                            bubble errors
10783:          - missingbubble - array ref of the bubble lines that have missing
10784:                            bubble errors
10785: 
10786:    $randomorder - True if exam folder has randomorder set
10787:    $randompick  - True if exam folder has randompick set
10788:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10789:                      for current line to question number used for same question
10790:                      in "Master Seqence" (as seen by Course Coordinator).
10791:    $startline   - Reference to hash where key is question number (0 is first)
10792:                   and value is number of first bubble line for current student
10793:                   or code-based randompick and/or randomorder.
10794: 
10795: 
10796: 
10797: =item  scantron_get_maxbubble() : 
10798: 
10799:    Arguments:
10800:        $nav_error  - Reference to scalar which is a flag to indicate a
10801:                       failure to retrieve a navmap object.
10802:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10803:        calling routine should trap the error condition and display the warning
10804:        found in &navmap_errormsg().
10805: 
10806:        $scantron_config - Reference to bubblesheet format configuration hash.
10807: 
10808:    Returns the maximum number of bubble lines that are expected to
10809:    occur. Does this by walking the selected sequence rendering the
10810:    resource and then checking &Apache::lonxml::get_problem_counter()
10811:    for what the current value of the problem counter is.
10812: 
10813:    Caches the results to $env{'form.scantron_maxbubble'},
10814:    $env{'form.scantron.bubble_lines.n'}, 
10815:    $env{'form.scantron.first_bubble_line.n'} and
10816:    $env{"form.scantron.sub_bubblelines.n"}
10817:    which are the total number of bubble lines, the number of bubble
10818:    lines for response n and number of the first bubble line for response n,
10819:    and a comma separated list of numbers of bubble lines for sub-questions
10820:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10821: 
10822: 
10823: =item  scantron_validate_missingbubbles() : 
10824: 
10825:    Validates all scanlines in the selected file to not have any
10826:     answers that don't have bubbles that have not been verified
10827:     to be bubble free.
10828: 
10829: =item  scantron_process_students() : 
10830: 
10831:    Routine that does the actual grading of the bubblesheet information.
10832: 
10833:    The parsed scanline hash is added to %env 
10834: 
10835:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10836:    foreach resource , with the form data of
10837: 
10838: 	'submitted'     =>'scantron' 
10839: 	'grade_target'  =>'grade',
10840: 	'grade_username'=> username of student
10841: 	'grade_domain'  => domain of student
10842: 	'grade_courseid'=> of course
10843: 	'grade_symb'    => symb of resource to grade
10844: 
10845:     This triggers a grading pass. The problem grading code takes care
10846:     of converting the bubbled letter information (now in %env) into a
10847:     valid submission.
10848: 
10849: =item  scantron_upload_scantron_data() :
10850: 
10851:     Creates the screen for adding a new bubblesheet data file to a course.
10852: 
10853: =item  scantron_upload_scantron_data_save() : 
10854: 
10855:    Adds a provided bubble information data file to the course if user
10856:    has the correct privileges to do so. 
10857: 
10858: =item  valid_file() :
10859: 
10860:    Validates that the requested bubble data file exists in the course.
10861: 
10862: =item  scantron_download_scantron_data() : 
10863: 
10864:    Shows a list of the three internal files (original, corrected,
10865:    skipped) for a specific bubblesheet data file that exists in the
10866:    course.
10867: 
10868: =item  scantron_validate_ID() : 
10869: 
10870:    Validates all scanlines in the selected file to not have any
10871:    invalid or underspecified student/employee IDs
10872: 
10873: =item navmap_errormsg() :
10874: 
10875:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10876:    Should be called whenever the request to instantiate a navmap object fails.
10877: 
10878: =back
10879: 
10880: =back
10881: 
10882: =cut

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