File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.41.2.1: download - view: text, annotated - select for diffs
Wed Nov 1 03:27:19 2017 UTC (6 years, 6 months ago) by raeburn
Branches: version_2_11_2_msu
- For 2.11.2 (modified).
  - Include changes in rev. 1.742.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.41.2.1 2017/11/01 03:27:19 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::bridgetask();
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: my %old_essays=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &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 />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: sub getpartlist {
  102:     my ($symb,$errorref) = @_;
  103: 
  104:     my $navmap   = Apache::lonnavmaps::navmap->new();
  105:     unless (ref($navmap)) {
  106:         if (ref($errorref)) { 
  107:             $$errorref = 'navmap';
  108:             return;
  109:         }
  110:     }
  111:     my $res      = $navmap->getBySymb($symb);
  112:     my $partlist = $res->parts();
  113:     my $url      = $res->src();
  114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  115: 
  116:     my @stores;
  117:     foreach my $part (@{ $partlist }) {
  118: 	foreach my $key (@metakeys) {
  119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  120: 	}
  121:     }
  122:     return @stores;
  123: }
  124: 
  125: # --- Get the symbolic name of a problem and the url
  126: sub get_symb {
  127:     my ($request,$silent) = @_;
  128:     my $symb=$env{'form.symb'};
  129:     unless ($symb) {
  130:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  131:         $symb = &Apache::lonnet::symbread($url);
  132:         if ($symb eq '') { 
  133: 	    if (!$silent) {
  134:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  135: 	        return ();
  136: 	    }
  137:         }
  138:     }
  139:     &Apache::lonenc::check_decrypt(\$symb);
  140:     return ($symb);
  141: }
  142: 
  143: #--- Format fullname, username:domain if different for display
  144: #--- Use anywhere where the student names are listed
  145: sub nameUserString {
  146:     my ($type,$fullname,$uname,$udom) = @_;
  147:     if ($type eq 'header') {
  148: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  149:     } else {
  150: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  151: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  152:     }
  153: }
  154: 
  155: #--- Get the partlist and the response type for a given problem. ---
  156: #--- Indicate if a response type is coded handgraded or not. ---
  157: sub response_type {
  158:     my ($symb,$response_error) = @_;
  159: 
  160:     my $navmap = Apache::lonnavmaps::navmap->new();
  161:     unless (ref($navmap)) {
  162:         if (ref($response_error)) {
  163:             $$response_error = 1;
  164:         }
  165:         return;
  166:     }
  167:     my $res = $navmap->getBySymb($symb);
  168:     unless (ref($res)) {
  169:         $$response_error = 1;
  170:         return;
  171:     }
  172:     my $partlist = $res->parts();
  173:     my %vPart = 
  174: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  175:     my (%response_types,%handgrade);
  176:     foreach my $part (@{ $partlist }) {
  177: 	next if (%vPart && !exists($vPart{$part}));
  178: 
  179: 	my @types = $res->responseType($part);
  180: 	my @ids = $res->responseIds($part);
  181: 	for (my $i=0; $i < scalar(@ids); $i++) {
  182: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  183: 	    $handgrade{$part.'_'.$ids[$i]} = 
  184: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  185: 				     '.handgrade',$symb);
  186: 	}
  187:     }
  188:     return ($partlist,\%handgrade,\%response_types);
  189: }
  190: 
  191: sub flatten_responseType {
  192:     my ($responseType) = @_;
  193:     my @part_response_id =
  194: 	map { 
  195: 	    my $part = $_;
  196: 	    map {
  197: 		[$part,$_]
  198: 		} sort(keys(%{ $responseType->{$part} }));
  199: 	} sort(keys(%$responseType));
  200:     return @part_response_id;
  201: }
  202: 
  203: sub get_display_part {
  204:     my ($partID,$symb)=@_;
  205:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  206:     if (defined($display) and $display ne '') {
  207:         $display.= ' (<span class="LC_internal_info">'
  208:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  209:     } else {
  210: 	$display=$partID;
  211:     }
  212:     return $display;
  213: }
  214: 
  215: #--- Show resource title
  216: #--- and parts and response type
  217: sub showResourceInfo {
  218:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  219:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  220:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  221:     if (ref($res_error)) {
  222:         if ($$res_error) {
  223:             return;
  224:         }
  225:     }
  226:     $result.=&Apache::loncommon::start_data_table()
  227:             .&Apache::loncommon::start_data_table_header_row();
  228:     if ($checkboxes) {
  229:         $result.='<th>&nbsp;</th>';
  230:     }
  231:     $result.='<th>'.&mt('Problem Part').'</th>'
  232:             .'<th>'.&mt('Res. ID').'</th>'
  233:             .'<th>'.&mt('Type').'</th>'
  234:             .&Apache::loncommon::end_data_table_header_row();
  235:     my %resptype = ();
  236:     my $hdgrade='no';
  237:     my %partsseen;
  238:     foreach my $partID (sort(keys(%$responseType))) {
  239:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  240:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  241:             my $responsetype = $responseType->{$partID}->{$resID};
  242:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  243:             $result.=&Apache::loncommon::start_data_table_row();
  244:             if ($checkboxes) {
  245:                 if (exists($partsseen{$partID})) {
  246:                     $result.="<td>&nbsp;</td>";
  247:                 } else {
  248:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  249:                 }
  250:                 $partsseen{$partID}=1;
  251:             }
  252:             my $display_part=&get_display_part($partID,$symb);
  253:             $result.='<td>'.$display_part.'</td>'
  254:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  255:                     .'<td>'.&mt($responsetype).'</td>'
  256: #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
  257:                     .&Apache::loncommon::end_data_table_row();
  258:         }
  259:     }
  260:     $result.=&Apache::loncommon::end_data_table();
  261:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  262: }
  263: 
  264: sub reset_caches {
  265:     &reset_analyze_cache();
  266:     &reset_perm();
  267:     &reset_old_essays();
  268: }
  269: 
  270: {
  271:     my %analyze_cache;
  272:     my %analyze_cache_formkeys;
  273: 
  274:     sub reset_analyze_cache {
  275: 	undef(%analyze_cache);
  276:         undef(%analyze_cache_formkeys);
  277:     }
  278: 
  279:     sub get_analyze {
  280: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  281: 	my $key = "$symb\0$uname\0$udom";
  282:         if ($type eq 'randomizetry') {
  283:             if ($trial ne '') {
  284:                 $key .= "\0".$trial;
  285:             }
  286:         }
  287: 	if (exists($analyze_cache{$key})) {
  288:             my $getupdate = 0;
  289:             if (ref($add_to_hash) eq 'HASH') {
  290:                 foreach my $item (keys(%{$add_to_hash})) {
  291:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  292:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  293:                             $getupdate = 1;
  294:                             last;
  295:                         }
  296:                     } else {
  297:                         $getupdate = 1;
  298:                     }
  299:                 }
  300:             }
  301:             if (!$getupdate) {
  302:                 return $analyze_cache{$key};
  303:             }
  304:         }
  305: 
  306: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  307: 	$url=&Apache::lonnet::clutter($url);
  308:         my %form = ('grade_target'      => 'analyze',
  309:                     'grade_domain'      => $udom,
  310:                     'grade_symb'        => $symb,
  311:                     'grade_courseid'    =>  $env{'request.course.id'},
  312:                     'grade_username'    => $uname,
  313:                     'grade_noincrement' => $no_increment);
  314:         if ($bubbles_per_row ne '') {
  315:             $form{'bubbles_per_row'} = $bubbles_per_row;
  316:         }
  317:         if ($type eq 'randomizetry') {
  318:             $form{'grade_questiontype'} = $type;
  319:             if ($rndseed ne '') {
  320:                 $form{'grade_rndseed'} = $rndseed;
  321:             }
  322:         }
  323:         if (ref($add_to_hash)) {
  324:             %form = (%form,%{$add_to_hash});
  325:         }
  326: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  327: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  328: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  329:         if (ref($add_to_hash) eq 'HASH') {
  330:             $analyze_cache_formkeys{$key} = $add_to_hash;
  331:         } else {
  332:             $analyze_cache_formkeys{$key} = {};
  333:         }
  334: 	return $analyze_cache{$key} = \%analyze;
  335:     }
  336: 
  337:     sub get_order {
  338: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  339: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  340: 	return $analyze->{"$partid.$respid.shown"};
  341:     }
  342: 
  343:     sub get_radiobutton_correct_foil {
  344: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  345: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  346:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  347:         if (ref($foils) eq 'ARRAY') {
  348: 	    foreach my $foil (@{$foils}) {
  349: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  350: 		    return $foil;
  351: 	        }
  352: 	    }
  353: 	}
  354:     }
  355: 
  356:     sub scantron_partids_tograde {
  357:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  358:         my (%analysis,@parts);
  359:         if (ref($resource)) {
  360:             my $symb = $resource->symb();
  361:             my $add_to_form;
  362:             if ($check_for_randomlist) {
  363:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  364:             }
  365:             if ($scancode) {
  366:                 if (ref($add_to_form) eq 'HASH') {
  367:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  368:                 } else {
  369:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  370:                 }
  371:             }
  372:             my $analyze =
  373:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  374:                              undef,undef,undef,$bubbles_per_row);
  375:             if (ref($analyze) eq 'HASH') {
  376:                 %analysis = %{$analyze};
  377:             }
  378:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  379:                 foreach my $part (@{$analysis{'parts'}}) {
  380:                     my ($id,$respid) = split(/\./,$part);
  381:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  382:                         push(@parts,$part);
  383:                     }
  384:                 }
  385:             }
  386:         }
  387:         return (\%analysis,\@parts);
  388:     }
  389: 
  390: }
  391: 
  392: #--- Clean response type for display
  393: #--- Currently filters option/rank/radiobutton/match/essay/Task
  394: #        response types only.
  395: sub cleanRecord {
  396:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  397: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  398:     my $grayFont = '<span class="LC_internal_info">';
  399:     if ($response =~ /^(option|rank)$/) {
  400: 	my %answer=&Apache::lonnet::str2hash($answer);
  401:         my @answer = %answer;
  402:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  403: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  404: 	my ($toprow,$bottomrow);
  405: 	foreach my $foil (@$order) {
  406: 	    if ($grading{$foil} == 1) {
  407: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  408: 	    } else {
  409: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  410: 	    }
  411: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  412: 	}
  413: 	return '<blockquote><table border="1">'.
  414: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  415: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  416: 	    $bottomrow.'</tr></table></blockquote>';
  417:     } elsif ($response eq 'match') {
  418: 	my %answer=&Apache::lonnet::str2hash($answer);
  419:         my @answer = %answer;
  420:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  421: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  422: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  423: 	my ($toprow,$middlerow,$bottomrow);
  424: 	foreach my $foil (@$order) {
  425: 	    my $item=shift(@items);
  426: 	    if ($grading{$foil} == 1) {
  427: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  428: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  429: 	    } else {
  430: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  431: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  432: 	    }
  433: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  434: 	}
  435: 	return '<blockquote><table border="1">'.
  436: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  437: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  438: 	    $middlerow.'</tr>'.
  439: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  440: 	    $bottomrow.'</tr></table></blockquote>';
  441:     } elsif ($response eq 'radiobutton') {
  442: 	my %answer=&Apache::lonnet::str2hash($answer);
  443: 	my ($toprow,$bottomrow);
  444: 	my $correct = 
  445: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  446: 	foreach my $foil (@$order) {
  447: 	    if (exists($answer{$foil})) {
  448: 		if ($foil eq $correct) {
  449: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  450: 		} else {
  451: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  452: 		}
  453: 	    } else {
  454: 		$toprow.='<td>'.&mt('false').'</td>';
  455: 	    }
  456: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  457: 	}
  458: 	return '<blockquote><table border="1">'.
  459: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  460: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  461: 	    $bottomrow.'</tr></table></blockquote>';
  462:     } elsif ($response eq 'essay') {
  463: 	if (! exists ($env{'form.'.$symb})) {
  464: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  465: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  466: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  467: 
  468: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  469: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  470: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  471: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  472: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  473: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  474: 	}
  475: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  476:     } elsif ( $response eq 'organic') {
  477:         my $result=&mt('Smile representation: [_1]',
  478:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  479: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  480: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  481: 	return $result;
  482:     } elsif ( $response eq 'Task') {
  483: 	if ( $answer eq 'SUBMITTED') {
  484: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  485: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  486: 	    return $result;
  487: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  488: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  489: 			       keys(%{$record}));
  490: 	    return join('<br />',($version,@matches));
  491: 			       
  492: 			       
  493: 	} else {
  494: 	    my $result =
  495: 		'<p>'
  496: 		.&mt('Overall result: [_1]',
  497: 		     $record->{$version."resource.$respid.$partid.status"})
  498: 		.'</p>';
  499: 	    
  500: 	    $result .= '<ul>';
  501: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  502: 			     keys(%{$record}));
  503: 	    foreach my $grade (sort(@grade)) {
  504: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  505: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  506: 				     $dim, $record->{$grade}).
  507: 			  '</li>';
  508: 	    }
  509: 	    $result.='</ul>';
  510: 	    return $result;
  511: 	}
  512:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  513:         # Respect multiple input fields, see Bug #5409 
  514: 	$answer = 
  515: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  516: 							      $answer);
  517:         return $answer;
  518:     }
  519:     return &HTML::Entities::encode($answer, '"<>&');
  520: }
  521: 
  522: #-- A couple of common js functions
  523: sub commonJSfunctions {
  524:     my $request = shift;
  525:     $request->print(<<COMMONJSFUNCTIONS);
  526: <script type="text/javascript" language="javascript">
  527:     function radioSelection(radioButton) {
  528: 	var selection=null;
  529: 	if (radioButton.length > 1) {
  530: 	    for (var i=0; i<radioButton.length; i++) {
  531: 		if (radioButton[i].checked) {
  532: 		    return radioButton[i].value;
  533: 		}
  534: 	    }
  535: 	} else {
  536: 	    if (radioButton.checked) return radioButton.value;
  537: 	}
  538: 	return selection;
  539:     }
  540: 
  541:     function pullDownSelection(selectOne) {
  542: 	var selection="";
  543: 	if (selectOne.length > 1) {
  544: 	    for (var i=0; i<selectOne.length; i++) {
  545: 		if (selectOne[i].selected) {
  546: 		    return selectOne[i].value;
  547: 		}
  548: 	    }
  549: 	} else {
  550:             // only one value it must be the selected one
  551: 	    return selectOne.value;
  552: 	}
  553:     }
  554: </script>
  555: COMMONJSFUNCTIONS
  556: }
  557: 
  558: #--- Dumps the class list with usernames,list of sections,
  559: #--- section, ids and fullnames for each user.
  560: sub getclasslist {
  561:     my ($getsec,$filterlist,$getgroup) = @_;
  562:     my @getsec;
  563:     my @getgroup;
  564:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  565:     if (!ref($getsec)) {
  566: 	if ($getsec ne '' && $getsec ne 'all') {
  567: 	    @getsec=($getsec);
  568: 	}
  569:     } else {
  570: 	@getsec=@{$getsec};
  571:     }
  572:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  573:     if (!ref($getgroup)) {
  574: 	if ($getgroup ne '' && $getgroup ne 'all') {
  575: 	    @getgroup=($getgroup);
  576: 	}
  577:     } else {
  578: 	@getgroup=@{$getgroup};
  579:     }
  580:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  581: 
  582:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  583:     # Bail out if we were unable to get the classlist
  584:     return if (! defined($classlist));
  585:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  586:     #
  587:     my %sections;
  588:     my %fullnames;
  589:     foreach my $student (keys(%$classlist)) {
  590:         my $end      = 
  591:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  592:         my $start    = 
  593:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  594:         my $id       = 
  595:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  596:         my $section  = 
  597:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  598:         my $fullname = 
  599:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  600:         my $status   = 
  601:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  602:         my $group   = 
  603:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  604: 	# filter students according to status selected
  605: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  606: 	    if (!($stu_status =~ $status)) {
  607: 		delete($classlist->{$student});
  608: 		next;
  609: 	    }
  610: 	}
  611: 	# filter students according to groups selected
  612: 	my @stu_groups = split(/,/,$group);
  613: 	if (@getgroup) {
  614: 	    my $exclude = 1;
  615: 	    foreach my $grp (@getgroup) {
  616: 	        foreach my $stu_group (@stu_groups) {
  617: 	            if ($stu_group eq $grp) {
  618: 	                $exclude = 0;
  619:     	            } 
  620: 	        }
  621:     	        if (($grp eq 'none') && !$group) {
  622:         	        $exclude = 0;
  623:         	}
  624: 	    }
  625: 	    if ($exclude) {
  626: 	        delete($classlist->{$student});
  627: 	    }
  628: 	}
  629: 	$section = ($section ne '' ? $section : 'none');
  630: 	if (&canview($section)) {
  631: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  632: 		$sections{$section}++;
  633: 		if ($classlist->{$student}) {
  634: 		    $fullnames{$student}=$fullname;
  635: 		}
  636: 	    } else {
  637: 		delete($classlist->{$student});
  638: 	    }
  639: 	} else {
  640: 	    delete($classlist->{$student});
  641: 	}
  642:     }
  643:     my %seen = ();
  644:     my @sections = sort(keys(%sections));
  645:     return ($classlist,\@sections,\%fullnames);
  646: }
  647: 
  648: sub canmodify {
  649:     my ($sec)=@_;
  650:     if ($perm{'mgr'}) {
  651: 	if (!defined($perm{'mgr_section'})) {
  652: 	    # can modify whole class
  653: 	    return 1;
  654: 	} else {
  655: 	    if ($sec eq $perm{'mgr_section'}) {
  656: 		#can modify the requested section
  657: 		return 1;
  658: 	    } else {
  659: 		# can't modify the request section
  660: 		return 0;
  661: 	    }
  662: 	}
  663:     }
  664:     #can't modify
  665:     return 0;
  666: }
  667: 
  668: sub canview {
  669:     my ($sec)=@_;
  670:     if ($perm{'vgr'}) {
  671: 	if (!defined($perm{'vgr_section'})) {
  672: 	    # can modify whole class
  673: 	    return 1;
  674: 	} else {
  675: 	    if ($sec eq $perm{'vgr_section'}) {
  676: 		#can modify the requested section
  677: 		return 1;
  678: 	    } else {
  679: 		# can't modify the request section
  680: 		return 0;
  681: 	    }
  682: 	}
  683:     }
  684:     #can't modify
  685:     return 0;
  686: }
  687: 
  688: #--- Retrieve the grade status of a student for all the parts
  689: sub student_gradeStatus {
  690:     my ($symb,$udom,$uname,$partlist) = @_;
  691:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  692:     my %partstatus = ();
  693:     foreach (@$partlist) {
  694: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  695: 	$status              = 'nothing' if ($status eq '');
  696: 	$partstatus{$_}      = $status;
  697: 	my $subkey           = "resource.$_.submitted_by";
  698: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  699:     }
  700:     return %partstatus;
  701: }
  702: 
  703: # hidden form and javascript that calls the form
  704: # Use by verifyscript and viewgrades
  705: # Shows a student's view of problem and submission
  706: sub jscriptNform {
  707:     my ($symb) = @_;
  708:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  709:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  710: 	'    function viewOneStudent(user,domain) {'."\n".
  711: 	'	document.onestudent.student.value = user;'."\n".
  712: 	'	document.onestudent.userdom.value = domain;'."\n".
  713: 	'	document.onestudent.submit();'."\n".
  714: 	'    }'."\n".
  715: 	'</script>'."\n";
  716:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  717: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  718: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  719: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  720: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  721: 	'<input type="hidden" name="command" value="submission" />'."\n".
  722: 	'<input type="hidden" name="student" value="" />'."\n".
  723: 	'<input type="hidden" name="userdom" value="" />'."\n".
  724: 	'</form>'."\n";
  725:     return $jscript;
  726: }
  727: 
  728: 
  729: 
  730: # Given the score (as a number [0-1] and the weight) what is the final
  731: # point value? This function will round to the nearest tenth, third,
  732: # or quarter if one of those is within the tolerance of .00001.
  733: sub compute_points {
  734:     my ($score, $weight) = @_;
  735:     
  736:     my $tolerance = .00001;
  737:     my $points = $score * $weight;
  738: 
  739:     # Check for nearness to 1/x.
  740:     my $check_for_nearness = sub {
  741:         my ($factor) = @_;
  742:         my $num = ($points * $factor) + $tolerance;
  743:         my $floored_num = floor($num);
  744:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  745:             return $floored_num / $factor;
  746:         }
  747:         return $points;
  748:     };
  749: 
  750:     $points = $check_for_nearness->(10);
  751:     $points = $check_for_nearness->(3);
  752:     $points = $check_for_nearness->(4);
  753:     
  754:     return $points;
  755: }
  756: 
  757: #------------------ End of general use routines --------------------
  758: 
  759: #
  760: # Find most similar essay
  761: #
  762: 
  763: sub most_similar {
  764:     my ($uname,$udom,$symb,$uessay)=@_;
  765: 
  766:     unless ($symb) { return ''; }
  767: 
  768:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  769: 
  770: # ignore spaces and punctuation
  771: 
  772:     $uessay=~s/\W+/ /gs;
  773: 
  774: # ignore empty submissions (occuring when only files are sent)
  775: 
  776:     unless ($uessay=~/\w+/s) { return ''; }
  777: 
  778: # these will be returned. Do not care if not at least 50 percent similar
  779:     my $limit=0.6;
  780:     my $sname='';
  781:     my $sdom='';
  782:     my $scrsid='';
  783:     my $sessay='';
  784: # go through all essays ...
  785:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  786: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  787: # ... except the same student
  788:         next if (($tname eq $uname) && ($tdom eq $udom));
  789: 	my $tessay=$old_essays{$symb}{$tkey};
  790: 	$tessay=~s/\W+/ /gs;
  791: # String similarity gives up if not even limit
  792: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  793: # Found one
  794: 	if ($tsimilar>$limit) {
  795: 	    $limit=$tsimilar;
  796: 	    $sname=$tname;
  797: 	    $sdom=$tdom;
  798: 	    $scrsid=$tcrsid;
  799: 	    $sessay=$old_essays{$symb}{$tkey};
  800: 	}
  801:     }
  802:     if ($limit>0.6) {
  803:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  804:     } else {
  805:        return ('','','','',0);
  806:     }
  807: }
  808: 
  809: #-------------------------------------------------------------------
  810: 
  811: #------------------------------------ Receipt Verification Routines
  812: #
  813: #--- Check whether a receipt number is valid.---
  814: sub verifyreceipt {
  815:     my $request  = shift;
  816: 
  817:     my $courseid = $env{'request.course.id'};
  818:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  819: 	$env{'form.receipt'};
  820:     $receipt     =~ s/[^\-\d]//g;
  821:     my ($symb)   = &get_symb($request);
  822: 
  823:     my $title.=
  824: 	'<h3><span class="LC_info">'.
  825: 	&mt('Verifying Receipt No. [_1]',$receipt).
  826: 	'</span></h3>'."\n".
  827: 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
  828: 	'</h4>'."\n";
  829: 
  830:     my ($string,$contents,$matches) = ('','',0);
  831:     my (undef,undef,$fullname) = &getclasslist('all','0');
  832:     
  833:     my $receiptparts=0;
  834:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  835: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  836:     my $parts=['0'];
  837:     if ($receiptparts) {
  838:         my $res_error; 
  839:         ($parts)=&response_type($symb,\$res_error);
  840:         if ($res_error) {
  841:             return &navmap_errormsg();
  842:         } 
  843:     }
  844:     
  845:     my $header = 
  846: 	&Apache::loncommon::start_data_table().
  847: 	&Apache::loncommon::start_data_table_header_row().
  848: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  849: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  850: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  851:     if ($receiptparts) {
  852: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  853:     }
  854:     $header.=
  855: 	&Apache::loncommon::end_data_table_header_row();
  856: 
  857:     foreach (sort 
  858: 	     {
  859: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  860: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  861: 		 }
  862: 		 return $a cmp $b;
  863: 	     } (keys(%$fullname))) {
  864: 	my ($uname,$udom)=split(/\:/);
  865: 	foreach my $part (@$parts) {
  866: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  867: 		$contents.=
  868: 		    &Apache::loncommon::start_data_table_row().
  869: 		    '<td>&nbsp;'."\n".
  870: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  871: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  872: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  873: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  874: 		if ($receiptparts) {
  875: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  876: 		}
  877: 		$contents.= 
  878: 		    &Apache::loncommon::end_data_table_row()."\n";
  879: 		
  880: 		$matches++;
  881: 	    }
  882: 	}
  883:     }
  884:     if ($matches == 0) {
  885:         $string = $title
  886:                  .'<p class="LC_warning">'
  887:                  .&mt('No match found for the above receipt number.')
  888:                  .'</p>';
  889:     } else {
  890: 	$string = &jscriptNform($symb).$title.
  891: 	    '<p>'.
  892: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  893: 	    '</p>'.
  894: 	    $header.
  895: 	    $contents.
  896: 	    &Apache::loncommon::end_data_table()."\n";
  897:     }
  898:     return $string.&show_grading_menu_form($symb);
  899: }
  900: 
  901: #--- This is called by a number of programs.
  902: #--- Called from the Grading Menu - View/Grade an individual student
  903: #--- Also called directly when one clicks on the subm button 
  904: #    on the problem page.
  905: sub listStudents {
  906:     my ($request) = shift;
  907: 
  908:     my ($symb) = &get_symb($request);
  909:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  910:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  911:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  912:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  913:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  914:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  915:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  916: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  917: 
  918:     my $result='<h3><span class="LC_info">&nbsp;'
  919: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  920: 	.'</span></h3>';
  921: 
  922:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  923: 
  924:     my %js_lt = &Apache::lonlocal::texthash (
  925: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  926: 		'single'   => 'Please select the student before clicking on the Next button.',
  927: 	     );
  928:     &js_escape(\%js_lt);
  929:     $request->print(<<LISTJAVASCRIPT);
  930: <script type="text/javascript" language="javascript">
  931:     function checkSelect(checkBox) {
  932: 	var ctr=0;
  933: 	var sense="";
  934: 	if (checkBox.length > 1) {
  935: 	    for (var i=0; i<checkBox.length; i++) {
  936: 		if (checkBox[i].checked) {
  937: 		    ctr++;
  938: 		}
  939: 	    }
  940: 	    sense = '$js_lt{'multiple'}';
  941: 	} else {
  942: 	    if (checkBox.checked) {
  943: 		ctr = 1;
  944: 	    }
  945: 	    sense = '$js_lt{'single'}';
  946: 	}
  947: 	if (ctr == 0) {
  948: 	    alert(sense);
  949: 	    return false;
  950: 	}
  951: 	document.gradesub.submit();
  952:     }
  953: 
  954:     function reLoadList(formname) {
  955: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  956: 	formname.command.value = 'submission';
  957: 	formname.submit();
  958:     }
  959: </script>
  960: LISTJAVASCRIPT
  961: 
  962:     &commonJSfunctions($request);
  963:     $request->print($result);
  964: 
  965:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  966:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  967:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  968: 	"\n".$table;
  969: 	
  970:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  971:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  972:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  973:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  974:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  975:                   .&Apache::lonhtmlcommon::row_closure();
  976:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  977:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  978:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  979:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  980:                   .&Apache::lonhtmlcommon::row_closure();
  981: 
  982:     my $submission_options;
  983:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  984: 	$submission_options.=
  985: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  986:     }
  987:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  988:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  989:     $env{'form.Status'} = $saveStatus;
  990:     $submission_options.=
  991:         '<span class="LC_nobreak">'.
  992:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  993:         &mt('last submission only').' </label></span>'."\n".
  994:         '<span class="LC_nobreak">'.
  995:         '<label><input type="radio" name="lastSub" value="last" /> '.
  996:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  997:         '<span class="LC_nobreak">'.
  998:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  999:         &mt('by dates and submissions').'</label></span>'."\n".
 1000:         '<span class="LC_nobreak">'.
 1001:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1002:         &mt('all details').'</label></span>';
 1003:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
 1004:                   .$submission_options
 1005:                   .&Apache::lonhtmlcommon::row_closure();
 1006: 
 1007:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1008:                   .'<select name="increment">'
 1009:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1010:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1011:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1012:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1013:                   .'</select>'
 1014:                   .&Apache::lonhtmlcommon::row_closure();
 1015: 
 1016:     $gradeTable .= 
 1017:         &build_section_inputs().
 1018: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1019: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1020: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1021: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1022: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1023: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1024: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1025: 
 1026:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1027: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1028:     } else {
 1029:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1030:                       .&Apache::lonhtmlcommon::StatusOptions(
 1031:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1032:                       .&Apache::lonhtmlcommon::row_closure();
 1033:     }
 1034: 
 1035:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1036:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1037:                   .&Apache::lonhtmlcommon::row_closure(1)
 1038:                   .&Apache::lonhtmlcommon::end_pick_box();
 1039: 
 1040:     $gradeTable .= '<p>'
 1041:                   .&mt('To '.lc($viewgrade)." 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"
 1042:                   .'<input type="hidden" name="command" value="processGroup" />'
 1043:                   .'</p>';
 1044: 
 1045: # checkall buttons
 1046:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1047:     $gradeTable.='<input type="button" '."\n".
 1048:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1049:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1050:     $gradeTable.=&check_buttons();
 1051:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1052:     $gradeTable.= &Apache::loncommon::start_data_table().
 1053: 	&Apache::loncommon::start_data_table_header_row();
 1054:     my $loop = 0;
 1055:     while ($loop < 2) {
 1056: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1057: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1058: 	if ($env{'form.showgrading'} eq 'yes' 
 1059: 	    && $submitonly ne 'queued'
 1060: 	    && $submitonly ne 'all') {
 1061: 	    foreach my $part (sort(@$partlist)) {
 1062: 		my $display_part=
 1063: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1064: 		$gradeTable.=
 1065: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1066: 	    }
 1067: 	} elsif ($submitonly eq 'queued') {
 1068: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1069: 	}
 1070: 	$loop++;
 1071: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1072:     }
 1073:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1074: 
 1075:     my $ctr = 0;
 1076:     foreach my $student (sort 
 1077: 			 {
 1078: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1079: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1080: 			     }
 1081: 			     return $a cmp $b;
 1082: 			 }
 1083: 			 (keys(%$fullname))) {
 1084: 	my ($uname,$udom) = split(/:/,$student);
 1085: 
 1086: 	my %status = ();
 1087: 
 1088: 	if ($submitonly eq 'queued') {
 1089: 	    my %queue_status = 
 1090: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1091: 							$udom,$uname);
 1092: 	    next if (!defined($queue_status{'gradingqueue'}));
 1093: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1094: 	}
 1095: 
 1096: 	if ($env{'form.showgrading'} eq 'yes' 
 1097: 	    && $submitonly ne 'queued'
 1098: 	    && $submitonly ne 'all') {
 1099: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1100: 	    my $submitted = 0;
 1101: 	    my $graded = 0;
 1102: 	    my $incorrect = 0;
 1103: 	    foreach (keys(%status)) {
 1104: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1105: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1106: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1107: 		
 1108: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1109: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1110: 		    $submitted = 0;
 1111: 		    my ($part)=split(/\./,$partid);
 1112: 		    $gradeTable.='<input type="hidden" name="'.
 1113: 			$student.':'.$part.':submitted_by" value="'.
 1114: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1115: 		}
 1116: 	    }
 1117: 	    
 1118: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1119: 				     $submitonly eq 'incorrect' ||
 1120: 				     $submitonly eq 'graded'));
 1121: 	    next if (!$graded && ($submitonly eq 'graded'));
 1122: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1123: 	}
 1124: 
 1125: 	$ctr++;
 1126: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1127:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1128: 	if ( $perm{'vgr'} eq 'F' ) {
 1129: 	    if ($ctr%2 ==1) {
 1130: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1131: 	    }
 1132: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1133:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1134:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1135: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1136: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1137: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1138: 
 1139: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1140: 		foreach (sort(keys(%status))) {
 1141: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1142: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1143: 		}
 1144: 	    }
 1145: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1146: 	    if ($ctr%2 ==0) {
 1147: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1148: 	    }
 1149: 	}
 1150:     }
 1151:     if ($ctr%2 ==1) {
 1152: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1153: 	    if ($env{'form.showgrading'} eq 'yes' 
 1154: 		&& $submitonly ne 'queued'
 1155: 		&& $submitonly ne 'all') {
 1156: 		foreach (@$partlist) {
 1157: 		    $gradeTable.='<td>&nbsp;</td>';
 1158: 		}
 1159: 	    } elsif ($submitonly eq 'queued') {
 1160: 		$gradeTable.='<td>&nbsp;</td>';
 1161: 	    }
 1162: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1163:     }
 1164: 
 1165:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1166:         '<input type="button" '.
 1167:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1168:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1169:     if ($ctr == 0) {
 1170: 	my $num_students=(scalar(keys(%$fullname)));
 1171: 	if ($num_students eq 0) {
 1172: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1173: 	} else {
 1174: 	    my $submissions='submissions';
 1175: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1176: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1177: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1178: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1179: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1180: 		    $num_students).
 1181: 		'</span><br />';
 1182: 	}
 1183:     } elsif ($ctr == 1) {
 1184: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1185:     }
 1186:     $gradeTable.=&show_grading_menu_form($symb);
 1187:     $request->print($gradeTable);
 1188:     return '';
 1189: }
 1190: 
 1191: #---- Called from the listStudents routine
 1192: 
 1193: sub check_script {
 1194:     my ($form, $type)=@_;
 1195:     my $chkallscript='<script type="text/javascript">
 1196:     function checkall() {
 1197:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1198:             ele = document.forms.'.$form.'.elements[i];
 1199:             if (ele.name == "'.$type.'") {
 1200:             document.forms.'.$form.'.elements[i].checked=true;
 1201:                                        }
 1202:         }
 1203:     }
 1204: 
 1205:     function checksec() {
 1206:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1207:             ele = document.forms.'.$form.'.elements[i];
 1208:            string = document.forms.'.$form.'.chksec.value;
 1209:            if
 1210:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1211:               document.forms.'.$form.'.elements[i].checked=true;
 1212:             }
 1213:         }
 1214:     }
 1215: 
 1216: 
 1217:     function uncheckall() {
 1218:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1219:             ele = document.forms.'.$form.'.elements[i];
 1220:             if (ele.name == "'.$type.'") {
 1221:             document.forms.'.$form.'.elements[i].checked=false;
 1222:                                        }
 1223:         }
 1224:     }
 1225: 
 1226: </script>'."\n";
 1227:     return $chkallscript;
 1228: }
 1229: 
 1230: sub check_buttons {
 1231:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1232:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1233:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1234:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1235:     return $buttons;
 1236: }
 1237: 
 1238: #     Displays the submissions for one student or a group of students
 1239: sub processGroup {
 1240:     my ($request)  = shift;
 1241:     my $ctr        = 0;
 1242:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1243:     my $total      = scalar(@stuchecked)-1;
 1244: 
 1245:     foreach my $student (@stuchecked) {
 1246: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1247: 	$env{'form.student'}        = $uname;
 1248: 	$env{'form.userdom'}        = $udom;
 1249: 	$env{'form.fullname'}       = $fullname;
 1250: 	&submission($request,$ctr,$total);
 1251: 	$ctr++;
 1252:     }
 1253:     return '';
 1254: }
 1255: 
 1256: #------------------------------------------------------------------------------------
 1257: #
 1258: #-------------------------- Next few routines handles grading by student, essentially
 1259: #                           handles essay response type problem/part
 1260: #
 1261: #--- Javascript to handle the submission page functionality ---
 1262: sub sub_page_js {
 1263:     my $request = shift;
 1264:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1265:     &js_escape(\$alertmsg);
 1266:     $request->print(<<SUBJAVASCRIPT);
 1267: <script type="text/javascript" language="javascript">
 1268:     function updateRadio(formname,id,weight) {
 1269: 	var gradeBox = formname["GD_BOX"+id];
 1270: 	var radioButton = formname["RADVAL"+id];
 1271: 	var oldpts = formname["oldpts"+id].value;
 1272: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1273: 	gradeBox.value = pts;
 1274: 	var resetbox = false;
 1275: 	if (isNaN(pts) || pts < 0) {
 1276: 	    alert("$alertmsg"+pts);
 1277: 	    for (var i=0; i<radioButton.length; i++) {
 1278: 		if (radioButton[i].checked) {
 1279: 		    gradeBox.value = i;
 1280: 		    resetbox = true;
 1281: 		}
 1282: 	    }
 1283: 	    if (!resetbox) {
 1284: 		formtextbox.value = "";
 1285: 	    }
 1286: 	    return;
 1287: 	}
 1288: 
 1289: 	if (pts > weight) {
 1290: 	    var resp = confirm("You entered a value ("+pts+
 1291: 			       ") greater than the weight for the part. Accept?");
 1292: 	    if (resp == false) {
 1293: 		gradeBox.value = oldpts;
 1294: 		return;
 1295: 	    }
 1296: 	}
 1297: 
 1298: 	for (var i=0; i<radioButton.length; i++) {
 1299: 	    radioButton[i].checked=false;
 1300: 	    if (pts == i && pts != "") {
 1301: 		radioButton[i].checked=true;
 1302: 	    }
 1303: 	}
 1304: 	updateSelect(formname,id);
 1305: 	formname["stores"+id].value = "0";
 1306:     }
 1307: 
 1308:     function writeBox(formname,id,pts) {
 1309: 	var gradeBox = formname["GD_BOX"+id];
 1310: 	if (checkSolved(formname,id) == 'update') {
 1311: 	    gradeBox.value = pts;
 1312: 	} else {
 1313: 	    var oldpts = formname["oldpts"+id].value;
 1314: 	    gradeBox.value = oldpts;
 1315: 	    var radioButton = formname["RADVAL"+id];
 1316: 	    for (var i=0; i<radioButton.length; i++) {
 1317: 		radioButton[i].checked=false;
 1318: 		if (i == oldpts) {
 1319: 		    radioButton[i].checked=true;
 1320: 		}
 1321: 	    }
 1322: 	}
 1323: 	formname["stores"+id].value = "0";
 1324: 	updateSelect(formname,id);
 1325: 	return;
 1326:     }
 1327: 
 1328:     function clearRadBox(formname,id) {
 1329: 	if (checkSolved(formname,id) == 'noupdate') {
 1330: 	    updateSelect(formname,id);
 1331: 	    return;
 1332: 	}
 1333: 	gradeSelect = formname["GD_SEL"+id];
 1334: 	for (var i=0; i<gradeSelect.length; i++) {
 1335: 	    if (gradeSelect[i].selected) {
 1336: 		var selectx=i;
 1337: 	    }
 1338: 	}
 1339: 	var stores = formname["stores"+id];
 1340: 	if (selectx == stores.value) { return };
 1341: 	var gradeBox = formname["GD_BOX"+id];
 1342: 	gradeBox.value = "";
 1343: 	var radioButton = formname["RADVAL"+id];
 1344: 	for (var i=0; i<radioButton.length; i++) {
 1345: 	    radioButton[i].checked=false;
 1346: 	}
 1347: 	stores.value = selectx;
 1348:     }
 1349: 
 1350:     function checkSolved(formname,id) {
 1351: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1352: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1353: 	    if (!reply) {return "noupdate";}
 1354: 	    formname.overRideScore.value = 'yes';
 1355: 	}
 1356: 	return "update";
 1357:     }
 1358: 
 1359:     function updateSelect(formname,id) {
 1360: 	formname["GD_SEL"+id][0].selected = true;
 1361: 	return;
 1362:     }
 1363: 
 1364: //=========== Check that a point is assigned for all the parts  ============
 1365:     function checksubmit(formname,val,total,parttot) {
 1366: 	formname.gradeOpt.value = val;
 1367: 	if (val == "Save & Next") {
 1368: 	    for (i=0;i<=total;i++) {
 1369: 		for (j=0;j<parttot;j++) {
 1370: 		    var partid = formname["partid"+i+"_"+j].value;
 1371: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1372: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1373: 			if (points == "") {
 1374: 			    var name = formname["name"+i].value;
 1375: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1376: 			    var resp = confirm("You did not assign a score for "+studentID+
 1377: 					       ", part "+partid+". Continue?");
 1378: 			    if (resp == false) {
 1379: 				formname["GD_BOX"+i+"_"+partid].focus();
 1380: 				return false;
 1381: 			    }
 1382: 			}
 1383: 		    }
 1384: 		}
 1385: 	    }
 1386: 	}
 1387: 	if (val == "Grade Student") {
 1388: 	    formname.showgrading.value = "yes";
 1389: 	    if (formname.Status.value == "") {
 1390: 		formname.Status.value = "Active";
 1391: 	    }
 1392: 	    formname.studentNo.value = total;
 1393: 	}
 1394: 	formname.submit();
 1395:     }
 1396: 
 1397: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1398:     function checkSubmitPage(formname,total) {
 1399: 	noscore = new Array(100);
 1400: 	var ptr = 0;
 1401: 	for (i=1;i<total;i++) {
 1402: 	    var partid = formname["q_"+i].value;
 1403: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1404: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1405: 		var status = formname["solved"+i+"_"+partid].value;
 1406: 		if (points == "" && status != "correct_by_student") {
 1407: 		    noscore[ptr] = i;
 1408: 		    ptr++;
 1409: 		}
 1410: 	    }
 1411: 	}
 1412: 	if (ptr != 0) {
 1413: 	    var sense = ptr == 1 ? ": " : "s: ";
 1414: 	    var prolist = "";
 1415: 	    if (ptr == 1) {
 1416: 		prolist = noscore[0];
 1417: 	    } else {
 1418: 		var i = 0;
 1419: 		while (i < ptr-1) {
 1420: 		    prolist += noscore[i]+", ";
 1421: 		    i++;
 1422: 		}
 1423: 		prolist += "and "+noscore[i];
 1424: 	    }
 1425: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1426: 	    if (resp == false) {
 1427: 		return false;
 1428: 	    }
 1429: 	}
 1430: 
 1431: 	formname.submit();
 1432:     }
 1433: </script>
 1434: SUBJAVASCRIPT
 1435: }
 1436: 
 1437: #--- javascript for essay type problem --
 1438: sub sub_page_kw_js {
 1439:     my $request = shift;
 1440:     my $iconpath = $request->dir_config('lonIconsURL');
 1441:     &commonJSfunctions($request);
 1442: 
 1443:     my $inner_js_msg_central=<<INNERJS;
 1444:     <script text="text/javascript">
 1445:     function checkInput() {
 1446:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1447:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1448:       var usrctr = document.msgcenter.usrctr.value;
 1449:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1450:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1451: 
 1452:       var msgchk = "";
 1453:       if (document.msgcenter.subchk.checked) {
 1454:          msgchk = "msgsub,";
 1455:       }
 1456:       var includemsg = 0;
 1457:       for (var i=1; i<=nmsg; i++) {
 1458:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1459:           var frmmsg = document.msgcenter["msg"+i];
 1460:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1461:           var showflg = opener.document.SCORE["shownOnce"+i];
 1462:           showflg.value = "1";
 1463:           var chkbox = document.msgcenter["msgn"+i];
 1464:           if (chkbox.checked) {
 1465:              msgchk += "savemsg"+i+",";
 1466:              includemsg = 1;
 1467:           }
 1468:       }
 1469:       if (document.msgcenter.newmsgchk.checked) {
 1470:          msgchk += "newmsg"+usrctr;
 1471:          includemsg = 1;
 1472:       }
 1473:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1474:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1475:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1476:       includemsg.value = msgchk;
 1477: 
 1478:       self.close()
 1479: 
 1480:     }
 1481:     </script>
 1482: INNERJS
 1483: 
 1484:     my $inner_js_highlight_central=<<INNERJS;
 1485:  <script type="text/javascript">
 1486:     function updateChoice(flag) {
 1487:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1488:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1489:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1490:       opener.document.SCORE.refresh.value = "on";
 1491:       if (opener.document.SCORE.keywords.value!=""){
 1492:          opener.document.SCORE.submit();
 1493:       }
 1494:       self.close()
 1495:     }
 1496: </script>
 1497: INNERJS
 1498: 
 1499:     my $start_page_msg_central = 
 1500:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1501: 				       {'js_ready'  => 1,
 1502: 					'only_body' => 1,
 1503: 					'bgcolor'   =>'#FFFFFF',});
 1504:     my $end_page_msg_central = 
 1505: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1506: 
 1507: 
 1508:     my $start_page_highlight_central = 
 1509:         &Apache::loncommon::start_page('Highlight Central',
 1510: 				       $inner_js_highlight_central,
 1511: 				       {'js_ready'  => 1,
 1512: 					'only_body' => 1,
 1513: 					'bgcolor'   =>'#FFFFFF',});
 1514:     my $end_page_highlight_central = 
 1515: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1516: 
 1517:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1518:     $docopen=~s/^document\.//;
 1519:     my %js_lt = &Apache::lonlocal::texthash(
 1520:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1521:                 plse => 'Please select a word or group of words from document and then click this link.',
 1522:                 adds => 'Add selection to keyword list? Edit if desired.',
 1523:                 col1 => 'red',
 1524:                 col2 => 'green',
 1525:                 col3 => 'blue',
 1526:                 siz1 => 'normal',
 1527:                 siz2 => '+1',
 1528:                 siz3 => '+2',
 1529:                 sty1 => 'normal',
 1530:                 sty2 => 'italic',
 1531:                 sty3 => 'bold',
 1532:              );
 1533:     my %html_js_lt = &Apache::lonlocal::texthash(
 1534:                 comp => 'Compose Message for: ',
 1535:                 incl => 'Include',
 1536:                 type => 'Type',
 1537:                 subj => 'Subject',
 1538:                 mesa => 'Message',
 1539:                 new  => 'New',
 1540:                 save => 'Save',
 1541:                 canc => 'Cancel',
 1542:                 kehi => 'Keyword Highlight Options',
 1543:                 txtc => 'Text Color',
 1544:                 font => 'Font Size',
 1545:                 fnst => 'Font Style',
 1546:              );
 1547:     &js_escape(\%js_lt);
 1548:     &html_escape(\%html_js_lt);
 1549:     &js_escape(\%html_js_lt);
 1550:     $request->print(<<SUBJAVASCRIPT);
 1551: <script type="text/javascript" language="javascript">
 1552: 
 1553: //===================== Show list of keywords ====================
 1554:   function keywords(formname) {
 1555:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1556:     if (nret==null) return;
 1557:     formname.keywords.value = nret;
 1558: 
 1559:     if (formname.keywords.value != "") {
 1560: 	formname.refresh.value = "on";
 1561: 	formname.submit();
 1562:     }
 1563:     return;
 1564:   }
 1565: 
 1566: //===================== Script to view submitted by ==================
 1567:   function viewSubmitter(submitter) {
 1568:     document.SCORE.refresh.value = "on";
 1569:     document.SCORE.NCT.value = "1";
 1570:     document.SCORE.unamedom0.value = submitter;
 1571:     document.SCORE.submit();
 1572:     return;
 1573:   }
 1574: 
 1575: //===================== Script to add keyword(s) ==================
 1576:   function getSel() {
 1577:     if (document.getSelection) txt = document.getSelection();
 1578:     else if (document.selection) txt = document.selection.createRange().text;
 1579:     else return;
 1580:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1581:     if (cleantxt=="") {
 1582: 	alert("$js_lt{'plse'}");
 1583: 	return;
 1584:     }
 1585:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1586:     if (nret==null) return;
 1587:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1588:     if (document.SCORE.keywords.value != "") {
 1589: 	document.SCORE.refresh.value = "on";
 1590: 	document.SCORE.submit();
 1591:     }
 1592:     return;
 1593:   }
 1594: 
 1595: //====================== Script for composing message ==============
 1596:    // preload images
 1597:    img1 = new Image();
 1598:    img1.src = "$iconpath/mailbkgrd.gif";
 1599:    img2 = new Image();
 1600:    img2.src = "$iconpath/mailto.gif";
 1601: 
 1602:   function msgCenter(msgform,usrctr,fullname) {
 1603:     var Nmsg  = msgform.savemsgN.value;
 1604:     savedMsgHeader(Nmsg,usrctr,fullname);
 1605:     var subject = msgform.msgsub.value;
 1606:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1607:     re = /msgsub/;
 1608:     var shwsel = "";
 1609:     if (re.test(msgchk)) { shwsel = "checked" }
 1610:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1611:     displaySubject(checkEntities(subject),shwsel);
 1612:     for (var i=1; i<=Nmsg; i++) {
 1613: 	var testmsg = "savemsg"+i+",";
 1614: 	re = new RegExp(testmsg,"g");
 1615: 	shwsel = "";
 1616: 	if (re.test(msgchk)) { shwsel = "checked" }
 1617: 	var message = document.SCORE["savemsg"+i].value;
 1618: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1619: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1620: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1621:     }
 1622:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1623:     shwsel = "";
 1624:     re = /newmsg/;
 1625:     if (re.test(msgchk)) { shwsel = "checked" }
 1626:     newMsg(newmsg,shwsel);
 1627:     msgTail(); 
 1628:     return;
 1629:   }
 1630: 
 1631:   function checkEntities(strx) {
 1632:     if (strx.length == 0) return strx;
 1633:     var orgStr = ["&", "<", ">", '"']; 
 1634:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1635:     var counter = 0;
 1636:     while (counter < 4) {
 1637: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1638: 	counter++;
 1639:     }
 1640:     return strx;
 1641:   }
 1642: 
 1643:   function strReplace(strx, orgStr, newStr) {
 1644:     return strx.split(orgStr).join(newStr);
 1645:   }
 1646: 
 1647:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1648:     var height = 70*Nmsg+250;
 1649:     if (height > 600) {
 1650: 	height = 600;
 1651:     }
 1652:     var xpos = (screen.width-600)/2;
 1653:     xpos = (xpos < 0) ? '0' : xpos;
 1654:     var ypos = (screen.height-height)/2-30;
 1655:     ypos = (ypos < 0) ? '0' : ypos;
 1656: 
 1657:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1658:     pWin.focus();
 1659:     pDoc = pWin.document;
 1660:     pDoc.$docopen;
 1661:     pDoc.write('$start_page_msg_central');
 1662: 
 1663:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1664:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1665:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1666: 
 1667:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1668:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1669:     pDoc.write("<td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1670: }
 1671:     function displaySubject(msg,shwsel) {
 1672:     pDoc = pWin.document;
 1673:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1674:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1675:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1676:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1677: }
 1678: 
 1679:   function displaySavedMsg(ctr,msg,shwsel) {
 1680:     pDoc = pWin.document;
 1681:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1682:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1683:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1684:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1685: }
 1686: 
 1687:   function newMsg(newmsg,shwsel) {
 1688:     pDoc = pWin.document;
 1689:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1690:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1691:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1692:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1693: }
 1694: 
 1695:   function msgTail() {
 1696:     pDoc = pWin.document;
 1697:     pDoc.write("<\\/table>");
 1698:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1699:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1700:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1701:     pDoc.write("<\\/form>");
 1702:     pDoc.write('$end_page_msg_central');
 1703:     pDoc.close();
 1704: }
 1705: 
 1706: //====================== Script for keyword highlight options ==============
 1707:   function kwhighlight() {
 1708:     var kwclr    = document.SCORE.kwclr.value;
 1709:     var kwsize   = document.SCORE.kwsize.value;
 1710:     var kwstyle  = document.SCORE.kwstyle.value;
 1711:     var redsel = "";
 1712:     var grnsel = "";
 1713:     var blusel = "";
 1714:     var txtcol1 = "$js_lt{'col1'}";
 1715:     var txtcol2 = "$js_lt{'col2'}";
 1716:     var txtcol3 = "$js_lt{'col3'}";
 1717:     var txtsiz1 = "$js_lt{'siz1'}";
 1718:     var txtsiz2 = "$js_lt{'siz2'}";
 1719:     var txtsiz3 = "$js_lt{'siz3'}";
 1720:     var txtsty1 = "$js_lt{'sty1'}";
 1721:     var txtsty2 = "$js_lt{'sty2'}";
 1722:     var txtsty3 = "$js_lt{'sty3'}";
 1723:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1724:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1725:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1726:     var sznsel = "";
 1727:     var sz1sel = "";
 1728:     var sz2sel = "";
 1729:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1730:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1731:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1732:     var synsel = "";
 1733:     var syisel = "";
 1734:     var sybsel = "";
 1735:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1736:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1737:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1738:     highlightCentral();
 1739:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1740:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1741:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1742:     highlightend();
 1743:     return;
 1744:   }
 1745: 
 1746:   function highlightCentral() {
 1747: //    if (window.hwdWin) window.hwdWin.close();
 1748:     var xpos = (screen.width-400)/2;
 1749:     xpos = (xpos < 0) ? '0' : xpos;
 1750:     var ypos = (screen.height-330)/2-30;
 1751:     ypos = (ypos < 0) ? '0' : ypos;
 1752: 
 1753:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1754:     hwdWin.focus();
 1755:     var hDoc = hwdWin.document;
 1756:     hDoc.$docopen;
 1757:     hDoc.write('$start_page_highlight_central');
 1758:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1759:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1760: 
 1761:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1762:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1763:   }
 1764: 
 1765:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1766:     var hDoc = hwdWin.document;
 1767:     hDoc.write("<tr>");
 1768:     hDoc.write("<td align=\\"left\\">");
 1769:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1770:     hDoc.write("<td align=\\"left\\">");
 1771:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1772:     hDoc.write("<td align=\\"left\\">");
 1773:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1774:     hDoc.write("<\\/tr>");
 1775:   }
 1776: 
 1777:   function highlightend() { 
 1778:     var hDoc = hwdWin.document;
 1779:     hDoc.write("<\\/table><br \\/>");
 1780:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1781:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1782:     hDoc.write("<\\/form>");
 1783:     hDoc.write('$end_page_highlight_central');
 1784:     hDoc.close();
 1785:   }
 1786: 
 1787: </script>
 1788: SUBJAVASCRIPT
 1789: }
 1790: 
 1791: sub get_increment {
 1792:     my $increment = $env{'form.increment'};
 1793:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1794:         $increment != .1) {
 1795:         $increment = 1;
 1796:     }
 1797:     return $increment;
 1798: }
 1799: 
 1800: sub gradeBox_start {
 1801:     return (
 1802:         &Apache::loncommon::start_data_table()
 1803:        .&Apache::loncommon::start_data_table_header_row()
 1804:        .'<th>'.&mt('Part').'</th>'
 1805:        .'<th>'.&mt('Points').'</th>'
 1806:        .'<th>&nbsp;</th>'
 1807:        .'<th>'.&mt('Assign Grade').'</th>'
 1808:        .'<th>'.&mt('Weight').'</th>'
 1809:        .'<th>'.&mt('Grade Status').'</th>'
 1810:        .&Apache::loncommon::end_data_table_header_row()
 1811:     );
 1812: }
 1813: 
 1814: sub gradeBox_end {
 1815:     return (
 1816:         &Apache::loncommon::end_data_table()
 1817:     );
 1818: }
 1819: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1820: sub gradeBox {
 1821:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1822:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1823: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1824:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1825:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1826:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1827:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1828:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1829: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1830:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1831:     my $display_part= &get_display_part($partid,$symb);
 1832:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1833: 				       [$partid]);
 1834:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1835:     if ($last_resets{$partid}) {
 1836:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1837:     }
 1838:     my $result=&Apache::loncommon::start_data_table_row();
 1839:     my $ctr = 0;
 1840:     my $thisweight = 0;
 1841:     my $increment = &get_increment();
 1842: 
 1843:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1844:     while ($thisweight<=$wgt) {
 1845: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1846:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1847: 	    $thisweight.')" value="'.$thisweight.'" '.
 1848: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1849: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1850:         $thisweight += $increment;
 1851: 	$ctr++;
 1852:     }
 1853:     $radio.='</tr></table>';
 1854: 
 1855:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1856: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1857: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1858: 	$wgt.')" /></td>'."\n";
 1859:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1860: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1861: 	' </td>'."\n";
 1862:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1863: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1864:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1865: 	$line.='<option></option>'.
 1866: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1867:     } else {
 1868: 	$line.='<option selected="selected"></option>'.
 1869: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1870:     }
 1871:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1872: 
 1873: 
 1874:     $result .= 
 1875: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1876:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1877:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1878: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1879: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1880: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1881:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1882:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1883:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1884:         $aggtries.'" />'."\n";
 1885:     my $res_error;
 1886:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1887:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1888:     if ($res_error) {
 1889:         return &navmap_errormsg();
 1890:     }
 1891:     return $result;
 1892: }
 1893: 
 1894: sub handback_box {
 1895:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1896:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1897:     my (@respids);
 1898:     my @part_response_id = &flatten_responseType($responseType);
 1899:     foreach my $part_response_id (@part_response_id) {
 1900:     	my ($part,$resp) = @{ $part_response_id };
 1901:         if ($part eq $partid) {
 1902:             push(@respids,$resp);
 1903:         }
 1904:     }
 1905:     my $result;
 1906:     foreach my $respid (@respids) {
 1907: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1908: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1909: 	next if (!@$files);
 1910: 	my $file_counter = 0;
 1911: 	foreach my $file (@$files) {
 1912: 	    if ($file =~ /\/portfolio\//) {
 1913:                 $file_counter++;
 1914:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1915:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1916:     	        $file_disp = "$name.$ext";
 1917:     	        $file = $file_path.$file_disp;
 1918:     	        $result.=&mt('Return commented version of [_1] to student.',
 1919:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1920:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1921:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1922: 	    }
 1923: 	}
 1924:         if ($file_counter) {
 1925:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1926:                        '<span class="LC_info">'.
 1927:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1928:         }
 1929:     }
 1930:     return $result;    
 1931: }
 1932: 
 1933: sub show_problem {
 1934:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1935:     my $rendered;
 1936:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1937:     &Apache::lonxml::remember_problem_counter();
 1938:     if ($mode eq 'both' or $mode eq 'text') {
 1939: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1940: 						       $env{'request.course.id'},
 1941: 						       undef,\%form);
 1942:     }
 1943:     if ($removeform) {
 1944: 	$rendered=~s|<form(.*?)>||g;
 1945: 	$rendered=~s|</form>||g;
 1946: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1947:     }
 1948:     my $companswer;
 1949:     if ($mode eq 'both' or $mode eq 'answer') {
 1950: 	&Apache::lonxml::restore_problem_counter();
 1951: 	$companswer=
 1952: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1953: 						    $env{'request.course.id'},
 1954: 						    %form);
 1955:     }
 1956:     if ($removeform) {
 1957: 	$companswer=~s|<form(.*?)>||g;
 1958: 	$companswer=~s|</form>||g;
 1959: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1960:     }
 1961:     my $renderheading = &mt('View of the problem');
 1962:     my $answerheading = &mt('Correct answer');
 1963:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1964:         my $stu_fullname = $env{'form.fullname'};
 1965:         if ($stu_fullname eq '') {
 1966:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1967:         }
 1968:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1969:         if ($forwhom ne '') {
 1970:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1971:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1972:         }
 1973:     }
 1974:     $rendered=
 1975:         '<div class="LC_Box">'
 1976:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1977:        .$rendered
 1978:        .'</div>';
 1979:     $companswer=
 1980:         '<div class="LC_Box">'
 1981:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1982:        .$companswer
 1983:        .'</div>';
 1984:     my $result;
 1985:     if ($mode eq 'both') {
 1986:         $result=$rendered.$companswer;
 1987:     } elsif ($mode eq 'text') {
 1988:         $result=$rendered;
 1989:     } elsif ($mode eq 'answer') {
 1990:         $result=$companswer;
 1991:     }
 1992:     return $result;
 1993: }
 1994: 
 1995: sub files_exist {
 1996:     my ($r, $symb) = @_;
 1997:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1998: 
 1999:     foreach my $student (@students) {
 2000:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2001:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2002: 					      $udom,$uname);
 2003:         my ($string,$timestamp)= &get_last_submission(\%record);
 2004:         foreach my $submission (@$string) {
 2005:             my ($partid,$respid) =
 2006: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2007:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2008: 					   \%record);
 2009:             return 1 if (@$files);
 2010:         }
 2011:     }
 2012:     return 0;
 2013: }
 2014: 
 2015: sub download_all_link {
 2016:     my ($r,$symb) = @_;
 2017:     my $all_students = 
 2018: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2019: 
 2020:     my $parts =
 2021: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2022: 
 2023:     my $identifier = &Apache::loncommon::get_cgi_id();
 2024:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2025:                              'cgi.'.$identifier.'.symb' => $symb,
 2026:                              'cgi.'.$identifier.'.parts' => $parts,});
 2027:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2028: 	      &mt('Download All Submitted Documents').'</a>');
 2029:     return
 2030: }
 2031: 
 2032: sub build_section_inputs {
 2033:     my $section_inputs;
 2034:     if ($env{'form.section'} eq '') {
 2035:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2036:     } else {
 2037:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2038:         foreach my $section (@sections) {
 2039:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2040:         }
 2041:     }
 2042:     return $section_inputs;
 2043: }
 2044: 
 2045: # --------------------------- show submissions of a student, option to grade 
 2046: sub submission {
 2047:     my ($request,$counter,$total) = @_;
 2048:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2049:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2050:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2051:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2052:     my ($symb) = &get_symb($request); 
 2053:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2054: 
 2055:     if (!&canview($usec)) {
 2056:         $request->print(
 2057:             '<span class="LC_warning">'.
 2058:             &mt('Unable to view requested student.').
 2059:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2060:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2061:             '</span>');
 2062: 	$request->print(&show_grading_menu_form($symb));
 2063: 	return;
 2064:     }
 2065: 
 2066:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2067:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2068:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2069:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2070:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2071: 	'" src="'.$request->dir_config('lonIconsURL').
 2072: 	'/check.gif" height="16" border="0" />';
 2073: 
 2074:     # header info
 2075:     if ($counter == 0) {
 2076: 	&sub_page_js($request);
 2077: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2078: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2079: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2080: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2081: 	    &download_all_link($request, $symb);
 2082: 	}
 2083: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2084: 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
 2085: 
 2086: 	# option to display problem, only once else it cause problems 
 2087:         # with the form later since the problem has a form.
 2088: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2089: 	    my $mode;
 2090: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2091: 		$mode='both';
 2092: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2093: 		$mode='text';
 2094: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2095: 		$mode='answer';
 2096: 	    }
 2097: 	    &Apache::lonxml::clear_problem_counter();
 2098: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2099: 	}
 2100: 
 2101: 	# kwclr is the only variable that is guaranteed not to be blank 
 2102:         # if this subroutine has been called once.
 2103: 	my %keyhash = ();
 2104: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2105: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2106: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2107: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2108: 
 2109: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2110: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2111: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2112: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2113: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2114: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2115: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2116: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2117: 	}
 2118: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2119: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2120: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2121: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2122: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2123: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2124: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2125: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2126: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2127: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2128: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2129: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2130: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2131: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2132: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2133: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2134: 			&build_section_inputs().
 2135: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2136: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2137: 			'<input type="hidden" name="NCT"'.
 2138: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2139: 	if ($env{'form.handgrade'} eq 'yes') {
 2140: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2141: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2142: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2143: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2144: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2145: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2146: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2147: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2148: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2149: 	    }
 2150: 	}
 2151: 	
 2152: 	my ($cts,$prnmsg) = (1,'');
 2153: 	while ($cts <= $env{'form.savemsgN'}) {
 2154: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2155: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2156: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2157: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2158: 		'" />'."\n".
 2159: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2160: 	    $cts++;
 2161: 	}
 2162: 	$request->print($prnmsg);
 2163: 
 2164: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2165: 
 2166:             my %lt = &Apache::lonlocal::texthash(
 2167:                           keyh => 'Keyword Highlighting for Essays',
 2168:                           keyw => 'Keyword Options',
 2169:                           list => 'List',
 2170:                           past => 'Paste Selection to List',
 2171:                           high => 'Highlight Attribute',
 2172:                      );
 2173: #
 2174: # Print out the keyword options line
 2175: #
 2176:             $request->print(
 2177:                 '<div class="LC_columnSection">'
 2178:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2179:                .&Apache::lonhtmlcommon::funclist_from_array(
 2180:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2181:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2182:  class="page">'.$lt{'past'}.'</a>',
 2183:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2184:                     {legend => $lt{'keyw'}})
 2185:                .'</fieldset></div>'
 2186:             );
 2187: 
 2188: #
 2189: # Load the other essays for similarity check
 2190: #
 2191:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2192: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2193: 	    $apath=&escape($apath);
 2194: 	    $apath=~s/\W/\_/gs;
 2195:             &init_old_essays($symb,$apath,$adom,$aname);
 2196:         }
 2197:     }
 2198: 
 2199: # This is where output for one specific student would start
 2200:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2201:     $request->print(
 2202:         "\n\n"
 2203:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2204:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2205:        ."\n"
 2206:     );
 2207: 
 2208:     # Show additional functions if allowed
 2209:     if ($perm{'vgr'}) {
 2210:         $request->print(
 2211:             &Apache::loncommon::track_student_link(
 2212:                 'View recent activity',
 2213:                 $uname,$udom,'check')
 2214:            .' '
 2215:         );
 2216:     }
 2217:     if ($perm{'opa'}) {
 2218:         $request->print(
 2219:             &Apache::loncommon::pprmlink(
 2220:                 &mt('Set/Change parameters'),
 2221:                 $uname,$udom,$symb,'check'));
 2222:     }
 2223: 
 2224:     # Show Problem
 2225:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2226: 	my $mode;
 2227: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2228: 	    $mode='both';
 2229: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2230: 	    $mode='text';
 2231: 	} elsif ($env{'form.vAns'} eq 'all') {
 2232: 	    $mode='answer';
 2233: 	}
 2234: 	&Apache::lonxml::clear_problem_counter();
 2235: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2236:     }
 2237: 
 2238:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2239:     my $res_error;
 2240:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2241:     if ($res_error) {
 2242:         $request->print(&navmap_errormsg());
 2243:         return;
 2244:     }
 2245: 
 2246:     # Display student info
 2247:     $request->print(($counter == 0 ? '' : '<br />'));
 2248: 
 2249:     my $result='<div class="LC_Box">'
 2250:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2251:     $result.='<input type="hidden" name="name'.$counter.
 2252:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2253:     if ($env{'form.handgrade'} eq 'no') {
 2254:         $result.='<p class="LC_info">'
 2255:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2256:                 ."</p>\n";
 2257:     }
 2258: 
 2259:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2260:     my $fullname;
 2261:     my $col_fullnames = [];
 2262:     if ($env{'form.handgrade'} eq 'yes') {
 2263: 	(my $sub_result,$fullname,$col_fullnames)=
 2264: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2265: 				 $counter);
 2266: 	$result.=$sub_result;
 2267:     }
 2268:     $request->print($result."\n");
 2269: 
 2270:     # print student answer/submission
 2271:     # Options are (1) Handgraded submission only
 2272:     #             (2) Last submission, includes submission that is not handgraded 
 2273:     #                  (for multi-response type part)
 2274:     #             (3) Last submission plus the parts info
 2275:     #             (4) The whole record for this student
 2276: 
 2277: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2278: 	
 2279: 	my $lastsubonly;
 2280: 
 2281:         if ($$timestamp eq '') {
 2282:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2283:         } else {
 2284:             $lastsubonly =
 2285:                 '<div class="LC_grade_submissions_body">'
 2286:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2287: 
 2288: 	    my %seenparts;
 2289: 	    my @part_response_id = &flatten_responseType($responseType);
 2290: 	    foreach my $part (@part_response_id) {
 2291: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2292: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2293: 
 2294: 		my ($partid,$respid) = @{ $part };
 2295: 		my $display_part=&get_display_part($partid,$symb);
 2296: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2297: 		    if (exists($seenparts{$partid})) { next; }
 2298: 		    $seenparts{$partid}=1;
 2299:                     $request->print(
 2300:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2301:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2302:                                    '<a href="javascript:viewSubmitter(\''.
 2303:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2304:                                    '\');" target="_self">'.
 2305:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2306:                         '<br />');
 2307: 		    next;
 2308: 		}
 2309: 		my $responsetype = $responseType->{$partid}->{$respid};
 2310: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2311:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2312:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2313:                         ' <span class="LC_internal_info">'.
 2314:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2315:                         '</span>&nbsp; &nbsp;'.
 2316: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2317: 		    next;
 2318: 		}
 2319: 		foreach my $submission (@$string) {
 2320: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2321: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2322: 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2323: 		    # Similarity check
 2324: 		    my $similar='';
 2325:                     my ($type,$trial,$rndseed);
 2326:                     if ($hide eq 'rand') {
 2327:                         $type = 'randomizetry';
 2328:                         $trial = $record{"resource.$partid.tries"};
 2329:                         $rndseed = $record{"resource.$partid.rndseed"};
 2330:                     }
 2331: 		    if ($env{'form.checkPlag'}) {
 2332: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2333: 			    &most_similar($uname,$udom,$symb,$subval);
 2334: 			if ($osim) {
 2335: 			    $osim=int($osim*100.0);
 2336: 			    my %old_course_desc = 
 2337: 				&Apache::lonnet::coursedescription($ocrsid,
 2338: 								   {'one_time' => 1});
 2339: 
 2340:                             if ($hide eq 'anon') {
 2341:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2342:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2343:                             } else {
 2344: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2345: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2346: 				        $osim,
 2347: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2348: 				        $old_course_desc{'description'},
 2349: 				        $old_course_desc{'num'},
 2350: 				        $old_course_desc{'domain'}).
 2351: 				    '</span></h3><blockquote><i>'.
 2352: 				    &keywords_highlight($oessay).
 2353: 				    '</i></blockquote><hr />';
 2354:                             }
 2355: 			}
 2356: 		    }
 2357: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2358:                                          undef,$type,$trial,$rndseed);
 2359:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2360:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2361: 			my $display_part=&get_display_part($partid,$symb);
 2362:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2363:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2364:                             ' <span class="LC_internal_info">'.
 2365:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2366:                             '</span>&nbsp; &nbsp;';
 2367: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2368: 			if (@$files) {
 2369:                             if ($hide eq 'anon') {
 2370:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2371:                             } else {
 2372:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2373:                                             .'<br /><span class="LC_warning">';
 2374:                                 if(@$files == 1) {
 2375:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2376:                                 } else {
 2377:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2378:                                 }
 2379:                                 $lastsubonly .= '</span>';
 2380: 
 2381:                                 foreach my $file (@$files) {
 2382:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2383:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2384:                                 }
 2385:                             }
 2386: 			    $lastsubonly.='<br />';
 2387: 			}
 2388:                         if ($hide eq 'anon') {
 2389:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2390:                         } else {
 2391: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2392:                             if ($draft) {
 2393:                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2394:                             }
 2395:                             $subval =
 2396: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2397: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2398:                             if ($responsetype eq 'essay') {
 2399:                                 $subval =~ s{\n}{<br />}g;
 2400:                             }
 2401:                             $lastsubonly.=$subval."\n";
 2402:                         }
 2403: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2404: 			$lastsubonly.='</div>';
 2405: 		    }
 2406: 		}
 2407: 	    }
 2408: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2409: 	}
 2410: 	$request->print($lastsubonly);
 2411:    if ($env{'form.lastSub'} eq 'datesub') {
 2412: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2413: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2414:     }
 2415:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2416:         my $identifier = (&canmodify($usec)? $counter : '');
 2417: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2418: 								 $env{'request.course.id'},
 2419: 								 $last,'.submission',
 2420: 								 'Apache::grades::keywords_highlight',
 2421:                                                                  $usec,$identifier));
 2422:     }
 2423: 
 2424:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2425: 	.$udom.'" />'."\n");
 2426:     # return if view submission with no grading option
 2427:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2428: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2429: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2430: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2431: 	$toGrade.='</div>'."\n";
 2432: 	if (($env{'form.command'} eq 'submission') || 
 2433: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2434: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2435: 	}
 2436: 	$request->print($toGrade);
 2437: 	return;
 2438:     } else {
 2439: 	$request->print('</div>'."\n");
 2440:     }
 2441: 
 2442:     # essay grading message center
 2443:     if ($env{'form.handgrade'} eq 'yes') {
 2444: 	my $result='<div class="LC_grade_message_center">';
 2445:     
 2446: 	$result.='<div class="LC_grade_message_center_header">'.
 2447: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2448: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2449: 	my $msgfor = $givenn.' '.$lastname;
 2450: 	if (scalar(@$col_fullnames) > 0) {
 2451: 	    my $lastone = pop(@$col_fullnames);
 2452: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2453: 	}
 2454: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2455: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2456: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2457: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2458: 	    ',\''.$msgfor.'\');" target="_self">'.
 2459: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2460: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2461: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2462: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2463: 	    '<br />&nbsp;('.
 2464: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2465: 	$result.='</div></div>';
 2466: 	$request->print($result);
 2467:     }
 2468: 
 2469:     my %seen = ();
 2470:     my @partlist;
 2471:     my @gradePartRespid;
 2472:     my @part_response_id = &flatten_responseType($responseType);
 2473:     $request->print(
 2474:         '<div class="LC_Box">'
 2475:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2476:     );
 2477:     $request->print(&gradeBox_start());
 2478:     foreach my $part_response_id (@part_response_id) {
 2479:     	my ($partid,$respid) = @{ $part_response_id };
 2480: 	my $part_resp = join('_',@{ $part_response_id });
 2481: 	next if ($seen{$partid} > 0);
 2482: 	$seen{$partid}++;
 2483: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2484: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2485: 	push(@partlist,$partid);
 2486: 	push(@gradePartRespid,$partid.'.'.$respid);
 2487: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2488:     }
 2489:     $request->print(&gradeBox_end()); # </div>
 2490:     $request->print('</div>');
 2491: 
 2492:     $request->print('<div class="LC_grade_info_links">');
 2493:     $request->print('</div>');
 2494: 
 2495:     $result='<input type="hidden" name="partlist'.$counter.
 2496: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2497:     $result.='<input type="hidden" name="gradePartRespid'.
 2498: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2499:     my $ctr = 0;
 2500:     while ($ctr < scalar(@partlist)) {
 2501: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2502: 	    $partlist[$ctr].'" />'."\n";
 2503: 	$ctr++;
 2504:     }
 2505:     $request->print($result.''."\n");
 2506: 
 2507: # Done with printing info for one student
 2508: 
 2509:     $request->print('</div>');#LC_grade_show_user
 2510: 
 2511: 
 2512:     # print end of form
 2513:     if ($counter == $total) {
 2514:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2515: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2516: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2517: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2518: 	my $ntstu ='<select name="NTSTU">'.
 2519: 	    '<option>1</option><option>2</option>'.
 2520: 	    '<option>3</option><option>5</option>'.
 2521: 	    '<option>7</option><option>10</option></select>'."\n";
 2522: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2523: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2524:         $endform.=&mt('[_1]student(s)',$ntstu);
 2525: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2526: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2527: 	    '<input type="button" value="'.&mt('Next').'" '.
 2528: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2529:         $endform.='<span class="LC_warning">'.
 2530:                   &mt('(Next and Previous (student) do not save the scores.)').
 2531:                   '</span>'."\n" ;
 2532:         $endform.="<input type='hidden' value='".&get_increment().
 2533:             "' name='increment' />";
 2534: 	$endform.='</td></tr></table></form>';
 2535: 	$endform.=&show_grading_menu_form($symb);
 2536: 	$request->print($endform);
 2537:     }
 2538:     return '';
 2539: }
 2540: 
 2541: sub check_collaborators {
 2542:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2543:     my ($result,@col_fullnames);
 2544:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2545:     foreach my $part (keys(%$handgrade)) {
 2546: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2547: 					'.maxcollaborators',
 2548: 					$symb,$udom,$uname);
 2549: 	next if ($ncol <= 0);
 2550: 	$part =~ s/\_/\./g;
 2551: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2552: 	my (@good_collaborators, @bad_collaborators);
 2553: 	foreach my $possible_collaborator
 2554: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2555: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2556: 	    next if ($possible_collaborator eq '');
 2557: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2558: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2559: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2560: 	    # Doing this grep allows 'fuzzy' specification
 2561: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2562: 			       keys(%$classlist));
 2563: 	    if (! scalar(@matches)) {
 2564: 		push(@bad_collaborators, $possible_collaborator);
 2565: 	    } else {
 2566: 		push(@good_collaborators, @matches);
 2567: 	    }
 2568: 	}
 2569: 	if (scalar(@good_collaborators) != 0) {
 2570: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2571: 	    foreach my $name (@good_collaborators) {
 2572: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2573: 		push(@col_fullnames, $givenn.' '.$lastname);
 2574: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2575: 	    }
 2576: 	    $result.='</ol><br />'."\n";
 2577: 	    my ($part)=split(/\./,$part);
 2578: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2579: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2580: 		"\n";
 2581: 	}
 2582: 	if (scalar(@bad_collaborators) > 0) {
 2583: 	    $result.='<div class="LC_warning">';
 2584: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2585: 	    $result .= '</div>';
 2586: 	}         
 2587: 	if (scalar(@bad_collaborators > $ncol)) {
 2588: 	    $result .= '<div class="LC_warning">';
 2589: 	    $result .= &mt('This student has submitted too many '.
 2590: 		'collaborators.  Maximum is [_1].',$ncol);
 2591: 	    $result .= '</div>';
 2592: 	}
 2593:     }
 2594:     return ($result,$fullname,\@col_fullnames);
 2595: }
 2596: 
 2597: #--- Retrieve the last submission for all the parts
 2598: sub get_last_submission {
 2599:     my ($returnhash)=@_;
 2600:     my (@string,$timestamp,%lasthidden);
 2601:     if ($$returnhash{'version'}) {
 2602: 	my %lasthash=();
 2603: 	my ($version);
 2604: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2605: 	    foreach my $key (sort(split(/\:/,
 2606: 					$$returnhash{$version.':keys'}))) {
 2607: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2608: 		$timestamp = 
 2609: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2610: 	    }
 2611: 	}
 2612:         my (%typeparts,%randombytry);
 2613:         my $showsurv = 
 2614:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2615:         foreach my $key (sort(keys(%lasthash))) {
 2616:             if ($key =~ /\.type$/) {
 2617:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2618:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2619:                     ($lasthash{$key} eq 'randomizetry')) {
 2620:                     my ($ign,@parts) = split(/\./,$key);
 2621:                     pop(@parts);
 2622:                     my $id = join('.',@parts);
 2623:                     if ($lasthash{$key} eq 'randomizetry') {
 2624:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2625:                     } else {
 2626:                         unless ($showsurv) {
 2627:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2628:                         }
 2629:                     }
 2630:                     delete($lasthash{$key});
 2631:                 }
 2632:             }
 2633:         }
 2634:         my @hidden = keys(%typeparts);
 2635:         my @randomize = keys(%randombytry);
 2636: 	foreach my $key (keys(%lasthash)) {
 2637: 	    next if ($key !~ /\.submission$/);
 2638:             my $hide;
 2639:             if (@hidden) {
 2640:                 foreach my $id (@hidden) {
 2641:                     if ($key =~ /^\Q$id\E/) {
 2642:                         $hide = 'anon';
 2643:                         last;
 2644:                     }
 2645:                 }
 2646:             }
 2647:             unless ($hide) {
 2648:                 if (@randomize) {
 2649:                     foreach my $id (@randomize) {
 2650:                         if ($key =~ /^\Q$id\E/) {
 2651:                             $hide = 'rand';
 2652:                             last;
 2653:                         }
 2654:                     }
 2655:                 }
 2656:             }
 2657: 	    my ($partid,$foo) = split(/submission$/,$key);
 2658: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
 2659:             push(@string, join(':', $key, $hide, $draft, (
 2660:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2661:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2662: 	}
 2663:     }
 2664:     if (!@string) {
 2665: 	$string[0] =
 2666: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2667:     }
 2668:     return (\@string,\$timestamp);
 2669: }
 2670: 
 2671: #--- High light keywords, with style choosen by user.
 2672: sub keywords_highlight {
 2673:     my $string    = shift;
 2674:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2675:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2676:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2677:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2678:     foreach my $keyword (@keylist) {
 2679: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2680:     }
 2681:     return $string;
 2682: }
 2683: 
 2684: # For Tasks provide a mechanism to display previous version for one specific student
 2685: 
 2686: sub show_previous_task_version {
 2687:     my ($request,$symb) = @_;
 2688:     if ($symb eq '') {
 2689:         $request->print(
 2690:             '<span class="LC_error">'.
 2691:             &mt('Unable to handle ambiguous references.').
 2692:             '</span>');
 2693:         return '';
 2694:     }
 2695:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2696:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2697:     if (!&canview($usec)) {
 2698:         $request->print('<span class="LC_warning">'.
 2699:                         &mt('Unable to view previous version for requested student.').
 2700:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2701:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2702:                         '</span>');
 2703:         return;
 2704:     }
 2705:     my $mode = 'both';
 2706:     my $isTask = ($symb =~/\.task$/);
 2707:     if ($isTask) {
 2708:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2709:             if ($env{'form.fullname'} eq '') {
 2710:                 $env{'form.fullname'} =
 2711:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2712:             }
 2713:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2714:             $request->print("\n\n".
 2715:                             '<div class="LC_grade_show_user">'.
 2716:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2717:                             '</h2>'."\n");
 2718:             &Apache::lonxml::clear_problem_counter();
 2719:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2720:                             {'previousversion' => $env{'form.previousversion'} }));
 2721:             $request->print("\n</div>");
 2722:         }
 2723:     }
 2724:     return;
 2725: }
 2726: 
 2727: sub choose_task_version_form {
 2728:     my ($symb,$uname,$udom,$nomenu) = @_;
 2729:     my $isTask = ($symb =~/\.task$/);
 2730:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2731:     if ($isTask) {
 2732:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2733:                                               $udom,$uname);
 2734:         if (($record{'resource.0.version'} eq '') ||
 2735:             ($record{'resource.0.version'} < 2)) {
 2736:             return ($record{'resource.0.version'},
 2737:                     $record{'resource.0.version'},$result,$js);
 2738:         } else {
 2739:             $current = $record{'resource.0.version'};
 2740:         }
 2741:         if ($env{'form.previousversion'}) {
 2742:             $displayed = $env{'form.previousversion'};
 2743:             $rowtitle = &mt('Choose another version:')
 2744:         } else {
 2745:             $displayed = $current;
 2746:             $rowtitle = &mt('Show earlier version:');
 2747:         }
 2748:         $result = '<div class="LC_left_float">';
 2749:         my $list;
 2750:         my $numversions = 0;
 2751:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2752:             if ($i == $current) {
 2753:                 if (!$env{'form.previousversion'} || $nomenu) {
 2754:                     next;
 2755:                 } else {
 2756:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2757:                     $numversions ++;
 2758:                 }
 2759:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2760:                 unless ($i == $env{'form.previousversion'}) {
 2761:                     $numversions ++;
 2762:                 }
 2763:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2764:             }
 2765:         }
 2766:         if ($numversions) {
 2767:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2768:             $result .=
 2769:                 '<form name="getprev" method="post" action=""'.
 2770:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2771:                 &Apache::loncommon::start_data_table().
 2772:                 &Apache::loncommon::start_data_table_row().
 2773:                 '<th align="left">'.$rowtitle.'</th>'.
 2774:                 '<td><select name="version">'.
 2775:                 '<option>'.&mt('Select').'</option>'.
 2776:                 $list.
 2777:                 '</select></td>'.
 2778:                 &Apache::loncommon::end_data_table_row();
 2779:             unless ($nomenu) {
 2780:                 $result .= &Apache::loncommon::start_data_table_row().
 2781:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2782:                 '<td><span class="LC_nobreak">'.
 2783:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2784:                 &mt('Yes').'</label>'.
 2785:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2786:                 '</span></td>'.
 2787:                 &Apache::loncommon::end_data_table_row();
 2788:             }
 2789:             $result .=
 2790:                 &Apache::loncommon::start_data_table_row().
 2791:                 '<th align="left">&nbsp;</th>'.
 2792:                 '<td>'.
 2793:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2794:                 '</td>'.
 2795:                 &Apache::loncommon::end_data_table_row().
 2796:                 &Apache::loncommon::end_data_table().
 2797:                 '</form>';
 2798:             $js = &previous_display_javascript($nomenu,$current);
 2799:         } elsif ($displayed && $nomenu) {
 2800:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2801:         } else {
 2802:             $result .= &mt('No previous versions to show for this student');
 2803:         }
 2804:         $result .= '</div>';
 2805:     }
 2806:     return ($current,$displayed,$result,$js);
 2807: }
 2808: 
 2809: sub previous_display_javascript {
 2810:     my ($nomenu,$current) = @_;
 2811:     my $js = <<"JSONE";
 2812: <script type="text/javascript">
 2813: // <![CDATA[
 2814: function previousVersion(uname,udom,symb) {
 2815:     var current = '$current';
 2816:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2817:     var prevstr = new RegExp("^\\\\d+\$");
 2818:     if (!prevstr.test(version)) {
 2819:         return false;
 2820:     }
 2821:     var url = '';
 2822:     if (version == current) {
 2823:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2824:     } else {
 2825:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2826:     }
 2827: JSONE
 2828:     if ($nomenu) {
 2829:         $js .= <<"JSTWO";
 2830:     document.location.href = url;
 2831: JSTWO
 2832:     } else {
 2833:         $js .= <<"JSTHREE";
 2834:     var newwin = 0;
 2835:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2836:         if (document.getprev.prevwin[i].checked == true) {
 2837:             newwin = document.getprev.prevwin[i].value;
 2838:         }
 2839:     }
 2840:     if (newwin == 1) {
 2841:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2842:         url = url+'&inhibitmenu=yes';
 2843:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2844:             previousWin = window.open(url,'',options,1);
 2845:         } else {
 2846:             previousWin.location.href = url;
 2847:         }
 2848:         previousWin.focus();
 2849:         return false;
 2850:     } else {
 2851:         document.location.href = url;
 2852:         return false;
 2853:     }
 2854: JSTHREE
 2855:     }
 2856:     $js .= <<"ENDJS";
 2857:     return false;
 2858: }
 2859: // ]]>
 2860: </script>
 2861: ENDJS
 2862: 
 2863: }
 2864: 
 2865: #--- Called from submission routine
 2866: sub processHandGrade {
 2867:     my ($request) = shift;
 2868:     my ($symb)   = &get_symb($request);
 2869:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2870:     my $button = $env{'form.gradeOpt'};
 2871:     my $ngrade = $env{'form.NCT'};
 2872:     my $ntstu  = $env{'form.NTSTU'};
 2873:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2874:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2875: 
 2876:     if ($button eq 'Save & Next') {
 2877: 	my $ctr = 0;
 2878: 	while ($ctr < $ngrade) {
 2879: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2880: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2881:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2882: 	    if ($errorflag eq 'no_score') {
 2883: 		$ctr++;
 2884: 		next;
 2885: 	    }
 2886: 	    if ($errorflag eq 'not_allowed') {
 2887:                 $request->print(
 2888:                     '<span class="LC_error">'
 2889:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2890:                    .'</span>');
 2891: 		$ctr++;
 2892: 		next;
 2893: 	    }
 2894:             if ($numhidden) {
 2895:                 $request->print(
 2896:                     '<span class="LC_info">'
 2897:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2898:                    .'</span><br />');
 2899:             }
 2900: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2901: 	    my ($subject,$message,$msgstatus) = ('','','');
 2902: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2903:             my ($feedurl,$showsymb) =
 2904: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2905: 	    my $messagetail;
 2906: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2907: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2908: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2909: 		$subject.=' ['.$restitle.']';
 2910: 		my (@msgnum) = split(/,/,$includemsg);
 2911: 		foreach (@msgnum) {
 2912: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2913: 		}
 2914: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2915: 		if ($env{'form.withgrades'.$ctr}) {
 2916: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2917: 		    $messagetail = " for <a href=\"".
 2918: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2919: 		}
 2920: 		$msgstatus = 
 2921:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2922: 						     $message.$messagetail,
 2923:                                                      undef,$feedurl,undef,
 2924:                                                      undef,undef,$showsymb,
 2925:                                                      $restitle);
 2926: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2927: 				$msgstatus.'<br />');
 2928: 	    }
 2929: 	    if ($env{'form.collaborator'.$ctr}) {
 2930: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2931: 		foreach my $collabstr (@collabstrs) {
 2932: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2933: 		    foreach my $collaborator (@collaborators) {
 2934: 			my ($errorflag,$pts,$wgt) = 
 2935: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2936: 					   $env{'form.unamedom'.$ctr},$part);
 2937: 			if ($errorflag eq 'not_allowed') {
 2938: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2939: 			    next;
 2940: 			} elsif ($message ne '') {
 2941: 			    my ($baseurl,$showsymb) = 
 2942: 				&get_feedurl_and_symb($symb,$collaborator,
 2943: 						      $udom);
 2944: 			    if ($env{'form.withgrades'.$ctr}) {
 2945: 				$messagetail = " for <a href=\"".
 2946:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2947: 			    }
 2948: 			    $msgstatus = 
 2949: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2950: 			}
 2951: 		    }
 2952: 		}
 2953: 	    }
 2954: 	    $ctr++;
 2955: 	}
 2956:     }
 2957: 
 2958:     if ($env{'form.handgrade'} eq 'yes') {
 2959: 	# Keywords sorted in alphabatical order
 2960: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2961: 	my %keyhash = ();
 2962: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2963: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2964: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2965: 	$env{'form.keywords'} = join(' ',@keywords);
 2966: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2967: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2968: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2969: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2970: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2971: 
 2972: 	# message center - Order of message gets changed. Blank line is eliminated.
 2973: 	# New messages are saved in env for the next student.
 2974: 	# All messages are saved in nohist_handgrade.db
 2975: 	my ($ctr,$idx) = (1,1);
 2976: 	while ($ctr <= $env{'form.savemsgN'}) {
 2977: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2978: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2979: 		$idx++;
 2980: 	    }
 2981: 	    $ctr++;
 2982: 	}
 2983: 	$ctr = 0;
 2984: 	while ($ctr < $ngrade) {
 2985: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2986: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2987: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2988: 		$idx++;
 2989: 	    }
 2990: 	    $ctr++;
 2991: 	}
 2992: 	$env{'form.savemsgN'} = --$idx;
 2993: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2994: 	my $putresult = &Apache::lonnet::put
 2995: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2996:     }
 2997:     # Called by Save & Refresh from Highlight Attribute Window
 2998:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2999:     if ($env{'form.refresh'} eq 'on') {
 3000: 	my ($ctr,$total) = (0,0);
 3001: 	while ($ctr < $ngrade) {
 3002: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3003: 	    $ctr++;
 3004: 	}
 3005: 	$env{'form.NTSTU'}=$ngrade;
 3006: 	$ctr = 0;
 3007: 	while ($ctr < $total) {
 3008: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3009: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3010: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3011: 	    &submission($request,$ctr,$total-1);
 3012: 	    $ctr++;
 3013: 	}
 3014: 	return '';
 3015:     }
 3016: 
 3017: # Go directly to grade student - from submission or link from chart page
 3018:     if ($button eq 'Grade Student') {
 3019: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 3020: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 3021: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3022: 	$env{'form.fullname'} = $$fullname{$processUser};
 3023: 	&submission($request,0,0);
 3024: 	return '';
 3025:     }
 3026: 
 3027:     # Get the next/previous one or group of students
 3028:     my $firststu = $env{'form.unamedom0'};
 3029:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3030:     my $ctr = 2;
 3031:     while ($laststu eq '') {
 3032: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3033: 	$ctr++;
 3034: 	$laststu = $firststu if ($ctr > $ngrade);
 3035:     }
 3036: 
 3037:     my (@parsedlist,@nextlist);
 3038:     my ($nextflg) = 0;
 3039:     foreach my $item (sort 
 3040: 	     {
 3041: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3042: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3043: 		 }
 3044: 		 return $a cmp $b;
 3045: 	     } (keys(%$fullname))) {
 3046: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3047: 	    push(@parsedlist,$item);
 3048: 	}
 3049: 	$nextflg = 1 if ($item eq $laststu);
 3050: 	if ($button eq 'Previous') {
 3051: 	    last if ($item eq $firststu);
 3052: 	    push(@parsedlist,$item);
 3053: 	}
 3054:     }
 3055:     $ctr = 0;
 3056:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3057:     my $res_error;
 3058:     my ($partlist) = &response_type($symb,\$res_error);
 3059:     if ($res_error) {
 3060:         $request->print(&navmap_errormsg());
 3061:         return;
 3062:     }
 3063:     foreach my $student (@parsedlist) {
 3064: 	my $submitonly=$env{'form.submitonly'};
 3065: 	my ($uname,$udom) = split(/:/,$student);
 3066: 	
 3067: 	if ($submitonly eq 'queued') {
 3068: 	    my %queue_status = 
 3069: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3070: 							$udom,$uname);
 3071: 	    next if (!defined($queue_status{'gradingqueue'}));
 3072: 	}
 3073: 
 3074: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3075: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3076: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3077: 	    my $submitted = 0;
 3078: 	    my $ungraded = 0;
 3079: 	    my $incorrect = 0;
 3080: 	    foreach my $item (keys(%status)) {
 3081: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3082: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3083: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3084: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3085: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3086: 		    $submitted = 0;
 3087: 		}
 3088: 	    }
 3089: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3090: 				     $submitonly eq 'incorrect' ||
 3091: 				     $submitonly eq 'graded'));
 3092: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3093: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3094: 	}
 3095: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3096: 	last if ($ctr == $ntstu);
 3097: 	$ctr++;
 3098:     }
 3099: 
 3100:     $ctr = 0;
 3101:     my $total = scalar(@nextlist)-1;
 3102: 
 3103:     foreach (sort(@nextlist)) {
 3104: 	my ($uname,$udom,$submitter) = split(/:/);
 3105: 	$env{'form.student'}  = $uname;
 3106: 	$env{'form.userdom'}  = $udom;
 3107: 	$env{'form.fullname'} = $$fullname{$_};
 3108: 	&submission($request,$ctr,$total);
 3109: 	$ctr++;
 3110:     }
 3111:     if ($total < 0) {
 3112: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3113: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3114: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3115: 	$the_end.=&show_grading_menu_form($symb);
 3116: 	$request->print($the_end);
 3117:     }
 3118:     return '';
 3119: }
 3120: 
 3121: #---- Save the score and award for each student, if changed
 3122: sub saveHandGrade {
 3123:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3124:     my @version_parts;
 3125:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3126: 					   $env{'request.course.id'});
 3127:     if (!&canmodify($usec)) { return('not_allowed'); }
 3128:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3129:     my @parts_graded;
 3130:     my %newrecord  = ();
 3131:     my ($pts,$wgt,$totchg) = ('','',0);
 3132:     my %aggregate = ();
 3133:     my $aggregateflag = 0;
 3134:     if ($env{'form.HIDE'.$newflg}) {
 3135:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3136:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3137:         $totchg += $numchgs;
 3138:     }
 3139:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3140:     foreach my $new_part (@parts) {
 3141: 	#collaborator ($submi may vary for different parts
 3142: 	if ($submitter && $new_part ne $part) { next; }
 3143: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3144: 	if ($dropMenu eq 'excused') {
 3145: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3146: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3147: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3148: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3149: 		}
 3150: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3151: 	    }
 3152: 	} elsif ($dropMenu eq 'reset status'
 3153: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3154: 	    foreach my $key (keys(%record)) {
 3155: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3156: 	    }
 3157: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3158: 		"$env{'user.name'}:$env{'user.domain'}";
 3159:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3160: 
 3161:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3162: 					       [$new_part]);
 3163:             my $aggtries =$totaltries;
 3164:             if ($last_resets{$new_part}) {
 3165:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3166: 					   $new_part);
 3167:             }
 3168: 
 3169:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3170:             if ($aggtries > 0) {
 3171:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3172:                 $aggregateflag = 1;
 3173:             }
 3174: 	} elsif ($dropMenu eq '') {
 3175: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3176: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3177: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3178: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3179: 		next;
 3180: 	    }
 3181: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3182: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3183: 	    my $partial= $pts/$wgt;
 3184: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3185: 		#do not update score for part if not changed.
 3186:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3187: 		next;
 3188: 	    } else {
 3189: 	        push(@parts_graded,$new_part);
 3190: 	    }
 3191: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3192: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3193: 	    }
 3194: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3195: 	    if ($partial == 0) {
 3196: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3197: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3198: 		}
 3199: 	    } else {
 3200: 		if ($record{$reckey} ne 'correct_by_override') {
 3201: 		    $newrecord{$reckey} = 'correct_by_override';
 3202: 		}
 3203: 	    }	    
 3204: 	    if ($submitter && 
 3205: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3206: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3207: 	    }
 3208: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3209: 		"$env{'user.name'}:$env{'user.domain'}";
 3210: 	}
 3211: 	# unless problem has been graded, set flag to version the submitted files
 3212: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3213: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3214: 	        $dropMenu eq 'reset status')
 3215: 	   {
 3216: 	    push(@version_parts,$new_part);
 3217: 	}
 3218:     }
 3219:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3220:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3221: 
 3222:     if (%newrecord) {
 3223:         if (@version_parts) {
 3224:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3225:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3226: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3227: 	    foreach my $new_part (@version_parts) {
 3228: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3229: 				$new_part,\%newrecord);
 3230: 	    }
 3231:         }
 3232: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3233: 				$env{'request.course.id'},$domain,$stuname);
 3234: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3235: 				     $cdom,$cnum,$domain,$stuname);
 3236:     }
 3237:     if ($aggregateflag) {
 3238:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3239: 			      $cdom,$cnum);
 3240:     }
 3241:     return ('',$pts,$wgt,$totchg);
 3242: }
 3243: 
 3244: sub makehidden {
 3245:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3246:     return unless (ref($record) eq 'HASH');
 3247:     my %modified;
 3248:     my $numchanged = 0;
 3249:     if (exists($record->{$version.':keys'})) {
 3250:         my $partsregexp = $parts;
 3251:         $partsregexp =~ s/,/|/g;
 3252:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3253:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3254:                  my $item = $1;
 3255:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3256:                      $modified{$key} = $record->{$version.':'.$key};
 3257:                  }
 3258:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3259:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3260:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3261:                 $modified{$key} = $record->{$version.':'.$key};
 3262:             }
 3263:         }
 3264:         if (keys(%modified)) {
 3265:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3266:                                           $domain,$stuname,$tolog) eq 'ok') {
 3267:                 $numchanged ++;
 3268:             }
 3269:         }
 3270:     }
 3271:     return $numchanged;
 3272: }
 3273: 
 3274: sub check_and_remove_from_queue {
 3275:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3276:     my @ungraded_parts;
 3277:     foreach my $part (@{$parts}) {
 3278: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3279: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3280: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3281: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3282: 		) {
 3283: 	    push(@ungraded_parts, $part);
 3284: 	}
 3285:     }
 3286:     if ( !@ungraded_parts ) {
 3287: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3288: 					       $cnum,$domain,$stuname);
 3289:     }
 3290: }
 3291: 
 3292: sub handback_files {
 3293:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3294:     my $portfolio_root = '/userfiles/portfolio';
 3295:     my $res_error;
 3296:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3297:     if ($res_error) {
 3298:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3299:         return;
 3300:     }
 3301:     my @handedback;
 3302:     my $file_msg;
 3303:     my @part_response_id = &flatten_responseType($responseType);
 3304:     foreach my $part_response_id (@part_response_id) {
 3305:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3306: 	my $part_resp = join('_',@{ $part_response_id });
 3307:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3308:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3309:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3310: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3311:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3312:                     my ($directory,$answer_file) = 
 3313:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3314:                     my ($answer_name,$answer_ver,$answer_ext) =
 3315: 		        &file_name_version_ext($answer_file);
 3316: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3317:                     my $getpropath = 1;
 3318:                     my ($dir_list,$listerror) =
 3319:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3320:                                                  $domain,$stuname,$getpropath);
 3321: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3322:                     # fix filename
 3323:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3324:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3325:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3326:             	                                $save_file_name);
 3327:                     if ($result !~ m|^/uploaded/|) {
 3328:                         $request->print('<br /><span class="LC_error">'.
 3329:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3330:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3331:                                         '</span>');
 3332:                     } else {
 3333:                         # mark the file as read only
 3334:                         push(@handedback,$save_file_name);
 3335: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3336: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3337: 			}
 3338:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3339: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3340: 
 3341:                     }
 3342:                     $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>'));
 3343:                 }
 3344:             }
 3345:         }
 3346:     }
 3347:     if (@handedback > 0) {
 3348:         $request->print('<br />');
 3349:         my @what = ($symb,$env{'request.course.id'},'handback');
 3350:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3351:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3352:         my ($subject,$message);
 3353:         if (scalar(@handedback) == 1) {
 3354:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3355:         } else {
 3356:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3357:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3358:         }
 3359:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3360:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3361:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3362:         my ($feedurl,$showsymb) =
 3363:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3364:         my $restitle = &Apache::lonnet::gettitle($symb);
 3365:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3366:         my $msgstatus =
 3367:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3368:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3369:                  $restitle);
 3370:         if ($msgstatus) {
 3371:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3372:         }
 3373:     }
 3374:     return;
 3375: }
 3376: 
 3377: sub get_feedurl_and_symb {
 3378:     my ($symb,$uname,$udom) = @_;
 3379:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3380:     $url = &Apache::lonnet::clutter($url);
 3381:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3382: 					$symb,$udom,$uname);
 3383:     if ($encrypturl =~ /^yes$/i) {
 3384: 	&Apache::lonenc::encrypted(\$url,1);
 3385: 	&Apache::lonenc::encrypted(\$symb,1);
 3386:     }
 3387:     return ($url,$symb);
 3388: }
 3389: 
 3390: sub get_submitted_files {
 3391:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3392:     my @files;
 3393:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3394:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3395:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3396:     	    push(@files,$file_url.$file);
 3397:         }
 3398:     }
 3399:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3400:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3401:     }
 3402:     return (\@files);
 3403: }
 3404: 
 3405: # ----------- Provides number of tries since last reset.
 3406: sub get_num_tries {
 3407:     my ($record,$last_reset,$part) = @_;
 3408:     my $timestamp = '';
 3409:     my $num_tries = 0;
 3410:     if ($$record{'version'}) {
 3411:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3412:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3413:                 $timestamp = $$record{$version.':timestamp'};
 3414:                 if ($timestamp > $last_reset) {
 3415:                     $num_tries ++;
 3416:                 } else {
 3417:                     last;
 3418:                 }
 3419:             }
 3420:         }
 3421:     }
 3422:     return $num_tries;
 3423: }
 3424: 
 3425: # ----------- Determine decrements required in aggregate totals 
 3426: sub decrement_aggs {
 3427:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3428:     my %decrement = (
 3429:                         attempts => 0,
 3430:                         users => 0,
 3431:                         correct => 0
 3432:                     );
 3433:     $decrement{'attempts'} = $aggtries;
 3434:     if ($solvedstatus =~ /^correct/) {
 3435:         $decrement{'correct'} = 1;
 3436:     }
 3437:     if ($aggtries == $totaltries) {
 3438:         $decrement{'users'} = 1;
 3439:     }
 3440:     foreach my $type (keys(%decrement)) {
 3441:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3442:     }
 3443:     return;
 3444: }
 3445: 
 3446: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3447: sub get_last_resets {
 3448:     my ($symb,$courseid,$partids) =@_;
 3449:     my %last_resets;
 3450:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3451:     my $cname = $env{'course.'.$courseid.'.num'};
 3452:     my @keys;
 3453:     foreach my $part (@{$partids}) {
 3454: 	push(@keys,"$symb\0$part\0resettime");
 3455:     }
 3456:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3457: 				     $cdom,$cname);
 3458:     foreach my $part (@{$partids}) {
 3459: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3460:     }
 3461:     return %last_resets;
 3462: }
 3463: 
 3464: # ----------- Handles creating versions for portfolio files as answers
 3465: sub version_portfiles {
 3466:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3467:     my $version_parts = join('|',@$v_flag);
 3468:     my @returned_keys;
 3469:     my $parts = join('|', @$parts_graded);
 3470:     my $portfolio_root = '/userfiles/portfolio';
 3471:     foreach my $key (keys(%$record)) {
 3472:         my $new_portfiles;
 3473:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3474:             my @versioned_portfiles;
 3475:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3476:             foreach my $file (@portfiles) {
 3477:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3478:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3479: 		my ($answer_name,$answer_ver,$answer_ext) =
 3480: 		    &file_name_version_ext($answer_file);
 3481:                 my $getpropath = 1;
 3482:                 my ($dir_list,$listerror) =
 3483:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3484:                                              $stu_name,$getpropath);
 3485:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3486:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3487:                 if ($new_answer ne 'problem getting file') {
 3488:                     push(@versioned_portfiles, $directory.$new_answer);
 3489:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3490:                         [$directory.$new_answer],
 3491:                         [$symb,$env{'request.course.id'},'graded']);
 3492:                 }
 3493:             }
 3494:             $$record{$key} = join(',',@versioned_portfiles);
 3495:             push(@returned_keys,$key);
 3496:         }
 3497:     } 
 3498:     return (@returned_keys);   
 3499: }
 3500: 
 3501: sub get_next_version {
 3502:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3503:     my $version;
 3504:     if (ref($dir_list) eq 'ARRAY') {
 3505:         foreach my $row (@{$dir_list}) {
 3506:             my ($file) = split(/\&/,$row,2);
 3507:             my ($file_name,$file_version,$file_ext) =
 3508: 	        &file_name_version_ext($file);
 3509:             if (($file_name eq $answer_name) && 
 3510: 	        ($file_ext eq $answer_ext)) {
 3511:                 # gets here if filename and extension match, 
 3512:                 # regardless of version
 3513:                 if ($file_version ne '') {
 3514:                     # a versioned file is found  so save it for later
 3515:                     if ($file_version > $version) {
 3516: 		        $version = $file_version;
 3517:                     }
 3518: 	        }
 3519:             }
 3520:         }
 3521:     }
 3522:     $version ++;
 3523:     return($version);
 3524: }
 3525: 
 3526: sub version_selected_portfile {
 3527:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3528:     my ($answer_name,$answer_ver,$answer_ext) =
 3529:         &file_name_version_ext($file_name);
 3530:     my $new_answer;
 3531:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3532:     if($env{'form.copy'} eq '-1') {
 3533:         $new_answer = 'problem getting file';
 3534:     } else {
 3535:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3536:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3537:                             $stu_name,$domain,'copy',
 3538: 		        '/portfolio'.$directory.$new_answer);
 3539:     }    
 3540:     return ($new_answer);
 3541: }
 3542: 
 3543: sub file_name_version_ext {
 3544:     my ($file)=@_;
 3545:     my @file_parts = split(/\./, $file);
 3546:     my ($name,$version,$ext);
 3547:     if (@file_parts > 1) {
 3548: 	$ext=pop(@file_parts);
 3549: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3550: 	    $version=pop(@file_parts);
 3551: 	}
 3552: 	$name=join('.',@file_parts);
 3553:     } else {
 3554: 	$name=join('.',@file_parts);
 3555:     }
 3556:     return($name,$version,$ext);
 3557: }
 3558: 
 3559: #--------------------------------------------------------------------------------------
 3560: #
 3561: #-------------------------- Next few routines handles grading by section or whole class
 3562: #
 3563: #--- Javascript to handle grading by section or whole class
 3564: sub viewgrades_js {
 3565:     my ($request) = shift;
 3566: 
 3567:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3568:     &js_escape(\$alertmsg);
 3569:     $request->print(<<VIEWJAVASCRIPT);
 3570: <script type="text/javascript" language="javascript">
 3571:    function writePoint(partid,weight,point) {
 3572: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3573: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3574: 	if (point == "textval") {
 3575: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3576: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3577: 		alert("$alertmsg"+parseFloat(point));
 3578: 		var resetbox = false;
 3579: 		for (var i=0; i<radioButton.length; i++) {
 3580: 		    if (radioButton[i].checked) {
 3581: 			textbox.value = i;
 3582: 			resetbox = true;
 3583: 		    }
 3584: 		}
 3585: 		if (!resetbox) {
 3586: 		    textbox.value = "";
 3587: 		}
 3588: 		return;
 3589: 	    }
 3590: 	    if (parseFloat(point) > parseFloat(weight)) {
 3591: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3592: 				   ") greater than the weight for the part. Accept?");
 3593: 		if (resp == false) {
 3594: 		    textbox.value = "";
 3595: 		    return;
 3596: 		}
 3597: 	    }
 3598: 	    for (var i=0; i<radioButton.length; i++) {
 3599: 		radioButton[i].checked=false;
 3600: 		if (parseFloat(point) == i) {
 3601: 		    radioButton[i].checked=true;
 3602: 		}
 3603: 	    }
 3604: 
 3605: 	} else {
 3606: 	    textbox.value = parseFloat(point);
 3607: 	}
 3608: 	for (i=0;i<document.classgrade.total.value;i++) {
 3609: 	    var user = document.classgrade["ctr"+i].value;
 3610: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3611: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3612: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3613: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3614: 	    if (saveval != "correct") {
 3615: 		scorename.value = point;
 3616: 		if (selname[0].selected != true) {
 3617: 		    selname[0].selected = true;
 3618: 		}
 3619: 	    }
 3620: 	}
 3621: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3622:     }
 3623: 
 3624:     function writeRadText(partid,weight) {
 3625: 	var selval   = document.classgrade["SELVAL_"+partid];
 3626: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3627:         var override = document.classgrade["FORCE_"+partid].checked;
 3628: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3629: 	if (selval[1].selected || selval[2].selected) {
 3630: 	    for (var i=0; i<radioButton.length; i++) {
 3631: 		radioButton[i].checked=false;
 3632: 
 3633: 	    }
 3634: 	    textbox.value = "";
 3635: 
 3636: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3637: 		var user = document.classgrade["ctr"+i].value;
 3638: 		user = user.replace(new RegExp(':', 'g'),"_");
 3639: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3640: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3641: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3642: 		if ((saveval != "correct") || override) {
 3643: 		    scorename.value = "";
 3644: 		    if (selval[1].selected) {
 3645: 			selname[1].selected = true;
 3646: 		    } else {
 3647: 			selname[2].selected = true;
 3648: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3649: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3650: 		    }
 3651: 		}
 3652: 	    }
 3653: 	} else {
 3654: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3655: 		var user = document.classgrade["ctr"+i].value;
 3656: 		user = user.replace(new RegExp(':', 'g'),"_");
 3657: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3658: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3659: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3660: 		if ((saveval != "correct") || override) {
 3661: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3662: 		    selname[0].selected = true;
 3663: 		}
 3664: 	    }
 3665: 	}	    
 3666:     }
 3667: 
 3668:     function changeSelect(partid,user) {
 3669: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3670: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3671: 	var point  = textbox.value;
 3672: 	var weight = document.classgrade["weight_"+partid].value;
 3673: 
 3674: 	if (isNaN(point) || parseFloat(point) < 0) {
 3675: 	    alert("$alertmsg"+parseFloat(point));
 3676: 	    textbox.value = "";
 3677: 	    return;
 3678: 	}
 3679: 	if (parseFloat(point) > parseFloat(weight)) {
 3680: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3681: 			       ") greater than the weight of the part. Accept?");
 3682: 	    if (resp == false) {
 3683: 		textbox.value = "";
 3684: 		return;
 3685: 	    }
 3686: 	}
 3687: 	selval[0].selected = true;
 3688:     }
 3689: 
 3690:     function changeOneScore(partid,user) {
 3691: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3692: 	if (selval[1].selected || selval[2].selected) {
 3693: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3694: 	    if (selval[2].selected) {
 3695: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3696: 	    }
 3697:         }
 3698:     }
 3699: 
 3700:     function resetEntry(numpart) {
 3701: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3702: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3703: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3704: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3705: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3706: 	    for (var i=0; i<radioButton.length; i++) {
 3707: 		radioButton[i].checked=false;
 3708: 
 3709: 	    }
 3710: 	    textbox.value = "";
 3711: 	    selval[0].selected = true;
 3712: 
 3713: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3714: 		var user = document.classgrade["ctr"+i].value;
 3715: 		user = user.replace(new RegExp(':', 'g'),"_");
 3716: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3717: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3718: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3719: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3720: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3721: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3722: 		if (saveselval == "excused") {
 3723: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3724: 		} else {
 3725: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3726: 		}
 3727: 	    }
 3728: 	}
 3729:     }
 3730: 
 3731: </script>
 3732: VIEWJAVASCRIPT
 3733: }
 3734: 
 3735: #--- show scores for a section or whole class w/ option to change/update a score
 3736: sub viewgrades {
 3737:     my ($request) = shift;
 3738:     &viewgrades_js($request);
 3739: 
 3740:     my ($symb) = &get_symb($request);
 3741:     #need to make sure we have the correct data for later EXT calls, 
 3742:     #thus invalidate the cache
 3743:     &Apache::lonnet::devalidatecourseresdata(
 3744:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3745:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3746:     &Apache::lonnet::clear_EXT_cache_status();
 3747: 
 3748:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3749:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3750: 
 3751:     #view individual student submission form - called using Javascript viewOneStudent
 3752:     $result.=&jscriptNform($symb);
 3753: 
 3754:     #beginning of class grading form
 3755:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3756:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3757: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3758: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3759: 	&build_section_inputs().
 3760: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3761: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3762: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3763: 
 3764:     #retrieve selected groups
 3765:     my (@groups,$group_display);
 3766:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3767:     if (grep(/^all$/,@groups)) {
 3768:         @groups = ('all');
 3769:     } elsif (grep(/^none$/,@groups)) {
 3770:         @groups = ('none');
 3771:     } elsif (@groups > 0) {
 3772:         $group_display = join(', ',@groups);
 3773:     }
 3774: 
 3775:     my ($common_header,$specific_header,@sections,$section_display);
 3776:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3777:     if (grep(/^all$/,@sections)) {
 3778:         @sections = ('all');
 3779:         if ($group_display) {
 3780:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3781:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3782:         } elsif (grep(/^none$/,@groups)) {
 3783:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3784:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3785:         } else {
 3786:             $common_header = &mt('Assign Common Grade to Class');
 3787:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3788:         }
 3789:     } elsif (grep(/^none$/,@sections)) {
 3790:         @sections = ('none');
 3791:         if ($group_display) {
 3792:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3793:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3794:         } elsif (grep(/^none$/,@groups)) {
 3795:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3796:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3797:         } else {
 3798:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3799:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3800:         }
 3801:     } else {
 3802:         $section_display = join (", ",@sections);
 3803:         if ($group_display) {
 3804:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3805:                                  $section_display,$group_display);
 3806:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3807:                                    $section_display,$group_display);
 3808:         } elsif (grep(/^none$/,@groups)) {
 3809:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3810:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3811:         } else {
 3812:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3813:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3814:         }
 3815:     }
 3816:     my %submit_types = &substatus_options();
 3817:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3818: 
 3819:     if ($env{'form.submitonly'} eq 'all') {
 3820:         $result.= '<h3>'.$common_header.'</h3>';
 3821:     } else {
 3822:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 3823:     }
 3824:     $result .= &Apache::loncommon::start_data_table();
 3825:     #radio buttons/text box for assigning points for a section or class.
 3826:     #handles different parts of a problem
 3827:     my $res_error;
 3828:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3829:     if ($res_error) {
 3830:         return &navmap_errormsg();
 3831:     }
 3832:     my %weight = ();
 3833:     my $ctsparts = 0;
 3834:     my %seen = ();
 3835:     my @part_response_id = &flatten_responseType($responseType);
 3836:     foreach my $part_response_id (@part_response_id) {
 3837:     	my ($partid,$respid) = @{ $part_response_id };
 3838: 	my $part_resp = join('_',@{ $part_response_id });
 3839: 	next if $seen{$partid};
 3840: 	$seen{$partid}++;
 3841: 	my $handgrade=$$handgrade{$part_resp};
 3842: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3843: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3844: 
 3845: 	my $display_part=&get_display_part($partid,$symb);
 3846: 	my $radio.='<table border="0"><tr>';  
 3847: 	my $ctr = 0;
 3848: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3849: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3850: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3851: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3852: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3853: 	    $ctr++;
 3854: 	}
 3855: 	$radio.='</tr></table>';
 3856: 	my $line = '<input type="text" name="TEXTVAL_'.
 3857: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3858: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3859: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3860: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3861:                 '<select name="SELVAL_'.$partid.'" '.
 3862: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3863: 		$weight{$partid}.')"> '.
 3864: 	    '<option selected="selected"> </option>'.
 3865: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3866: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3867: 	    '</select></td>'.
 3868:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3869: 	$line.='<input type="hidden" name="partid_'.
 3870: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3871: 	$line.='<input type="hidden" name="weight_'.
 3872: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3873: 
 3874: 	$result.=
 3875: 	    &Apache::loncommon::start_data_table_row()."\n".
 3876: 	    '<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>'.
 3877: 	    &Apache::loncommon::end_data_table_row()."\n";
 3878: 	$ctsparts++;
 3879:     }
 3880:     $result.=&Apache::loncommon::end_data_table()."\n".
 3881: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3882:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3883: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3884: 
 3885:     #table listing all the students in a section/class
 3886:     #header of table
 3887:     if ($env{'form.submitonly'} eq 'all') { 
 3888:         $result.= '<h3>'.$specific_header.'</h3>';
 3889:     } else {
 3890:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3891:     }
 3892:     $result.= &Apache::loncommon::start_data_table().
 3893: 	      &Apache::loncommon::start_data_table_header_row().
 3894: 	      '<th>'.&mt('No.').'</th>'.
 3895: 	      '<th>'.&nameUserString('header')."</th>\n";
 3896:     my $partserror;
 3897:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3898:     if ($partserror) {
 3899:         return &navmap_errormsg();
 3900:     }
 3901:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3902:     my @partids = ();
 3903:     foreach my $part (@parts) {
 3904: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3905:         my $narrowtext = &mt('Tries');
 3906: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3907: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3908: 	my ($partid) = &split_part_type($part);
 3909:         push(@partids,$partid);
 3910: 	my $display_part=&get_display_part($partid,$symb);
 3911: 	if ($display =~ /^Partial Credit Factor/) {
 3912: 	    $result.='<th>'.
 3913:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3914:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3915: 	    next;
 3916: 	    
 3917: 	} else {
 3918: 	    if ($display =~ /Problem Status/) {
 3919: 		my $grade_status_mt = &mt('Grade Status');
 3920: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3921: 	    }
 3922: 	    my $part_mt = &mt('Part:');
 3923: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3924: 	}
 3925: 
 3926: 	$result.='<th>'.$display.'</th>'."\n";
 3927:     }
 3928:     $result.=&Apache::loncommon::end_data_table_header_row();
 3929: 
 3930:     my %last_resets = 
 3931: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3932: 
 3933:     #get info for each student
 3934:     #list all the students - with points and grade status
 3935:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3936:     my $ctr = 0;
 3937:     foreach (sort 
 3938: 	     {
 3939: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3940: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3941: 		 }
 3942: 		 return $a cmp $b;
 3943: 	     } (keys(%$fullname))) {
 3944: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3945: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 3946:     }
 3947:     $result.=&Apache::loncommon::end_data_table();
 3948:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3949:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3950: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3951:     if ($ctr == 0) {
 3952:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3953:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3954:                 '<span class="LC_warning">';
 3955:         if ($env{'form.submitonly'} eq 'all') {
 3956:             if (grep(/^all$/,@sections)) {
 3957:                 if (grep(/^all$/,@groups)) {
 3958:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3959:                                    $stu_status);
 3960:                 } elsif (grep(/^none$/,@groups)) {
 3961:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 3962:                                    $stu_status);
 3963:                 } else {
 3964:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3965:                                    $group_display,$stu_status);
 3966:                 }
 3967:             } elsif (grep(/^none$/,@sections)) {
 3968:                 if (grep(/^all$/,@groups)) {
 3969:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 3970:                                    $stu_status);
 3971:                 } elsif (grep(/^none$/,@groups)) {
 3972:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 3973:                                    $stu_status);
 3974:                 } else {
 3975:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3976:                                    $group_display,$stu_status);
 3977:                 }
 3978:             } else {
 3979:                 if (grep(/^all$/,@groups)) {
 3980:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3981:                                    $section_display,$stu_status);
 3982:                 } elsif (grep(/^none$/,@groups)) {
 3983:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 3984:                                    $section_display,$stu_status);
 3985:                 } else {
 3986:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 3987:                                    $section_display,$group_display,$stu_status);
 3988:                 }
 3989:             }
 3990:         } else {
 3991:             if (grep(/^all$/,@sections)) {
 3992:                 if (grep(/^all$/,@groups)) {
 3993:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3994:                                    $stu_status,$submission_status);
 3995:                 } elsif (grep(/^none$/,@groups)) {
 3996:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3997:                                    $stu_status,$submission_status);
 3998:                 } else {
 3999:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4000:                                    $group_display,$stu_status,$submission_status);
 4001:                 }
 4002:             } elsif (grep(/^none$/,@sections)) {
 4003:                 if (grep(/^all$/,@groups)) {
 4004:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4005:                                    $stu_status,$submission_status);
 4006:                 } elsif (grep(/^none$/,@groups)) {
 4007:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4008:                                    $stu_status,$submission_status);
 4009:                 } else {
 4010:                     $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.',
 4011:                                    $group_display,$stu_status,$submission_status);
 4012:                 }
 4013:             } else {
 4014:                 if (grep(/^all$/,@groups)) {
 4015:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4016:                                    $section_display,$stu_status,$submission_status);
 4017:                 } elsif (grep(/^none$/,@groups)) {
 4018:                     $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.',
 4019:                                    $section_display,$stu_status,$submission_status);
 4020:                 } else {
 4021:                     $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.',
 4022:                                    $section_display,$group_display,$stu_status,$submission_status);
 4023:                 }
 4024:             }
 4025: 	}
 4026: 	$result .= '</span><br />';
 4027:     }
 4028:     $result.=&show_grading_menu_form($symb);
 4029:     return $result;
 4030: }
 4031: 
 4032: #--- call by previous routine to display each student who satisfies submission filter.
 4033: sub viewstudentgrade {
 4034:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4035:     my ($uname,$udom) = split(/:/,$student);
 4036:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4037:     my $submitonly = $env{'form.submitonly'};
 4038:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4039:         my %partstatus = ();
 4040:         if (ref($parts) eq 'ARRAY') {
 4041:             foreach my $apart (@{$parts}) {
 4042:                 my ($part,$type) = &split_part_type($apart);
 4043:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4044:                 $status = 'nothing' if ($status eq '');
 4045:                 $partstatus{$part}      = $status;
 4046:                 my $subkey = "resource.$part.submitted_by";
 4047:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4048:             }
 4049:             my $submitted = 0;
 4050:             my $graded = 0;
 4051:             my $incorrect = 0;
 4052:             foreach my $key (keys(%partstatus)) {
 4053:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4054:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4055:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4056: 
 4057:                 my $partid = (split(/\./,$key))[1];
 4058:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4059:                     $submitted = 0;
 4060:                 }
 4061:             }
 4062:             return if (!$submitted && ($submitonly eq 'yes' ||
 4063:                                        $submitonly eq 'incorrect' ||
 4064:                                        $submitonly eq 'graded'));
 4065:             return if (!$graded && ($submitonly eq 'graded'));
 4066:             return if (!$incorrect && $submitonly eq 'incorrect');
 4067:         }
 4068:     }
 4069:     if ($submitonly eq 'queued') {
 4070:         my ($cdom,$cnum) = split(/_/,$courseid);
 4071:         my %queue_status =
 4072:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4073:                                                     $udom,$uname);
 4074:         return if (!defined($queue_status{'gradingqueue'}));
 4075:     }
 4076:     $$ctr++;
 4077:     my %aggregates = ();
 4078:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4079: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4080: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4081: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4082: 	'\');" target="_self">'.$fullname.'</a> '.
 4083: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4084:     $student=~s/:/_/; # colon doen't work in javascript for names
 4085:     foreach my $apart (@$parts) {
 4086: 	my ($part,$type) = &split_part_type($apart);
 4087: 	my $score=$record{"resource.$part.$type"};
 4088:         $result.='<td align="center">';
 4089:         my ($aggtries,$totaltries);
 4090:         unless (exists($aggregates{$part})) {
 4091: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4092: 
 4093: 	    $aggtries = $totaltries;
 4094:             if ($$last_resets{$part}) {  
 4095:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4096: 					   $part);
 4097:             }
 4098:             $result.='<input type="hidden" name="'.
 4099:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4100:             $result.='<input type="hidden" name="'.
 4101:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4102:             $aggregates{$part} = 1;
 4103:         }
 4104: 	if ($type eq 'awarded') {
 4105: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4106: 	    $result.='<input type="hidden" name="'.
 4107: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4108: 	    $result.='<input type="text" name="'.
 4109: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4110:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4111: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4112: 	} elsif ($type eq 'solved') {
 4113: 	    my ($status,$foo)=split(/_/,$score,2);
 4114: 	    $status = 'nothing' if ($status eq '');
 4115: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4116: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4117: 	    $result.='&nbsp;<select name="'.
 4118: 		'GD_'.$student.'_'.$part.'_solved" '.
 4119:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4120: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4121: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4122: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4123: 	    $result.="</select>&nbsp;</td>\n";
 4124: 	} else {
 4125: 	    $result.='<input type="hidden" name="'.
 4126: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4127: 		    "\n";
 4128: 	    $result.='<input type="text" name="'.
 4129: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4130: 		'value="'.$score.'" size="4" /></td>'."\n";
 4131: 	}
 4132:     }
 4133:     $result.=&Apache::loncommon::end_data_table_row();
 4134:     return $result;
 4135: }
 4136: 
 4137: #--- change scores for all the students in a section/class
 4138: #    record does not get update if unchanged
 4139: sub editgrades {
 4140:     my ($request) = @_;
 4141: 
 4142:     my ($symb)=&get_symb($request);
 4143:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4144:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4145:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 4146:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4147: 
 4148:     my $result= &Apache::loncommon::start_data_table().
 4149: 	&Apache::loncommon::start_data_table_header_row().
 4150: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4151: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4152:     my %scoreptr = (
 4153: 		    'correct'  =>'correct_by_override',
 4154: 		    'incorrect'=>'incorrect_by_override',
 4155: 		    'excused'  =>'excused',
 4156: 		    'ungraded' =>'ungraded_attempted',
 4157:                     'credited' =>'credit_attempted',
 4158: 		    'nothing'  => '',
 4159: 		    );
 4160:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4161: 
 4162:     my (@partid);
 4163:     my %weight = ();
 4164:     my %columns = ();
 4165:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4166: 
 4167:     my $partserror;
 4168:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4169:     if ($partserror) {
 4170:         return &navmap_errormsg();
 4171:     }
 4172:     my $header;
 4173:     while ($ctr < $env{'form.totalparts'}) {
 4174: 	my $partid = $env{'form.partid_'.$ctr};
 4175: 	push(@partid,$partid);
 4176: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4177: 	$ctr++;
 4178:     }
 4179:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4180:     foreach my $partid (@partid) {
 4181: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4182: 	    '<th align="center">'.&mt('New Score').'</th>';
 4183: 	$columns{$partid}=2;
 4184: 	foreach my $stores (@parts) {
 4185: 	    my ($part,$type) = &split_part_type($stores);
 4186: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4187: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4188: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4189: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4190:             my $narrowtext = &mt('Tries');
 4191: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4192: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4193: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4194: 	    $columns{$partid}+=2;
 4195: 	}
 4196:     }
 4197:     foreach my $partid (@partid) {
 4198: 	my $display_part=&get_display_part($partid,$symb);
 4199: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4200: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4201: 	    '</th>';
 4202: 
 4203:     }
 4204:     $result .= &Apache::loncommon::end_data_table_header_row().
 4205: 	&Apache::loncommon::start_data_table_header_row().
 4206: 	$header.
 4207: 	&Apache::loncommon::end_data_table_header_row();
 4208:     my @noupdate;
 4209:     my ($updateCtr,$noupdateCtr) = (1,1);
 4210:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4211: 	my $line;
 4212: 	my $user = $env{'form.ctr'.$i};
 4213: 	my ($uname,$udom)=split(/:/,$user);
 4214: 	my %newrecord;
 4215: 	my $updateflag = 0;
 4216: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4217: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4218: 	if (!&canmodify($usec)) {
 4219: 	    my $numcols=scalar(@partid)*4+2;
 4220: 	    push(@noupdate,
 4221: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 4222: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 4223: 	    next;
 4224: 	}
 4225:         my %aggregate = ();
 4226:         my $aggregateflag = 0;
 4227: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4228: 	foreach (@partid) {
 4229: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4230: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4231: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4232: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4233: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4234: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4235: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4236: 	    my $score;
 4237: 	    if ($partial eq '') {
 4238: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4239: 	    } elsif ($partial > 0) {
 4240: 		$score = 'correct_by_override';
 4241: 	    } elsif ($partial == 0) {
 4242: 		$score = 'incorrect_by_override';
 4243: 	    }
 4244: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4245: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4246: 
 4247: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4248: 		"$env{'user.name'}:$env{'user.domain'}";
 4249: 	    if ($dropMenu eq 'reset status' &&
 4250: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4251: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4252: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4253: 		$newrecord{'resource.'.$_.'.award'} = '';
 4254: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4255: 		$updateflag = 1;
 4256:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4257:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4258:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4259:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4260:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4261:                     $aggregateflag = 1;
 4262:                 }
 4263: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4264: 		$updateflag = 1;
 4265: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4266: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4267: 		$rec_update++;
 4268: 	    }
 4269: 
 4270: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4271: 		'<td align="center">'.$awarded.
 4272: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4273: 
 4274: 
 4275: 	    my $partid=$_;
 4276: 	    foreach my $stores (@parts) {
 4277: 		my ($part,$type) = &split_part_type($stores);
 4278: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4279: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4280: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4281: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4282: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4283: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4284: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4285: 		    $updateflag=1;
 4286: 		}
 4287: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4288: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4289: 	    }
 4290: 	}
 4291: 	$line.="\n";
 4292: 
 4293: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4294: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4295: 
 4296: 	if ($updateflag) {
 4297: 	    $count++;
 4298: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4299: 				    $udom,$uname);
 4300: 
 4301: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4302: 					      $cnum,$udom,$uname)) {
 4303: 		# need to figure out if should be in queue.
 4304: 		my %record =  
 4305: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4306: 					     $udom,$uname);
 4307: 		my $all_graded = 1;
 4308: 		my $none_graded = 1;
 4309: 		foreach my $part (@parts) {
 4310: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4311: 			$all_graded = 0;
 4312: 		    } else {
 4313: 			$none_graded = 0;
 4314: 		    }
 4315: 		}
 4316: 
 4317: 		if ($all_graded || $none_graded) {
 4318: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4319: 							   $symb,$cdom,$cnum,
 4320: 							   $udom,$uname);
 4321: 		}
 4322: 	    }
 4323: 
 4324: 	    $result.=&Apache::loncommon::start_data_table_row().
 4325: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4326: 		&Apache::loncommon::end_data_table_row();
 4327: 	    $updateCtr++;
 4328: 	} else {
 4329: 	    push(@noupdate,
 4330: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4331: 	    $noupdateCtr++;
 4332: 	}
 4333:         if ($aggregateflag) {
 4334:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4335: 				  $cdom,$cnum);
 4336:         }
 4337:     }
 4338:     if (@noupdate) {
 4339: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4340: 	my $numcols=scalar(@partid)*4+2;
 4341: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4342: 	    '<td align="center" colspan="'.$numcols.'">'.
 4343: 	    &mt('No Changes Occurred For the Students Below').
 4344: 	    '</td>'.
 4345: 	    &Apache::loncommon::end_data_table_row();
 4346: 	foreach my $line (@noupdate) {
 4347: 	    $result.=
 4348: 		&Apache::loncommon::start_data_table_row().
 4349: 		$line.
 4350: 		&Apache::loncommon::end_data_table_row();
 4351: 	}
 4352:     }
 4353:     $result .= &Apache::loncommon::end_data_table().
 4354: 	&show_grading_menu_form($symb);
 4355:     my $msg = '<p><b>'.
 4356: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4357: 	    $rec_update,$count).'</b><br />'.
 4358: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4359: 	'</b></p>';
 4360:     return $title.$msg.$result;
 4361: }
 4362: 
 4363: sub split_part_type {
 4364:     my ($partstr) = @_;
 4365:     my ($temp,@allparts)=split(/_/,$partstr);
 4366:     my $type=pop(@allparts);
 4367:     my $part=join('_',@allparts);
 4368:     return ($part,$type);
 4369: }
 4370: 
 4371: #------------- end of section for handling grading by section/class ---------
 4372: #
 4373: #----------------------------------------------------------------------------
 4374: 
 4375: 
 4376: #----------------------------------------------------------------------------
 4377: #
 4378: #-------------------------- Next few routines handles grading by csv upload
 4379: #
 4380: #--- Javascript to handle csv upload
 4381: sub csvupload_javascript_reverse_associate {
 4382:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4383:     my $error2=&mt('You need to specify at least one grading field');
 4384:   &js_escape(\$error1);
 4385:   &js_escape(\$error2);
 4386:   return(<<ENDPICK);
 4387:   function verify(vf) {
 4388:     var foundsomething=0;
 4389:     var founduname=0;
 4390:     var foundID=0;
 4391:     for (i=0;i<=vf.nfields.value;i++) {
 4392:       tw=eval('vf.f'+i+'.selectedIndex');
 4393:       if (i==0 && tw!=0) { foundID=1; }
 4394:       if (i==1 && tw!=0) { founduname=1; }
 4395:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4396:     }
 4397:     if (founduname==0 && foundID==0) {
 4398: 	alert('$error1');
 4399: 	return;
 4400:     }
 4401:     if (foundsomething==0) {
 4402: 	alert('$error2');
 4403: 	return;
 4404:     }
 4405:     vf.submit();
 4406:   }
 4407:   function flip(vf,tf) {
 4408:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4409:     var i;
 4410:     for (i=0;i<=vf.nfields.value;i++) {
 4411:       //can not pick the same destination field for both name and domain
 4412:       if (((i ==0)||(i ==1)) && 
 4413:           ((tf==0)||(tf==1)) && 
 4414:           (i!=tf) &&
 4415:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4416:         eval('vf.f'+i+'.selectedIndex=0;')
 4417:       }
 4418:     }
 4419:   }
 4420: ENDPICK
 4421: }
 4422: 
 4423: sub csvupload_javascript_forward_associate {
 4424:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4425:     my $error2=&mt('You need to specify at least one grading field');
 4426:   &js_escape(\$error1);
 4427:   &js_escape(\$error2);
 4428:   return(<<ENDPICK);
 4429:   function verify(vf) {
 4430:     var foundsomething=0;
 4431:     var founduname=0;
 4432:     var foundID=0;
 4433:     for (i=0;i<=vf.nfields.value;i++) {
 4434:       tw=eval('vf.f'+i+'.selectedIndex');
 4435:       if (tw==1) { foundID=1; }
 4436:       if (tw==2) { founduname=1; }
 4437:       if (tw>3) { foundsomething=1; }
 4438:     }
 4439:     if (founduname==0 && foundID==0) {
 4440: 	alert('$error1');
 4441: 	return;
 4442:     }
 4443:     if (foundsomething==0) {
 4444: 	alert('$error2');
 4445: 	return;
 4446:     }
 4447:     vf.submit();
 4448:   }
 4449:   function flip(vf,tf) {
 4450:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4451:     var i;
 4452:     //can not pick the same destination field twice
 4453:     for (i=0;i<=vf.nfields.value;i++) {
 4454:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4455:         eval('vf.f'+i+'.selectedIndex=0;')
 4456:       }
 4457:     }
 4458:   }
 4459: ENDPICK
 4460: }
 4461: 
 4462: sub csvuploadmap_header {
 4463:     my ($request,$symb,$datatoken,$distotal)= @_;
 4464:     my $javascript;
 4465:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4466: 	$javascript=&csvupload_javascript_reverse_associate();
 4467:     } else {
 4468: 	$javascript=&csvupload_javascript_forward_associate();
 4469:     }
 4470: 
 4471:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4472:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4473:     my $ignore=&mt('Ignore First Line');
 4474:     $symb = &Apache::lonenc::check_encrypt($symb);
 4475:     $request->print(<<ENDPICK);
 4476: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4477: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4478: $result
 4479: <hr />
 4480: <h3>Identify fields</h3>
 4481: Total number of records found in file: $distotal <hr />
 4482: Enter as many fields as you can. The system will inform you and bring you back
 4483: to this page if the data selected is insufficient to run your class.<hr />
 4484: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4485: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4486: <input type="hidden" name="associate"  value="" />
 4487: <input type="hidden" name="phase"      value="three" />
 4488: <input type="hidden" name="datatoken"  value="$datatoken" />
 4489: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4490: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4491: <input type="hidden" name="upfile_associate" 
 4492:                                        value="$env{'form.upfile_associate'}" />
 4493: <input type="hidden" name="symb"       value="$symb" />
 4494: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4495: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4496: <input type="hidden" name="command"    value="csvuploadoptions" />
 4497: <hr />
 4498: <script type="text/javascript" language="Javascript">
 4499: $javascript
 4500: </script>
 4501: ENDPICK
 4502:     return '';
 4503: 
 4504: }
 4505: 
 4506: sub csvupload_fields {
 4507:     my ($symb,$errorref) = @_;
 4508:     my (@parts) = &getpartlist($symb,$errorref);
 4509:     if (ref($errorref)) {
 4510:         if ($$errorref) {
 4511:             return;
 4512:         }
 4513:     }
 4514: 
 4515:     my @fields=(['ID','Student/Employee ID'],
 4516: 		['username','Student Username'],
 4517: 		['domain','Student Domain']);
 4518:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4519:     foreach my $part (sort(@parts)) {
 4520: 	my @datum;
 4521: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4522: 	my $name=$part;
 4523: 	if  (!$display) { $display = $name; }
 4524: 	@datum=($name,$display);
 4525: 	if ($name=~/^stores_(.*)_awarded/) {
 4526: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4527: 	}
 4528: 	push(@fields,\@datum);
 4529:     }
 4530:     return (@fields);
 4531: }
 4532: 
 4533: sub csvuploadmap_footer {
 4534:     my ($request,$i,$keyfields) =@_;
 4535:     my $buttontext = &mt('Assign Grades');
 4536:     $request->print(<<ENDPICK);
 4537: </table>
 4538: <input type="hidden" name="nfields" value="$i" />
 4539: <input type="hidden" name="keyfields" value="$keyfields" />
 4540: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4541: </form>
 4542: ENDPICK
 4543: }
 4544: 
 4545: sub checkforfile_js {
 4546:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4547:     &js_escape(\$alertmsg);
 4548:     my $result =<<CSVFORMJS;
 4549: <script type="text/javascript" language="javascript">
 4550:     function checkUpload(formname) {
 4551: 	if (formname.upfile.value == "") {
 4552: 	    alert("$alertmsg");
 4553: 	    return false;
 4554: 	}
 4555: 	formname.submit();
 4556:     }
 4557:     </script>
 4558: CSVFORMJS
 4559:     return $result;
 4560: }
 4561: 
 4562: sub upcsvScores_form {
 4563:     my ($request) = shift;
 4564:     my ($symb)=&get_symb($request);
 4565:     if (!$symb) {return '';}
 4566:     my $result=&checkforfile_js();
 4567:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4568:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4569:     $result.=$table;
 4570:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4571:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4572:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4573: 	'</b></td></tr>'."\n";
 4574:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4575:     my $upload=&mt("Upload Scores");
 4576:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4577:     my $ignore=&mt('Ignore First Line');
 4578:     $symb = &Apache::lonenc::check_encrypt($symb);
 4579:     $result.=<<ENDUPFORM;
 4580: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4581: <input type="hidden" name="symb" value="$symb" />
 4582: <input type="hidden" name="command" value="csvuploadmap" />
 4583: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4584: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4585: $upfile_select
 4586: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4587: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4588: </form>
 4589: ENDUPFORM
 4590:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4591:                            &mt("How do I create a CSV file from a spreadsheet"))
 4592:     .'</td></tr></table>'."\n";
 4593:     $result.='</td></tr></table><br /><br />'."\n";
 4594:     $result.=&show_grading_menu_form($symb);
 4595:     return $result;
 4596: }
 4597: 
 4598: 
 4599: sub csvuploadmap {
 4600:     my ($request)= @_;
 4601:     my ($symb)=&get_symb($request);
 4602:     if (!$symb) {return '';}
 4603: 
 4604:     my $datatoken;
 4605:     if (!$env{'form.datatoken'}) {
 4606: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4607:     } else {
 4608:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4609:         if ($datatoken ne '') {
 4610:             &Apache::loncommon::load_tmp_file($request,$datatoken);
 4611:         }
 4612:     }
 4613:     my @records=&Apache::loncommon::upfile_record_sep();
 4614:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4615:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4616:     my ($i,$keyfields);
 4617:     if (@records) {
 4618:         my $fieldserror;
 4619: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4620:         if ($fieldserror) {
 4621:             $request->print(&navmap_errormsg());
 4622:             return;
 4623:         }
 4624: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4625: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4626: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4627: 							  \@fields);
 4628: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4629: 	    chop($keyfields);
 4630: 	} else {
 4631: 	    unshift(@fields,['none','']);
 4632: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4633: 							    \@fields);
 4634:             foreach my $rec (@records) {
 4635:                 my %temp = &Apache::loncommon::record_sep($rec);
 4636:                 if (%temp) {
 4637:                     $keyfields=join(',',sort(keys(%temp)));
 4638:                     last;
 4639:                 }
 4640:             }
 4641: 	}
 4642:     }
 4643:     &csvuploadmap_footer($request,$i,$keyfields);
 4644:     $request->print(&show_grading_menu_form($symb));
 4645: 
 4646:     return '';
 4647: }
 4648: 
 4649: sub csvuploadoptions {
 4650:     my ($request)= @_;
 4651:     my ($symb)=&get_symb($request);
 4652:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4653:     my $ignore=&mt('Ignore First Line');
 4654:     $request->print(<<ENDPICK);
 4655: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4656: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4657: <input type="hidden" name="command"    value="csvuploadassign" />
 4658: <!--
 4659: <p>
 4660: <label>
 4661:    <input type="checkbox" name="show_full_results" />
 4662:    Show a table of all changes
 4663: </label>
 4664: </p>
 4665: -->
 4666: <p>
 4667: <label>
 4668:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4669:    Overwrite any existing score
 4670: </label>
 4671: </p>
 4672: ENDPICK
 4673:     my %fields=&get_fields();
 4674:     if (!defined($fields{'domain'})) {
 4675: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4676: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4677:     }
 4678:     foreach my $key (sort(keys(%env))) {
 4679: 	if ($key !~ /^form\.(.*)$/) { next; }
 4680: 	my $cleankey=$1;
 4681: 	if ($cleankey eq 'command') { next; }
 4682: 	$request->print('<input type="hidden" name="'.$cleankey.
 4683: 			'"  value="'.$env{$key}.'" />'."\n");
 4684:     }
 4685:     # FIXME do a check for any duplicated user ids...
 4686:     # FIXME do a check for any invalid user ids?...
 4687:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4688: <hr /></form>'."\n");
 4689:     $request->print(&show_grading_menu_form($symb));
 4690:     return '';
 4691: }
 4692: 
 4693: sub get_fields {
 4694:     my %fields;
 4695:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4696:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4697: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4698: 	    if ($env{'form.f'.$i} ne 'none') {
 4699: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4700: 	    }
 4701: 	} else {
 4702: 	    if ($env{'form.f'.$i} ne 'none') {
 4703: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4704: 	    }
 4705: 	}
 4706:     }
 4707:     return %fields;
 4708: }
 4709: 
 4710: sub csvuploadassign {
 4711:     my ($request)= @_;
 4712:     my ($symb)=&get_symb($request);
 4713:     if (!$symb) {return '';}
 4714:     my $error_msg = '';
 4715:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4716:     if ($datatoken ne '') {
 4717:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4718:     }
 4719:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4720:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4721:     my %fields=&get_fields();
 4722:     $request->print('<h3>Assigning Grades</h3>');
 4723:     my $courseid=$env{'request.course.id'};
 4724:     my ($classlist) = &getclasslist('all',0);
 4725:     my @notallowed;
 4726:     my @skipped;
 4727:     my @warnings;
 4728:     my $countdone=0;
 4729:     foreach my $grade (@gradedata) {
 4730: 	my %entries=&Apache::loncommon::record_sep($grade);
 4731: 	my $domain;
 4732: 	if ($entries{$fields{'domain'}}) {
 4733: 	    $domain=$entries{$fields{'domain'}};
 4734: 	} else {
 4735: 	    $domain=$env{'form.default_domain'};
 4736: 	}
 4737: 	$domain=~s/\s//g;
 4738: 	my $username=$entries{$fields{'username'}};
 4739: 	$username=~s/\s//g;
 4740: 	if (!$username) {
 4741: 	    my $id=$entries{$fields{'ID'}};
 4742: 	    $id=~s/\s//g;
 4743: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4744: 	    $username=$ids{$id};
 4745: 	}
 4746: 	if (!exists($$classlist{"$username:$domain"})) {
 4747: 	    my $id=$entries{$fields{'ID'}};
 4748: 	    $id=~s/\s//g;
 4749: 	    if ($id) {
 4750: 		push(@skipped,"$id:$domain");
 4751: 	    } else {
 4752: 		push(@skipped,"$username:$domain");
 4753: 	    }
 4754: 	    next;
 4755: 	}
 4756: 	my $usec=$classlist->{"$username:$domain"}[5];
 4757: 	if (!&canmodify($usec)) {
 4758: 	    push(@notallowed,"$username:$domain");
 4759: 	    next;
 4760: 	}
 4761: 	my %points;
 4762: 	my %grades;
 4763: 	foreach my $dest (keys(%fields)) {
 4764: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4765: 		$dest eq 'domain') { next; }
 4766: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4767: 	    if ($dest=~/stores_(.*)_points/) {
 4768: 		my $part=$1;
 4769: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4770: 					      $symb,$domain,$username);
 4771:                 if ($wgt) {
 4772:                     $entries{$fields{$dest}}=~s/\s//g;
 4773:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4774:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4775:                                           : 'correct_by_override';
 4776:                     if ($pcr>1) {
 4777:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4778:                     }
 4779:                     $grades{"resource.$part.awarded"}=$pcr;
 4780:                     $grades{"resource.$part.solved"}=$award;
 4781:                     $points{$part}=1;
 4782:                 } else {
 4783:                     $error_msg = "<br />" .
 4784:                         &mt("Some point values were assigned"
 4785:                             ." for problems with a weight "
 4786:                             ."of zero. These values were "
 4787:                             ."ignored.");
 4788:                 }
 4789: 	    } else {
 4790: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4791: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4792: 		my $store_key=$dest;
 4793: 		$store_key=~s/^stores/resource/;
 4794: 		$store_key=~s/_/\./g;
 4795: 		$grades{$store_key}=$entries{$fields{$dest}};
 4796: 	    }
 4797: 	}
 4798: 	if (! %grades) { 
 4799:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4800:         } else {
 4801: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4802: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4803: 					   $env{'request.course.id'},
 4804: 					   $domain,$username);
 4805: 	   if ($result eq 'ok') {
 4806: 	      $request->print('.');
 4807: # Remove from grading queue
 4808:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4809:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4810:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4811:                                              $domain,$username);
 4812: 	   } else {
 4813: 	      $request->print("<p><span class=\"LC_error\">".
 4814:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4815:                                   "$username:$domain",$result)."</span></p>");
 4816: 	   }
 4817: 	   $request->rflush();
 4818: 	   $countdone++;
 4819:         }
 4820:     }
 4821:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4822:     if (@warnings) {
 4823:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4824:         $request->print(join(', ',@warnings));
 4825:     }
 4826:     if (@skipped) {
 4827: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4828:         $request->print(join(', ',@skipped));
 4829:     }
 4830:     if (@notallowed) {
 4831: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4832: 	$request->print(join(', ',@notallowed));
 4833:     }
 4834:     $request->print("<br />\n");
 4835:     $request->print(&show_grading_menu_form($symb));
 4836:     return $error_msg;
 4837: }
 4838: #------------- end of section for handling csv file upload ---------
 4839: #
 4840: #-------------------------------------------------------------------
 4841: #
 4842: #-------------- Next few routines handle grading by page/sequence
 4843: #
 4844: #--- Select a page/sequence and a student to grade
 4845: sub pickStudentPage {
 4846:     my ($request) = shift;
 4847: 
 4848:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4849:     &js_escape(\$alertmsg);
 4850:     $request->print(<<LISTJAVASCRIPT);
 4851: <script type="text/javascript" language="javascript">
 4852: 
 4853: function checkPickOne(formname) {
 4854:     if (radioSelection(formname.student) == null) {
 4855: 	alert("$alertmsg");
 4856: 	return;
 4857:     }
 4858:     ptr = pullDownSelection(formname.selectpage);
 4859:     formname.page.value = formname["page"+ptr].value;
 4860:     formname.title.value = formname["title"+ptr].value;
 4861:     formname.submit();
 4862: }
 4863: 
 4864: </script>
 4865: LISTJAVASCRIPT
 4866:     &commonJSfunctions($request);
 4867:     my ($symb) = &get_symb($request);
 4868:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4869:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4870:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4871: 
 4872:     my $result='<h3><span class="LC_info">&nbsp;'.
 4873: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4874: 
 4875:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4876:     my $map_error;
 4877:     my ($titles,$symbx) = &getSymbMap($map_error);
 4878:     if ($map_error) {
 4879:         $request->print(&navmap_errormsg());
 4880:         return; 
 4881:     }
 4882:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4883: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4884: #    my $type=($curpage =~ /\.(page|sequence)/);
 4885:     my $select = '<select name="selectpage">'."\n";
 4886:     my $ctr=0;
 4887:     foreach (@$titles) {
 4888: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4889: 	$select.='<option value="'.$ctr.'" '.
 4890: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4891: 	    '>'.$showtitle.'</option>'."\n";
 4892: 	$ctr++;
 4893:     }
 4894:     $select.= '</select>';
 4895:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4896: 
 4897:     $ctr=0;
 4898:     foreach (@$titles) {
 4899: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4900: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4901: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4902: 	$ctr++;
 4903:     }
 4904:     $result.='<input type="hidden" name="page" />'."\n".
 4905: 	'<input type="hidden" name="title" />'."\n";
 4906: 
 4907:     my $options =
 4908: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4909: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4910:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4911: 
 4912:     $options =
 4913: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4914: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4915: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4916:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4917:     
 4918:     $result.=&build_section_inputs();
 4919:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4920:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4921: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4922: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4923: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4924: 
 4925:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4926: 
 4927:     $result.='&nbsp;<input type="button" '.
 4928:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4929: 
 4930:     $request->print($result);
 4931: 
 4932:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4933: 	&Apache::loncommon::start_data_table().
 4934: 	&Apache::loncommon::start_data_table_header_row().
 4935: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4936: 	'<th>'.&nameUserString('header').'</th>'.
 4937: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4938: 	'<th>'.&nameUserString('header').'</th>'.
 4939: 	&Apache::loncommon::end_data_table_header_row();
 4940:  
 4941:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4942:     my $ptr = 1;
 4943:     foreach my $student (sort 
 4944: 			 {
 4945: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4946: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4947: 			     }
 4948: 			     return $a cmp $b;
 4949: 			 } (keys(%$fullname))) {
 4950: 	my ($uname,$udom) = split(/:/,$student);
 4951: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4952:                                   : '</td>');
 4953: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4954: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4955: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4956: 	$studentTable.=
 4957: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4958:                          : '');
 4959: 	$ptr++;
 4960:     }
 4961:     if ($ptr%2 == 0) {
 4962: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4963: 	    &Apache::loncommon::end_data_table_row();
 4964:     }
 4965:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4966:     $studentTable.='<input type="button" '.
 4967:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4968: 
 4969:     $studentTable.=&show_grading_menu_form($symb);
 4970:     $request->print($studentTable);
 4971: 
 4972:     return '';
 4973: }
 4974: 
 4975: sub getSymbMap {
 4976:     my ($map_error) = @_;
 4977:     my $navmap = Apache::lonnavmaps::navmap->new();
 4978:     unless (ref($navmap)) {
 4979:         if (ref($map_error)) {
 4980:             $$map_error = 'navmap';
 4981:         }
 4982:         return;
 4983:     }
 4984:     my %symbx = ();
 4985:     my @titles = ();
 4986:     my $minder = 0;
 4987: 
 4988:     # Gather every sequence that has problems.
 4989:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4990: 					       1,0,1);
 4991:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4992: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4993: 	    my $title = $minder.'.'.
 4994: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4995: 	    push(@titles, $title); # minder in case two titles are identical
 4996: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4997: 	    $minder++;
 4998: 	}
 4999:     }
 5000:     return \@titles,\%symbx;
 5001: }
 5002: 
 5003: #
 5004: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5005: sub displayPage {
 5006:     my ($request) = shift;
 5007: 
 5008:     my ($symb) = &get_symb($request);
 5009:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5010:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5011:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5012:     my $pageTitle = $env{'form.page'};
 5013:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5014:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5015:     my $usec=$classlist->{$env{'form.student'}}[5];
 5016: 
 5017:     #need to make sure we have the correct data for later EXT calls, 
 5018:     #thus invalidate the cache
 5019:     &Apache::lonnet::devalidatecourseresdata(
 5020:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5021:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5022:     &Apache::lonnet::clear_EXT_cache_status();
 5023: 
 5024:     if (!&canview($usec)) {
 5025: 	$request->print('<span class="LC_warning">'.
 5026:                         &mt('Unable to view requested student. ([_1])',
 5027:                             $env{'form.student'}).
 5028:                         '</span>');
 5029:         $request->print(&show_grading_menu_form($symb));
 5030:         return;
 5031:     }
 5032:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5033:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5034: 	'</h3>'."\n";
 5035:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5036:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5037: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5038:     } else {
 5039: 	delete($env{'form.CODE'});
 5040:     }
 5041:     &sub_page_js($request);
 5042:     $request->print($result);
 5043: 
 5044:     my $navmap = Apache::lonnavmaps::navmap->new();
 5045:     unless (ref($navmap)) {
 5046:         $request->print(&navmap_errormsg());
 5047:         $request->print(&show_grading_menu_form($symb));
 5048:         return;
 5049:     }
 5050:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5051:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5052:     if (!$map) {
 5053: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5054: 	$request->print(&show_grading_menu_form($symb));
 5055: 	return; 
 5056:     }
 5057:     my $iterator = $navmap->getIterator($map->map_start(),
 5058: 					$map->map_finish());
 5059: 
 5060:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5061: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5062: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5063: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5064: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5065: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5066: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5067: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 5068: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 5069: 
 5070:     if (defined($env{'form.CODE'})) {
 5071: 	$studentTable.=
 5072: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5073:     }
 5074:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5075: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5076: 
 5077:     $studentTable.='&nbsp;<span class="LC_info">'.
 5078:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5079:         '</span>'."\n".
 5080: 	&Apache::loncommon::start_data_table().
 5081: 	&Apache::loncommon::start_data_table_header_row().
 5082: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 5083: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5084: 	&Apache::loncommon::end_data_table_header_row();
 5085: 
 5086:     &Apache::lonxml::clear_problem_counter();
 5087:     my ($depth,$question,$prob) = (1,1,1);
 5088:     $iterator->next(); # skip the first BEGIN_MAP
 5089:     my $curRes = $iterator->next(); # for "current resource"
 5090:     while ($depth > 0) {
 5091:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5092:         if($curRes == $iterator->END_MAP) { $depth--; }
 5093: 
 5094:         if (ref($curRes) && $curRes->is_problem()) {
 5095: 	    my $parts = $curRes->parts();
 5096:             my $title = $curRes->compTitle();
 5097: 	    my $symbx = $curRes->symb();
 5098: 	    $studentTable.=
 5099: 		&Apache::loncommon::start_data_table_row().
 5100: 		'<td align="center" valign="top" >'.$prob.
 5101: 		(scalar(@{$parts}) == 1 ? '' 
 5102: 		                        : '<br />('.&mt('[_1]parts',
 5103: 							scalar(@{$parts}).'&nbsp;').')'
 5104: 		 ).
 5105: 		 '</td>';
 5106: 	    $studentTable.='<td valign="top">';
 5107: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5108: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5109: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5110: 					     undef,'both',\%form);
 5111: 	    } else {
 5112: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5113: 		$companswer =~ s|<form(.*?)>||g;
 5114: 		$companswer =~ s|</form>||g;
 5115: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5116: #		    $companswer =~ s/$1/ /ms;
 5117: #		    $request->print('match='.$1."<br />\n");
 5118: #		}
 5119: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5120: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5121: 	    }
 5122: 
 5123: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5124: 
 5125: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5126: 		if ($record{'version'} eq '') {
 5127: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5128: 		} else {
 5129: 		    my %responseType = ();
 5130: 		    foreach my $partid (@{$parts}) {
 5131: 			my @responseIds =$curRes->responseIds($partid);
 5132: 			my @responseType =$curRes->responseType($partid);
 5133: 			my %responseIds;
 5134: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5135: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5136: 			}
 5137: 			$responseType{$partid} = \%responseIds;
 5138: 		    }
 5139: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5140: 
 5141: 		}
 5142: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5143: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5144:                 my $identifier = (&canmodify($usec)? $prob : '');
 5145: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5146: 									$env{'request.course.id'},
 5147: 									'','.submission',undef,
 5148:                                                                         $usec,$identifier);
 5149:  
 5150: 	    }
 5151: 	    if (&canmodify($usec)) {
 5152:             $studentTable.=&gradeBox_start();
 5153: 		foreach my $partid (@{$parts}) {
 5154: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5155: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5156: 		    $question++;
 5157: 		}
 5158:             $studentTable.=&gradeBox_end();
 5159: 		$prob++;
 5160: 	    }
 5161: 	    $studentTable.='</td></tr>';
 5162: 
 5163: 	}
 5164:         $curRes = $iterator->next();
 5165:     }
 5166: 
 5167:     $studentTable.=
 5168:         '</table>'."\n".
 5169:         '<input type="button" value="'.&mt('Save').'" '.
 5170:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5171:         '</form>'."\n";
 5172:     $studentTable.=&show_grading_menu_form($symb);
 5173:     $request->print($studentTable);
 5174: 
 5175:     return '';
 5176: }
 5177: 
 5178: sub displaySubByDates {
 5179:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5180:     my $isCODE=0;
 5181:     my $isTask = ($symb =~/\.task$/);
 5182:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5183:     my $studentTable=&Apache::loncommon::start_data_table().
 5184: 	&Apache::loncommon::start_data_table_header_row().
 5185: 	'<th>'.&mt('Date/Time').'</th>'.
 5186: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5187:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5188: 	'<th>'.&mt('Submission').'</th>'.
 5189: 	'<th>'.&mt('Status').'</th>'.
 5190: 	&Apache::loncommon::end_data_table_header_row();
 5191:     my ($version);
 5192:     my %mark;
 5193:     my %orders;
 5194:     $mark{'correct_by_student'} = $checkIcon;
 5195:     if (!exists($$record{'1:timestamp'})) {
 5196: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5197:     }
 5198: 
 5199:     my $interaction;
 5200:     my $no_increment = 1;
 5201:     my (%lastrndseed,%lasttype);
 5202:     for ($version=1;$version<=$$record{'version'};$version++) {
 5203: 	my $timestamp = 
 5204: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5205: 	if (exists($$record{$version.':resource.0.version'})) {
 5206: 	    $interaction = $$record{$version.':resource.0.version'};
 5207: 	}
 5208:         if ($isTask && $env{'form.previousversion'}) {
 5209:             next unless ($interaction == $env{'form.previousversion'});
 5210:         }
 5211: 	my $where = ($isTask ? "$version:resource.$interaction"
 5212: 		             : "$version:resource");
 5213: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5214: 	    '<td>'.$timestamp.'</td>';
 5215: 	if ($isCODE) {
 5216: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5217: 	}
 5218:         if ($isTask) {
 5219:             $studentTable.='<td>'.$interaction.'</td>';
 5220:         }
 5221: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5222: 	my @displaySub = ();
 5223: 	foreach my $partid (@{$parts}) {
 5224:             my ($hidden,$type);
 5225:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5226:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5227:                 $hidden = 1;
 5228:             }
 5229: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5230: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5231: 	    
 5232: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5233: 	    my $display_part=&get_display_part($partid,$symb);
 5234: 	    foreach my $matchKey (@matchKey) {
 5235: 		if (exists($$record{$version.':'.$matchKey}) &&
 5236: 		    $$record{$version.':'.$matchKey} ne '') {
 5237:                     
 5238: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5239: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5240:                     $displaySub[0].='<span class="LC_nobreak">';
 5241:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5242:                                    .' <span class="LC_internal_info">'
 5243:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5244:                                    .'</span>'
 5245:                                    .' <b>';
 5246:                     if ($hidden) {
 5247:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5248:                     } else {
 5249:                         my ($trial,$rndseed,$newvariation);
 5250:                         if ($type eq 'randomizetry') {
 5251:                             $trial = $$record{"$where.$partid.tries"};
 5252:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5253:                         }
 5254: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5255: 			    $displaySub[0].=&mt('Trial not counted');
 5256: 		        } else {
 5257: 			    $displaySub[0].=&mt('Trial: [_1]',
 5258: 					    $$record{"$where.$partid.tries"});
 5259:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5260:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5261:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5262:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5263:                                 }
 5264:                             }
 5265:                             $lastrndseed{$partid} = $rndseed;
 5266:                             $lasttype{$partid} = $type;
 5267: 		        }
 5268: 		        my $responseType=($isTask ? 'Task'
 5269:                                               : $responseType->{$partid}->{$responseId});
 5270: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5271: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5272: 			    $orders{$partid}->{$responseId}=
 5273: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5274:                                            $no_increment,$type,$trial,$rndseed);
 5275: 		        }
 5276: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5277: 		        $displaySub[0].='&nbsp; '.
 5278: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5279:                     }
 5280: 		}
 5281: 	    }
 5282: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5283: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5284: 				    $$record{"$where.$partid.checkedin"},
 5285: 				    $$record{"$where.$partid.checkedin.slot"}).
 5286: 					'<br />';
 5287: 	    }
 5288: 	    if (exists $$record{"$where.$partid.award"}) {
 5289: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5290: 		    lc($$record{"$where.$partid.award"}).' '.
 5291: 		    $mark{$$record{"$where.$partid.solved"}}.
 5292: 		    '<br />';
 5293: 	    }
 5294: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5295: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5296: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5297: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5298: 		$displaySub[2].=
 5299: 		    $$record{"$version:resource.$partid.regrader"}.
 5300: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5301: 	    }
 5302: 	}
 5303: 	# needed because old essay regrader has not parts info
 5304: 	if (exists $$record{"$version:resource.regrader"}) {
 5305: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5306: 	}
 5307: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5308: 	if ($displaySub[2]) {
 5309: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5310: 	}
 5311: 	$studentTable.='&nbsp;</td>'.
 5312: 	    &Apache::loncommon::end_data_table_row();
 5313:     }
 5314:     $studentTable.=&Apache::loncommon::end_data_table();
 5315:     return $studentTable;
 5316: }
 5317: 
 5318: sub updateGradeByPage {
 5319:     my ($request) = shift;
 5320: 
 5321:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5322:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5323:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5324:     my $pageTitle = $env{'form.page'};
 5325:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5326:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5327:     my $usec=$classlist->{$env{'form.student'}}[5];
 5328:     if (!&canmodify($usec)) {
 5329: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5330: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5331: 	return;
 5332:     }
 5333:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5334:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5335: 	'</h3>'."\n";
 5336: 
 5337:     $request->print($result);
 5338: 
 5339: 
 5340:     my $navmap = Apache::lonnavmaps::navmap->new();
 5341:     unless (ref($navmap)) {
 5342:         $request->print(&navmap_errormsg());
 5343:         return;
 5344:     }
 5345:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5346:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5347:     if (!$map) {
 5348: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5349: 	my ($symb)=&get_symb($request);
 5350: 	$request->print(&show_grading_menu_form($symb));
 5351: 	return; 
 5352:     }
 5353:     my $iterator = $navmap->getIterator($map->map_start(),
 5354: 					$map->map_finish());
 5355: 
 5356:     my $studentTable=
 5357: 	&Apache::loncommon::start_data_table().
 5358: 	&Apache::loncommon::start_data_table_header_row().
 5359: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5360: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5361: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5362: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5363: 	&Apache::loncommon::end_data_table_header_row();
 5364: 
 5365:     $iterator->next(); # skip the first BEGIN_MAP
 5366:     my $curRes = $iterator->next(); # for "current resource"
 5367:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5368:     while ($depth > 0) {
 5369:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5370:         if($curRes == $iterator->END_MAP) { $depth--; }
 5371: 
 5372:         if (ref($curRes) && $curRes->is_problem()) {
 5373: 	    my $parts = $curRes->parts();
 5374:             my $title = $curRes->compTitle();
 5375: 	    my $symbx = $curRes->symb();
 5376: 	    $studentTable.=
 5377: 		&Apache::loncommon::start_data_table_row().
 5378: 		'<td align="center" valign="top" >'.$prob.
 5379: 		(scalar(@{$parts}) == 1 ? '' 
 5380:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5381: 		.')').'</td>';
 5382: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5383: 
 5384: 	    my %newrecord=();
 5385: 	    my @displayPts=();
 5386:             my %aggregate = ();
 5387:             my $aggregateflag = 0;
 5388:             if ($env{'form.HIDE'.$prob}) {
 5389:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5390:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5391:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5392:                 $hideflag += $numchgs;
 5393:             }
 5394: 	    foreach my $partid (@{$parts}) {
 5395: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5396: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5397: 
 5398: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5399: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5400: 		my $partial = $newpts/$wgt;
 5401: 		my $score;
 5402: 		if ($partial > 0) {
 5403: 		    $score = 'correct_by_override';
 5404: 		} elsif ($newpts ne '') { #empty is taken as 0
 5405: 		    $score = 'incorrect_by_override';
 5406: 		}
 5407: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5408: 		if ($dropMenu eq 'excused') {
 5409: 		    $partial = '';
 5410: 		    $score = 'excused';
 5411: 		} elsif ($dropMenu eq 'reset status'
 5412: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5413: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5414: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5415: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5416: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5417: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5418: 		    $changeflag++;
 5419: 		    $newpts = '';
 5420:                     
 5421:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5422:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5423:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5424:                     if ($aggtries > 0) {
 5425:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5426:                         $aggregateflag = 1;
 5427:                     }
 5428: 		}
 5429: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5430: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5431: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5432: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5433: 		    '&nbsp;<br />';
 5434: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5435: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5436: 		    '&nbsp;<br />';
 5437: 		$question++;
 5438: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5439: 
 5440: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5441: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5442: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5443: 		    if (scalar(keys(%newrecord)) > 0);
 5444: 
 5445: 		$changeflag++;
 5446: 	    }
 5447: 	    if (scalar(keys(%newrecord)) > 0) {
 5448: 		my %record = 
 5449: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5450: 					     $udom,$uname);
 5451: 
 5452: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5453: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5454: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5455: 		    $newrecord{'resource.CODE'} = '';
 5456: 		}
 5457: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5458: 					$udom,$uname);
 5459: 		%record = &Apache::lonnet::restore($symbx,
 5460: 						   $env{'request.course.id'},
 5461: 						   $udom,$uname);
 5462: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5463: 					     $cdom,$cnum,$udom,$uname);
 5464: 	    }
 5465: 	    
 5466:             if ($aggregateflag) {
 5467:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5468:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5469:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5470:             }
 5471: 
 5472: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5473: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5474: 		&Apache::loncommon::end_data_table_row();
 5475: 
 5476: 	    $prob++;
 5477: 	}
 5478:         $curRes = $iterator->next();
 5479:     }
 5480: 
 5481:     $studentTable.=&Apache::loncommon::end_data_table();
 5482:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5483:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5484: 		  &mt('The scores were changed for [quant,_1,problem].',
 5485: 		  $changeflag).'<br />');
 5486:     my $hidemsg=($hideflag == 0 ? '' :
 5487:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5488:                      $hideflag).'<br />');
 5489:     $request->print($hidemsg.$grademsg.$studentTable);
 5490: 
 5491:     return '';
 5492: }
 5493: 
 5494: #-------- end of section for handling grading by page/sequence ---------
 5495: #
 5496: #-------------------------------------------------------------------
 5497: 
 5498: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5499: #
 5500: #------ start of section for handling grading by page/sequence ---------
 5501: 
 5502: =pod
 5503: 
 5504: =head1 Bubble sheet grading routines
 5505: 
 5506:   For this documentation:
 5507: 
 5508:    'scanline' refers to the full line of characters
 5509:    from the file that we are parsing that represents one entire sheet
 5510: 
 5511:    'bubble line' refers to the data
 5512:    representing the line of bubbles that are on the physical bubblesheet
 5513: 
 5514: 
 5515: The overall process is that a scanned in bubblesheet data is uploaded
 5516: into a course. When a user wants to grade, they select a
 5517: sequence/folder of resources, a file of bubblesheet info, and pick
 5518: one of the predefined configurations for what each scanline looks
 5519: like.
 5520: 
 5521: Next each scanline is checked for any errors of either 'missing
 5522: bubbles' (it's an error because it may have been mis-scanned
 5523: because too light bubbling), 'double bubble' (each bubble line should
 5524: have no more than one letter picked), invalid or duplicated CODE,
 5525: invalid student/employee ID
 5526: 
 5527: If the CODE option is used that determines the randomization of the
 5528: homework problems, either way the student/employee ID is looked up into a
 5529: username:domain.
 5530: 
 5531: During the validation phase the instructor can choose to skip scanlines. 
 5532: 
 5533: After the validation phase, there are now 3 bubblesheet files
 5534: 
 5535:   scantron_original_filename (unmodified original file)
 5536:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5537:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5538: 
 5539: Also there is a separate hash nohist_scantrondata that contains extra
 5540: correction information that isn't representable in the bubblesheet
 5541: file (see &scantron_getfile() for more information)
 5542: 
 5543: After all scanlines are either valid, marked as valid or skipped, then
 5544: foreach line foreach problem in the picked sequence, an ssi request is
 5545: made that simulates a user submitting their selected letter(s) against
 5546: the homework problem.
 5547: 
 5548: =over 4
 5549: 
 5550: 
 5551: 
 5552: =item defaultFormData
 5553: 
 5554:   Returns html hidden inputs used to hold context/default values.
 5555: 
 5556:  Arguments:
 5557:   $symb - $symb of the current resource 
 5558: 
 5559: =cut
 5560: 
 5561: sub defaultFormData {
 5562:     my ($symb)=@_;
 5563:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5564:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5565:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5566: }
 5567: 
 5568: 
 5569: =pod 
 5570: 
 5571: =item getSequenceDropDown
 5572: 
 5573:    Return html dropdown of possible sequences to grade
 5574:  
 5575:  Arguments:
 5576:    $symb - $symb of the current resource
 5577:    $map_error - ref to scalar which will container error if
 5578:                 $navmap object is unavailable in &getSymbMap().
 5579: 
 5580: =cut
 5581: 
 5582: sub getSequenceDropDown {
 5583:     my ($symb,$map_error)=@_;
 5584:     my $result='<select name="selectpage">'."\n";
 5585:     my ($titles,$symbx) = &getSymbMap($map_error);
 5586:     if (ref($map_error)) {
 5587:         return if ($$map_error);
 5588:     }
 5589:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5590:     my $ctr=0;
 5591:     foreach (@$titles) {
 5592: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5593: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5594: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5595: 	    '>'.$showtitle.'</option>'."\n";
 5596: 	$ctr++;
 5597:     }
 5598:     $result.= '</select>';
 5599:     return $result;
 5600: }
 5601: 
 5602: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5603:                                    # key is zero-based index - 0, 1, 2 ...
 5604: 
 5605: my %first_bubble_line;             # First bubble line no. for each bubble.
 5606: 
 5607: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5608:                                    # matchresponse or rankresponse, where 
 5609:                                    # an individual response can have multiple 
 5610:                                    # lines
 5611: 
 5612: my %responsetype_per_response;     # responsetype for each response
 5613: 
 5614: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5615:                                    # numbered response. Needed when randomorder
 5616:                                    # or randompick are in use. Key is ID, value 
 5617:                                    # is response number.
 5618: 
 5619: # Save and restore the bubble lines array to the form env.
 5620: 
 5621: 
 5622: sub save_bubble_lines {
 5623:     foreach my $line (keys(%bubble_lines_per_response)) {
 5624: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5625: 	$env{"form.scantron.first_bubble_line.$line"} =
 5626: 	    $first_bubble_line{$line};
 5627:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5628:             $subdivided_bubble_lines{$line};
 5629:         $env{"form.scantron.responsetype.$line"} =
 5630:             $responsetype_per_response{$line};
 5631:     }
 5632:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5633:         my $line = $masterseq_id_responsenum{$resid};
 5634:         $env{"form.scantron.residpart.$line"} = $resid;
 5635:     }
 5636: }
 5637: 
 5638: 
 5639: sub restore_bubble_lines {
 5640:     my $line = 0;
 5641:     %bubble_lines_per_response = ();
 5642:     %masterseq_id_responsenum = ();
 5643:     while ($env{"form.scantron.bubblelines.$line"}) {
 5644: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5645: 	$bubble_lines_per_response{$line} = $value;
 5646: 	$first_bubble_line{$line}  =
 5647: 	    $env{"form.scantron.first_bubble_line.$line"};
 5648:         $subdivided_bubble_lines{$line} =
 5649:             $env{"form.scantron.sub_bubblelines.$line"};
 5650:         $responsetype_per_response{$line} =
 5651:             $env{"form.scantron.responsetype.$line"};
 5652:         my $id = $env{"form.scantron.residpart.$line"};
 5653:         $masterseq_id_responsenum{$id} = $line;
 5654: 	$line++;
 5655:     }
 5656: }
 5657: 
 5658: =pod 
 5659: 
 5660: =item scantron_filenames
 5661: 
 5662:    Returns a list of the scantron files in the current course 
 5663: 
 5664: =cut
 5665: 
 5666: sub scantron_filenames {
 5667:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5668:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5669:     my $getpropath = 1;
 5670:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5671:                                                         $cname,$getpropath);
 5672:     my @possiblenames;
 5673:     if (ref($dirlist) eq 'ARRAY') {
 5674:         foreach my $filename (sort(@{$dirlist})) {
 5675: 	    ($filename)=split(/&/,$filename);
 5676: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5677: 	    $filename=~s/^scantron_orig_//;
 5678: 	    push(@possiblenames,$filename);
 5679:         }
 5680:     }
 5681:     return @possiblenames;
 5682: }
 5683: 
 5684: =pod 
 5685: 
 5686: =item scantron_uploads
 5687: 
 5688:    Returns  html drop-down list of scantron files in current course.
 5689: 
 5690:  Arguments:
 5691:    $file2grade - filename to set as selected in the dropdown
 5692: 
 5693: =cut
 5694: 
 5695: sub scantron_uploads {
 5696:     my ($file2grade) = @_;
 5697:     my $result=	'<select name="scantron_selectfile">';
 5698:     $result.="<option></option>";
 5699:     foreach my $filename (sort(&scantron_filenames())) {
 5700: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5701:     }
 5702:     $result.="</select>";
 5703:     return $result;
 5704: }
 5705: 
 5706: =pod 
 5707: 
 5708: =item scantron_scantab
 5709: 
 5710:   Returns html drop down of the scantron formats in the scantronformat.tab
 5711:   file.
 5712: 
 5713: =cut
 5714: 
 5715: sub scantron_scantab {
 5716:     my $result='<select name="scantron_format">'."\n";
 5717:     $result.='<option></option>'."\n";
 5718:     my @lines = &get_scantronformat_file();
 5719:     if (@lines > 0) {
 5720:         foreach my $line (@lines) {
 5721:             next if (($line =~ /^\#/) || ($line eq ''));
 5722: 	    my ($name,$descrip)=split(/:/,$line);
 5723: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5724:         }
 5725:     }
 5726:     $result.='</select>'."\n";
 5727:     return $result;
 5728: }
 5729: 
 5730: =pod
 5731: 
 5732: =item get_scantronformat_file
 5733: 
 5734:   Returns an array containing lines from the scantron format file for
 5735:   the domain of the course.
 5736: 
 5737:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5738:   lines are from this file.
 5739: 
 5740:   Otherwise, if a default.tab has been published in RES space by the 
 5741:   domainconfig user, lines are from this file.
 5742: 
 5743:   Otherwise, fall back to getting lines from the legacy file on the
 5744:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5745: 
 5746: =cut
 5747: 
 5748: sub get_scantronformat_file {
 5749:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5750:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5751:     my $gottab = 0;
 5752:     my @lines;
 5753:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5754:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5755:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5756:             if ($formatfile ne '-1') {
 5757:                 @lines = split("\n",$formatfile,-1);
 5758:                 $gottab = 1;
 5759:             }
 5760:         }
 5761:     }
 5762:     if (!$gottab) {
 5763:         my $confname = $cdom.'-domainconfig';
 5764:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5765:         my $formatfile =  &Apache::lonnet::getfile($default);
 5766:         if ($formatfile ne '-1') {
 5767:             @lines = split("\n",$formatfile,-1);
 5768:             $gottab = 1;
 5769:         }
 5770:     }
 5771:     if (!$gottab) {
 5772:         my @domains = &Apache::lonnet::current_machine_domains();
 5773:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5774:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5775:             @lines = <$fh>;
 5776:             close($fh);
 5777:         } else {
 5778:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5779:             @lines = <$fh>;
 5780:             close($fh);
 5781:         }
 5782:     }
 5783:     return @lines;
 5784: }
 5785: 
 5786: =pod 
 5787: 
 5788: =item scantron_CODElist
 5789: 
 5790:   Returns html drop down of the saved CODE lists from current course,
 5791:   generated from earlier printings.
 5792: 
 5793: =cut
 5794: 
 5795: sub scantron_CODElist {
 5796:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5797:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5798:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5799:     my $namechoice='<option></option>';
 5800:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5801: 	if ($name =~ /^error: 2 /) { next; }
 5802: 	if ($name =~ /^type\0/) { next; }
 5803: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5804:     }
 5805:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5806:     return $namechoice;
 5807: }
 5808: 
 5809: =pod 
 5810: 
 5811: =item scantron_CODEunique
 5812: 
 5813:   Returns the html for "Each CODE to be used once" radio.
 5814: 
 5815: =cut
 5816: 
 5817: sub scantron_CODEunique {
 5818:     my $result='<span class="LC_nobreak">
 5819:                  <label><input type="radio" name="scantron_CODEunique"
 5820:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5821:                 </span>
 5822:                 <span class="LC_nobreak">
 5823:                  <label><input type="radio" name="scantron_CODEunique"
 5824:                         value="no" />'.&mt('No').' </label>
 5825:                 </span>';
 5826:     return $result;
 5827: }
 5828: 
 5829: =pod 
 5830: 
 5831: =item scantron_selectphase
 5832: 
 5833:   Generates the initial screen to start the bubblesheet process.
 5834:   Allows for - starting a grading run.
 5835:              - downloading existing scan data (original, corrected
 5836:                                                 or skipped info)
 5837: 
 5838:              - uploading new scan data
 5839: 
 5840:  Arguments:
 5841:   $r          - The Apache request object
 5842:   $file2grade - name of the file that contain the scanned data to score
 5843: 
 5844: =cut
 5845: 
 5846: sub scantron_selectphase {
 5847:     my ($r,$file2grade) = @_;
 5848:     my ($symb)=&get_symb($r);
 5849:     if (!$symb) {return '';}
 5850:     my $map_error;
 5851:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5852:     if ($map_error) {
 5853:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5854:         return;
 5855:     }
 5856:     my $default_form_data=&defaultFormData($symb);
 5857:     my $grading_menu_button=&show_grading_menu_form($symb);
 5858:     my $file_selector=&scantron_uploads($file2grade);
 5859:     my $format_selector=&scantron_scantab();
 5860:     my $CODE_selector=&scantron_CODElist();
 5861:     my $CODE_unique=&scantron_CODEunique();
 5862:     my $result;
 5863: 
 5864:     $ssi_error = 0;
 5865: 
 5866:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5867:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5868: 
 5869:         # Chunk of form to prompt for a scantron file upload.
 5870: 
 5871:         $r->print('
 5872:     <br />
 5873:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5874:        '.&Apache::loncommon::start_data_table_header_row().'
 5875:             <th>
 5876:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5877:             </th>
 5878:        '.&Apache::loncommon::end_data_table_header_row().'
 5879:        '.&Apache::loncommon::start_data_table_row().'
 5880:             <td>
 5881: ');
 5882:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5883:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5884:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5885:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5886:     &js_escape(\$alertmsg);
 5887:     $r->print('
 5888:               <script type="text/javascript" language="javascript">
 5889:     function checkUpload(formname) {
 5890:         if (formname.upfile.value == "") {
 5891:             alert("'.$alertmsg.'");
 5892:             return false;
 5893:         }
 5894:         formname.submit();
 5895:     }
 5896:               </script>
 5897: 
 5898:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5899:                 '.$default_form_data.'
 5900:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5901:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5902:                 <input name="command" value="scantronupload_save" type="hidden" />
 5903:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5904:                 <br />
 5905:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5906:               </form>
 5907: ');
 5908: 
 5909:         $r->print('
 5910:             </td>
 5911:        '.&Apache::loncommon::end_data_table_row().'
 5912:        '.&Apache::loncommon::end_data_table().'
 5913: ');
 5914:     }
 5915: 
 5916:     # Chunk of form to prompt for a file to grade and how:
 5917: 
 5918:     $result.= '
 5919:     <br />
 5920:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5921:     <input type="hidden" name="command" value="scantron_warning" />
 5922:     '.$default_form_data.'
 5923:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5924:        '.&Apache::loncommon::start_data_table_header_row().'
 5925:             <th colspan="2">
 5926:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5927:             </th>
 5928:        '.&Apache::loncommon::end_data_table_header_row().'
 5929:        '.&Apache::loncommon::start_data_table_row().'
 5930:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5931:        '.&Apache::loncommon::end_data_table_row().'
 5932:        '.&Apache::loncommon::start_data_table_row().'
 5933:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5934:        '.&Apache::loncommon::end_data_table_row().'
 5935:        '.&Apache::loncommon::start_data_table_row().'
 5936:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5937:        '.&Apache::loncommon::end_data_table_row().'
 5938:        '.&Apache::loncommon::start_data_table_row().'
 5939:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5940:        '.&Apache::loncommon::end_data_table_row().'
 5941:        '.&Apache::loncommon::start_data_table_row().'
 5942:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5943:        '.&Apache::loncommon::end_data_table_row().'
 5944:        '.&Apache::loncommon::start_data_table_row().'
 5945: 	    <td> '.&mt('Options:').' </td>
 5946:             <td>
 5947: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5948:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5949:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5950: 	    </td>
 5951:        '.&Apache::loncommon::end_data_table_row().'
 5952:        '.&Apache::loncommon::start_data_table_row().'
 5953:             <td colspan="2">
 5954:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5955:             </td>
 5956:        '.&Apache::loncommon::end_data_table_row().'
 5957:     '.&Apache::loncommon::end_data_table().'
 5958:     </form>
 5959: ';
 5960:    
 5961:     $r->print($result);
 5962: 
 5963:     # Chunk of the form that prompts to view a scoring office file,
 5964:     # corrected file, skipped records in a file.
 5965: 
 5966:     $r->print('
 5967:    <br />
 5968:    <form action="/adm/grades" name="scantron_download">
 5969:      '.$default_form_data.'
 5970:      <input type="hidden" name="command" value="scantron_download" />
 5971:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5972:        '.&Apache::loncommon::start_data_table_header_row().'
 5973:               <th>
 5974:                 &nbsp;'.&mt('Download a scoring office file').'
 5975:               </th>
 5976:        '.&Apache::loncommon::end_data_table_header_row().'
 5977:        '.&Apache::loncommon::start_data_table_row().'
 5978:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5979:                 <br />
 5980:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5981:        '.&Apache::loncommon::end_data_table_row().'
 5982:      '.&Apache::loncommon::end_data_table().'
 5983:    </form>
 5984:    <br />
 5985: ');
 5986: 
 5987:     &Apache::lonpickcode::code_list($r,2);
 5988: 
 5989:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5990:              $default_form_data."\n".
 5991:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5992:              &Apache::loncommon::start_data_table_header_row()."\n".
 5993:              '<th colspan="2">
 5994:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5995:              '</th>'."\n".
 5996:               &Apache::loncommon::end_data_table_header_row()."\n".
 5997:               &Apache::loncommon::start_data_table_row()."\n".
 5998:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5999:               '<td> '.$sequence_selector.' </td>'.
 6000:               &Apache::loncommon::end_data_table_row()."\n".
 6001:               &Apache::loncommon::start_data_table_row()."\n".
 6002:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6003:               '<td> '.$file_selector.' </td>'."\n".
 6004:               &Apache::loncommon::end_data_table_row()."\n".
 6005:               &Apache::loncommon::start_data_table_row()."\n".
 6006:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6007:               '<td> '.$format_selector.' </td>'."\n".
 6008:               &Apache::loncommon::end_data_table_row()."\n".
 6009:               &Apache::loncommon::start_data_table_row()."\n".
 6010:               '<td> '.&mt('Options').' </td>'."\n".
 6011:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6012:               &Apache::loncommon::end_data_table_row()."\n".
 6013:               &Apache::loncommon::start_data_table_row()."\n".
 6014:               '<td colspan="2">'."\n".
 6015:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6016:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6017:               '</td>'."\n".
 6018:               &Apache::loncommon::end_data_table_row()."\n".
 6019:               &Apache::loncommon::end_data_table()."\n".
 6020:               '</form><br />');
 6021:     $r->print($grading_menu_button);
 6022:     return;
 6023: }
 6024: 
 6025: =pod
 6026: 
 6027: =item get_scantron_config
 6028: 
 6029:    Parse and return the scantron configuration line selected as a
 6030:    hash of configuration file fields.
 6031: 
 6032:  Arguments:
 6033:     which - the name of the configuration to parse from the file.
 6034: 
 6035: 
 6036:  Returns:
 6037:             If the named configuration is not in the file, an empty
 6038:             hash is returned.
 6039:     a hash with the fields
 6040:       name         - internal name for the this configuration setup
 6041:       description  - text to display to operator that describes this config
 6042:       CODElocation - if 0 or the string 'none'
 6043:                           - no CODE exists for this config
 6044:                      if -1 || the string 'letter'
 6045:                           - a CODE exists for this config and is
 6046:                             a string of letters
 6047:                      Unsupported value (but planned for future support)
 6048:                           if a positive integer
 6049:                                - The CODE exists as the first n items from
 6050:                                  the question section of the form
 6051:                           if the string 'number'
 6052:                                - The CODE exists for this config and is
 6053:                                  a string of numbers
 6054:       CODEstart   - (only matter if a CODE exists) column in the line where
 6055:                      the CODE starts
 6056:       CODElength  - length of the CODE
 6057:       IDstart     - column where the student/employee ID starts
 6058:       IDlength    - length of the student/employee ID info
 6059:       Qstart      - column where the information from the bubbled
 6060:                     'questions' start
 6061:       Qlength     - number of columns comprising a single bubble line from
 6062:                     the sheet. (usually either 1 or 10)
 6063:       Qon         - either a single character representing the character used
 6064:                     to signal a bubble was chosen in the positional setup, or
 6065:                     the string 'letter' if the letter of the chosen bubble is
 6066:                     in the final, or 'number' if a number representing the
 6067:                     chosen bubble is in the file (1->A 0->J)
 6068:       Qoff        - the character used to represent that a bubble was
 6069:                     left blank
 6070:       PaperID     - if the scanning process generates a unique number for each
 6071:                     sheet scanned the column that this ID number starts in
 6072:       PaperIDlength - number of columns that comprise the unique ID number
 6073:                       for the sheet of paper
 6074:       FirstName   - column that the first name starts in
 6075:       FirstNameLength - number of columns that the first name spans
 6076:  
 6077:       LastName    - column that the last name starts in
 6078:       LastNameLength - number of columns that the last name spans
 6079:       BubblesPerRow - number of bubbles available in each row used to
 6080:                       bubble an answer. (If not specified, 10 assumed).
 6081: 
 6082: =cut
 6083: 
 6084: sub get_scantron_config {
 6085:     my ($which) = @_;
 6086:     my @lines = &get_scantronformat_file();
 6087:     my %config;
 6088:     #FIXME probably should move to XML it has already gotten a bit much now
 6089:     foreach my $line (@lines) {
 6090: 	my ($name,$descrip)=split(/:/,$line);
 6091: 	if ($name ne $which ) { next; }
 6092: 	chomp($line);
 6093: 	my @config=split(/:/,$line);
 6094: 	$config{'name'}=$config[0];
 6095: 	$config{'description'}=$config[1];
 6096: 	$config{'CODElocation'}=$config[2];
 6097: 	$config{'CODEstart'}=$config[3];
 6098: 	$config{'CODElength'}=$config[4];
 6099: 	$config{'IDstart'}=$config[5];
 6100: 	$config{'IDlength'}=$config[6];
 6101: 	$config{'Qstart'}=$config[7];
 6102:  	$config{'Qlength'}=$config[8];
 6103: 	$config{'Qoff'}=$config[9];
 6104: 	$config{'Qon'}=$config[10];
 6105: 	$config{'PaperID'}=$config[11];
 6106: 	$config{'PaperIDlength'}=$config[12];
 6107: 	$config{'FirstName'}=$config[13];
 6108: 	$config{'FirstNamelength'}=$config[14];
 6109: 	$config{'LastName'}=$config[15];
 6110: 	$config{'LastNamelength'}=$config[16];
 6111:         $config{'BubblesPerRow'}=$config[17];
 6112: 	last;
 6113:     }
 6114:     return %config;
 6115: }
 6116: 
 6117: =pod 
 6118: 
 6119: =item username_to_idmap
 6120: 
 6121:     creates a hash keyed by student/employee ID with values of the corresponding
 6122:     student username:domain.
 6123: 
 6124:   Arguments:
 6125: 
 6126:     $classlist - reference to the class list hash. This is a hash
 6127:                  keyed by student name:domain  whose elements are references
 6128:                  to arrays containing various chunks of information
 6129:                  about the student. (See loncoursedata for more info).
 6130: 
 6131:   Returns
 6132:     %idmap - the constructed hash
 6133: 
 6134: =cut
 6135: 
 6136: sub username_to_idmap {
 6137:     my ($classlist)= @_;
 6138:     my %idmap;
 6139:     foreach my $student (keys(%$classlist)) {
 6140:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6141:         unless ($id eq '') {
 6142:             if (!exists($idmap{$id})) {
 6143:                 $idmap{$id} = $student;
 6144:             } else {
 6145:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6146:                 if ($status eq 'Active') {
 6147:                     $idmap{$id} = $student;
 6148:                 }
 6149:             }
 6150:         }
 6151:     }
 6152:     return %idmap;
 6153: }
 6154: 
 6155: =pod
 6156: 
 6157: =item scantron_fixup_scanline
 6158: 
 6159:    Process a requested correction to a scanline.
 6160: 
 6161:   Arguments:
 6162:     $scantron_config   - hash from &get_scantron_config()
 6163:     $scan_data         - hash of correction information 
 6164:                           (see &scantron_getfile())
 6165:     $line              - existing scanline
 6166:     $whichline         - line number of the passed in scanline
 6167:     $field             - type of change to process 
 6168:                          (either 
 6169:                           'ID'     -> correct the student/employee ID
 6170:                           'CODE'   -> correct the CODE
 6171:                           'answer' -> fixup the submitted answers)
 6172:     
 6173:    $args               - hash of additional info,
 6174:                           - 'ID' 
 6175:                                'newid' -> studentID to use in replacement
 6176:                                           of existing one
 6177:                           - 'CODE' 
 6178:                                'CODE_ignore_dup' - set to true if duplicates
 6179:                                                    should be ignored.
 6180: 	                       'CODE' - is new code or 'use_unfound'
 6181:                                         if the existing unfound code should
 6182:                                         be used as is
 6183:                           - 'answer'
 6184:                                'response' - new answer or 'none' if blank
 6185:                                'question' - the bubble line to change
 6186:                                'questionnum' - the question identifier,
 6187:                                                may include subquestion. 
 6188: 
 6189:   Returns:
 6190:     $line - the modified scanline
 6191: 
 6192:   Side effects: 
 6193:     $scan_data - may be updated
 6194: 
 6195: =cut
 6196: 
 6197: 
 6198: sub scantron_fixup_scanline {
 6199:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6200:     if ($field eq 'ID') {
 6201: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6202: 	    return ($line,1,'New value too large');
 6203: 	}
 6204: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6205: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6206: 				     $args->{'newid'});
 6207: 	}
 6208: 	substr($line,$$scantron_config{'IDstart'}-1,
 6209: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6210: 	if ($args->{'newid'}=~/^\s*$/) {
 6211: 	    &scan_data($scan_data,"$whichline.user",
 6212: 		       $args->{'username'}.':'.$args->{'domain'});
 6213: 	}
 6214:     } elsif ($field eq 'CODE') {
 6215: 	if ($args->{'CODE_ignore_dup'}) {
 6216: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6217: 	}
 6218: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6219: 	if ($args->{'CODE'} ne 'use_unfound') {
 6220: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6221: 		return ($line,1,'New CODE value too large');
 6222: 	    }
 6223: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6224: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6225: 	    }
 6226: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6227: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6228: 	}
 6229:     } elsif ($field eq 'answer') {
 6230: 	my $length=$scantron_config->{'Qlength'};
 6231: 	my $off=$scantron_config->{'Qoff'};
 6232: 	my $on=$scantron_config->{'Qon'};
 6233: 	my $answer=${off}x$length;
 6234: 	if ($args->{'response'} eq 'none') {
 6235: 	    &scan_data($scan_data,
 6236: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6237: 	} else {
 6238: 	    if ($on eq 'letter') {
 6239: 		my @alphabet=('A'..'Z');
 6240: 		$answer=$alphabet[$args->{'response'}];
 6241: 	    } elsif ($on eq 'number') {
 6242: 		$answer=$args->{'response'}+1;
 6243: 		if ($answer == 10) { $answer = '0'; }
 6244: 	    } else {
 6245: 		substr($answer,$args->{'response'},1)=$on;
 6246: 	    }
 6247: 	    &scan_data($scan_data,
 6248: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6249: 	}
 6250: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6251: 	substr($line,$where-1,$length)=$answer;
 6252:     }
 6253:     return $line;
 6254: }
 6255: 
 6256: =pod
 6257: 
 6258: =item scan_data
 6259: 
 6260:     Edit or look up  an item in the scan_data hash.
 6261: 
 6262:   Arguments:
 6263:     $scan_data  - The hash (see scantron_getfile)
 6264:     $key        - shorthand of the key to edit (actual key is
 6265:                   scantronfilename_key).
 6266:     $data        - New value of the hash entry.
 6267:     $delete      - If true, the entry is removed from the hash.
 6268: 
 6269:   Returns:
 6270:     The new value of the hash table field (undefined if deleted).
 6271: 
 6272: =cut
 6273: 
 6274: 
 6275: sub scan_data {
 6276:     my ($scan_data,$key,$value,$delete)=@_;
 6277:     my $filename=$env{'form.scantron_selectfile'};
 6278:     if (defined($value)) {
 6279: 	$scan_data->{$filename.'_'.$key} = $value;
 6280:     }
 6281:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6282:     return $scan_data->{$filename.'_'.$key};
 6283: }
 6284: 
 6285: # ----- These first few routines are general use routines.----
 6286: 
 6287: # Return the number of occurences of a pattern in a string.
 6288: 
 6289: sub occurence_count {
 6290:     my ($string, $pattern) = @_;
 6291: 
 6292:     my @matches = ($string =~ /$pattern/g);
 6293: 
 6294:     return scalar(@matches);
 6295: }
 6296: 
 6297: 
 6298: # Take a string known to have digits and convert all the
 6299: # digits into letters in the range J,A..I.
 6300: 
 6301: sub digits_to_letters {
 6302:     my ($input) = @_;
 6303: 
 6304:     my @alphabet = ('J', 'A'..'I');
 6305: 
 6306:     my @input    = split(//, $input);
 6307:     my $output ='';
 6308:     for (my $i = 0; $i < scalar(@input); $i++) {
 6309: 	if ($input[$i] =~ /\d/) {
 6310: 	    $output .= $alphabet[$input[$i]];
 6311: 	} else {
 6312: 	    $output .= $input[$i];
 6313: 	}
 6314:     }
 6315:     return $output;
 6316: }
 6317: 
 6318: =pod 
 6319: 
 6320: =item scantron_parse_scanline
 6321: 
 6322:   Decodes a scanline from the selected scantron file
 6323: 
 6324:  Arguments:
 6325:     line             - The text of the scantron file line to process
 6326:     whichline        - Line number
 6327:     scantron_config  - Hash describing the format of the scantron lines.
 6328:     scan_data        - Hash of extra information about the scanline
 6329:                        (see scantron_getfile for more information)
 6330:     just_header      - True if should not process question answers but only
 6331:                        the stuff to the left of the answers.
 6332:     randomorder      - True if randomorder in use
 6333:     randompick       - True if randompick in use
 6334:     sequence         - Exam folder URL
 6335:     master_seq       - Ref to array containing symbs in exam folder
 6336:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6337:                        (corresponding values are resource objects)
 6338:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6339:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6340:                        are refs to an array of resource objects, ordered
 6341:                        according to order used for CODE, when randomorder
 6342:                        and or randompick are in use.
 6343:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6344:                        for current line to question number used for same question
 6345:                         in "Master Sequence" (as seen by Course Coordinator).
 6346:     startline        - Ref to hash where key is question number (0 is first)
 6347:                        and value is number of first bubble line for current 
 6348:                        student or code-based randompick and/or randomorder.
 6349:     totalref         - Ref of scalar used to score total number of bubble
 6350:                        lines needed for responses in a scan line (used when
 6351:                        randompick in use. 
 6352: 
 6353:  Returns:
 6354:    Hash containing the result of parsing the scanline
 6355: 
 6356:    Keys are all proceeded by the string 'scantron.'
 6357: 
 6358:        CODE    - the CODE in use for this scanline
 6359:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6360:                  by the operator
 6361:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6362:                             CODEs were selected, but the usage has been
 6363:                             forced by the operator
 6364:        ID  - student/employee ID
 6365:        PaperID - if used, the ID number printed on the sheet when the 
 6366:                  paper was scanned
 6367:        FirstName - first name from the sheet
 6368:        LastName  - last name from the sheet
 6369: 
 6370:      if just_header was not true these key may also exist
 6371: 
 6372:        missingerror - a list of bubble ranges that are considered to be answers
 6373:                       to a single question that don't have any bubbles filled in.
 6374:                       Of the form questionnumber:firstbubblenumber:count.
 6375:        doubleerror  - a list of bubble ranges that are considered to be answers
 6376:                       to a single question that have more than one bubble filled in.
 6377:                       Of the form questionnumber::firstbubblenumber:count
 6378:    
 6379:                 In the above, count is the number of bubble responses in the
 6380:                 input line needed to represent the possible answers to the question.
 6381:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6382:                 per line would have count = 2.
 6383: 
 6384:        maxquest     - the number of the last bubble line that was parsed
 6385: 
 6386:        (<number> starts at 1)
 6387:        <number>.answer - zero or more letters representing the selected
 6388:                          letters from the scanline for the bubble line 
 6389:                          <number>.
 6390:                          if blank there was either no bubble or there where
 6391:                          multiple bubbles, (consult the keys missingerror and
 6392:                          doubleerror if this is an error condition)
 6393: 
 6394: =cut
 6395: 
 6396: sub scantron_parse_scanline {
 6397:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6398:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6399:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6400: 
 6401:     my %record;
 6402:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6403:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6404: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6405: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6406: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6407: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6408: 	    $record{'scantron.CODE'}=substr($data,
 6409: 					    $$scantron_config{'CODEstart'}-1,
 6410: 					    $$scantron_config{'CODElength'});
 6411: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6412: 		$record{'scantron.useCODE'}=1;
 6413: 	    }
 6414: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6415: 		$record{'scantron.CODE_ignore_dup'}=1;
 6416: 	    }
 6417: 	} else {
 6418: 	    #FIXME interpret first N questions
 6419: 	}
 6420:     }
 6421:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6422: 				  $$scantron_config{'IDlength'});
 6423:     $record{'scantron.PaperID'}=
 6424: 	substr($data,$$scantron_config{'PaperID'}-1,
 6425: 	       $$scantron_config{'PaperIDlength'});
 6426:     $record{'scantron.FirstName'}=
 6427: 	substr($data,$$scantron_config{'FirstName'}-1,
 6428: 	       $$scantron_config{'FirstNamelength'});
 6429:     $record{'scantron.LastName'}=
 6430: 	substr($data,$$scantron_config{'LastName'}-1,
 6431: 	       $$scantron_config{'LastNamelength'});
 6432:     if ($just_header) { return \%record; }
 6433: 
 6434:     my @alphabet=('A'..'Z');
 6435:     my $questnum=0;
 6436:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6437: 
 6438:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6439:     if ($randompick || $randomorder) {
 6440:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6441:                                          $master_seq,$symb_to_resource,
 6442:                                          $partids_by_symb,$orderedforcode,
 6443:                                          $respnumlookup,$startline);
 6444:         if ($total) {
 6445:             $lastpos = $total*$$scantron_config{'Qlength'};
 6446:         }
 6447:         if (ref($totalref)) {
 6448:             $$totalref = $total;
 6449:         }
 6450:     }
 6451:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6452:     chomp($questions);		# Get rid of any trailing \n.
 6453:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6454:     while (length($questions)) {
 6455:         my $answers_needed;
 6456:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6457:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6458:         } else {
 6459:             $answers_needed = $bubble_lines_per_response{$questnum};
 6460:         }
 6461:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6462:                              || 1;
 6463:         $questnum++;
 6464:         my $quest_id = $questnum;
 6465:         my $currentquest = substr($questions,0,$answer_length);
 6466:         $questions       = substr($questions,$answer_length);
 6467:         if (length($currentquest) < $answer_length) { next; }
 6468: 
 6469:         my $subdivided;
 6470:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6471:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6472:         } else {
 6473:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6474:         }
 6475:         if ($subdivided =~ /,/) {
 6476:             my $subquestnum = 1;
 6477:             my $subquestions = $currentquest;
 6478:             my @subanswers_needed = split(/,/,$subdivided);
 6479:             foreach my $subans (@subanswers_needed) {
 6480:                 my $subans_length =
 6481:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6482:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6483:                 $subquestions   = substr($subquestions,$subans_length);
 6484:                 $quest_id = "$questnum.$subquestnum";
 6485:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6486:                     ($$scantron_config{'Qon'} eq 'number')) {
 6487:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6488:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6489:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6490:                         $randomorder,$randompick,$respnumlookup);
 6491:                 } else {
 6492:                     $ansnum = &scantron_validator_positional($ansnum,
 6493:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6494:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6495:                         $randomorder,$randompick,$respnumlookup);
 6496:                 }
 6497:                 $subquestnum ++;
 6498:             }
 6499:         } else {
 6500:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6501:                 ($$scantron_config{'Qon'} eq 'number')) {
 6502:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6503:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6504:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6505:                     $randomorder,$randompick,$respnumlookup);
 6506:             } else {
 6507:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6508:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6509:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6510:                     $randomorder,$randompick,$respnumlookup);
 6511:             }
 6512:         }
 6513:     }
 6514:     $record{'scantron.maxquest'}=$questnum;
 6515:     return \%record;
 6516: }
 6517: 
 6518: sub get_master_seq {
 6519:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6520:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6521:                    (ref($symb_to_resource) eq 'HASH'));
 6522:     my $resource_error;
 6523:     foreach my $resource (@{$resources}) {
 6524:         my $ressymb;
 6525:         if (ref($resource)) {
 6526:             $ressymb = $resource->symb();
 6527:             push(@{$master_seq},$ressymb);
 6528:             $symb_to_resource->{$ressymb} = $resource;
 6529:         } else {
 6530:             $resource_error = 1;
 6531:             last;
 6532:         }
 6533:     }
 6534:     return $resource_error;
 6535: }
 6536: 
 6537: sub get_respnum_lookups {
 6538:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6539:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6540:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6541:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6542:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6543:                    (ref($startline) eq 'HASH'));
 6544:     my ($user,$scancode);
 6545:     if ((exists($record->{'scantron.CODE'})) &&
 6546:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6547:         $scancode = $record->{'scantron.CODE'};
 6548:     } else {
 6549:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6550:     }
 6551:     my @mapresources =
 6552:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6553:                      $orderedforcode);
 6554:     my $total = 0;
 6555:     my $count = 0;
 6556:     foreach my $resource (@mapresources) {
 6557:         my $id = $resource->id();
 6558:         my $symb = $resource->symb();
 6559:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6560:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6561:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6562:                 if ($respnum ne '') {
 6563:                     $respnumlookup->{$count} = $respnum;
 6564:                     $startline->{$count} = $total;
 6565:                     $total += $bubble_lines_per_response{$respnum};
 6566:                     $count ++;
 6567:                 }
 6568:             }
 6569:         }
 6570:     }
 6571:     return $total;
 6572: }
 6573: 
 6574: sub scantron_validator_lettnum {
 6575:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6576:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6577:         $randompick,$respnumlookup) = @_;
 6578: 
 6579:     # Qon 'letter' implies for each slot in currquest we have:
 6580:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6581:     #    about anything else (esp. a value of Qoff) for missing
 6582:     #    bubbles.
 6583:     #
 6584:     # Qon 'number' implies each slot gives a digit that indexes the
 6585:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6586:     #    and * or ? for double bubbles on a single line.
 6587:     #
 6588: 
 6589:     my $matchon;
 6590:     if ($$scantron_config{'Qon'} eq 'letter') {
 6591:         $matchon = '[A-Z]';
 6592:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6593:         $matchon = '\d';
 6594:     }
 6595:     my $occurrences = 0;
 6596:     my $responsenum = $questnum-1;
 6597:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6598:        $responsenum = $respnumlookup->{$questnum-1}
 6599:     }
 6600:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6601:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6602:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6603:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6604:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6605:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6606:         my @singlelines = split('',$currquest);
 6607:         foreach my $entry (@singlelines) {
 6608:             $occurrences = &occurence_count($entry,$matchon);
 6609:             if ($occurrences > 1) {
 6610:                 last;
 6611:             }
 6612:         }
 6613:     } else {
 6614:         $occurrences = &occurence_count($currquest,$matchon); 
 6615:     }
 6616:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6617:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6618:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6619:             my $bubble = substr($currquest,$ans,1);
 6620:             if ($bubble =~ /$matchon/ ) {
 6621:                 if ($$scantron_config{'Qon'} eq 'number') {
 6622:                     if ($bubble == 0) {
 6623:                         $bubble = 10; 
 6624:                     }
 6625:                     $record->{"scantron.$ansnum.answer"} = 
 6626:                         $alphabet->[$bubble-1];
 6627:                 } else {
 6628:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6629:                 }
 6630:             } else {
 6631:                 $record->{"scantron.$ansnum.answer"}='';
 6632:             }
 6633:             $ansnum++;
 6634:         }
 6635:     } elsif (!defined($currquest)
 6636:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6637:             || (&occurence_count($currquest,$matchon) == 0)) {
 6638:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6639:             $record->{"scantron.$ansnum.answer"}='';
 6640:             $ansnum++;
 6641:         }
 6642:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6643:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6644:         }
 6645:     } else {
 6646:         if ($$scantron_config{'Qon'} eq 'number') {
 6647:             $currquest = &digits_to_letters($currquest);            
 6648:         }
 6649:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6650:             my $bubble = substr($currquest,$ans,1);
 6651:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6652:             $ansnum++;
 6653:         }
 6654:     }
 6655:     return $ansnum;
 6656: }
 6657: 
 6658: sub scantron_validator_positional {
 6659:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6660:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6661:         $randomorder,$randompick,$respnumlookup) = @_;
 6662: 
 6663:     # Otherwise there's a positional notation;
 6664:     # each bubble line requires Qlength items, and there are filled in
 6665:     # bubbles for each case where there 'Qon' characters.
 6666:     #
 6667: 
 6668:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6669: 
 6670:     # If the split only gives us one element.. the full length of the
 6671:     # answer string, no bubbles are filled in:
 6672: 
 6673:     if ($answers_needed eq '') {
 6674:         return;
 6675:     }
 6676: 
 6677:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6678:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6679:             $record->{"scantron.$ansnum.answer"}='';
 6680:             $ansnum++;
 6681:         }
 6682:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6683:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6684:         }
 6685:     } elsif (scalar(@array) == 2) {
 6686:         my $location = length($array[0]);
 6687:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6688:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6689:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6690:             if ($ans eq $line_num) {
 6691:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6692:             } else {
 6693:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6694:             }
 6695:             $ansnum++;
 6696:          }
 6697:     } else {
 6698:         #  If there's more than one instance of a bubble character
 6699:         #  That's a double bubble; with positional notation we can
 6700:         #  record all the bubbles filled in as well as the
 6701:         #  fact this response consists of multiple bubbles.
 6702:         #
 6703:         my $responsenum = $questnum-1;
 6704:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6705:             $responsenum = $respnumlookup->{$questnum-1}
 6706:         }
 6707:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6708:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6709:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6710:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6711:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6712:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6713:             my $doubleerror = 0;
 6714:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6715:                    (!$doubleerror)) {
 6716:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6717:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6718:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6719:                if (length(@currarray) > 2) {
 6720:                    $doubleerror = 1;
 6721:                } 
 6722:             }
 6723:             if ($doubleerror) {
 6724:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6725:             }
 6726:         } else {
 6727:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6728:         }
 6729:         my $item = $ansnum;
 6730:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6731:             $record->{"scantron.$item.answer"} = '';
 6732:             $item ++;
 6733:         }
 6734: 
 6735:         my @ans=@array;
 6736:         my $i=0;
 6737:         my $increment = 0;
 6738:         while ($#ans) {
 6739:             $i+=length($ans[0]) + $increment;
 6740:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6741:             my $bubble = $i%$$scantron_config{'Qlength'};
 6742:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6743:             shift(@ans);
 6744:             $increment = 1;
 6745:         }
 6746:         $ansnum += $answers_needed;
 6747:     }
 6748:     return $ansnum;
 6749: }
 6750: 
 6751: =pod
 6752: 
 6753: =item scantron_add_delay
 6754: 
 6755:    Adds an error message that occurred during the grading phase to a
 6756:    queue of messages to be shown after grading pass is complete
 6757: 
 6758:  Arguments:
 6759:    $delayqueue  - arrary ref of hash ref of error messages
 6760:    $scanline    - the scanline that caused the error
 6761:    $errormesage - the error message
 6762:    $errorcode   - a numeric code for the error
 6763: 
 6764:  Side Effects:
 6765:    updates the $delayqueue to have a new hash ref of the error
 6766: 
 6767: =cut
 6768: 
 6769: sub scantron_add_delay {
 6770:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6771:     push(@$delayqueue,
 6772: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6773: 	  'ecode' => $errorcode }
 6774: 	 );
 6775: }
 6776: 
 6777: =pod
 6778: 
 6779: =item scantron_find_student
 6780: 
 6781:    Finds the username for the current scanline
 6782: 
 6783:   Arguments:
 6784:    $scantron_record - hash result from scantron_parse_scanline
 6785:    $scan_data       - hash of correction information 
 6786:                       (see &scantron_getfile() form more information)
 6787:    $idmap           - hash from &username_to_idmap()
 6788:    $line            - number of current scanline
 6789:  
 6790:   Returns:
 6791:    Either 'username:domain' or undef if unknown
 6792: 
 6793: =cut
 6794: 
 6795: sub scantron_find_student {
 6796:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6797:     my $scanID=$$scantron_record{'scantron.ID'};
 6798:     if ($scanID =~ /^\s*$/) {
 6799:  	return &scan_data($scan_data,"$line.user");
 6800:     }
 6801:     foreach my $id (keys(%$idmap)) {
 6802:  	if (lc($id) eq lc($scanID)) {
 6803:  	    return $$idmap{$id};
 6804:  	}
 6805:     }
 6806:     return undef;
 6807: }
 6808: 
 6809: =pod
 6810: 
 6811: =item scantron_filter
 6812: 
 6813:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6814:    hidden resources was selected
 6815: 
 6816: =cut
 6817: 
 6818: sub scantron_filter {
 6819:     my ($curres)=@_;
 6820: 
 6821:     if (ref($curres) && $curres->is_problem()) {
 6822: 	# if the user has asked to not have either hidden
 6823: 	# or 'randomout' controlled resources to be graded
 6824: 	# don't include them
 6825: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6826: 	    && $curres->randomout) {
 6827: 	    return 0;
 6828: 	}
 6829: 	return 1;
 6830:     }
 6831:     return 0;
 6832: }
 6833: 
 6834: =pod
 6835: 
 6836: =item scantron_process_corrections
 6837: 
 6838:    Gets correction information out of submitted form data and corrects
 6839:    the scanline
 6840: 
 6841: =cut
 6842: 
 6843: sub scantron_process_corrections {
 6844:     my ($r) = @_;
 6845:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6846:     my ($scanlines,$scan_data)=&scantron_getfile();
 6847:     my $classlist=&Apache::loncoursedata::get_classlist();
 6848:     my $which=$env{'form.scantron_line'};
 6849:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6850:     my ($skip,$err,$errmsg);
 6851:     if ($env{'form.scantron_skip_record'}) {
 6852: 	$skip=1;
 6853:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6854: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6855: 	    $env{'form.scantron_domain'};
 6856: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6857: 	($line,$err,$errmsg)=
 6858: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6859: 				     'ID',{'newid'=>$newid,
 6860: 				    'username'=>$env{'form.scantron_username'},
 6861: 				    'domain'=>$env{'form.scantron_domain'}});
 6862:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6863: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6864: 	my $newCODE;
 6865: 	my %args;
 6866: 	if      ($resolution eq 'use_unfound') {
 6867: 	    $newCODE='use_unfound';
 6868: 	} elsif ($resolution eq 'use_found') {
 6869: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6870: 	} elsif ($resolution eq 'use_typed') {
 6871: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6872: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6873: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6874: 	}
 6875: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6876: 	    $args{'CODE_ignore_dup'}=1;
 6877: 	}
 6878: 	$args{'CODE'}=$newCODE;
 6879: 	($line,$err,$errmsg)=
 6880: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6881: 				     'CODE',\%args);
 6882:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6883: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6884: 	    ($line,$err,$errmsg)=
 6885: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6886: 					 $which,'answer',
 6887: 					 { 'question'=>$question,
 6888: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6889:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6890: 	    if ($err) { last; }
 6891: 	}
 6892:     }
 6893:     if ($err) {
 6894: 	$r->print(
 6895:             '<p class="LC_error">'
 6896:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6897:                 $errmsg)
 6898:            .'</p>');
 6899:     } else {
 6900: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6901: 	&scantron_putfile($scanlines,$scan_data);
 6902:     }
 6903: }
 6904: 
 6905: =pod
 6906: 
 6907: =item reset_skipping_status
 6908: 
 6909:    Forgets the current set of remember skipped scanlines (and thus
 6910:    reverts back to considering all lines in the
 6911:    scantron_skipped_<filename> file)
 6912: 
 6913: =cut
 6914: 
 6915: sub reset_skipping_status {
 6916:     my ($scanlines,$scan_data)=&scantron_getfile();
 6917:     &scan_data($scan_data,'remember_skipping',undef,1);
 6918:     &scantron_putfile(undef,$scan_data);
 6919: }
 6920: 
 6921: =pod
 6922: 
 6923: =item start_skipping
 6924: 
 6925:    Marks a scanline to be skipped. 
 6926: 
 6927: =cut
 6928: 
 6929: sub start_skipping {
 6930:     my ($scan_data,$i)=@_;
 6931:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6932:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6933: 	$remembered{$i}=2;
 6934:     } else {
 6935: 	$remembered{$i}=1;
 6936:     }
 6937:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6938: }
 6939: 
 6940: =pod
 6941: 
 6942: =item should_be_skipped
 6943: 
 6944:    Checks whether a scanline should be skipped.
 6945: 
 6946: =cut
 6947: 
 6948: sub should_be_skipped {
 6949:     my ($scanlines,$scan_data,$i)=@_;
 6950:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6951: 	# not redoing old skips
 6952: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6953: 	return 0;
 6954:     }
 6955:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6956: 
 6957:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6958: 	return 0;
 6959:     }
 6960:     return 1;
 6961: }
 6962: 
 6963: =pod
 6964: 
 6965: =item remember_current_skipped
 6966: 
 6967:    Discovers what scanlines are in the scantron_skipped_<filename>
 6968:    file and remembers them into scan_data for later use.
 6969: 
 6970: =cut
 6971: 
 6972: sub remember_current_skipped {
 6973:     my ($scanlines,$scan_data)=&scantron_getfile();
 6974:     my %to_remember;
 6975:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6976: 	if ($scanlines->{'skipped'}[$i]) {
 6977: 	    $to_remember{$i}=1;
 6978: 	}
 6979:     }
 6980: 
 6981:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6982:     &scantron_putfile(undef,$scan_data);
 6983: }
 6984: 
 6985: =pod
 6986: 
 6987: =item check_for_error
 6988: 
 6989:     Checks if there was an error when attempting to remove a specific
 6990:     scantron_.. bubblesheet data file. Prints out an error if
 6991:     something went wrong.
 6992: 
 6993: =cut
 6994: 
 6995: sub check_for_error {
 6996:     my ($r,$result)=@_;
 6997:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6998: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6999:     }
 7000: }
 7001: 
 7002: =pod
 7003: 
 7004: =item scantron_warning_screen
 7005: 
 7006:    Interstitial screen to make sure the operator has selected the
 7007:    correct options before we start the validation phase.
 7008: 
 7009: =cut
 7010: 
 7011: sub scantron_warning_screen {
 7012:     my ($button_text)=@_;
 7013:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7014:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7015:     my $CODElist;
 7016:     if ($scantron_config{'CODElocation'} &&
 7017: 	$scantron_config{'CODEstart'} &&
 7018: 	$scantron_config{'CODElength'}) {
 7019: 	$CODElist=$env{'form.scantron_CODElist'};
 7020: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7021: 	$CODElist=
 7022: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7023: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7024:     }
 7025:     my $lastbubblepoints;
 7026:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7027:         $lastbubblepoints =
 7028:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7029:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7030:     }
 7031:     return ('
 7032: <p>
 7033: <span class="LC_warning">
 7034: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7035: </p>
 7036: <table>
 7037: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7038: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7039: '.$CODElist.$lastbubblepoints.'
 7040: </table>
 7041: <br />
 7042: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 7043: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 7044: 
 7045: <br />
 7046: ');
 7047: }
 7048: 
 7049: =pod
 7050: 
 7051: =item scantron_do_warning
 7052: 
 7053:    Check if the operator has picked something for all required
 7054:    fields. Error out if something is missing.
 7055: 
 7056: =cut
 7057: 
 7058: sub scantron_do_warning {
 7059:     my ($r)=@_;
 7060:     my ($symb)=&get_symb($r);
 7061:     if (!$symb) {return '';}
 7062:     my $default_form_data=&defaultFormData($symb);
 7063:     $r->print(&scantron_form_start().$default_form_data);
 7064:     if ( $env{'form.selectpage'} eq '' ||
 7065: 	 $env{'form.scantron_selectfile'} eq '' ||
 7066: 	 $env{'form.scantron_format'} eq '' ) {
 7067: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7068: 	if ( $env{'form.selectpage'} eq '') {
 7069: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7070: 	} 
 7071: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7072: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7073: 	} 
 7074: 	if ( $env{'form.scantron_format'} eq '') {
 7075: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7076: 	} 
 7077:     } else {
 7078: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 7079:         my $bubbledbyhand=&hand_bubble_option();
 7080: 	$r->print('
 7081: '.$warning.$bubbledbyhand.'
 7082: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7083: <input type="hidden" name="command" value="scantron_validate" />
 7084: ');
 7085:     }
 7086:     $r->print("</form><br />".&show_grading_menu_form($symb));
 7087:     return '';
 7088: }
 7089: 
 7090: =pod
 7091: 
 7092: =item scantron_form_start
 7093: 
 7094:     html hidden input for remembering all selected grading options
 7095: 
 7096: =cut
 7097: 
 7098: sub scantron_form_start {
 7099:     my ($max_bubble)=@_;
 7100:     my $result= <<SCANTRONFORM;
 7101: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7102:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7103:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7104:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7105:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7106:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7107:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7108:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7109:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7110:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7111: SCANTRONFORM
 7112: 
 7113:   my $line = 0;
 7114:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7115:        my $chunk =
 7116: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7117:        $chunk .=
 7118: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7119:        $chunk .= 
 7120:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7121:        $chunk .=
 7122:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7123:        $chunk .=
 7124:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7125:        $result .= $chunk;
 7126:        $line++;
 7127:     }
 7128:     return $result;
 7129: }
 7130: 
 7131: =pod
 7132: 
 7133: =item scantron_validate_file
 7134: 
 7135:     Dispatch routine for doing validation of a bubblesheet data file.
 7136: 
 7137:     Also processes any necessary information resets that need to
 7138:     occur before validation begins (ignore previous corrections,
 7139:     restarting the skipped records processing)
 7140: 
 7141: =cut
 7142: 
 7143: sub scantron_validate_file {
 7144:     my ($r) = @_;
 7145:     my ($symb)=&get_symb($r);
 7146:     if (!$symb) {return '';}
 7147:     my $default_form_data=&defaultFormData($symb);
 7148:     
 7149:     # do the detection of only doing skipped records first before we delete
 7150:     # them when doing the corrections reset
 7151:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7152: 	&reset_skipping_status();
 7153:     }
 7154:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7155: 	&remember_current_skipped();
 7156: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7157:     }
 7158: 
 7159:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7160: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7161: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7162: 	&check_for_error($r,&scantron_remove_scan_data());
 7163: 	$env{'form.scantron_options_ignore'}='done';
 7164:     }
 7165: 
 7166:     if ($env{'form.scantron_corrections'}) {
 7167: 	&scantron_process_corrections($r);
 7168:     }
 7169:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7170:     #get the student pick code ready
 7171:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7172:     my $nav_error;
 7173:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7174:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7175:     if ($nav_error) {
 7176:         $r->print(&navmap_errormsg());
 7177:         return '';
 7178:     }
 7179:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7180:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7181:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7182:     }
 7183:     $r->print($result);
 7184:     
 7185:     my @validate_phases=( 'sequence',
 7186: 			  'ID',
 7187: 			  'CODE',
 7188: 			  'doublebubble',
 7189: 			  'missingbubbles');
 7190:     if (!$env{'form.validatepass'}) {
 7191: 	$env{'form.validatepass'} = 0;
 7192:     }
 7193:     my $currentphase=$env{'form.validatepass'};
 7194: 
 7195: 
 7196:     my $stop=0;
 7197:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7198: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7199: 	$r->rflush();
 7200: 
 7201: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7202: 	{
 7203: 	    no strict 'refs';
 7204: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7205: 	}
 7206:     }
 7207:     if (!$stop) {
 7208: 	my $warning=&scantron_warning_screen('Start Grading');
 7209: 	$r->print(&mt('Validation process complete.').'<br />'.
 7210:                   $warning.
 7211:                   &mt('Perform verification for each student after storage of submissions?').
 7212:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7213:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7214:                   ('&nbsp;'x3).'<label>'.
 7215:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7216:                   '</label></span><br />'.
 7217:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7218:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 7219:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7220:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7221:     } else {
 7222: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7223: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7224:     }
 7225:     if ($stop) {
 7226: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7227: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7228: 	    $r->print(' '.&mt('this error').' <br />');
 7229: 
 7230: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 7231: 	} else {
 7232:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7233: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7234:             } else {
 7235:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7236:             }
 7237: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7238: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7239: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7240: 	}
 7241:     }
 7242:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 7243:     return '';
 7244: }
 7245: 
 7246: 
 7247: =pod
 7248: 
 7249: =item scantron_remove_file
 7250: 
 7251:    Removes the requested bubblesheet data file, makes sure that
 7252:    scantron_original_<filename> is never removed
 7253: 
 7254: 
 7255: =cut
 7256: 
 7257: sub scantron_remove_file {
 7258:     my ($which)=@_;
 7259:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7260:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7261:     my $file='scantron_';
 7262:     if ($which eq 'corrected' || $which eq 'skipped') {
 7263: 	$file.=$which.'_';
 7264:     } else {
 7265: 	return 'refused';
 7266:     }
 7267:     $file.=$env{'form.scantron_selectfile'};
 7268:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7269: }
 7270: 
 7271: 
 7272: =pod
 7273: 
 7274: =item scantron_remove_scan_data
 7275: 
 7276:    Removes all scan_data correction for the requested bubblesheet
 7277:    data file.  (In the case that both the are doing skipped records we need
 7278:    to remember the old skipped lines for the time being so that element
 7279:    persists for a while.)
 7280: 
 7281: =cut
 7282: 
 7283: sub scantron_remove_scan_data {
 7284:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7285:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7286:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7287:     my @todelete;
 7288:     my $filename=$env{'form.scantron_selectfile'};
 7289:     foreach my $key (@keys) {
 7290: 	if ($key=~/^\Q$filename\E_/) {
 7291: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7292: 		$key=~/remember_skipping/) {
 7293: 		next;
 7294: 	    }
 7295: 	    push(@todelete,$key);
 7296: 	}
 7297:     }
 7298:     my $result;
 7299:     if (@todelete) {
 7300: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7301: 				       \@todelete,$cdom,$cname);
 7302:     } else {
 7303: 	$result = 'ok';
 7304:     }
 7305:     return $result;
 7306: }
 7307: 
 7308: 
 7309: =pod
 7310: 
 7311: =item scantron_getfile
 7312: 
 7313:     Fetches the requested bubblesheet data file (all 3 versions), and
 7314:     the scan_data hash
 7315:   
 7316:   Arguments:
 7317:     None
 7318: 
 7319:   Returns:
 7320:     2 hash references
 7321: 
 7322:      - first one has 
 7323:          orig      -
 7324:          corrected -
 7325:          skipped   -  each of which points to an array ref of the specified
 7326:                       file broken up into individual lines
 7327:          count     - number of scanlines
 7328:  
 7329:      - second is the scan_data hash possible keys are
 7330:        ($number refers to scanline numbered $number and thus the key affects
 7331:         only that scanline
 7332:         $bubline refers to the specific bubble line element and the aspects
 7333:         refers to that specific bubble line element)
 7334: 
 7335:        $number.user - username:domain to use
 7336:        $number.CODE_ignore_dup 
 7337:                     - ignore the duplicate CODE error 
 7338:        $number.useCODE
 7339:                     - use the CODE in the scanline as is
 7340:        $number.no_bubble.$bubline
 7341:                     - it is valid that there is no bubbled in bubble
 7342:                       at $number $bubline
 7343:        remember_skipping
 7344:                     - a frozen hash containing keys of $number and values
 7345:                       of either 
 7346:                         1 - we are on a 'do skipped records pass' and plan
 7347:                             on processing this line
 7348:                         2 - we are on a 'do skipped records pass' and this
 7349:                             scanline has been marked to skip yet again
 7350: 
 7351: =cut
 7352: 
 7353: sub scantron_getfile {
 7354:     #FIXME really would prefer a scantron directory
 7355:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7356:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7357:     my $lines;
 7358:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7359: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7360:     my %scanlines;
 7361:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7362:     my $temp=$scanlines{'orig'};
 7363:     $scanlines{'count'}=$#$temp;
 7364: 
 7365:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7366: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7367:     if ($lines eq '-1') {
 7368: 	$scanlines{'corrected'}=[];
 7369:     } else {
 7370: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7371:     }
 7372:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7373: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7374:     if ($lines eq '-1') {
 7375: 	$scanlines{'skipped'}=[];
 7376:     } else {
 7377: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7378:     }
 7379:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7380:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7381:     my %scan_data = @tmp;
 7382:     return (\%scanlines,\%scan_data);
 7383: }
 7384: 
 7385: =pod
 7386: 
 7387: =item lonnet_putfile
 7388: 
 7389:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7390: 
 7391:  Arguments:
 7392:    $contents - data to store
 7393:    $filename - filename to store $contents into
 7394: 
 7395:  Returns:
 7396:    result value from &Apache::lonnet::finishuserfileupload
 7397: 
 7398: =cut
 7399: 
 7400: sub lonnet_putfile {
 7401:     my ($contents,$filename)=@_;
 7402:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7403:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7404:     $env{'form.sillywaytopassafilearound'}=$contents;
 7405:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7406: 
 7407: }
 7408: 
 7409: =pod
 7410: 
 7411: =item scantron_putfile
 7412: 
 7413:     Stores the current version of the bubblesheet data files, and the
 7414:     scan_data hash. (Does not modify the original version only the
 7415:     corrected and skipped versions.
 7416: 
 7417:  Arguments:
 7418:     $scanlines - hash ref that looks like the first return value from
 7419:                  &scantron_getfile()
 7420:     $scan_data - hash ref that looks like the second return value from
 7421:                  &scantron_getfile()
 7422: 
 7423: =cut
 7424: 
 7425: sub scantron_putfile {
 7426:     my ($scanlines,$scan_data) = @_;
 7427:     #FIXME really would prefer a scantron directory
 7428:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7429:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7430:     if ($scanlines) {
 7431: 	my $prefix='scantron_';
 7432: # no need to update orig, shouldn't change
 7433: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7434: #		    $env{'form.scantron_selectfile'});
 7435: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7436: 			$prefix.'corrected_'.
 7437: 			$env{'form.scantron_selectfile'});
 7438: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7439: 			$prefix.'skipped_'.
 7440: 			$env{'form.scantron_selectfile'});
 7441:     }
 7442:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7443: }
 7444: 
 7445: =pod
 7446: 
 7447: =item scantron_get_line
 7448: 
 7449:    Returns the correct version of the scanline
 7450: 
 7451:  Arguments:
 7452:     $scanlines - hash ref that looks like the first return value from
 7453:                  &scantron_getfile()
 7454:     $scan_data - hash ref that looks like the second return value from
 7455:                  &scantron_getfile()
 7456:     $i         - number of the requested line (starts at 0)
 7457: 
 7458:  Returns:
 7459:    A scanline, (either the original or the corrected one if it
 7460:    exists), or undef if the requested scanline should be
 7461:    skipped. (Either because it's an skipped scanline, or it's an
 7462:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7463:    pass.
 7464: 
 7465: =cut
 7466: 
 7467: sub scantron_get_line {
 7468:     my ($scanlines,$scan_data,$i)=@_;
 7469:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7470:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7471:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7472:     return $scanlines->{'orig'}[$i]; 
 7473: }
 7474: 
 7475: =pod
 7476: 
 7477: =item scantron_todo_count
 7478: 
 7479:     Counts the number of scanlines that need processing.
 7480: 
 7481:  Arguments:
 7482:     $scanlines - hash ref that looks like the first return value from
 7483:                  &scantron_getfile()
 7484:     $scan_data - hash ref that looks like the second return value from
 7485:                  &scantron_getfile()
 7486: 
 7487:  Returns:
 7488:     $count - number of scanlines to process
 7489: 
 7490: =cut
 7491: 
 7492: sub get_todo_count {
 7493:     my ($scanlines,$scan_data)=@_;
 7494:     my $count=0;
 7495:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7496: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7497: 	if ($line=~/^[\s\cz]*$/) { next; }
 7498: 	$count++;
 7499:     }
 7500:     return $count;
 7501: }
 7502: 
 7503: =pod
 7504: 
 7505: =item scantron_put_line
 7506: 
 7507:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7508:     data file.
 7509: 
 7510:  Arguments:
 7511:     $scanlines - hash ref that looks like the first return value from
 7512:                  &scantron_getfile()
 7513:     $scan_data - hash ref that looks like the second return value from
 7514:                  &scantron_getfile()
 7515:     $i         - line number to update
 7516:     $newline   - contents of the updated scanline
 7517:     $skip      - if true make the line for skipping and update the
 7518:                  'skipped' file
 7519: 
 7520: =cut
 7521: 
 7522: sub scantron_put_line {
 7523:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7524:     if ($skip) {
 7525: 	$scanlines->{'skipped'}[$i]=$newline;
 7526: 	&start_skipping($scan_data,$i);
 7527: 	return;
 7528:     }
 7529:     $scanlines->{'corrected'}[$i]=$newline;
 7530: }
 7531: 
 7532: =pod
 7533: 
 7534: =item scantron_clear_skip
 7535: 
 7536:    Remove a line from the 'skipped' file
 7537: 
 7538:  Arguments:
 7539:     $scanlines - hash ref that looks like the first return value from
 7540:                  &scantron_getfile()
 7541:     $scan_data - hash ref that looks like the second return value from
 7542:                  &scantron_getfile()
 7543:     $i         - line number to update
 7544: 
 7545: =cut
 7546: 
 7547: sub scantron_clear_skip {
 7548:     my ($scanlines,$scan_data,$i)=@_;
 7549:     if (exists($scanlines->{'skipped'}[$i])) {
 7550: 	undef($scanlines->{'skipped'}[$i]);
 7551: 	return 1;
 7552:     }
 7553:     return 0;
 7554: }
 7555: 
 7556: =pod
 7557: 
 7558: =item scantron_filter_not_exam
 7559: 
 7560:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7561:    filter out resources that are not marked as 'exam' mode
 7562: 
 7563: =cut
 7564: 
 7565: sub scantron_filter_not_exam {
 7566:     my ($curres)=@_;
 7567:     
 7568:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7569: 	# if the user has asked to not have either hidden
 7570: 	# or 'randomout' controlled resources to be graded
 7571: 	# don't include them
 7572: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7573: 	    && $curres->randomout) {
 7574: 	    return 0;
 7575: 	}
 7576: 	return 1;
 7577:     }
 7578:     return 0;
 7579: }
 7580: 
 7581: =pod
 7582: 
 7583: =item scantron_validate_sequence
 7584: 
 7585:     Validates the selected sequence, checking for resource that are
 7586:     not set to exam mode.
 7587: 
 7588: =cut
 7589: 
 7590: sub scantron_validate_sequence {
 7591:     my ($r,$currentphase) = @_;
 7592: 
 7593:     my $navmap=Apache::lonnavmaps::navmap->new();
 7594:     unless (ref($navmap)) {
 7595:         $r->print(&navmap_errormsg());
 7596:         return (1,$currentphase);
 7597:     }
 7598:     my (undef,undef,$sequence)=
 7599: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7600: 
 7601:     my $map=$navmap->getResourceByUrl($sequence);
 7602: 
 7603:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7604:                                     value="ignore" />');
 7605:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7606: 	my @resources=
 7607: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7608: 	if (@resources) {
 7609: 	    $r->print('<p class="LC_warning">'
 7610:                .&mt('Some resources in the sequence currently are not set to'
 7611:                    .' exam mode. Grading these resources currently may not'
 7612:                    .' work correctly.')
 7613:                .'</p>'
 7614:             );
 7615: 	    return (1,$currentphase);
 7616: 	}
 7617:     }
 7618: 
 7619:     return (0,$currentphase+1);
 7620: }
 7621: 
 7622: 
 7623: 
 7624: sub scantron_validate_ID {
 7625:     my ($r,$currentphase) = @_;
 7626:     
 7627:     #get student info
 7628:     my $classlist=&Apache::loncoursedata::get_classlist();
 7629:     my %idmap=&username_to_idmap($classlist);
 7630: 
 7631:     #get scantron line setup
 7632:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7633:     my ($scanlines,$scan_data)=&scantron_getfile();
 7634: 
 7635:     my $nav_error;
 7636:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7637:     if ($nav_error) {
 7638:         $r->print(&navmap_errormsg());
 7639:         return(1,$currentphase);
 7640:     }
 7641: 
 7642:     my %found=('ids'=>{},'usernames'=>{});
 7643:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7644: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7645: 	if ($line=~/^[\s\cz]*$/) { next; }
 7646: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7647: 						 $scan_data);
 7648: 	my $id=$$scan_record{'scantron.ID'};
 7649: 	my $found;
 7650: 	foreach my $checkid (keys(%idmap)) {
 7651: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7652: 	}
 7653: 	if ($found) {
 7654: 	    my $username=$idmap{$found};
 7655: 	    if ($found{'ids'}{$found}) {
 7656: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7657: 					 $line,'duplicateID',$found);
 7658: 		return(1,$currentphase);
 7659: 	    } elsif ($found{'usernames'}{$username}) {
 7660: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7661: 					 $line,'duplicateID',$username);
 7662: 		return(1,$currentphase);
 7663: 	    }
 7664: 	    #FIXME store away line we previously saw the ID on to use above
 7665: 	    $found{'ids'}{$found}++;
 7666: 	    $found{'usernames'}{$username}++;
 7667: 	} else {
 7668: 	    if ($id =~ /^\s*$/) {
 7669: 		my $username=&scan_data($scan_data,"$i.user");
 7670: 		if (defined($username) && $found{'usernames'}{$username}) {
 7671: 		    &scantron_get_correction($r,$i,$scan_record,
 7672: 					     \%scantron_config,
 7673: 					     $line,'duplicateID',$username);
 7674: 		    return(1,$currentphase);
 7675: 		} elsif (!defined($username)) {
 7676: 		    &scantron_get_correction($r,$i,$scan_record,
 7677: 					     \%scantron_config,
 7678: 					     $line,'incorrectID');
 7679: 		    return(1,$currentphase);
 7680: 		}
 7681: 		$found{'usernames'}{$username}++;
 7682: 	    } else {
 7683: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7684: 					 $line,'incorrectID');
 7685: 		return(1,$currentphase);
 7686: 	    }
 7687: 	}
 7688:     }
 7689: 
 7690:     return (0,$currentphase+1);
 7691: }
 7692: 
 7693: 
 7694: sub scantron_get_correction {
 7695:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7696:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7697: #FIXME in the case of a duplicated ID the previous line, probably need
 7698: #to show both the current line and the previous one and allow skipping
 7699: #the previous one or the current one
 7700: 
 7701:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7702:         $r->print(
 7703:             '<p class="LC_warning">'
 7704:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7705:                 "<b>$error</b>",
 7706:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7707:            ."</p> \n");
 7708:     } else {
 7709:         $r->print(
 7710:             '<p class="LC_warning">'
 7711:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7712:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7713:            ."</p> \n");
 7714:     }
 7715:     my $message =
 7716:         '<p>'
 7717:        .&mt('The ID on the form is [_1]',
 7718:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7719:        .'<br />'
 7720:        .&mt('The name on the paper is [_1], [_2]',
 7721:             $$scan_record{'scantron.LastName'},
 7722:             $$scan_record{'scantron.FirstName'})
 7723:        .'</p>';
 7724: 
 7725:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7726:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7727:                            # Array populated for doublebubble or
 7728:     my @lines_to_correct;  # missingbubble errors to build javascript
 7729:                            # to validate radio button checking   
 7730: 
 7731:     if ($error =~ /ID$/) {
 7732: 	if ($error eq 'incorrectID') {
 7733: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7734: 		      "</p>\n");
 7735: 	} elsif ($error eq 'duplicateID') {
 7736: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7737: 	}
 7738: 	$r->print($message);
 7739: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7740: 	$r->print("\n<ul><li> ");
 7741: 	#FIXME it would be nice if this sent back the user ID and
 7742: 	#could do partial userID matches
 7743: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7744: 				       'scantron_username','scantron_domain'));
 7745: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7746: 	$r->print("\n:\n".
 7747: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7748: 
 7749: 	$r->print('</li>');
 7750:     } elsif ($error =~ /CODE$/) {
 7751: 	if ($error eq 'incorrectCODE') {
 7752: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7753: 	} elsif ($error eq 'duplicateCODE') {
 7754: 	    $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");
 7755: 	}
 7756:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7757:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7758:                  ."</p>\n");
 7759: 	$r->print($message);
 7760: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7761: 	$r->print("\n<br /> ");
 7762: 	my $i=0;
 7763: 	if ($error eq 'incorrectCODE' 
 7764: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7765: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7766: 	    if ($closest > 0) {
 7767: 		foreach my $testcode (@{$closest}) {
 7768: 		    my $checked='';
 7769: 		    if (!$i) { $checked=' checked="checked"'; }
 7770: 		    $r->print("
 7771:    <label>
 7772:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7773:        ".&mt("Use the similar CODE [_1] instead.",
 7774: 	    "<b><tt>".$testcode."</tt></b>")."
 7775:     </label>
 7776:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7777: 		    $r->print("\n<br />");
 7778: 		    $i++;
 7779: 		}
 7780: 	    }
 7781: 	}
 7782: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7783: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7784: 	    $r->print("
 7785:     <label>
 7786:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7787:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7788: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7789:     </label>");
 7790: 	    $r->print("\n<br />");
 7791: 	}
 7792: 
 7793: 	$r->print(<<ENDSCRIPT);
 7794: <script type="text/javascript">
 7795: function change_radio(field) {
 7796:     var slct=document.scantronupload.scantron_CODE_resolution;
 7797:     var i;
 7798:     for (i=0;i<slct.length;i++) {
 7799:         if (slct[i].value==field) { slct[i].checked=true; }
 7800:     }
 7801: }
 7802: </script>
 7803: ENDSCRIPT
 7804: 	my $href="/adm/pickcode?".
 7805: 	   "form=".&escape("scantronupload").
 7806: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7807: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7808: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7809: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7810: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7811: 	    $r->print("
 7812:     <label>
 7813:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7814:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7815: 	     "<a target='_blank' href='$href'>","</a>")."
 7816:     </label> 
 7817:     ".&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\')" />'));
 7818: 	    $r->print("\n<br />");
 7819: 	}
 7820: 	$r->print("
 7821:     <label>
 7822:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7823:        ".&mt("Use [_1] as the CODE.",
 7824: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7825: 	$r->print("\n<br /><br />");
 7826:     } elsif ($error eq 'doublebubble') {
 7827: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7828: 
 7829: 	# The form field scantron_questions is acutally a list of line numbers.
 7830: 	# represented by this form so:
 7831: 
 7832: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7833:                                                 $respnumlookup,$startline);
 7834: 
 7835: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7836: 		  $line_list.'" />');
 7837: 	$r->print($message);
 7838: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7839: 	foreach my $question (@{$arg}) {
 7840: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7841:                                                    $scan_record, $error,
 7842:                                                    $randomorder,$randompick,
 7843:                                                    $respnumlookup,$startline);
 7844:             push(@lines_to_correct,@linenums);
 7845: 	}
 7846:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7847:     } elsif ($error eq 'missingbubble') {
 7848: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7849: 	$r->print($message);
 7850: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7851: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7852: 
 7853: 	# The form field scantron_questions is actually a list of line numbers not
 7854: 	# a list of question numbers. Therefore:
 7855: 	#
 7856: 	
 7857: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7858:                                                 $respnumlookup,$startline);
 7859: 
 7860: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7861: 		  $line_list.'" />');
 7862: 	foreach my $question (@{$arg}) {
 7863: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7864:                                                    $scan_record, $error,
 7865:                                                    $randomorder,$randompick,
 7866:                                                    $respnumlookup,$startline);
 7867:             push(@lines_to_correct,@linenums);
 7868: 	}
 7869:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7870:     } else {
 7871: 	$r->print("\n<ul>");
 7872:     }
 7873:     $r->print("\n</li></ul>");
 7874: }
 7875: 
 7876: sub verify_bubbles_checked {
 7877:     my (@ansnums) = @_;
 7878:     my $ansnumstr = join('","',@ansnums);
 7879:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7880:     &js_escape(\$warning);
 7881:     my $output = (<<ENDSCRIPT);
 7882: <script type="text/javascript">
 7883: function verify_bubble_radio(form) {
 7884:     var ansnumArray = new Array ("$ansnumstr");
 7885:     var need_bubble_count = 0;
 7886:     for (var i=0; i<ansnumArray.length; i++) {
 7887:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7888:             var bubble_picked = 0; 
 7889:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7890:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7891:                     bubble_picked = 1;
 7892:                 }
 7893:             }
 7894:             if (bubble_picked == 0) {
 7895:                 need_bubble_count ++;
 7896:             }
 7897:         }
 7898:     }
 7899:     if (need_bubble_count) {
 7900:         alert("$warning");
 7901:         return;
 7902:     }
 7903:     form.submit(); 
 7904: }
 7905: </script>
 7906: ENDSCRIPT
 7907:     return $output;
 7908: }
 7909: 
 7910: =pod
 7911: 
 7912: =item  questions_to_line_list
 7913: 
 7914: Converts a list of questions into a string of comma separated
 7915: line numbers in the answer sheet used by the questions.  This is
 7916: used to fill in the scantron_questions form field.
 7917: 
 7918:   Arguments:
 7919:      questions    - Reference to an array of questions.
 7920:      randomorder  - True if randomorder in use.
 7921:      randompick   - True if randompick in use.
 7922:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7923:                      for current line to question number used for same question
 7924:                      in "Master Seqence" (as seen by Course Coordinator).
 7925:      startline    - Reference to hash where key is question number (0 is first)
 7926:                     and key is number of first bubble line for current student
 7927:                     or code-based randompick and/or randomorder.
 7928: 
 7929: =cut
 7930: 
 7931: 
 7932: sub questions_to_line_list {
 7933:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7934:     my @lines;
 7935: 
 7936:     foreach my $item (@{$questions}) {
 7937:         my $question = $item;
 7938:         my ($first,$count,$last);
 7939:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7940:             $question = $1;
 7941:             my $subquestion = $2;
 7942:             my $responsenum = $question-1;
 7943:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7944:                 $responsenum = $respnumlookup->{$question-1};
 7945:                 if (ref($startline) eq 'HASH') {
 7946:                     $first = $startline->{$question-1} + 1;
 7947:                 }
 7948:             } else {
 7949:                 $first = $first_bubble_line{$responsenum} + 1;
 7950:             }
 7951:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7952:             my $subcount = 1;
 7953:             while ($subcount<$subquestion) {
 7954:                 $first += $subans[$subcount-1];
 7955:                 $subcount ++;
 7956:             }
 7957:             $count = $subans[$subquestion-1];
 7958:         } else {
 7959:             my $responsenum = $question-1;
 7960:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7961:                 $responsenum = $respnumlookup->{$question-1};
 7962:                 if (ref($startline) eq 'HASH') {
 7963:                     $first = $startline->{$question-1} + 1;
 7964:                 }
 7965:             } else {
 7966:                 $first = $first_bubble_line{$responsenum} + 1;
 7967:             }
 7968:             $count   = $bubble_lines_per_response{$responsenum};
 7969:         }
 7970:         $last = $first+$count-1;
 7971:         push(@lines, ($first..$last));
 7972:     }
 7973:     return join(',', @lines);
 7974: }
 7975: 
 7976: =pod 
 7977: 
 7978: =item prompt_for_corrections
 7979: 
 7980: Prompts for a potentially multiline correction to the
 7981: user's bubbling (factors out common code from scantron_get_correction
 7982: for multi and missing bubble cases).
 7983: 
 7984:  Arguments:
 7985:    $r           - Apache request object.
 7986:    $question    - The question number to prompt for.
 7987:    $scan_config - The scantron file configuration hash.
 7988:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7989:    $error       - Type of error
 7990:    $randomorder - True if randomorder in use.
 7991:    $randompick  - True if randompick in use.
 7992:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7993:                     for current line to question number used for same question
 7994:                     in "Master Seqence" (as seen by Course Coordinator).
 7995:    $startline   - Reference to hash where key is question number (0 is first)
 7996:                   and value is number of first bubble line for current student
 7997:                   or code-based randompick and/or randomorder.
 7998: 
 7999:  Implicit inputs:
 8000:    %bubble_lines_per_response   - Starting line numbers for each question.
 8001:                                   Numbered from 0 (but question numbers are from
 8002:                                   1.
 8003:    %first_bubble_line           - Starting bubble line for each question.
 8004:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8005:                                   type problems render as separate sub-questions, 
 8006:                                   in exam mode. This hash contains a 
 8007:                                   comma-separated list of the lines per 
 8008:                                   sub-question.
 8009:    %responsetype_per_response   - essayresponse, formularesponse,
 8010:                                   stringresponse, imageresponse, reactionresponse,
 8011:                                   and organicresponse type problem parts can have
 8012:                                   multiple lines per response if the weight
 8013:                                   assigned exceeds 10.  In this case, only
 8014:                                   one bubble per line is permitted, but more 
 8015:                                   than one line might contain bubbles, e.g.
 8016:                                   bubbling of: line 1 - J, line 2 - J, 
 8017:                                   line 3 - B would assign 22 points.  
 8018: 
 8019: =cut
 8020: 
 8021: sub prompt_for_corrections {
 8022:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8023:         $randompick, $respnumlookup, $startline) = @_;
 8024:     my ($current_line,$lines);
 8025:     my @linenums;
 8026:     my $questionnum = $question;
 8027:     my ($first,$responsenum);
 8028:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8029:         $question = $1;
 8030:         my $subquestion = $2;
 8031:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8032:             $responsenum = $respnumlookup->{$question-1};
 8033:             if (ref($startline) eq 'HASH') {
 8034:                 $first = $startline->{$question-1};
 8035:             }
 8036:         } else {
 8037:             $responsenum = $question-1;
 8038:             $first = $first_bubble_line{$responsenum};
 8039:         }
 8040:         $current_line = $first + 1 ;
 8041:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8042:         my $subcount = 1;
 8043:         while ($subcount<$subquestion) {
 8044:             $current_line += $subans[$subcount-1];
 8045:             $subcount ++;
 8046:         }
 8047:         $lines = $subans[$subquestion-1];
 8048:     } else {
 8049:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8050:             $responsenum = $respnumlookup->{$question-1};
 8051:             if (ref($startline) eq 'HASH') {
 8052:                 $first = $startline->{$question-1};
 8053:             }
 8054:         } else {
 8055:             $responsenum = $question-1;
 8056:             $first = $first_bubble_line{$responsenum};
 8057:         }
 8058:         $current_line = $first + 1;
 8059:         $lines        = $bubble_lines_per_response{$responsenum};
 8060:     }
 8061:     if ($lines > 1) {
 8062:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8063:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8064:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8065:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8066:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8067:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8068:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8069:             $r->print(&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).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&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.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 8070:         } else {
 8071:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8072:         }
 8073:     }
 8074:     for (my $i =0; $i < $lines; $i++) {
 8075:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8076: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8077: 	        		  $questionnum,$error,split('', $selected));
 8078:         push(@linenums,$current_line);
 8079: 	$current_line++;
 8080:     }
 8081:     if ($lines > 1) {
 8082: 	$r->print("<hr /><br />");
 8083:     }
 8084:     return @linenums;
 8085: }
 8086: 
 8087: =pod
 8088: 
 8089: =item scantron_bubble_selector
 8090:   
 8091:    Generates the html radiobuttons to correct a single bubble line
 8092:    possibly showing the existing the selected bubbles if known
 8093: 
 8094:  Arguments:
 8095:     $r           - Apache request object
 8096:     $scan_config - hash from &get_scantron_config()
 8097:     $line        - Number of the line being displayed.
 8098:     $questionnum - Question number (may include subquestion)
 8099:     $error       - Type of error.
 8100:     @selected    - Array of bubbles picked on this line.
 8101: 
 8102: =cut
 8103: 
 8104: sub scantron_bubble_selector {
 8105:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8106:     my $max=$$scan_config{'Qlength'};
 8107: 
 8108:     my $scmode=$$scan_config{'Qon'};
 8109:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8110:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8111:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8112:             $max=$$scan_config{'BubblesPerRow'};
 8113:             if (($scmode eq 'number') && ($max > 10)) {
 8114:                 $max = 10;
 8115:             } elsif (($scmode eq 'letter') && $max > 26) {
 8116:                 $max = 26;
 8117:             }
 8118:         } else {
 8119:             $max = 10;
 8120:         }
 8121:     }
 8122: 
 8123:     my @alphabet=('A'..'Z');
 8124:     $r->print(&Apache::loncommon::start_data_table().
 8125:               &Apache::loncommon::start_data_table_row());
 8126:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8127:     for (my $i=0;$i<$max+1;$i++) {
 8128: 	$r->print("\n".'<td align="center">');
 8129: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8130: 	else { $r->print('&nbsp;'); }
 8131: 	$r->print('</td>');
 8132:     }
 8133:     $r->print(&Apache::loncommon::end_data_table_row().
 8134:               &Apache::loncommon::start_data_table_row());
 8135:     for (my $i=0;$i<$max;$i++) {
 8136: 	$r->print("\n".
 8137: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8138: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8139:     }
 8140:     my $nobub_checked = ' ';
 8141:     if ($error eq 'missingbubble') {
 8142:         $nobub_checked = ' checked = "checked" ';
 8143:     }
 8144:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8145: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8146:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8147:               $line.'" value="'.$questionnum.'" /></td>');
 8148:     $r->print(&Apache::loncommon::end_data_table_row().
 8149:               &Apache::loncommon::end_data_table());
 8150: }
 8151: 
 8152: =pod
 8153: 
 8154: =item num_matches
 8155: 
 8156:    Counts the number of characters that are the same between the two arguments.
 8157: 
 8158:  Arguments:
 8159:    $orig - CODE from the scanline
 8160:    $code - CODE to match against
 8161: 
 8162:  Returns:
 8163:    $count - integer count of the number of same characters between the
 8164:             two arguments
 8165: 
 8166: =cut
 8167: 
 8168: sub num_matches {
 8169:     my ($orig,$code) = @_;
 8170:     my @code=split(//,$code);
 8171:     my @orig=split(//,$orig);
 8172:     my $same=0;
 8173:     for (my $i=0;$i<scalar(@code);$i++) {
 8174: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8175:     }
 8176:     return $same;
 8177: }
 8178: 
 8179: =pod
 8180: 
 8181: =item scantron_get_closely_matching_CODEs
 8182: 
 8183:    Cycles through all CODEs and finds the set that has the greatest
 8184:    number of same characters as the provided CODE
 8185: 
 8186:  Arguments:
 8187:    $allcodes - hash ref returned by &get_codes()
 8188:    $CODE     - CODE from the current scanline
 8189: 
 8190:  Returns:
 8191:    2 element list
 8192:     - first elements is number of how closely matching the best fit is 
 8193:       (5 means best set has 5 matching characters)
 8194:     - second element is an arrary ref containing the set of valid CODEs
 8195:       that best fit the passed in CODE
 8196: 
 8197: =cut
 8198: 
 8199: sub scantron_get_closely_matching_CODEs {
 8200:     my ($allcodes,$CODE)=@_;
 8201:     my @CODEs;
 8202:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8203: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8204:     }
 8205: 
 8206:     return ($#CODEs,$CODEs[-1]);
 8207: }
 8208: 
 8209: =pod
 8210: 
 8211: =item get_codes
 8212: 
 8213:    Builds a hash which has keys of all of the valid CODEs from the selected
 8214:    set of remembered CODEs.
 8215: 
 8216:  Arguments:
 8217:   $old_name - name of the set of remembered CODEs
 8218:   $cdom     - domain of the course
 8219:   $cnum     - internal course name
 8220: 
 8221:  Returns:
 8222:   %allcodes - keys are the valid CODEs, values are all 1
 8223: 
 8224: =cut
 8225: 
 8226: sub get_codes {
 8227:     my ($old_name, $cdom, $cnum) = @_;
 8228:     if (!$old_name) {
 8229: 	$old_name=$env{'form.scantron_CODElist'};
 8230:     }
 8231:     if (!$cdom) {
 8232: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8233:     }
 8234:     if (!$cnum) {
 8235: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8236:     }
 8237:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8238: 				    $cdom,$cnum);
 8239:     my %allcodes;
 8240:     if ($result{"type\0$old_name"} eq 'number') {
 8241: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8242:     } else {
 8243: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8244:     }
 8245:     return %allcodes;
 8246: }
 8247: 
 8248: =pod
 8249: 
 8250: =item scantron_validate_CODE
 8251: 
 8252:    Validates all scanlines in the selected file to not have any
 8253:    invalid or underspecified CODEs and that none of the codes are
 8254:    duplicated if this was requested.
 8255: 
 8256: =cut
 8257: 
 8258: sub scantron_validate_CODE {
 8259:     my ($r,$currentphase) = @_;
 8260:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8261:     if ($scantron_config{'CODElocation'} &&
 8262: 	$scantron_config{'CODEstart'} &&
 8263: 	$scantron_config{'CODElength'}) {
 8264: 	if (!defined($env{'form.scantron_CODElist'})) {
 8265: 	    &FIXME_blow_up()
 8266: 	}
 8267:     } else {
 8268: 	return (0,$currentphase+1);
 8269:     }
 8270:     
 8271:     my %usedCODEs;
 8272: 
 8273:     my %allcodes=&get_codes();
 8274: 
 8275:     my $nav_error;
 8276:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8277:     if ($nav_error) {
 8278:         $r->print(&navmap_errormsg());
 8279:         return(1,$currentphase);
 8280:     }
 8281: 
 8282:     my ($scanlines,$scan_data)=&scantron_getfile();
 8283:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8284: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8285: 	if ($line=~/^[\s\cz]*$/) { next; }
 8286: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8287: 						 $scan_data);
 8288: 	my $CODE=$$scan_record{'scantron.CODE'};
 8289: 	my $error=0;
 8290: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8291: 	    &scantron_get_correction($r,$i,$scan_record,
 8292: 				     \%scantron_config,
 8293: 				     $line,'incorrectCODE',\%allcodes);
 8294: 	    return(1,$currentphase);
 8295: 	}
 8296: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8297: 	    && !$$scan_record{'scantron.useCODE'}) {
 8298: 	    &scantron_get_correction($r,$i,$scan_record,
 8299: 				     \%scantron_config,
 8300: 				     $line,'incorrectCODE',\%allcodes);
 8301: 	    return(1,$currentphase);
 8302: 	}
 8303: 	if (exists($usedCODEs{$CODE}) 
 8304: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8305: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8306: 	    &scantron_get_correction($r,$i,$scan_record,
 8307: 				     \%scantron_config,
 8308: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8309: 	    return(1,$currentphase);
 8310: 	}
 8311: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8312:     }
 8313:     return (0,$currentphase+1);
 8314: }
 8315: 
 8316: =pod
 8317: 
 8318: =item scantron_validate_doublebubble
 8319: 
 8320:    Validates all scanlines in the selected file to not have any
 8321:    bubble lines with multiple bubbles marked.
 8322: 
 8323: =cut
 8324: 
 8325: sub scantron_validate_doublebubble {
 8326:     my ($r,$currentphase) = @_;
 8327:     #get student info
 8328:     my $classlist=&Apache::loncoursedata::get_classlist();
 8329:     my %idmap=&username_to_idmap($classlist);
 8330:     my (undef,undef,$sequence)=
 8331:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8332: 
 8333:     #get scantron line setup
 8334:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8335:     my ($scanlines,$scan_data)=&scantron_getfile();
 8336: 
 8337:     my $navmap = Apache::lonnavmaps::navmap->new();
 8338:     unless (ref($navmap)) {
 8339:         $r->print(&navmap_errormsg());
 8340:         return(1,$currentphase);
 8341:     }
 8342:     my $map=$navmap->getResourceByUrl($sequence);
 8343:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8344:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8345:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8346:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8347: 
 8348:     my $nav_error;
 8349:     if (ref($map)) {
 8350:         $randomorder = $map->randomorder();
 8351:         $randompick = $map->randompick();
 8352:         if ($randomorder || $randompick) {
 8353:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8354:             if ($nav_error) {
 8355:                 $r->print(&navmap_errormsg());
 8356:                 return(1,$currentphase);
 8357:             }
 8358:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8359:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8360:         }
 8361:     } else {
 8362:         $r->print(&navmap_errormsg());
 8363:         return(1,$currentphase);
 8364:     }
 8365: 
 8366:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8367:     if ($nav_error) {
 8368:         $r->print(&navmap_errormsg());
 8369:         return(1,$currentphase);
 8370:     }
 8371: 
 8372:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8373: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8374: 	if ($line=~/^[\s\cz]*$/) { next; }
 8375: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8376: 						 $scan_data,undef,\%idmap,$randomorder,
 8377:                                                  $randompick,$sequence,\@master_seq,
 8378:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8379:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8380: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8381: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8382: 				 'doublebubble',
 8383: 				 $$scan_record{'scantron.doubleerror'},
 8384:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8385:     	return (1,$currentphase);
 8386:     }
 8387:     return (0,$currentphase+1);
 8388: }
 8389: 
 8390: 
 8391: sub scantron_get_maxbubble {
 8392:     my ($nav_error,$scantron_config) = @_;
 8393:     if (defined($env{'form.scantron_maxbubble'}) &&
 8394: 	$env{'form.scantron_maxbubble'}) {
 8395: 	&restore_bubble_lines();
 8396: 	return $env{'form.scantron_maxbubble'};
 8397:     }
 8398: 
 8399:     my (undef, undef, $sequence) =
 8400: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8401: 
 8402:     my $navmap=Apache::lonnavmaps::navmap->new();
 8403:     unless (ref($navmap)) {
 8404:         if (ref($nav_error)) {
 8405:             $$nav_error = 1;
 8406:         }
 8407:         return;
 8408:     }
 8409:     my $map=$navmap->getResourceByUrl($sequence);
 8410:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8411:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8412: 
 8413:     &Apache::lonxml::clear_problem_counter();
 8414: 
 8415:     my $uname       = $env{'user.name'};
 8416:     my $udom        = $env{'user.domain'};
 8417:     my $cid         = $env{'request.course.id'};
 8418:     my $total_lines = 0;
 8419:     %bubble_lines_per_response = ();
 8420:     %first_bubble_line         = ();
 8421:     %subdivided_bubble_lines   = ();
 8422:     %responsetype_per_response = ();
 8423:     %masterseq_id_responsenum  = ();
 8424: 
 8425:     my $response_number = 0;
 8426:     my $bubble_line     = 0;
 8427:     foreach my $resource (@resources) {
 8428:         my $resid = $resource->id();
 8429:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8430:                                                           $udom,undef,$bubbles_per_row);
 8431:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8432: 	    foreach my $part_id (@{$parts}) {
 8433:                 my $lines;
 8434: 
 8435: 	        # TODO - make this a persistent hash not an array.
 8436: 
 8437:                 # optionresponse, matchresponse and rankresponse type items 
 8438:                 # render as separate sub-questions in exam mode.
 8439:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8440:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8441:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8442:                     my ($numbub,$numshown);
 8443:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8444:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8445:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8446:                         }
 8447:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8448:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8449:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8450:                         }
 8451:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8452:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8453:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8454:                         }
 8455:                     }
 8456:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8457:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8458:                     }
 8459:                     my $bubbles_per_row =
 8460:                         &bubblesheet_bubbles_per_row($scantron_config);
 8461:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8462:                     if (($numbub % $bubbles_per_row) != 0) {
 8463:                         $inner_bubble_lines++;
 8464:                     }
 8465:                     for (my $i=0; $i<$numshown; $i++) {
 8466:                         $subdivided_bubble_lines{$response_number} .= 
 8467:                             $inner_bubble_lines.',';
 8468:                     }
 8469:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8470:                     $lines = $numshown * $inner_bubble_lines;
 8471:                 } else {
 8472:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8473:                 }
 8474: 
 8475:                 $first_bubble_line{$response_number} = $bubble_line;
 8476: 	        $bubble_lines_per_response{$response_number} = $lines;
 8477:                 $responsetype_per_response{$response_number} = 
 8478:                     $analysis->{$part_id.'.type'};
 8479:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8480: 	        $response_number++;
 8481: 
 8482: 	        $bubble_line +=  $lines;
 8483: 	        $total_lines +=  $lines;
 8484: 	    }
 8485:         }
 8486:     }
 8487:     &Apache::lonnet::delenv('scantron.');
 8488: 
 8489:     &save_bubble_lines();
 8490:     $env{'form.scantron_maxbubble'} =
 8491: 	$total_lines;
 8492:     return $env{'form.scantron_maxbubble'};
 8493: }
 8494: 
 8495: sub bubblesheet_bubbles_per_row {
 8496:     my ($scantron_config) = @_;
 8497:     my $bubbles_per_row;
 8498:     if (ref($scantron_config) eq 'HASH') {
 8499:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8500:     }
 8501:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8502:         $bubbles_per_row = 10;
 8503:     }
 8504:     return $bubbles_per_row;
 8505: }
 8506: 
 8507: sub scantron_validate_missingbubbles {
 8508:     my ($r,$currentphase) = @_;
 8509:     #get student info
 8510:     my $classlist=&Apache::loncoursedata::get_classlist();
 8511:     my %idmap=&username_to_idmap($classlist);
 8512:     my (undef,undef,$sequence)=
 8513:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8514: 
 8515:     #get scantron line setup
 8516:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8517:     my ($scanlines,$scan_data)=&scantron_getfile();
 8518: 
 8519:     my $navmap = Apache::lonnavmaps::navmap->new();
 8520:     unless (ref($navmap)) {
 8521:         $r->print(&navmap_errormsg());
 8522:         return(1,$currentphase);
 8523:     }
 8524: 
 8525:     my $map=$navmap->getResourceByUrl($sequence);
 8526:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8527:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8528:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8529:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8530: 
 8531:     my $nav_error;
 8532:     if (ref($map)) {
 8533:         $randomorder = $map->randomorder();
 8534:         $randompick = $map->randompick();
 8535:         if ($randomorder || $randompick) {
 8536:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8537:             if ($nav_error) {
 8538:                 $r->print(&navmap_errormsg());
 8539:                 return(1,$currentphase);
 8540:             }
 8541:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8542:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8543:         }
 8544:     } else {
 8545:         $r->print(&navmap_errormsg());
 8546:         return(1,$currentphase);
 8547:     }
 8548: 
 8549: 
 8550:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8551:     if ($nav_error) {
 8552:         $r->print(&navmap_errormsg());
 8553:         return(1,$currentphase);
 8554:     }
 8555: 
 8556:     if (!$max_bubble) { $max_bubble=2**31; }
 8557:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8558: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8559: 	if ($line=~/^[\s\cz]*$/) { next; }
 8560:         my $scan_record =
 8561:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8562:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8563:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8564:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8565: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8566: 	my @to_correct;
 8567: 	
 8568: 	# Probably here's where the error is...
 8569: 
 8570: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8571:             my $lastbubble;
 8572:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8573:                 my $question = $1;
 8574:                 my $subquestion = $2;
 8575:                 my ($first,$responsenum);
 8576:                 if ($randomorder || $randompick) {
 8577:                     $responsenum = $respnumlookup{$question-1};
 8578:                     $first = $startline{$question-1};
 8579:                 } else {
 8580:                     $responsenum = $question-1;
 8581:                     $first = $first_bubble_line{$responsenum};
 8582:                 }
 8583:                 if (!defined($first)) { next; }
 8584:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8585:                 my $subcount = 1;
 8586:                 while ($subcount<$subquestion) {
 8587:                     $first += $subans[$subcount-1];
 8588:                     $subcount ++;
 8589:                 }
 8590:                 my $count = $subans[$subquestion-1];
 8591:                 $lastbubble = $first + $count;
 8592:             } else {
 8593:                 my ($first,$responsenum);
 8594:                 if ($randomorder || $randompick) {
 8595:                     $responsenum = $respnumlookup{$missing-1};
 8596:                     $first = $startline{$missing-1};
 8597:                 } else {
 8598:                     $responsenum = $missing-1;
 8599:                     $first = $first_bubble_line{$responsenum};
 8600:                 }
 8601:                 if (!defined($first)) { next; }
 8602:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8603:             }
 8604:             if ($lastbubble > $max_bubble) { next; }
 8605: 	    push(@to_correct,$missing);
 8606: 	}
 8607: 	if (@to_correct) {
 8608: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8609: 				     $line,'missingbubble',\@to_correct,
 8610:                                      $randomorder,$randompick,\%respnumlookup,
 8611:                                      \%startline);
 8612: 	    return (1,$currentphase);
 8613: 	}
 8614: 
 8615:     }
 8616:     return (0,$currentphase+1);
 8617: }
 8618: 
 8619: sub hand_bubble_option {
 8620:     my (undef, undef, $sequence) =
 8621:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8622:     return if ($sequence eq '');
 8623:     my $navmap = Apache::lonnavmaps::navmap->new();
 8624:     unless (ref($navmap)) {
 8625:         return;
 8626:     }
 8627:     my $needs_hand_bubbles;
 8628:     my $map=$navmap->getResourceByUrl($sequence);
 8629:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8630:     foreach my $res (@resources) {
 8631:         if (ref($res)) {
 8632:             if ($res->is_problem()) {
 8633:                 my $partlist = $res->parts();
 8634:                 foreach my $part (@{ $partlist }) {
 8635:                     my @types = $res->responseType($part);
 8636:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8637:                         $needs_hand_bubbles = 1;
 8638:                         last;
 8639:                     }
 8640:                 }
 8641:             }
 8642:         }
 8643:     }
 8644:     if ($needs_hand_bubbles) {
 8645:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8646:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8647:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8648:                &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 />').
 8649:                '<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;'.
 8650:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8651:     }
 8652:     return;
 8653: }
 8654: 
 8655: sub scantron_process_students {
 8656:     my ($r) = @_;
 8657: 
 8658:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8659:     my ($symb)=&get_symb($r);
 8660:     if (!$symb) {
 8661: 	return '';
 8662:     }
 8663:     my $default_form_data=&defaultFormData($symb);
 8664: 
 8665:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8666:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8667:     my ($scanlines,$scan_data)=&scantron_getfile();
 8668:     my $classlist=&Apache::loncoursedata::get_classlist();
 8669:     my %idmap=&username_to_idmap($classlist);
 8670:     my $navmap=Apache::lonnavmaps::navmap->new();
 8671:     unless (ref($navmap)) {
 8672:         $r->print(&navmap_errormsg());
 8673:         return '';
 8674:     }
 8675:     my $map=$navmap->getResourceByUrl($sequence);
 8676:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8677:         %grader_randomlists_by_symb);
 8678:     if (ref($map)) {
 8679:         $randomorder = $map->randomorder();
 8680:         $randompick = $map->randompick();
 8681:     } else {
 8682:         $r->print(&navmap_errormsg());
 8683:         return '';
 8684:     }
 8685:     my $nav_error;
 8686:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8687:     if ($randomorder || $randompick) {
 8688:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8689:         if ($nav_error) {
 8690:             $r->print(&navmap_errormsg());
 8691:             return '';
 8692:         }
 8693:     }
 8694:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8695:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8696: 
 8697:     my ($uname,$udom);
 8698:     my $result= <<SCANTRONFORM;
 8699: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8700:   <input type="hidden" name="command" value="scantron_configphase" />
 8701:   $default_form_data
 8702: SCANTRONFORM
 8703:     $r->print($result);
 8704: 
 8705:     my @delayqueue;
 8706:     my (%completedstudents,%scandata);
 8707:     
 8708:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8709:     my $count=&get_todo_count($scanlines,$scan_data);
 8710:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8711:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8712: 					  'Processing first student');
 8713:     $r->print('<br />');
 8714:     my $start=&Time::HiRes::time();
 8715:     my $i=-1;
 8716:     my $started;
 8717: 
 8718:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8719:     if ($nav_error) {
 8720:         $r->print(&navmap_errormsg());
 8721:         return '';
 8722:     }
 8723: 
 8724:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8725:     # the user and return.
 8726: 
 8727:     if ($ssi_error) {
 8728: 	$r->print("</form>");
 8729: 	&ssi_print_error($r);
 8730: 	$r->print(&show_grading_menu_form($symb));
 8731:         &Apache::lonnet::remove_lock($lock);
 8732: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8733:     }
 8734: 
 8735:     my %lettdig = &letter_to_digits();
 8736:     my $numletts = scalar(keys(%lettdig));
 8737:     my %orderedforcode;
 8738: 
 8739:     while ($i<$scanlines->{'count'}) {
 8740:  	($uname,$udom)=('','');
 8741:  	$i++;
 8742:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8743:  	if ($line=~/^[\s\cz]*$/) { next; }
 8744: 	if ($started) {
 8745: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8746: 						     'last student');
 8747: 	}
 8748: 	$started=1;
 8749:         my %respnumlookup = ();
 8750:         my %startline = ();
 8751:         my $total;
 8752:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8753:  						 $scan_data,undef,\%idmap,$randomorder,
 8754:                                                  $randompick,$sequence,\@master_seq,
 8755:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8756:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8757:                                                  \$total);
 8758:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8759:  					      \%idmap,$i)) {
 8760:   	    &scantron_add_delay(\@delayqueue,$line,
 8761:  				'Unable to find a student that matches',1);
 8762:  	    next;
 8763:   	}
 8764:  	if (exists $completedstudents{$uname}) {
 8765:  	    &scantron_add_delay(\@delayqueue,$line,
 8766:  				'Student '.$uname.' has multiple sheets',2);
 8767:  	    next;
 8768:  	}
 8769:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8770:         my $user = $uname.':'.$usec;
 8771:   	($uname,$udom)=split(/:/,$uname);
 8772: 
 8773:         my $scancode;
 8774:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8775:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8776:             $scancode = $scan_record->{'scantron.CODE'};
 8777:         } else {
 8778:             $scancode = '';
 8779:         }
 8780: 
 8781:         my @mapresources = @resources;
 8782:         if ($randomorder || $randompick) {
 8783:             @mapresources =
 8784:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8785:                              \%orderedforcode);
 8786:         }
 8787:         my (%partids_by_symb,$res_error);
 8788:         foreach my $resource (@mapresources) {
 8789:             my $ressymb;
 8790:             if (ref($resource)) {
 8791:                 $ressymb = $resource->symb();
 8792:             } else {
 8793:                 $res_error = 1;
 8794:                 last;
 8795:             }
 8796:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8797:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8798:                 my $currcode;
 8799:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8800:                     $currcode = $scancode;
 8801:                 }
 8802:                 my ($analysis,$parts) =
 8803:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8804:                                               $uname,$udom,undef,$bubbles_per_row,
 8805:                                               $currcode);
 8806:                 $partids_by_symb{$ressymb} = $parts;
 8807:             } else {
 8808:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8809:             }
 8810:         }
 8811: 
 8812:         if ($res_error) {
 8813:             &scantron_add_delay(\@delayqueue,$line,
 8814:                                 'An error occurred while grading student '.$uname,2);
 8815:             next;
 8816:         }
 8817: 
 8818: 	&Apache::lonxml::clear_problem_counter();
 8819:   	&Apache::lonnet::appenv($scan_record);
 8820: 
 8821: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8822: 	    &scantron_putfile($scanlines,$scan_data);
 8823: 	}
 8824: 	
 8825:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8826:                                    \@mapresources,\%partids_by_symb,
 8827:                                    $bubbles_per_row,$randomorder,$randompick,
 8828:                                    \%respnumlookup,\%startline) 
 8829:             eq 'ssi_error') {
 8830:             $ssi_error = 0; # So end of handler error message does not trigger.
 8831:             $r->print("</form>");
 8832:             &ssi_print_error($r);
 8833:             $r->print(&show_grading_menu_form($symb));
 8834:             &Apache::lonnet::remove_lock($lock);
 8835:             return '';      # Why return ''?  Beats me.
 8836:         }
 8837: 
 8838:         if (($scancode) && ($randomorder || $randompick)) {
 8839:             my $parmresult =
 8840:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8841:                                                        '0_examcode',2,$scancode,
 8842:                                                        'string_examcode',$uname,
 8843:                                                        $udom);
 8844:         }
 8845: 	$completedstudents{$uname}={'line'=>$line};
 8846:         if ($env{'form.verifyrecord'}) {
 8847:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8848:             if ($randompick) {
 8849:                 if ($total) {
 8850:                     $lastpos = $total*$scantron_config{'Qlength'};
 8851:                 }
 8852:             }
 8853: 
 8854:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8855:             chomp($studentdata);
 8856:             $studentdata =~ s/\r$//;
 8857:             my $studentrecord = '';
 8858:             my $counter = -1;
 8859:             foreach my $resource (@mapresources) {
 8860:                 my $ressymb = $resource->symb();
 8861:                 ($counter,my $recording) =
 8862:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8863:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8864:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8865:                                              $randompick,\%respnumlookup,\%startline);
 8866:                 $studentrecord .= $recording;
 8867:             }
 8868:             if ($studentrecord ne $studentdata) {
 8869:                 &Apache::lonxml::clear_problem_counter();
 8870:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8871:                                            \@mapresources,\%partids_by_symb,
 8872:                                            $bubbles_per_row,$randomorder,$randompick,
 8873:                                            \%respnumlookup,\%startline)
 8874:                     eq 'ssi_error') {
 8875:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8876:                     $r->print("</form>");
 8877:                     &ssi_print_error($r);
 8878:                     $r->print(&show_grading_menu_form($symb));
 8879:                     &Apache::lonnet::remove_lock($lock);
 8880:                     delete($completedstudents{$uname});
 8881:                     return '';
 8882:                 }
 8883:                 $counter = -1;
 8884:                 $studentrecord = '';
 8885:                 foreach my $resource (@mapresources) {
 8886:                     my $ressymb = $resource->symb();
 8887:                     ($counter,my $recording) =
 8888:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8889:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8890:                                                  \%scantron_config,\%lettdig,$numletts,
 8891:                                                  $randomorder,$randompick,\%respnumlookup,
 8892:                                                  \%startline);
 8893:                     $studentrecord .= $recording;
 8894:                 }
 8895:                 if ($studentrecord ne $studentdata) {
 8896:                     $r->print('<p><span class="LC_warning">');
 8897:                     if ($scancode eq '') {
 8898:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8899:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8900:                     } else {
 8901:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8902:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8903:                     }
 8904:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8905:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8906:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8907:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8908:                               &Apache::loncommon::start_data_table_row().
 8909:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8910:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8911:                               &Apache::loncommon::end_data_table_row().
 8912:                               &Apache::loncommon::start_data_table_row().
 8913:                               '<td>'.&mt('Stored submissions').'</td>'.
 8914:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8915:                               &Apache::loncommon::end_data_table_row().
 8916:                               &Apache::loncommon::end_data_table().'</p>');
 8917:                 } else {
 8918:                     $r->print('<br /><span class="LC_warning">'.
 8919:                              &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 />'.
 8920:                              &mt("As a consequence, this user's submission history records two tries.").
 8921:                                  '</span><br />');
 8922:                 }
 8923:             }
 8924:         }
 8925:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8926:     } continue {
 8927: 	&Apache::lonxml::clear_problem_counter();
 8928: 	&Apache::lonnet::delenv('scantron.');
 8929:     }
 8930:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8931:     &Apache::lonnet::remove_lock($lock);
 8932: #    my $lasttime = &Time::HiRes::time()-$start;
 8933: #    $r->print("<p>took $lasttime</p>");
 8934: 
 8935:     $r->print("</form>");
 8936:     $r->print(&show_grading_menu_form($symb));
 8937:     return '';
 8938: }
 8939: 
 8940: sub graders_resources_pass {
 8941:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8942:         $bubbles_per_row) = @_;
 8943:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8944:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8945:         foreach my $resource (@{$resources}) {
 8946:             my $ressymb = $resource->symb();
 8947:             my ($analysis,$parts) =
 8948:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8949:                                           $env{'user.name'},$env{'user.domain'},
 8950:                                           1,$bubbles_per_row);
 8951:             $grader_partids_by_symb->{$ressymb} = $parts;
 8952:             if (ref($analysis) eq 'HASH') {
 8953:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8954:                     $grader_randomlists_by_symb->{$ressymb} =
 8955:                         $analysis->{'parts_withrandomlist'};
 8956:                 }
 8957:             }
 8958:         }
 8959:     }
 8960:     return;
 8961: }
 8962: 
 8963: =pod
 8964: 
 8965: =item users_order
 8966: 
 8967:   Returns array of resources in current map, ordered based on either CODE,
 8968:   if this is a CODEd exam, or based on student's identity if this is a
 8969:   "NAMEd" exam.
 8970: 
 8971:   Should be used when randomorder and/or randompick applied when the 
 8972:   corresponding exam was printed, prior to students completing bubblesheets 
 8973:   for the version of the exam the student received.
 8974: 
 8975: =cut
 8976: 
 8977: sub users_order  {
 8978:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8979:     my @mapresources;
 8980:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8981:         return @mapresources;
 8982:     }
 8983:     if ($scancode) {
 8984:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8985:             @mapresources = @{$orderedforcode->{$scancode}};
 8986:         } else {
 8987:             $env{'form.CODE'} = $scancode;
 8988:             my $actual_seq =
 8989:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8990:                                                                $master_seq,
 8991:                                                                $user,$scancode,1);
 8992:             if (ref($actual_seq) eq 'ARRAY') {
 8993:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8994:                 if (ref($orderedforcode) eq 'HASH') {
 8995:                     if (@mapresources > 0) {
 8996:                         $orderedforcode->{$scancode} = \@mapresources;
 8997:                     }
 8998:                 }
 8999:             }
 9000:             delete($env{'form.CODE'});
 9001:         }
 9002:     } else {
 9003:         my $actual_seq =
 9004:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9005:                                                            $master_seq,
 9006:                                                            $user,undef,1);
 9007:         if (ref($actual_seq) eq 'ARRAY') {
 9008:             @mapresources =
 9009:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9010:         }
 9011:     }
 9012:     return @mapresources;
 9013: }
 9014: 
 9015: sub grade_student_bubbles {
 9016:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9017:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9018:     my $uselookup = 0;
 9019:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9020:         (ref($startline) eq 'HASH')) {
 9021:         $uselookup = 1;
 9022:     }
 9023: 
 9024:     if (ref($resources) eq 'ARRAY') {
 9025:         my $count = 0;
 9026:         foreach my $resource (@{$resources}) {
 9027:             my $ressymb = $resource->symb();
 9028:             my %form = ('submitted'      => 'scantron',
 9029:                         'grade_target'   => 'grade',
 9030:                         'grade_username' => $uname,
 9031:                         'grade_domain'   => $udom,
 9032:                         'grade_courseid' => $env{'request.course.id'},
 9033:                         'grade_symb'     => $ressymb,
 9034:                         'CODE'           => $scancode
 9035:                        );
 9036:             if ($bubbles_per_row ne '') {
 9037:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9038:             }
 9039:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9040:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9041:             }
 9042:             if (ref($parts) eq 'HASH') {
 9043:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9044:                     foreach my $part (@{$parts->{$ressymb}}) {
 9045:                         if ($uselookup) {
 9046:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9047:                         } else {
 9048:                             $form{'scantron_questnum_start.'.$part} =
 9049:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9050:                         }
 9051:                         $count++;
 9052:                     }
 9053:                 }
 9054:             }
 9055:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9056:             return 'ssi_error' if ($ssi_error);
 9057:             last if (&Apache::loncommon::connection_aborted($r));
 9058:         }
 9059:     }
 9060:     return;
 9061: }
 9062: 
 9063: sub scantron_upload_scantron_data {
 9064:     my ($r)=@_;
 9065:     my $dom = $env{'request.role.domain'};
 9066:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9067:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9068:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9069: 							  'domainid',
 9070: 							  'coursename',$dom);
 9071:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9072:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9073:     my ($symb) = &get_symb($r,1);
 9074:     my $default_form_data=&defaultFormData($symb);
 9075:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9076:     &js_escape(\$nofile_alert);
 9077:     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.");
 9078:     &js_escape(\$nocourseid_alert);
 9079:     $r->print('
 9080: <script type="text/javascript" language="javascript">
 9081:     function checkUpload(formname) {
 9082: 	if (formname.upfile.value == "") {
 9083: 	    alert("'.$nofile_alert.'");
 9084: 	    return false;
 9085: 	}
 9086:         if (formname.courseid.value == "") {
 9087:             alert("'.$nocourseid_alert.'");
 9088:             return false;
 9089:         }
 9090: 	formname.submit();
 9091:     }
 9092: 
 9093:     function ToSyllabus() {
 9094:         var cdom = '."'$dom'".';
 9095:         var cnum = document.rules.courseid.value;
 9096:         if (cdom == "" || cdom == null) {
 9097:             return;
 9098:         }
 9099:         if (cnum == "" || cnum == null) {
 9100:            return;
 9101:         }
 9102:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9103:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9104:         return;
 9105:     }
 9106: 
 9107: </script>
 9108: 
 9109: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9110: 
 9111: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9112: '.$default_form_data.
 9113:   &Apache::lonhtmlcommon::start_pick_box().
 9114:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9115:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9116:   &Apache::lonhtmlcommon::row_closure().
 9117:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9118:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9119:   &Apache::lonhtmlcommon::row_closure().
 9120:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9121:   '<input name="domainid" type="hidden" />'.$domdesc.
 9122:   &Apache::lonhtmlcommon::row_closure().
 9123:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9124:   '<input type="file" name="upfile" size="50" />'.
 9125:   &Apache::lonhtmlcommon::row_closure(1).
 9126:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9127: 
 9128: <input name="command" value="scantronupload_save" type="hidden" />
 9129: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9130: </form>
 9131: ');
 9132:     return '';
 9133: }
 9134: 
 9135: 
 9136: sub scantron_upload_scantron_data_save {
 9137:     my($r)=@_;
 9138:     my ($symb)=&get_symb($r,1);
 9139:     my $doanotherupload=
 9140: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9141: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9142: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9143: 	'</form>'."\n";
 9144:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9145: 	!&Apache::lonnet::allowed('usc',
 9146: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9147: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9148: 	if ($symb) {
 9149: 	    $r->print(&show_grading_menu_form($symb));
 9150: 	} else {
 9151: 	    $r->print($doanotherupload);
 9152: 	}
 9153: 	return '';
 9154:     }
 9155:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9156:     my $uploadedfile;
 9157:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9158:     if (length($env{'form.upfile'}) < 2) {
 9159:         $r->print(
 9160:             &Apache::lonhtmlcommon::confirm_success(
 9161:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9162:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9163:     } else {
 9164:         my $result = 
 9165:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 9166:                                             $env{'form.courseid'},$env{'form.domainid'});
 9167: 	if ($result =~ m{^/uploaded/}) {
 9168:             $r->print(
 9169:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9170:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9171:                         (length($env{'form.upfile'})-1),
 9172:                         '<span class="LC_filename">'.$result.'</span>'));
 9173:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9174:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9175:                                                        $env{'form.courseid'},$uploadedfile));
 9176: 	} else {
 9177:             $r->print(
 9178:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9179:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9180:                           $result,
 9181: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9182: 	}
 9183:     }
 9184:     if ($symb) {
 9185: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 9186:     } else {
 9187: 	$r->print($doanotherupload);
 9188:     }
 9189:     return '';
 9190: }
 9191: 
 9192: sub validate_uploaded_scantron_file {
 9193:     my ($cdom,$cname,$fname) = @_;
 9194:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9195:     my @lines;
 9196:     if ($scanlines ne '-1') {
 9197:         @lines=split("\n",$scanlines,-1);
 9198:     }
 9199:     my $output;
 9200:     if (@lines) {
 9201:         my (%counts,$max_match_format);
 9202:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9203:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9204:         my %idmap = &username_to_idmap($classlist);
 9205:         foreach my $key (keys(%idmap)) {
 9206:             my $lckey = lc($key);
 9207:             $idmap{$lckey} = $idmap{$key};
 9208:         }
 9209:         my %unique_formats;
 9210:         my @formatlines = &get_scantronformat_file();
 9211:         foreach my $line (@formatlines) {
 9212:             chomp($line);
 9213:             my @config = split(/:/,$line);
 9214:             my $idstart = $config[5];
 9215:             my $idlength = $config[6];
 9216:             if (($idstart ne '') && ($idlength > 0)) {
 9217:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9218:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9219:                 } else {
 9220:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9221:                 }
 9222:             }
 9223:         }
 9224:         foreach my $key (keys(%unique_formats)) {
 9225:             my ($idstart,$idlength) = split(':',$key);
 9226:             %{$counts{$key}} = (
 9227:                                'found'   => 0,
 9228:                                'total'   => 0,
 9229:                               );
 9230:             foreach my $line (@lines) {
 9231:                 next if ($line =~ /^#/);
 9232:                 next if ($line =~ /^[\s\cz]*$/);
 9233:                 my $id = substr($line,$idstart-1,$idlength);
 9234:                 $id = lc($id);
 9235:                 if (exists($idmap{$id})) {
 9236:                     $counts{$key}{'found'} ++;
 9237:                 }
 9238:                 $counts{$key}{'total'} ++;
 9239:             }
 9240:             if ($counts{$key}{'total'}) {
 9241:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9242:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9243:                     $max_match_pct = $percent_match;
 9244:                     $max_match_format = $key;
 9245:                     $found_match_count = $counts{$key}{'found'};
 9246:                     $max_match_count = $counts{$key}{'total'};
 9247:                 }
 9248:             }
 9249:         }
 9250:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9251:             my $format_descs;
 9252:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9253:             for (my $i=0; $i<$numwithformat; $i++) {
 9254:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9255:                 if ($i<$numwithformat-2) {
 9256:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9257:                 } elsif ($i==$numwithformat-2) {
 9258:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9259:                 } elsif ($i==$numwithformat-1) {
 9260:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9261:                 }
 9262:             }
 9263:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9264:             $output .= '<br />';
 9265:             if ($found_match_count == $max_match_count) {
 9266:                 # 100% matching entries
 9267:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9268:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9269:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9270:                 &mt('Comparison of student IDs in the uploaded file with'.
 9271:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9272:                     ' in the file (for the format defined for [_3]).',
 9273:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9274:             } else {
 9275:                 # Not all entries matching? -> Show warning and additional info
 9276:                 $output .=
 9277:                     &Apache::lonhtmlcommon::confirm_success(
 9278:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9279:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9280:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9281:                     &mt('Comparison of student IDs in the uploaded file with'.
 9282:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9283:                         ' in the file (for the format defined for [_3]).',
 9284:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9285:                     '<p class="LC_info">'.
 9286:                     &mt('A low percentage of matches results from one of the following:').
 9287:                     '</p><ul>'.
 9288:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9289:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9290:                                '<i>'.$cdom.'</i>').'</li>'.
 9291:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9292:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9293:                     '</ul>';
 9294:             }
 9295:         }
 9296:     } else {
 9297:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9298:     }
 9299:     return $output;
 9300: }
 9301: 
 9302: sub valid_file {
 9303:     my ($requested_file)=@_;
 9304:     foreach my $filename (sort(&scantron_filenames())) {
 9305: 	if ($requested_file eq $filename) { return 1; }
 9306:     }
 9307:     return 0;
 9308: }
 9309: 
 9310: sub scantron_download_scantron_data {
 9311:     my ($r)=@_;
 9312:     my ($symb) = &get_symb($r,1);
 9313:     my $default_form_data=&defaultFormData($symb);
 9314:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9315:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9316:     my $file=$env{'form.scantron_selectfile'};
 9317:     if (! &valid_file($file)) {
 9318: 	$r->print('
 9319: 	<p>
 9320: 	    '.&mt('The requested filename was invalid.').'
 9321:         </p>
 9322: ');
 9323: 	$r->print(&show_grading_menu_form($symb));
 9324: 	return;
 9325:     }
 9326:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9327:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9328:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9329:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9330:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9331:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9332:     $r->print('
 9333:     <p>
 9334: 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
 9335: 	      '<a href="'.$orig.'">','</a>').'
 9336:     </p>
 9337:     <p>
 9338: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9339: 	      '<a href="'.$corrected.'">','</a>').'
 9340:     </p>
 9341:     <p>
 9342: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9343: 	      '<a href="'.$skipped.'">','</a>').'
 9344:     </p>
 9345: ');
 9346:     $r->print(&show_grading_menu_form($symb));
 9347:     return '';
 9348: }
 9349: 
 9350: sub checkscantron_results {
 9351:     my ($r) = @_;
 9352:     my ($symb)=&get_symb($r);
 9353:     if (!$symb) {return '';}
 9354:     my $grading_menu_button=&show_grading_menu_form($symb);
 9355:     my $cid = $env{'request.course.id'};
 9356:     my %lettdig = &letter_to_digits();
 9357:     my $numletts = scalar(keys(%lettdig));
 9358:     my $cnum = $env{'course.'.$cid.'.num'};
 9359:     my $cdom = $env{'course.'.$cid.'.domain'};
 9360:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9361:     my %record;
 9362:     my %scantron_config =
 9363:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9364:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9365:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9366:     my $classlist=&Apache::loncoursedata::get_classlist();
 9367:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9368:     my $navmap=Apache::lonnavmaps::navmap->new();
 9369:     unless (ref($navmap)) {
 9370:         $r->print(&navmap_errormsg());
 9371:         return '';
 9372:     }
 9373:     my $map=$navmap->getResourceByUrl($sequence);
 9374:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9375:         %grader_randomlists_by_symb,%orderedforcode);
 9376:     if (ref($map)) {
 9377:         $randomorder=$map->randomorder();
 9378:         $randompick=$map->randompick();
 9379:     }
 9380:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9381:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9382:     if ($nav_error) {
 9383:         $r->print(&navmap_errormsg());
 9384:         return '';
 9385:     }
 9386:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9387:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9388:     my ($uname,$udom);
 9389:     my (%scandata,%lastname,%bylast);
 9390:     $r->print('
 9391: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9392: 
 9393:     my @delayqueue;
 9394:     my %completedstudents;
 9395: 
 9396:     my $count=&get_todo_count($scanlines,$scan_data);
 9397:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9398:     my ($username,$domain,$started);
 9399:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9400:     if ($nav_error) {
 9401:         $r->print(&navmap_errormsg());
 9402:         return '';
 9403:     }
 9404: 
 9405:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9406:                                           'Processing first student');
 9407:     my $start=&Time::HiRes::time();
 9408:     my $i=-1;
 9409: 
 9410:     while ($i<$scanlines->{'count'}) {
 9411:         ($username,$domain,$uname)=('','','');
 9412:         $i++;
 9413:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9414:         if ($line=~/^[\s\cz]*$/) { next; }
 9415:         if ($started) {
 9416:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9417:                                                      'last student');
 9418:         }
 9419:         $started=1;
 9420:         my $scan_record=
 9421:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9422:                                                      $scan_data);
 9423:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9424:                                               \%idmap,$i)) {
 9425:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9426:                                 'Unable to find a student that matches',1);
 9427:             next;
 9428:         }
 9429:         if (exists $completedstudents{$uname}) {
 9430:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9431:                                 'Student '.$uname.' has multiple sheets',2);
 9432:             next;
 9433:         }
 9434:         my $pid = $scan_record->{'scantron.ID'};
 9435:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9436:         push(@{$bylast{$lastname{$pid}}},$pid);
 9437:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9438:         my $user = $uname.':'.$usec;
 9439:         ($username,$domain)=split(/:/,$uname);
 9440: 
 9441:         my $scancode;
 9442:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9443:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9444:             $scancode = $scan_record->{'scantron.CODE'};
 9445:         } else {
 9446:             $scancode = '';
 9447:         }
 9448: 
 9449:         my @mapresources = @resources;
 9450:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9451:         my %respnumlookup=();
 9452:         my %startline=();
 9453:         if ($randomorder || $randompick) {
 9454:             @mapresources =
 9455:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9456:                              \%orderedforcode);
 9457:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9458:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9459:                                              \%grader_partids_by_symb,\%orderedforcode,
 9460:                                              \%respnumlookup,\%startline);
 9461:             if ($randompick && $total) {
 9462:                 $lastpos = $total*$scantron_config{'Qlength'};
 9463:             }
 9464:         }
 9465:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9466:         chomp($scandata{$pid});
 9467:         $scandata{$pid} =~ s/\r$//;
 9468: 
 9469:         my $counter = -1;
 9470:         foreach my $resource (@mapresources) {
 9471:             my $parts;
 9472:             my $ressymb = $resource->symb();
 9473:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9474:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9475:                 my $currcode;
 9476:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9477:                     $currcode = $scancode;
 9478:                 }
 9479:                 (my $analysis,$parts) =
 9480:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9481:                                               $username,$domain,undef,
 9482:                                               $bubbles_per_row,$currcode);
 9483:             } else {
 9484:                 $parts = $grader_partids_by_symb{$ressymb};
 9485:             }
 9486:             ($counter,my $recording) =
 9487:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9488:                                          $scandata{$pid},$parts,
 9489:                                          \%scantron_config,\%lettdig,$numletts,
 9490:                                          $randomorder,$randompick,
 9491:                                          \%respnumlookup,\%startline);
 9492:             $record{$pid} .= $recording;
 9493:         }
 9494:     }
 9495:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9496:     $r->print('<br />');
 9497:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9498:     $passed = 0;
 9499:     $failed = 0;
 9500:     $numstudents = 0;
 9501:     foreach my $last (sort(keys(%bylast))) {
 9502:         if (ref($bylast{$last}) eq 'ARRAY') {
 9503:             foreach my $pid (sort(@{$bylast{$last}})) {
 9504:                 my $showscandata = $scandata{$pid};
 9505:                 my $showrecord = $record{$pid};
 9506:                 $showscandata =~ s/\s/&nbsp;/g;
 9507:                 $showrecord =~ s/\s/&nbsp;/g;
 9508:                 if ($scandata{$pid} eq $record{$pid}) {
 9509:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9510:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9511: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9512: '</tr>'."\n".
 9513: '<tr class="'.$css_class.'">'."\n".
 9514: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9515:                     $passed ++;
 9516:                 } else {
 9517:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9518:                     $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".
 9519: '</tr>'."\n".
 9520: '<tr class="'.$css_class.'">'."\n".
 9521: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9522: '</tr>'."\n";
 9523:                     $failed ++;
 9524:                 }
 9525:                 $numstudents ++;
 9526:             }
 9527:         }
 9528:     }
 9529:     $r->print('<p>'.
 9530:               &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).',
 9531:                   '<b>',
 9532:                   $numstudents,
 9533:                   '</b>',
 9534:                   $env{'form.scantron_maxbubble'}).
 9535:               '</p>'
 9536:     );
 9537:     $r->print('<p>'
 9538:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9539:              .'<br />'
 9540:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9541:              .'</p>');
 9542:     if ($passed) {
 9543:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9544:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9545:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9546:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9547:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9548:                  $okstudents."\n".
 9549:                  &Apache::loncommon::end_data_table().'<br />');
 9550:     }
 9551:     if ($failed) {
 9552:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9553:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9554:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9555:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9556:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9557:                  $badstudents."\n".
 9558:                  &Apache::loncommon::end_data_table()).'<br />'.
 9559:                  &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.');  
 9560:     }
 9561:     $r->print('</form><br />'.$grading_menu_button);
 9562:     return;
 9563: }
 9564: 
 9565: sub verify_scantron_grading {
 9566:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9567:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9568:         $respnumlookup,$startline) = @_;
 9569:     my ($record,%expected,%startpos);
 9570:     return ($counter,$record) if (!ref($resource));
 9571:     return ($counter,$record) if (!$resource->is_problem());
 9572:     my $symb = $resource->symb();
 9573:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9574:     foreach my $part_id (@{$partids}) {
 9575:         $counter ++;
 9576:         $expected{$part_id} = 0;
 9577:         my $respnum = $counter;
 9578:         if ($randomorder || $randompick) {
 9579:             $respnum = $respnumlookup->{$counter};
 9580:             $startpos{$part_id} = $startline->{$counter} + 1;
 9581:         } else {
 9582:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9583:         }
 9584:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9585:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9586:             foreach my $item (@sub_lines) {
 9587:                 $expected{$part_id} += $item;
 9588:             }
 9589:         } else {
 9590:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9591:         }
 9592:     }
 9593:     if ($symb) {
 9594:         my %recorded;
 9595:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9596:         if ($returnhash{'version'}) {
 9597:             my %lasthash=();
 9598:             my $version;
 9599:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9600:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9601:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9602:                 }
 9603:             }
 9604:             foreach my $key (keys(%lasthash)) {
 9605:                 if ($key =~ /\.scantron$/) {
 9606:                     my $value = &unescape($lasthash{$key});
 9607:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9608:                     if ($value eq '') {
 9609:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9610:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9611:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9612:                             }
 9613:                         }
 9614:                     } else {
 9615:                         my @tocheck;
 9616:                         my @items = split(//,$value);
 9617:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9618:                             ($scantron_config->{'Qon'} eq 'number')) {
 9619:                             if (@items < $expected{$part_id}) {
 9620:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9621:                                 my @singles = split(//,$fragment);
 9622:                                 foreach my $pos (@singles) {
 9623:                                     if ($pos eq ' ') {
 9624:                                         push(@tocheck,$pos);
 9625:                                     } else {
 9626:                                         my $next = shift(@items);
 9627:                                         push(@tocheck,$next);
 9628:                                     }
 9629:                                 }
 9630:                             } else {
 9631:                                 @tocheck = @items;
 9632:                             }
 9633:                             foreach my $letter (@tocheck) {
 9634:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9635:                                     if ($letter !~ /^[A-J]$/) {
 9636:                                         $letter = $scantron_config->{'Qoff'};
 9637:                                     }
 9638:                                     $recorded{$part_id} .= $letter;
 9639:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9640:                                     my $digit;
 9641:                                     if ($letter !~ /^[A-J]$/) {
 9642:                                         $digit = $scantron_config->{'Qoff'};
 9643:                                     } else {
 9644:                                         $digit = $lettdig->{$letter};
 9645:                                     }
 9646:                                     $recorded{$part_id} .= $digit;
 9647:                                 }
 9648:                             }
 9649:                         } else {
 9650:                             @tocheck = @items;
 9651:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9652:                                 my $curr_sub = shift(@tocheck);
 9653:                                 my $digit;
 9654:                                 if ($curr_sub =~ /^[A-J]$/) {
 9655:                                     $digit = $lettdig->{$curr_sub}-1;
 9656:                                 }
 9657:                                 if ($curr_sub eq 'J') {
 9658:                                     $digit += scalar($numletts);
 9659:                                 }
 9660:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9661:                                     if ($j == $digit) {
 9662:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9663:                                     } else {
 9664:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9665:                                     }
 9666:                                 }
 9667:                             }
 9668:                         }
 9669:                     }
 9670:                 }
 9671:             }
 9672:         }
 9673:         foreach my $part_id (@{$partids}) {
 9674:             if ($recorded{$part_id} eq '') {
 9675:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9676:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9677:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9678:                     }
 9679:                 }
 9680:             }
 9681:             $record .= $recorded{$part_id};
 9682:         }
 9683:     }
 9684:     return ($counter,$record);
 9685: }
 9686: 
 9687: sub letter_to_digits {
 9688:     my %lettdig = (
 9689:                     A => 1,
 9690:                     B => 2,
 9691:                     C => 3,
 9692:                     D => 4,
 9693:                     E => 5,
 9694:                     F => 6,
 9695:                     G => 7,
 9696:                     H => 8,
 9697:                     I => 9,
 9698:                     J => 0,
 9699:                   );
 9700:     return %lettdig;
 9701: }
 9702: 
 9703: 
 9704: #-------- end of section for handling grading scantron forms -------
 9705: #
 9706: #-------------------------------------------------------------------
 9707: 
 9708: #-------------------------- Menu interface -------------------------
 9709: #
 9710: #--- Show a Grading Menu button - Calls the next routine ---
 9711: sub show_grading_menu_form {
 9712:     my ($symb)=@_;
 9713:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9714: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9715: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9716: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9717: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9718: 	'</form>'."\n";
 9719:     return $result;
 9720: }
 9721: 
 9722: # -- Retrieve choices for grading form
 9723: sub savedState {
 9724:     my %savedState = ();
 9725:     if ($env{'form.saveState'}) {
 9726: 	foreach (split(/:/,$env{'form.saveState'})) {
 9727: 	    my ($key,$value) = split(/=/,$_,2);
 9728: 	    $savedState{$key} = $value;
 9729: 	}
 9730:     }
 9731:     return \%savedState;
 9732: }
 9733: 
 9734: #--- Href with symb and command ---
 9735: 
 9736: sub href_symb_cmd {
 9737:     my ($symb,$cmd)=@_;
 9738:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9739: }
 9740: 
 9741: sub grading_menu {
 9742:     my ($request) = @_;
 9743:     my ($symb)=&get_symb($request);
 9744:     if (!$symb) {return '';}
 9745:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9746:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9747: 
 9748:     $request->print($table);
 9749:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9750:                   'handgrade'=>$hdgrade,
 9751:                   'probTitle'=>$probTitle,
 9752:                   'command'=>'submit_options',
 9753:                   'saveState'=>"",
 9754:                   'gradingMenu'=>1,
 9755:                   'showgrading'=>"yes");
 9756:     
 9757:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9758:     
 9759:     $fields{'command'} = 'csvform';
 9760:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9761:     
 9762:     $fields{'command'} = 'processclicker';
 9763:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9764:     
 9765:     $fields{'command'} = 'scantron_selectphase';
 9766:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9767:     
 9768:     my @menu = ({	categorytitle=>'Course Grading',
 9769:             items =>[
 9770:                         {	linktext => 'Manual Grading/View Submissions',
 9771:                     		url => $url1,
 9772:                     		permission => 'F',
 9773:                     		icon => 'edit-find-replace.png',
 9774:                     		linktitle => 'Start the process of hand grading submissions.'
 9775:                         },
 9776:                 	    {	linktext => 'Upload Scores',
 9777:                     		url => $url2,
 9778:                     		permission => 'F',
 9779:                     		icon => 'uploadscores.png',
 9780:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9781:                 	    },
 9782:                 	    {	linktext => 'Process Clicker',
 9783:                     		url => $url3,
 9784:                     		permission => 'F',
 9785:                     		icon => 'addClickerInfoFile.png',
 9786:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9787:                 	    },
 9788:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9789:                     		url => $url4,
 9790:                     		permission => 'F',
 9791:                     		icon => 'stat.png',
 9792:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9793:                 	    }
 9794:                     ]
 9795:             });
 9796: 
 9797:     #$fields{'command'} = 'verify';
 9798:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9799:     #
 9800:     # Create the menu
 9801:     my $Str;
 9802:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9803:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9804:     $Str .= '<input type="hidden" name="command" value="" />'.
 9805:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9806: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9807: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9808: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9809: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9810: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9811: 
 9812:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9813:     #$menudata->{'jscript'}
 9814:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9815:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9816:         ' /> '.
 9817:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9818:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9819: 
 9820:     $Str .="</form>\n";
 9821:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9822:     $request->print(<<GRADINGMENUJS);
 9823: <script type="text/javascript" language="javascript">
 9824:     function checkChoice(formname,val,cmdx) {
 9825: 	if (val <= 2) {
 9826: 	    var cmd = radioSelection(formname.radioChoice);
 9827: 	    var cmdsave = cmd;
 9828: 	} else {
 9829: 	    cmd = cmdx;
 9830: 	    cmdsave = 'submission';
 9831: 	}
 9832: 	formname.command.value = cmd;
 9833: 	if (val < 5) formname.submit();
 9834: 	if (val == 5) {
 9835: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9836: 	        return false;
 9837: 	    } else {
 9838: 	        formname.submit();
 9839: 	    }
 9840: 	}
 9841:     }
 9842: 
 9843:     function checkReceiptNo(formname,nospace) {
 9844: 	var receiptNo = formname.receipt.value;
 9845: 	var checkOpt = false;
 9846: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9847: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9848: 	if (checkOpt) {
 9849: 	    alert("$receiptalert");
 9850: 	    formname.receipt.value = "";
 9851: 	    formname.receipt.focus();
 9852: 	    return false;
 9853: 	}
 9854: 	return true;
 9855:     }
 9856: </script>
 9857: GRADINGMENUJS
 9858:     &commonJSfunctions($request);
 9859:     return $Str;    
 9860: }
 9861: 
 9862: 
 9863: #--- Displays the submissions first page -------
 9864: sub submit_options {
 9865:     my ($request) = @_;
 9866:     my ($symb)=&get_symb($request);
 9867:     if (!$symb) {return '';}
 9868:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9869: 
 9870:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9871:     $request->print(<<GRADINGMENUJS);
 9872: <script type="text/javascript" language="javascript">
 9873:     function checkChoice(formname,val,cmdx) {
 9874: 	if (val <= 2) {
 9875: 	    var cmd = radioSelection(formname.radioChoice);
 9876: 	    var cmdsave = cmd;
 9877: 	} else {
 9878: 	    cmd = cmdx;
 9879: 	    cmdsave = 'submission';
 9880: 	}
 9881: 	formname.command.value = cmd;
 9882: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9883: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9884: 	if (val < 5) formname.submit();
 9885: 	if (val == 5) {
 9886: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9887: 	    formname.submit();
 9888: 	}
 9889: 	if (val < 7) formname.submit();
 9890:     }
 9891: 
 9892:     function checkReceiptNo(formname,nospace) {
 9893: 	var receiptNo = formname.receipt.value;
 9894: 	var checkOpt = false;
 9895: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9896: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9897: 	if (checkOpt) {
 9898: 	    alert("$receiptalert");
 9899: 	    formname.receipt.value = "";
 9900: 	    formname.receipt.focus();
 9901: 	    return false;
 9902: 	}
 9903: 	return true;
 9904:     }
 9905: </script>
 9906: GRADINGMENUJS
 9907:     &commonJSfunctions($request);
 9908:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9909:     my $result;
 9910:     my (undef,$sections) = &getclasslist('all','0');
 9911:     my $savedState = &savedState();
 9912:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9913:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9914:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9915:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9916: 
 9917:     # Preselect sections
 9918:     my $selsec="";
 9919:     if (ref($sections)) {
 9920:         foreach my $section (sort(@$sections)) {
 9921:             $selsec.='<option value="'.$section.'" '.
 9922:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9923:         }
 9924:     }
 9925: 
 9926:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9927: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9928: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9929: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9930: 	'<input type="hidden" name="command"     value="" />'."\n".
 9931: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9932: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9933: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9934: 
 9935:     $result.='
 9936: <h2>
 9937:   '.&mt('Grade Current Resource').'
 9938: </h2>
 9939: <div>
 9940:   '.$table.'
 9941: </div>
 9942: 
 9943: <div class="LC_columnSection">
 9944:   
 9945:     <fieldset>
 9946:       <legend>
 9947:        '.&mt('Sections').'
 9948:       </legend>
 9949:       <select name="section" multiple="multiple" size="5">'."\n";
 9950:     $result.= $selsec;
 9951:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9952:     $result.='
 9953:     </fieldset>
 9954:   
 9955:     <fieldset>
 9956:       <legend>
 9957:         '.&mt('Groups').'
 9958:       </legend>
 9959:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9960:     </fieldset>
 9961:   
 9962:     <fieldset>
 9963:       <legend>
 9964:         '.&mt('Access Status').'
 9965:       </legend>
 9966:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9967:     </fieldset>
 9968:   
 9969:     <fieldset>
 9970:       <legend>
 9971:         '.&mt('Submission Status').'
 9972:       </legend>
 9973:       <select name="submitonly" size="5">
 9974: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9975: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9976: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9977: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9978:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9979:       </select>
 9980:     </fieldset>
 9981:   
 9982: </div>
 9983: 
 9984: <br />
 9985:           <div>
 9986:             <div>
 9987:               <label>
 9988:                 <input type="radio" name="radioChoice" value="submission" '.
 9989:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9990:              &mt('Select individual students to grade and view submissions.').'
 9991: 	      </label> 
 9992:             </div>
 9993:             <div>
 9994: 	      <label>
 9995:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9996:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9997:                     &mt('Grade all selected students in a grading table.').'
 9998:               </label>
 9999:             </div>
10000:             <div>
10001: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10002:             </div>
10003:           </div>
10004: 
10005: 
10006:         <h2>
10007:          '.&mt('Grade Complete Folder for One Student').'
10008:         </h2>
10009:         <div>
10010:             <div>
10011:               <label>
10012:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
10013: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
10014:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
10015:               </label>
10016:             </div>
10017:             <div>
10018: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10019:             </div>
10020:         </div>
10021:   </form>';
10022:     $result .= &show_grading_menu_form($symb);
10023:     return $result;
10024: }
10025: 
10026: sub substatus_options {
10027:     return &Apache::lonlocal::texthash(
10028:                                       'yes'       => 'with submissions',
10029:                                       'queued'    => 'in grading queue',
10030:                                       'graded'    => 'with ungraded submissions',
10031:                                       'incorrect' => 'with incorrect submissions',
10032:                                       'all'       => 'with any status',
10033:                                       );
10034: }
10035: 
10036: sub reset_perm {
10037:     undef(%perm);
10038: }
10039: 
10040: sub init_perm {
10041:     &reset_perm();
10042:     foreach my $test_perm ('vgr','mgr','opa') {
10043: 
10044: 	my $scope = $env{'request.course.id'};
10045: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10046: 
10047: 	    $scope .= '/'.$env{'request.course.sec'};
10048: 	    if ( $perm{$test_perm}=
10049: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10050: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10051: 	    } else {
10052: 		delete($perm{$test_perm});
10053: 	    }
10054: 	}
10055:     }
10056: }
10057: 
10058: sub init_old_essays {
10059:     my ($symb,$apath,$adom,$aname) = @_;
10060:     if ($symb ne '') {
10061:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10062:         if (keys(%essays) > 0) {
10063:             $old_essays{$symb} = \%essays;
10064:         }
10065:     }
10066:     return;
10067: }
10068: 
10069: sub reset_old_essays {
10070:     undef(%old_essays);
10071: }
10072: 
10073: sub gather_clicker_ids {
10074:     my %clicker_ids;
10075: 
10076:     my $classlist = &Apache::loncoursedata::get_classlist();
10077: 
10078:     # Set up a couple variables.
10079:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10080:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10081:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10082: 
10083:     foreach my $student (keys(%$classlist)) {
10084:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10085:         my $username = $classlist->{$student}->[$username_idx];
10086:         my $domain   = $classlist->{$student}->[$domain_idx];
10087:         my $clickers =
10088: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10089:         foreach my $id (split(/\,/,$clickers)) {
10090:             $id=~s/^[\#0]+//;
10091:             $id=~s/[\-\:]//g;
10092:             if (exists($clicker_ids{$id})) {
10093: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10094:             } else {
10095: 		$clicker_ids{$id}=$username.':'.$domain;
10096:             }
10097:         }
10098:     }
10099:     return %clicker_ids;
10100: }
10101: 
10102: sub gather_adv_clicker_ids {
10103:     my %clicker_ids;
10104:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10105:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10106:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10107:     foreach my $element (sort(keys(%coursepersonnel))) {
10108:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10109:             my ($puname,$pudom)=split(/\:/,$person);
10110:             my $clickers =
10111: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10112:             foreach my $id (split(/\,/,$clickers)) {
10113: 		$id=~s/^[\#0]+//;
10114:                 $id=~s/[\-\:]//g;
10115: 		if (exists($clicker_ids{$id})) {
10116: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10117: 		} else {
10118: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10119: 		}
10120:             }
10121:         }
10122:     }
10123:     return %clicker_ids;
10124: }
10125: 
10126: sub clicker_grading_parameters {
10127:     return ('gradingmechanism' => 'scalar',
10128:             'upfiletype' => 'scalar',
10129:             'specificid' => 'scalar',
10130:             'pcorrect' => 'scalar',
10131:             'pincorrect' => 'scalar');
10132: }
10133: 
10134: sub process_clicker {
10135:     my ($r)=@_;
10136:     my ($symb)=&get_symb($r);
10137:     if (!$symb) {return '';}
10138:     my $result=&checkforfile_js();
10139:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
10140:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
10141:     $result.=$table;
10142:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
10143:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
10144:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
10145:         '</b></td></tr>'."\n";
10146:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
10147: # Attempt to restore parameters from last session, set defaults if not present
10148:     my %Saveable_Parameters=&clicker_grading_parameters();
10149:     &Apache::loncommon::restore_course_settings('grades_clicker',
10150:                                                  \%Saveable_Parameters);
10151:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10152:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10153:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10154:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10155: 
10156:     my %checked;
10157:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10158:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10159:           $checked{$gradingmechanism}=' checked="checked"';
10160:        }
10161:     }
10162: 
10163:     my $upload=&mt("Upload File");
10164:     my $type=&mt("Type");
10165:     my $attendance=&mt("Award points just for participation");
10166:     my $personnel=&mt("Correctness determined from response by course personnel");
10167:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10168:     my $given=&mt("Correctness determined from given list of answers").' '.
10169:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10170:     my $pcorrect=&mt("Percentage points for correct solution");
10171:     my $pincorrect=&mt("Percentage points for incorrect solution");
10172:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10173:                                                    {'iclicker' => 'i>clicker',
10174:                                                     'interwrite' => 'interwrite PRS',
10175:                                                     'turning' => 'Turning Technologies'});
10176:     $symb = &Apache::lonenc::check_encrypt($symb);
10177:     $result.=<<ENDUPFORM;
10178: <script type="text/javascript">
10179: function sanitycheck() {
10180: // Accept only integer percentages
10181:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10182:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10183: // Find out grading choice
10184:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10185:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10186:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10187:       }
10188:    }
10189: // By default, new choice equals user selection
10190:    newgradingchoice=gradingchoice;
10191: // Not good to give more points for false answers than correct ones
10192:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10193:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10194:    }
10195: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10196:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10197:       document.forms.gradesupload.pcorrect.value=100;
10198:       document.forms.gradesupload.pincorrect.value=100;
10199:    }
10200: // If the values are different, cannot be attendance only
10201:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10202:        (gradingchoice=='attendance')) {
10203:        newgradingchoice='personnel';
10204:    }
10205: // Change grading choice to new one
10206:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10207:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10208:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10209:       } else {
10210:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10211:       }
10212:    }
10213: // Remember the old state
10214:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10215: }
10216: </script>
10217: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10218: <input type="hidden" name="symb" value="$symb" />
10219: <input type="hidden" name="command" value="processclickerfile" />
10220: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10221: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10222: <input type="file" name="upfile" size="50" />
10223: <br /><label>$type: $selectform</label>
10224: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10225: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10226: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10227: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10228: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10229: <br />&nbsp;&nbsp;&nbsp;
10230: <input type="text" name="givenanswer" size="50" />
10231: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10232: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10233: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10234: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10235: </form>
10236: ENDUPFORM
10237:     $result.='</td></tr></table>'."\n".
10238:              '</td></tr></table><br /><br />'."\n";
10239:     $result.=&show_grading_menu_form($symb);
10240:     return $result;
10241: }
10242: 
10243: sub process_clicker_file {
10244:     my ($r)=@_;
10245:     my ($symb)=&get_symb($r);
10246:     if (!$symb) {return '';}
10247: 
10248:     my %Saveable_Parameters=&clicker_grading_parameters();
10249:     &Apache::loncommon::store_course_settings('grades_clicker',
10250:                                               \%Saveable_Parameters);
10251: 
10252:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10253:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10254: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10255: 	return $result.&show_grading_menu_form($symb);
10256:     }
10257:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10258:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10259:         return $result.&show_grading_menu_form($symb);
10260:     }
10261:     my $foundgiven=0;
10262:     if ($env{'form.gradingmechanism'} eq 'given') {
10263:         $env{'form.givenanswer'}=~s/^\s*//gs;
10264:         $env{'form.givenanswer'}=~s/\s*$//gs;
10265:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10266:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10267:         my @answers=split(/\,/,$env{'form.givenanswer'});
10268:         $foundgiven=$#answers+1;
10269:     }
10270:     my %clicker_ids=&gather_clicker_ids();
10271:     my %correct_ids;
10272:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10273: 	%correct_ids=&gather_adv_clicker_ids();
10274:     }
10275:     if ($env{'form.gradingmechanism'} eq 'specific') {
10276: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10277: 	   $correct_id=~tr/a-z/A-Z/;
10278: 	   $correct_id=~s/\s//gs;
10279: 	   $correct_id=~s/^[\#0]+//;
10280:            $correct_id=~s/[\-\:]//g;
10281:            if ($correct_id) {
10282: 	      $correct_ids{$correct_id}='specified';
10283:            }
10284:         }
10285:     }
10286:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10287: 	$result.=&mt('Score based on attendance only');
10288:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10289:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10290:     } else {
10291: 	my $number=0;
10292: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10293: 	foreach my $id (sort(keys(%correct_ids))) {
10294: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10295: 	    if ($correct_ids{$id} eq 'specified') {
10296: 		$result.=&mt('specified');
10297: 	    } else {
10298: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10299: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10300: 	    }
10301: 	    $number++;
10302: 	}
10303:         $result.="</p>\n";
10304:         if ($number==0) {
10305:             $result .=
10306:                  &Apache::lonhtmlcommon::confirm_success(
10307:                      &mt('No IDs found to determine correct answer'),1);
10308:             return $result,.&show_grading_menu_form($symb);
10309:         }
10310:     }
10311:     if (length($env{'form.upfile'}) < 2) {
10312:         $result .=
10313:             &Apache::lonhtmlcommon::confirm_success(
10314:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10315:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10316:         return $result.&show_grading_menu_form($symb);
10317:     }
10318: 
10319: # Were able to get all the info needed, now analyze the file
10320: 
10321:     $result.=&Apache::loncommon::studentbrowser_javascript();
10322:     $symb = &Apache::lonenc::check_encrypt($symb);
10323:     my $heading=&mt('Scanning clicker file');
10324:     $result.=(<<ENDHEADER);
10325: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10326: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10327: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10328: <form method="post" action="/adm/grades" name="clickeranalysis">
10329: <input type="hidden" name="symb" value="$symb" />
10330: <input type="hidden" name="command" value="assignclickergrades" />
10331: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10332: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10333: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10334: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10335: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10336: ENDHEADER
10337:     if ($env{'form.gradingmechanism'} eq 'given') {
10338:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10339:     } 
10340:     my %responses;
10341:     my @questiontitles;
10342:     my $errormsg='';
10343:     my $number=0;
10344:     if ($env{'form.upfiletype'} eq 'iclicker') {
10345: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10346:     }
10347:     if ($env{'form.upfiletype'} eq 'interwrite') {
10348:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10349:     }
10350:     if ($env{'form.upfiletype'} eq 'turning') {
10351:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10352:     }
10353:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10354:              '<input type="hidden" name="number" value="'.$number.'" />'.
10355:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10356:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10357:              '<br />';
10358:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10359:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10360:        return $result.&show_grading_menu_form($symb);
10361:     } 
10362: # Remember Question Titles
10363: # FIXME: Possibly need delimiter other than ":"
10364:     for (my $i=0;$i<$number;$i++) {
10365:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10366:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10367:     }
10368:     my $correct_count=0;
10369:     my $student_count=0;
10370:     my $unknown_count=0;
10371: # Match answers with usernames
10372: # FIXME: Possibly need delimiter other than ":"
10373:     foreach my $id (keys(%responses)) {
10374:        if ($correct_ids{$id}) {
10375:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10376:           $correct_count++;
10377:        } elsif ($clicker_ids{$id}) {
10378:           if ($clicker_ids{$id}=~/\,/) {
10379: # More than one user with the same clicker!
10380:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10381:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10382:                            "<select name='multi".$id."'>";
10383:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10384:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10385:              }
10386:              $result.='</select>';
10387:              $unknown_count++;
10388:           } else {
10389: # Good: found one and only one user with the right clicker
10390:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10391:              $student_count++;
10392:           }
10393:        } else {
10394:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10395:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10396:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10397:                    "\n".&mt("Domain").": ".
10398:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10399:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10400:           $unknown_count++;
10401:        }
10402:     }
10403:     $result.='<hr />'.
10404:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10405:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10406:        if ($correct_count==0) {
10407:           $errormsg.="Found no correct answers for grading!";
10408:        } elsif ($correct_count>1) {
10409:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10410:        }
10411:     }
10412:     if ($number<1) {
10413:        $errormsg.="Found no questions.";
10414:     }
10415:     if ($errormsg) {
10416:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10417:     } else {
10418:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10419:     }
10420:     $result.='</form></td></tr></table>'."\n".
10421:              '</td></tr></table><br /><br />'."\n";
10422:     return $result.&show_grading_menu_form($symb);
10423: }
10424: 
10425: sub iclicker_eval {
10426:     my ($questiontitles,$responses)=@_;
10427:     my $number=0;
10428:     my $errormsg='';
10429:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10430:         my %components=&Apache::loncommon::record_sep($line);
10431:         my @entries=map {$components{$_}} (sort(keys(%components)));
10432: 	if ($entries[0] eq 'Question') {
10433: 	    for (my $i=3;$i<$#entries;$i+=6) {
10434: 		$$questiontitles[$number]=$entries[$i];
10435: 		$number++;
10436: 	    }
10437: 	}
10438: 	if ($entries[0]=~/^\#/) {
10439: 	    my $id=$entries[0];
10440: 	    my @idresponses;
10441: 	    $id=~s/^[\#0]+//;
10442: 	    for (my $i=0;$i<$number;$i++) {
10443: 		my $idx=3+$i*6;
10444:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10445: 		push(@idresponses,$entries[$idx]);
10446: 	    }
10447: 	    $$responses{$id}=join(',',@idresponses);
10448: 	}
10449:     }
10450:     return ($errormsg,$number);
10451: }
10452: 
10453: sub interwrite_eval {
10454:     my ($questiontitles,$responses)=@_;
10455:     my $number=0;
10456:     my $errormsg='';
10457:     my $skipline=1;
10458:     my $questionnumber=0;
10459:     my %idresponses=();
10460:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10461:         my %components=&Apache::loncommon::record_sep($line);
10462:         my @entries=map {$components{$_}} (sort(keys(%components)));
10463:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10464:         if ($entries[1] eq 'Response') { $skipline=1; }
10465:         next if $skipline;
10466:         if ($entries[0]!=$questionnumber) {
10467:            $questionnumber=$entries[0];
10468:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10469:            $number++;
10470:         }
10471:         my $id=$entries[4];
10472:         $id=~s/^[\#0]+//;
10473:         $id=~s/^v\d*\://i;
10474:         $id=~s/[\-\:]//g;
10475:         $idresponses{$id}[$number]=$entries[6];
10476:     }
10477:     foreach my $id (keys(%idresponses)) {
10478:        $$responses{$id}=join(',',@{$idresponses{$id}});
10479:        $$responses{$id}=~s/^\s*\,//;
10480:     }
10481:     return ($errormsg,$number);
10482: }
10483: 
10484: sub turning_eval {
10485:     my ($questiontitles,$responses)=@_;
10486:     my $number=0;
10487:     my $errormsg='';
10488:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10489:         my %components=&Apache::loncommon::record_sep($line);
10490:         my @entries=map {$components{$_}} (sort(keys(%components)));
10491:         if ($#entries>$number) { $number=$#entries; }
10492:         my $id=$entries[0];
10493:         my @idresponses;
10494:         $id=~s/^[\#0]+//;
10495:         unless ($id) { next; }
10496:         for (my $idx=1;$idx<=$#entries;$idx++) {
10497:             $entries[$idx]=~s/\,/\;/g;
10498:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10499:             push(@idresponses,$entries[$idx]);
10500:         }
10501:         $$responses{$id}=join(',',@idresponses);
10502:     }
10503:     for (my $i=1; $i<=$number; $i++) {
10504:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10505:     }
10506:     return ($errormsg,$number);
10507: }
10508: 
10509: sub assign_clicker_grades {
10510:     my ($r)=@_;
10511:     my ($symb)=&get_symb($r);
10512:     if (!$symb) {return '';}
10513: # See which part we are saving to
10514:     my $res_error;
10515:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10516:     if ($res_error) {
10517:         return &navmap_errormsg();
10518:     }
10519: # FIXME: This should probably look for the first handgradeable part
10520:     my $part=$$partlist[0];
10521: # Start screen output
10522:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10523: 
10524:     $result .= '<br />'.
10525:                &Apache::loncommon::start_data_table().
10526:                &Apache::loncommon::start_data_table_header_row().
10527:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10528:                &Apache::loncommon::end_data_table_header_row().
10529:                &Apache::loncommon::start_data_table_row().'<td>';
10530: 
10531: # Get correct result
10532: # FIXME: Possibly need delimiter other than ":"
10533:     my @correct=();
10534:     my $gradingmechanism=$env{'form.gradingmechanism'};
10535:     my $number=$env{'form.number'};
10536:     if ($gradingmechanism ne 'attendance') {
10537:        foreach my $key (keys(%env)) {
10538:           if ($key=~/^form\.correct\:/) {
10539:              my @input=split(/\,/,$env{$key});
10540:              for (my $i=0;$i<=$#input;$i++) {
10541:                  if (($correct[$i]) && ($input[$i]) &&
10542:                      ($correct[$i] ne $input[$i])) {
10543:                     $result.='<br /><span class="LC_warning">'.
10544:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10545:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10546:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10547:                     $correct[$i]=$input[$i];
10548:                  }
10549:              }
10550:           }
10551:        }
10552:        for (my $i=0;$i<$number;$i++) {
10553:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10554:              $result.='<br /><span class="LC_error">'.
10555:                       &mt('No correct result given for question "[_1]"!',
10556:                           $env{'form.question:'.$i}).'</span>';
10557:           }
10558:        }
10559:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10560:     }
10561: # Start grading
10562:     my $pcorrect=$env{'form.pcorrect'};
10563:     my $pincorrect=$env{'form.pincorrect'};
10564:     my $storecount=0;
10565:     my %users=();
10566:     foreach my $key (keys(%env)) {
10567:        my $user='';
10568:        if ($key=~/^form\.student\:(.*)$/) {
10569:           $user=$1;
10570:        }
10571:        if ($key=~/^form\.unknown\:(.*)$/) {
10572:           my $id=$1;
10573:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10574:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10575:           } elsif ($env{'form.multi'.$id}) {
10576:              $user=$env{'form.multi'.$id};
10577:           }
10578:        }
10579:        if ($user) {
10580:           if ($users{$user}) {
10581:              $result.='<br /><span class="LC_warning">'.
10582:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10583:                       '</span><br />';
10584:           }
10585:           $users{$user}=1;
10586:           my @answer=split(/\,/,$env{$key});
10587:           my $sum=0;
10588:           my $realnumber=$number;
10589:           for (my $i=0;$i<$number;$i++) {
10590:              if  ($correct[$i] eq '-') {
10591:                 $realnumber--;
10592:              } elsif ($answer[$i]) {
10593:                 if ($gradingmechanism eq 'attendance') {
10594:                    $sum+=$pcorrect;
10595:                 } elsif ($correct[$i] eq '*') {
10596:                    $sum+=$pcorrect;
10597:                 } else {
10598: # We actually grade if correct or not
10599:                    my $increment=$pincorrect;
10600: # Special case: numerical answer "0"
10601:                    if ($correct[$i] eq '0') {
10602:                       if ($answer[$i]=~/^[0\.]+$/) {
10603:                          $increment=$pcorrect;
10604:                       }
10605: # General numerical answer, both evaluate to something non-zero
10606:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10607:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10608:                          $increment=$pcorrect;
10609:                       }
10610: # Must be just alphanumeric
10611:                    } elsif ($answer[$i] eq $correct[$i]) {
10612:                       $increment=$pcorrect;
10613:                    }
10614:                    $sum+=$increment;
10615:                 }
10616:              }
10617:           }
10618:           my $ave=$sum/(100*$realnumber);
10619: # Store
10620:           my ($username,$domain)=split(/\:/,$user);
10621:           my %grades=();
10622:           $grades{"resource.$part.solved"}='correct_by_override';
10623:           $grades{"resource.$part.awarded"}=$ave;
10624:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10625:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10626:                                                  $env{'request.course.id'},
10627:                                                  $domain,$username);
10628:           if ($returncode ne 'ok') {
10629:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10630:           } else {
10631:              $storecount++;
10632:           }
10633:        }
10634:     }
10635: # We are done
10636:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10637:              '</td>'.
10638:              &Apache::loncommon::end_data_table_row().
10639:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10640:     return $result.&show_grading_menu_form($symb);
10641: }
10642: 
10643: sub navmap_errormsg {
10644:     return '<div class="LC_error">'.
10645:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10646:            &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>').
10647:            '</div>';
10648: }
10649: 
10650: sub startpage {
10651:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10652:     if ($nomenu) {
10653:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10654:     } else {
10655:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10656:                                                  {'bread_crumbs' => $crumbs}));
10657:     }
10658:     unless ($nodisplayflag) {
10659:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10660:     }
10661: }
10662: 
10663: sub handler {
10664:     my $request=$_[0];
10665:     &reset_caches();
10666:     if ($request->header_only) {
10667:         &Apache::loncommon::content_type($request,'text/html');
10668:         $request->send_http_header;
10669:         return OK;
10670:     }
10671:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10672: 
10673:     my $symb=&get_symb($request,1);
10674:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10675:     my $command=$commands[0];
10676: 
10677:     if ($#commands > 0) {
10678: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10679:     }
10680: 
10681:     $ssi_error = 0;
10682:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10683:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10684:                                                     {'bread_crumbs' => $brcrum});
10685:     if ($symb eq '' && $command eq '') {
10686: 	if ($env{'user.adv'}) {
10687:             &Apache::loncommon::content_type($request,'text/html');
10688:             $request->send_http_header;
10689:             $request->print($start_page);
10690: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10691: 		($env{'form.codethree'})) {
10692: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10693: 		    $env{'form.codethree'};
10694: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10695: 		    &Apache::lonnet::checkin($token);
10696: 		if ($tsymb) {
10697: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10698: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10699: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10700: 					  ('grade_username' => $tuname,
10701: 					   'grade_domain' => $tudom,
10702: 					   'grade_courseid' => $tcrsid,
10703: 					   'grade_symb' => $tsymb)));
10704: 		    } else {
10705: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10706: 		    }
10707: 		} else {
10708: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10709: 		}
10710: 	    } else {
10711: 		$request->print(&Apache::lonxml::tokeninputfield());
10712: 	    }
10713:         } elsif ($env{'request.course.id'}) {
10714:             &init_perm(); 
10715:             if (!%perm) {
10716:                 $request->internal_redirect('/adm/quickgrades');
10717:                 return OK;
10718:             } else {
10719:                 &Apache::loncommon::content_type($request,'text/html');
10720:                 $request->send_http_header;
10721:                 $request->print($start_page);
10722:             }
10723:         }
10724:     } else {
10725:         &init_perm();
10726:         if (!$env{'request.course.id'}) {
10727:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10728:                     ($command =~ /^scantronupload/)) {
10729:                 # Not in a course.
10730:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10731:                 return HTTP_NOT_ACCEPTABLE;
10732:             }
10733:         } elsif (!%perm) {
10734:             $request->internal_redirect('/adm/quickgrades');
10735:         }
10736:         &Apache::loncommon::content_type($request,'text/html');
10737:         $request->send_http_header;
10738:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10739:             $request->print($start_page); 
10740:         }
10741: 	if ($command eq 'submission' && $perm{'vgr'}) {
10742:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10743:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10744:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10745:                     &choose_task_version_form($symb,$env{'form.student'},
10746:                                               $env{'form.userdom'});
10747:             }
10748:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10749:             if ($versionform) {
10750:                 $request->print($versionform);
10751:             }
10752:             $request->print('<br clear="all" />');
10753: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10754:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10755:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10756:                 &choose_task_version_form($symb,$env{'form.student'},
10757:                                           $env{'form.userdom'},
10758:                                           $env{'form.inhibitmenu'});
10759:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10760:             if ($versionform) {
10761:                 $request->print($versionform);
10762:             }
10763:             $request->print('<br clear="all" />');
10764:             $request->print(&show_previous_task_version($request,$symb));
10765: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10766: 	    &pickStudentPage($request);
10767: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10768: 	    &displayPage($request);
10769: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10770: 	    &updateGradeByPage($request);
10771: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10772: 	    &processGroup($request);
10773: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10774: 	    $request->print(&grading_menu($request));
10775: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10776: 	    $request->print(&submit_options($request));
10777: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10778: 	    $request->print(&viewgrades($request));
10779: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10780: 	    $request->print(&processHandGrade($request));
10781: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10782: 	    $request->print(&editgrades($request));
10783: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10784: 	    $request->print(&verifyreceipt($request));
10785:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10786:             $request->print(&process_clicker($request));
10787:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10788:             $request->print(&process_clicker_file($request));
10789:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10790:             $request->print(&assign_clicker_grades($request));
10791: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10792: 	    $request->print(&upcsvScores_form($request));
10793: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10794: 	    $request->print(&csvupload($request));
10795: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10796: 	    $request->print(&csvuploadmap($request));
10797: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10798: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10799: 		$request->print(&csvuploadoptions($request));
10800: 	    } else {
10801: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10802: 		    $env{'form.upfile_associate'} = 'reverse';
10803: 		} else {
10804: 		    $env{'form.upfile_associate'} = 'forward';
10805: 		}
10806: 		$request->print(&csvuploadmap($request));
10807: 	    }
10808: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10809: 	    $request->print(&csvuploadassign($request));
10810: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10811: 	    $request->print(&scantron_selectphase($request));
10812:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10813:  	    $request->print(&scantron_do_warning($request));
10814: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10815: 	    $request->print(&scantron_validate_file($request));
10816: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10817: 	    $request->print(&scantron_process_students($request));
10818:  	} elsif ($command eq 'scantronupload' && 
10819:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10820: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10821:  	    $request->print(&scantron_upload_scantron_data($request)); 
10822:  	} elsif ($command eq 'scantronupload_save' &&
10823:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10824: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10825:  	    $request->print(&scantron_upload_scantron_data_save($request));
10826:  	} elsif ($command eq 'scantron_download' &&
10827: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10828:  	    $request->print(&scantron_download_scantron_data($request));
10829:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10830:             $request->print(&checkscantron_results($request));     
10831: 	} elsif ($command) {
10832: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10833: 	}
10834:     }
10835:     if ($ssi_error) {
10836: 	&ssi_print_error($request);
10837:     }
10838:     $request->print(&Apache::loncommon::end_page());
10839:     &reset_caches();
10840:     return OK;
10841: }
10842: 
10843: 1;
10844: 
10845: __END__;
10846: 
10847: 
10848: =head1 NAME
10849: 
10850: Apache::grades
10851: 
10852: =head1 SYNOPSIS
10853: 
10854: Handles the viewing of grades.
10855: 
10856: This is part of the LearningOnline Network with CAPA project
10857: described at http://www.lon-capa.org.
10858: 
10859: =head1 OVERVIEW
10860: 
10861: Do an ssi with retries:
10862: While I'd love to factor out this with the vesrion in lonprintout,
10863: 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
10864: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10865: 
10866: At least the logic that drives this has been pulled out into loncommon.
10867: 
10868: 
10869: 
10870: ssi_with_retries - Does the server side include of a resource.
10871:                      if the ssi call returns an error we'll retry it up to
10872:                      the number of times requested by the caller.
10873:                      If we still have a problem, no text is appended to the
10874:                      output and we set some global variables.
10875:                      to indicate to the caller an SSI error occurred.  
10876:                      All of this is supposed to deal with the issues described
10877:                      in LON-CAPA BZ 5631 see:
10878:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10879:                      by informing the user that this happened.
10880: 
10881: Parameters:
10882:   resource   - The resource to include.  This is passed directly, without
10883:                interpretation to lonnet::ssi.
10884:   form       - The form hash parameters that guide the interpretation of the resource
10885:                
10886:   retries    - Number of retries allowed before giving up completely.
10887: Returns:
10888:   On success, returns the rendered resource identified by the resource parameter.
10889: Side Effects:
10890:   The following global variables can be set:
10891:    ssi_error                - If an unrecoverable error occurred this becomes true.
10892:                               It is up to the caller to initialize this to false
10893:                               if desired.
10894:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10895:                               of the resource that could not be rendered by the ssi
10896:                               call.
10897:    ssi_error_message   - The error string fetched from the ssi response
10898:                               in the event of an error.
10899: 
10900: 
10901: =head1 HANDLER SUBROUTINE
10902: 
10903: ssi_with_retries()
10904: 
10905: =head1 SUBROUTINES
10906: 
10907: =over
10908: 
10909: =item scantron_get_correction() : 
10910: 
10911:    Builds the interface screen to interact with the operator to fix a
10912:    specific error condition in a specific scanline
10913: 
10914:  Arguments:
10915:     $r           - Apache request object
10916:     $i           - number of the current scanline
10917:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10918:     $scan_config - hash ref as returned from &get_scantron_config()
10919:     $line        - full contents of the current scanline
10920:     $error       - error condition, valid values are
10921:                    'incorrectCODE', 'duplicateCODE',
10922:                    'doublebubble', 'missingbubble',
10923:                    'duplicateID', 'incorrectID'
10924:     $arg         - extra information needed
10925:        For errors:
10926:          - duplicateID   - paper number that this studentID was seen before on
10927:          - duplicateCODE - array ref of the paper numbers this CODE was
10928:                            seen on before
10929:          - incorrectCODE - current incorrect CODE 
10930:          - doublebubble  - array ref of the bubble lines that have double
10931:                            bubble errors
10932:          - missingbubble - array ref of the bubble lines that have missing
10933:                            bubble errors
10934: 
10935:    $randomorder - True if exam folder has randomorder set
10936:    $randompick  - True if exam folder has randompick set
10937:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10938:                      for current line to question number used for same question
10939:                      in "Master Seqence" (as seen by Course Coordinator).
10940:    $startline   - Reference to hash where key is question number (0 is first)
10941:                   and value is number of first bubble line for current student
10942:                   or code-based randompick and/or randomorder.
10943: 
10944: 
10945: =item  scantron_get_maxbubble() : 
10946: 
10947:    Arguments:
10948:        $nav_error  - Reference to scalar which is a flag to indicate a
10949:                       failure to retrieve a navmap object.
10950:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10951:        calling routine should trap the error condition and display the warning
10952:        found in &navmap_errormsg().
10953: 
10954:        $scantron_config - Reference to bubblesheet format configuration hash.
10955: 
10956:    Returns the maximum number of bubble lines that are expected to
10957:    occur. Does this by walking the selected sequence rendering the
10958:    resource and then checking &Apache::lonxml::get_problem_counter()
10959:    for what the current value of the problem counter is.
10960: 
10961:    Caches the results to $env{'form.scantron_maxbubble'},
10962:    $env{'form.scantron.bubble_lines.n'}, 
10963:    $env{'form.scantron.first_bubble_line.n'} and
10964:    $env{"form.scantron.sub_bubblelines.n"}
10965:    which are the total number of bubble lines, the number of bubble
10966:    lines for response n and number of the first bubble line for response n,
10967:    and a comma separated list of numbers of bubble lines for sub-questions
10968:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10969: 
10970: 
10971: =item  scantron_validate_missingbubbles() : 
10972: 
10973:    Validates all scanlines in the selected file to not have any
10974:     answers that don't have bubbles that have not been verified
10975:     to be bubble free.
10976: 
10977: =item  scantron_process_students() : 
10978: 
10979:    Routine that does the actual grading of the bubblesheet information.
10980: 
10981:    The parsed scanline hash is added to %env 
10982: 
10983:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10984:    foreach resource , with the form data of
10985: 
10986: 	'submitted'     =>'scantron' 
10987: 	'grade_target'  =>'grade',
10988: 	'grade_username'=> username of student
10989: 	'grade_domain'  => domain of student
10990: 	'grade_courseid'=> of course
10991: 	'grade_symb'    => symb of resource to grade
10992: 
10993:     This triggers a grading pass. The problem grading code takes care
10994:     of converting the bubbled letter information (now in %env) into a
10995:     valid submission.
10996: 
10997: =item  scantron_upload_scantron_data() :
10998: 
10999:     Creates the screen for adding a new bubblesheet data file to a course.
11000: 
11001: =item  scantron_upload_scantron_data_save() : 
11002: 
11003:    Adds a provided bubble information data file to the course if user
11004:    has the correct privileges to do so. 
11005: 
11006: =item  valid_file() :
11007: 
11008:    Validates that the requested bubble data file exists in the course.
11009: 
11010: =item  scantron_download_scantron_data() : 
11011: 
11012:    Shows a list of the three internal files (original, corrected,
11013:    skipped) for a specific bubblesheet data file that exists in the
11014:    course.
11015: 
11016: =item  scantron_validate_ID() : 
11017: 
11018:    Validates all scanlines in the selected file to not have any
11019:    invalid or underspecified student/employee IDs
11020: 
11021: =item navmap_errormsg() :
11022: 
11023:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11024:    Should be called whenever the request to instantiate a navmap object fails.  
11025: 
11026: =back
11027: 
11028: =cut

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