File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.40.2.1: download - view: text, annotated - select for diffs
Tue Oct 9 15:45:43 2018 UTC (5 years, 7 months ago) by raeburn
Branches: version_2_11_2_vcu
Diff to branchpoint 1.596.2.12.2.40: preferred, unified
- For 2.11.2 (modified)
  Include changes in 1.751 and 1.752

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.40.2.1 2018/10/09 15:45:43 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 Apache::lontexconvert();
   48: use String::Similarity;
   49: use LONCAPA;
   50: 
   51: use POSIX qw(floor);
   52: 
   53: 
   54: 
   55: my %perm=();
   56: my %old_essays=();
   57: 
   58: #  These variables are used to recover from ssi errors
   59: 
   60: my $ssi_retries = 5;
   61: my $ssi_error;
   62: my $ssi_error_resource;
   63: my $ssi_error_message;
   64: 
   65: 
   66: sub ssi_with_retries {
   67:     my ($resource, $retries, %form) = @_;
   68:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   69:     if ($response->is_error) {
   70: 	$ssi_error          = 1;
   71: 	$ssi_error_resource = $resource;
   72: 	$ssi_error_message  = $response->code . " " . $response->message;
   73:     }
   74: 
   75:     return $content;
   76: 
   77: }
   78: #
   79: #  Prodcuces an ssi retry failure error message to the user:
   80: #
   81: 
   82: sub ssi_print_error {
   83:     my ($r) = @_;
   84:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   85:     $r->print('
   86: <br />
   87: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   88: <p>
   89: '.&mt('Unable to retrieve a resource from a server:').'<br />
   90: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   91: '.&mt('Error:').' '.$ssi_error_message.'
   92: </p>
   93: <p>'.
   94: &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 />'.
   95: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   96: '</p>');
   97:     return;
   98: }
   99: 
  100: #
  101: # --- Retrieve the parts from the metadata file.---
  102: sub getpartlist {
  103:     my ($symb,$errorref) = @_;
  104: 
  105:     my $navmap   = Apache::lonnavmaps::navmap->new();
  106:     unless (ref($navmap)) {
  107:         if (ref($errorref)) { 
  108:             $$errorref = 'navmap';
  109:             return;
  110:         }
  111:     }
  112:     my $res      = $navmap->getBySymb($symb);
  113:     my $partlist = $res->parts();
  114:     my $url      = $res->src();
  115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  116: 
  117:     my @stores;
  118:     foreach my $part (@{ $partlist }) {
  119: 	foreach my $key (@metakeys) {
  120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  121: 	}
  122:     }
  123:     return @stores;
  124: }
  125: 
  126: # --- Get the symbolic name of a problem and the url
  127: sub get_symb {
  128:     my ($request,$silent) = @_;
  129:     my $symb=$env{'form.symb'};
  130:     unless ($symb) {
  131:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  132:         $symb = &Apache::lonnet::symbread($url);
  133:         if ($symb eq '') { 
  134: 	    if (!$silent) {
  135:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  136: 	        return ();
  137: 	    }
  138:         }
  139:     }
  140:     &Apache::lonenc::check_decrypt(\$symb);
  141:     return ($symb);
  142: }
  143: 
  144: #--- Format fullname, username:domain if different for display
  145: #--- Use anywhere where the student names are listed
  146: sub nameUserString {
  147:     my ($type,$fullname,$uname,$udom) = @_;
  148:     if ($type eq 'header') {
  149: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  150:     } else {
  151: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  152: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  153:     }
  154: }
  155: 
  156: #--- Get the partlist and the response type for a given problem. ---
  157: #--- Indicate if a response type is coded handgraded or not. ---
  158: sub response_type {
  159:     my ($symb,$response_error) = @_;
  160: 
  161:     my $navmap = Apache::lonnavmaps::navmap->new();
  162:     unless (ref($navmap)) {
  163:         if (ref($response_error)) {
  164:             $$response_error = 1;
  165:         }
  166:         return;
  167:     }
  168:     my $res = $navmap->getBySymb($symb);
  169:     unless (ref($res)) {
  170:         $$response_error = 1;
  171:         return;
  172:     }
  173:     my $partlist = $res->parts();
  174:     my %vPart = 
  175: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  176:     my (%response_types,%handgrade);
  177:     foreach my $part (@{ $partlist }) {
  178: 	next if (%vPart && !exists($vPart{$part}));
  179: 
  180: 	my @types = $res->responseType($part);
  181: 	my @ids = $res->responseIds($part);
  182: 	for (my $i=0; $i < scalar(@ids); $i++) {
  183: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  184: 	    $handgrade{$part.'_'.$ids[$i]} = 
  185: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  186: 				     '.handgrade',$symb);
  187: 	}
  188:     }
  189:     return ($partlist,\%handgrade,\%response_types);
  190: }
  191: 
  192: sub flatten_responseType {
  193:     my ($responseType) = @_;
  194:     my @part_response_id =
  195: 	map { 
  196: 	    my $part = $_;
  197: 	    map {
  198: 		[$part,$_]
  199: 		} sort(keys(%{ $responseType->{$part} }));
  200: 	} sort(keys(%$responseType));
  201:     return @part_response_id;
  202: }
  203: 
  204: sub get_display_part {
  205:     my ($partID,$symb)=@_;
  206:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  207:     if (defined($display) and $display ne '') {
  208:         $display.= ' (<span class="LC_internal_info">'
  209:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  210:     } else {
  211: 	$display=$partID;
  212:     }
  213:     return $display;
  214: }
  215: 
  216: #--- Show resource title
  217: #--- and parts and response type
  218: sub showResourceInfo {
  219:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  220:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  221:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  222:     if (ref($res_error)) {
  223:         if ($$res_error) {
  224:             return;
  225:         }
  226:     }
  227:     $result.=&Apache::loncommon::start_data_table()
  228:             .&Apache::loncommon::start_data_table_header_row();
  229:     if ($checkboxes) {
  230:         $result.='<th>&nbsp;</th>';
  231:     }
  232:     $result.='<th>'.&mt('Problem Part').'</th>'
  233:             .'<th>'.&mt('Res. ID').'</th>'
  234:             .'<th>'.&mt('Type').'</th>'
  235:             .&Apache::loncommon::end_data_table_header_row();
  236:     my %resptype = ();
  237:     my $hdgrade='no';
  238:     my %partsseen;
  239:     foreach my $partID (sort(keys(%$responseType))) {
  240:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  241:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  242:             my $responsetype = $responseType->{$partID}->{$resID};
  243:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  244:             $result.=&Apache::loncommon::start_data_table_row();
  245:             if ($checkboxes) {
  246:                 if (exists($partsseen{$partID})) {
  247:                     $result.="<td>&nbsp;</td>";
  248:                 } else {
  249:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  250:                 }
  251:                 $partsseen{$partID}=1;
  252:             }
  253:             my $display_part=&get_display_part($partID,$symb);
  254:             $result.='<td>'.$display_part.'</td>'
  255:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  256:                     .'<td>'.&mt($responsetype).'</td>'
  257: #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
  258:                     .&Apache::loncommon::end_data_table_row();
  259:         }
  260:     }
  261:     $result.=&Apache::loncommon::end_data_table();
  262:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  263: }
  264: 
  265: sub reset_caches {
  266:     &reset_analyze_cache();
  267:     &reset_perm();
  268:     &reset_old_essays();
  269: }
  270: 
  271: {
  272:     my %analyze_cache;
  273:     my %analyze_cache_formkeys;
  274: 
  275:     sub reset_analyze_cache {
  276: 	undef(%analyze_cache);
  277:         undef(%analyze_cache_formkeys);
  278:     }
  279: 
  280:     sub get_analyze {
  281: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  282: 	my $key = "$symb\0$uname\0$udom";
  283:         if ($type eq 'randomizetry') {
  284:             if ($trial ne '') {
  285:                 $key .= "\0".$trial;
  286:             }
  287:         }
  288: 	if (exists($analyze_cache{$key})) {
  289:             my $getupdate = 0;
  290:             if (ref($add_to_hash) eq 'HASH') {
  291:                 foreach my $item (keys(%{$add_to_hash})) {
  292:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  293:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  294:                             $getupdate = 1;
  295:                             last;
  296:                         }
  297:                     } else {
  298:                         $getupdate = 1;
  299:                     }
  300:                 }
  301:             }
  302:             if (!$getupdate) {
  303:                 return $analyze_cache{$key};
  304:             }
  305:         }
  306: 
  307: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  308: 	$url=&Apache::lonnet::clutter($url);
  309:         my %form = ('grade_target'      => 'analyze',
  310:                     'grade_domain'      => $udom,
  311:                     'grade_symb'        => $symb,
  312:                     'grade_courseid'    =>  $env{'request.course.id'},
  313:                     'grade_username'    => $uname,
  314:                     'grade_noincrement' => $no_increment);
  315:         if ($bubbles_per_row ne '') {
  316:             $form{'bubbles_per_row'} = $bubbles_per_row;
  317:         }
  318:         if ($type eq 'randomizetry') {
  319:             $form{'grade_questiontype'} = $type;
  320:             if ($rndseed ne '') {
  321:                 $form{'grade_rndseed'} = $rndseed;
  322:             }
  323:         }
  324:         if (ref($add_to_hash)) {
  325:             %form = (%form,%{$add_to_hash});
  326:         }
  327: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  328: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  329: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  330:         if (ref($add_to_hash) eq 'HASH') {
  331:             $analyze_cache_formkeys{$key} = $add_to_hash;
  332:         } else {
  333:             $analyze_cache_formkeys{$key} = {};
  334:         }
  335: 	return $analyze_cache{$key} = \%analyze;
  336:     }
  337: 
  338:     sub get_order {
  339: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  340: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  341: 	return $analyze->{"$partid.$respid.shown"};
  342:     }
  343: 
  344:     sub get_radiobutton_correct_foil {
  345: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  346: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  347:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  348:         if (ref($foils) eq 'ARRAY') {
  349: 	    foreach my $foil (@{$foils}) {
  350: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  351: 		    return $foil;
  352: 	        }
  353: 	    }
  354: 	}
  355:     }
  356: 
  357:     sub scantron_partids_tograde {
  358:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  359:         my (%analysis,@parts);
  360:         if (ref($resource)) {
  361:             my $symb = $resource->symb();
  362:             my $add_to_form;
  363:             if ($check_for_randomlist) {
  364:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  365:             }
  366:             my $analyze =
  367:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  368:                              undef,undef,undef,$bubbles_per_row);
  369:             if (ref($analyze) eq 'HASH') {
  370:                 %analysis = %{$analyze};
  371:             }
  372:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  373:                 foreach my $part (@{$analysis{'parts'}}) {
  374:                     my ($id,$respid) = split(/\./,$part);
  375:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  376:                         push(@parts,$part);
  377:                     }
  378:                 }
  379:             }
  380:         }
  381:         return (\%analysis,\@parts);
  382:     }
  383: 
  384: }
  385: 
  386: #--- Clean response type for display
  387: #--- Currently filters option/rank/radiobutton/match/essay/Task
  388: #        response types only.
  389: sub cleanRecord {
  390:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  391: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  392:     my $grayFont = '<span class="LC_internal_info">';
  393:     if ($response =~ /^(option|rank)$/) {
  394: 	my %answer=&Apache::lonnet::str2hash($answer);
  395:         my @answer = %answer;
  396:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  397: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  398: 	my ($toprow,$bottomrow);
  399: 	foreach my $foil (@$order) {
  400: 	    if ($grading{$foil} == 1) {
  401: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  402: 	    } else {
  403: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  404: 	    }
  405: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  406: 	}
  407: 	return '<blockquote><table border="1">'.
  408: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  409: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  410: 	    $bottomrow.'</tr></table></blockquote>';
  411:     } elsif ($response eq 'match') {
  412: 	my %answer=&Apache::lonnet::str2hash($answer);
  413:         my @answer = %answer;
  414:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  415: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  416: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  417: 	my ($toprow,$middlerow,$bottomrow);
  418: 	foreach my $foil (@$order) {
  419: 	    my $item=shift(@items);
  420: 	    if ($grading{$foil} == 1) {
  421: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  422: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  423: 	    } else {
  424: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  425: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  426: 	    }
  427: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  428: 	}
  429: 	return '<blockquote><table border="1">'.
  430: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  431: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  432: 	    $middlerow.'</tr>'.
  433: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  434: 	    $bottomrow.'</tr></table></blockquote>';
  435:     } elsif ($response eq 'radiobutton') {
  436: 	my %answer=&Apache::lonnet::str2hash($answer);
  437: 	my ($toprow,$bottomrow);
  438: 	my $correct = 
  439: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  440: 	foreach my $foil (@$order) {
  441: 	    if (exists($answer{$foil})) {
  442: 		if ($foil eq $correct) {
  443: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  444: 		} else {
  445: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  446: 		}
  447: 	    } else {
  448: 		$toprow.='<td>'.&mt('false').'</td>';
  449: 	    }
  450: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  451: 	}
  452: 	return '<blockquote><table border="1">'.
  453: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  454: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  455: 	    $bottomrow.'</tr></table></blockquote>';
  456:     } elsif ($response eq 'essay') {
  457: 	if (! exists ($env{'form.'.$symb})) {
  458: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  459: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  460: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  461: 
  462: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  463: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  464: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  465: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  466: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  467: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  468: 	}
  469:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  470: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  471:     } elsif ( $response eq 'organic') {
  472:         my $result=&mt('Smile representation: [_1]',
  473:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  474: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  475: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  476: 	return $result;
  477:     } elsif ( $response eq 'Task') {
  478: 	if ( $answer eq 'SUBMITTED') {
  479: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  480: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  481: 	    return $result;
  482: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  483: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  484: 			       keys(%{$record}));
  485: 	    return join('<br />',($version,@matches));
  486: 			       
  487: 			       
  488: 	} else {
  489: 	    my $result =
  490: 		'<p>'
  491: 		.&mt('Overall result: [_1]',
  492: 		     $record->{$version."resource.$respid.$partid.status"})
  493: 		.'</p>';
  494: 	    
  495: 	    $result .= '<ul>';
  496: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  497: 			     keys(%{$record}));
  498: 	    foreach my $grade (sort(@grade)) {
  499: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  500: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  501: 				     $dim, $record->{$grade}).
  502: 			  '</li>';
  503: 	    }
  504: 	    $result.='</ul>';
  505: 	    return $result;
  506: 	}
  507:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  508:         # Respect multiple input fields, see Bug #5409 
  509: 	$answer = 
  510: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  511: 							      $answer);
  512:         return $answer;
  513:     }
  514:     return &HTML::Entities::encode($answer, '"<>&');
  515: }
  516: 
  517: #-- A couple of common js functions
  518: sub commonJSfunctions {
  519:     my $request = shift;
  520:     $request->print(<<COMMONJSFUNCTIONS);
  521: <script type="text/javascript" language="javascript">
  522:     function radioSelection(radioButton) {
  523: 	var selection=null;
  524: 	if (radioButton.length > 1) {
  525: 	    for (var i=0; i<radioButton.length; i++) {
  526: 		if (radioButton[i].checked) {
  527: 		    return radioButton[i].value;
  528: 		}
  529: 	    }
  530: 	} else {
  531: 	    if (radioButton.checked) return radioButton.value;
  532: 	}
  533: 	return selection;
  534:     }
  535: 
  536:     function pullDownSelection(selectOne) {
  537: 	var selection="";
  538: 	if (selectOne.length > 1) {
  539: 	    for (var i=0; i<selectOne.length; i++) {
  540: 		if (selectOne[i].selected) {
  541: 		    return selectOne[i].value;
  542: 		}
  543: 	    }
  544: 	} else {
  545:             // only one value it must be the selected one
  546: 	    return selectOne.value;
  547: 	}
  548:     }
  549: </script>
  550: COMMONJSFUNCTIONS
  551: }
  552: 
  553: #--- Dumps the class list with usernames,list of sections,
  554: #--- section, ids and fullnames for each user.
  555: sub getclasslist {
  556:     my ($getsec,$filterlist,$getgroup) = @_;
  557:     my @getsec;
  558:     my @getgroup;
  559:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  560:     if (!ref($getsec)) {
  561: 	if ($getsec ne '' && $getsec ne 'all') {
  562: 	    @getsec=($getsec);
  563: 	}
  564:     } else {
  565: 	@getsec=@{$getsec};
  566:     }
  567:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  568:     if (!ref($getgroup)) {
  569: 	if ($getgroup ne '' && $getgroup ne 'all') {
  570: 	    @getgroup=($getgroup);
  571: 	}
  572:     } else {
  573: 	@getgroup=@{$getgroup};
  574:     }
  575:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  576: 
  577:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  578:     # Bail out if we were unable to get the classlist
  579:     return if (! defined($classlist));
  580:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  581:     #
  582:     my %sections;
  583:     my %fullnames;
  584:     foreach my $student (keys(%$classlist)) {
  585:         my $end      = 
  586:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  587:         my $start    = 
  588:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  589:         my $id       = 
  590:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  591:         my $section  = 
  592:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  593:         my $fullname = 
  594:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  595:         my $status   = 
  596:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  597:         my $group   = 
  598:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  599: 	# filter students according to status selected
  600: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  601: 	    if (!($stu_status =~ $status)) {
  602: 		delete($classlist->{$student});
  603: 		next;
  604: 	    }
  605: 	}
  606: 	# filter students according to groups selected
  607: 	my @stu_groups = split(/,/,$group);
  608: 	if (@getgroup) {
  609: 	    my $exclude = 1;
  610: 	    foreach my $grp (@getgroup) {
  611: 	        foreach my $stu_group (@stu_groups) {
  612: 	            if ($stu_group eq $grp) {
  613: 	                $exclude = 0;
  614:     	            } 
  615: 	        }
  616:     	        if (($grp eq 'none') && !$group) {
  617:         	        $exclude = 0;
  618:         	}
  619: 	    }
  620: 	    if ($exclude) {
  621: 	        delete($classlist->{$student});
  622: 	    }
  623: 	}
  624: 	$section = ($section ne '' ? $section : 'none');
  625: 	if (&canview($section)) {
  626: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  627: 		$sections{$section}++;
  628: 		if ($classlist->{$student}) {
  629: 		    $fullnames{$student}=$fullname;
  630: 		}
  631: 	    } else {
  632: 		delete($classlist->{$student});
  633: 	    }
  634: 	} else {
  635: 	    delete($classlist->{$student});
  636: 	}
  637:     }
  638:     my %seen = ();
  639:     my @sections = sort(keys(%sections));
  640:     return ($classlist,\@sections,\%fullnames);
  641: }
  642: 
  643: sub canmodify {
  644:     my ($sec)=@_;
  645:     if ($perm{'mgr'}) {
  646: 	if (!defined($perm{'mgr_section'})) {
  647: 	    # can modify whole class
  648: 	    return 1;
  649: 	} else {
  650: 	    if ($sec eq $perm{'mgr_section'}) {
  651: 		#can modify the requested section
  652: 		return 1;
  653: 	    } else {
  654: 		# can't modify the request section
  655: 		return 0;
  656: 	    }
  657: 	}
  658:     }
  659:     #can't modify
  660:     return 0;
  661: }
  662: 
  663: sub canview {
  664:     my ($sec)=@_;
  665:     if ($perm{'vgr'}) {
  666: 	if (!defined($perm{'vgr_section'})) {
  667: 	    # can modify whole class
  668: 	    return 1;
  669: 	} else {
  670: 	    if ($sec eq $perm{'vgr_section'}) {
  671: 		#can modify the requested section
  672: 		return 1;
  673: 	    } else {
  674: 		# can't modify the request section
  675: 		return 0;
  676: 	    }
  677: 	}
  678:     }
  679:     #can't modify
  680:     return 0;
  681: }
  682: 
  683: #--- Retrieve the grade status of a student for all the parts
  684: sub student_gradeStatus {
  685:     my ($symb,$udom,$uname,$partlist) = @_;
  686:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  687:     my %partstatus = ();
  688:     foreach (@$partlist) {
  689: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  690: 	$status              = 'nothing' if ($status eq '');
  691: 	$partstatus{$_}      = $status;
  692: 	my $subkey           = "resource.$_.submitted_by";
  693: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  694:     }
  695:     return %partstatus;
  696: }
  697: 
  698: # hidden form and javascript that calls the form
  699: # Use by verifyscript and viewgrades
  700: # Shows a student's view of problem and submission
  701: sub jscriptNform {
  702:     my ($symb) = @_;
  703:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  704:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  705: 	'    function viewOneStudent(user,domain) {'."\n".
  706: 	'	document.onestudent.student.value = user;'."\n".
  707: 	'	document.onestudent.userdom.value = domain;'."\n".
  708: 	'	document.onestudent.submit();'."\n".
  709: 	'    }'."\n".
  710: 	'</script>'."\n";
  711:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  712: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  713: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  714: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  715: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  716: 	'<input type="hidden" name="command" value="submission" />'."\n".
  717: 	'<input type="hidden" name="student" value="" />'."\n".
  718: 	'<input type="hidden" name="userdom" value="" />'."\n".
  719: 	'</form>'."\n";
  720:     return $jscript;
  721: }
  722: 
  723: 
  724: 
  725: # Given the score (as a number [0-1] and the weight) what is the final
  726: # point value? This function will round to the nearest tenth, third,
  727: # or quarter if one of those is within the tolerance of .00001.
  728: sub compute_points {
  729:     my ($score, $weight) = @_;
  730:     
  731:     my $tolerance = .00001;
  732:     my $points = $score * $weight;
  733: 
  734:     # Check for nearness to 1/x.
  735:     my $check_for_nearness = sub {
  736:         my ($factor) = @_;
  737:         my $num = ($points * $factor) + $tolerance;
  738:         my $floored_num = floor($num);
  739:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  740:             return $floored_num / $factor;
  741:         }
  742:         return $points;
  743:     };
  744: 
  745:     $points = $check_for_nearness->(10);
  746:     $points = $check_for_nearness->(3);
  747:     $points = $check_for_nearness->(4);
  748:     
  749:     return $points;
  750: }
  751: 
  752: #------------------ End of general use routines --------------------
  753: 
  754: #
  755: # Find most similar essay
  756: #
  757: 
  758: sub most_similar {
  759:     my ($uname,$udom,$symb,$uessay)=@_;
  760: 
  761:     unless ($symb) { return ''; }
  762: 
  763:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  764: 
  765: # ignore spaces and punctuation
  766: 
  767:     $uessay=~s/\W+/ /gs;
  768: 
  769: # ignore empty submissions (occuring when only files are sent)
  770: 
  771:     unless ($uessay=~/\w+/s) { return ''; }
  772: 
  773: # these will be returned. Do not care if not at least 50 percent similar
  774:     my $limit=0.6;
  775:     my $sname='';
  776:     my $sdom='';
  777:     my $scrsid='';
  778:     my $sessay='';
  779: # go through all essays ...
  780:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  781: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  782: # ... except the same student
  783:         next if (($tname eq $uname) && ($tdom eq $udom));
  784: 	my $tessay=$old_essays{$symb}{$tkey};
  785: 	$tessay=~s/\W+/ /gs;
  786: # String similarity gives up if not even limit
  787: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  788: # Found one
  789: 	if ($tsimilar>$limit) {
  790: 	    $limit=$tsimilar;
  791: 	    $sname=$tname;
  792: 	    $sdom=$tdom;
  793: 	    $scrsid=$tcrsid;
  794: 	    $sessay=$old_essays{$symb}{$tkey};
  795: 	}
  796:     }
  797:     if ($limit>0.6) {
  798:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  799:     } else {
  800:        return ('','','','',0);
  801:     }
  802: }
  803: 
  804: #-------------------------------------------------------------------
  805: 
  806: #------------------------------------ Receipt Verification Routines
  807: #
  808: #--- Check whether a receipt number is valid.---
  809: sub verifyreceipt {
  810:     my $request  = shift;
  811: 
  812:     my $courseid = $env{'request.course.id'};
  813:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  814: 	$env{'form.receipt'};
  815:     $receipt     =~ s/[^\-\d]//g;
  816:     my ($symb)   = &get_symb($request);
  817: 
  818:     my $title.=
  819: 	'<h3><span class="LC_info">'.
  820: 	&mt('Verifying Receipt No. [_1]',$receipt).
  821: 	'</span></h3>'."\n".
  822: 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
  823: 	'</h4>'."\n";
  824: 
  825:     my ($string,$contents,$matches) = ('','',0);
  826:     my (undef,undef,$fullname) = &getclasslist('all','0');
  827:     
  828:     my $receiptparts=0;
  829:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  830: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  831:     my $parts=['0'];
  832:     if ($receiptparts) {
  833:         my $res_error; 
  834:         ($parts)=&response_type($symb,\$res_error);
  835:         if ($res_error) {
  836:             return &navmap_errormsg();
  837:         } 
  838:     }
  839:     
  840:     my $header = 
  841: 	&Apache::loncommon::start_data_table().
  842: 	&Apache::loncommon::start_data_table_header_row().
  843: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  844: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  845: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  846:     if ($receiptparts) {
  847: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  848:     }
  849:     $header.=
  850: 	&Apache::loncommon::end_data_table_header_row();
  851: 
  852:     foreach (sort 
  853: 	     {
  854: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  855: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  856: 		 }
  857: 		 return $a cmp $b;
  858: 	     } (keys(%$fullname))) {
  859: 	my ($uname,$udom)=split(/\:/);
  860: 	foreach my $part (@$parts) {
  861: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  862: 		$contents.=
  863: 		    &Apache::loncommon::start_data_table_row().
  864: 		    '<td>&nbsp;'."\n".
  865: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  866: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  867: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  868: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  869: 		if ($receiptparts) {
  870: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  871: 		}
  872: 		$contents.= 
  873: 		    &Apache::loncommon::end_data_table_row()."\n";
  874: 		
  875: 		$matches++;
  876: 	    }
  877: 	}
  878:     }
  879:     if ($matches == 0) {
  880:         $string = $title
  881:                  .'<p class="LC_warning">'
  882:                  .&mt('No match found for the above receipt number.')
  883:                  .'</p>';
  884:     } else {
  885: 	$string = &jscriptNform($symb).$title.
  886: 	    '<p>'.
  887: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  888: 	    '</p>'.
  889: 	    $header.
  890: 	    $contents.
  891: 	    &Apache::loncommon::end_data_table()."\n";
  892:     }
  893:     return $string.&show_grading_menu_form($symb);
  894: }
  895: 
  896: #--- This is called by a number of programs.
  897: #--- Called from the Grading Menu - View/Grade an individual student
  898: #--- Also called directly when one clicks on the subm button 
  899: #    on the problem page.
  900: sub listStudents {
  901:     my ($request) = shift;
  902: 
  903:     my ($symb) = &get_symb($request);
  904:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  905:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  906:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  907:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  908:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  909:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  910:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  911: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  912: 
  913:     my $result='<h3><span class="LC_info">&nbsp;'
  914: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  915: 	.'</span></h3>';
  916: 
  917:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  918: 
  919:     my %js_lt = &Apache::lonlocal::texthash (
  920: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  921: 		'single'   => 'Please select the student before clicking on the Next button.',
  922: 	     );
  923:     &js_escape(\%js_lt);
  924:     $request->print(<<LISTJAVASCRIPT);
  925: <script type="text/javascript" language="javascript">
  926:     function checkSelect(checkBox) {
  927: 	var ctr=0;
  928: 	var sense="";
  929: 	if (checkBox.length > 1) {
  930: 	    for (var i=0; i<checkBox.length; i++) {
  931: 		if (checkBox[i].checked) {
  932: 		    ctr++;
  933: 		}
  934: 	    }
  935: 	    sense = '$js_lt{'multiple'}';
  936: 	} else {
  937: 	    if (checkBox.checked) {
  938: 		ctr = 1;
  939: 	    }
  940: 	    sense = '$js_lt{'single'}';
  941: 	}
  942: 	if (ctr == 0) {
  943: 	    alert(sense);
  944: 	    return false;
  945: 	}
  946: 	document.gradesub.submit();
  947:     }
  948: 
  949:     function reLoadList(formname) {
  950: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  951: 	formname.command.value = 'submission';
  952: 	formname.submit();
  953:     }
  954: </script>
  955: LISTJAVASCRIPT
  956: 
  957:     &commonJSfunctions($request);
  958:     $request->print($result);
  959: 
  960:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  961:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  962:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  963: 	"\n".$table;
  964: 	
  965:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  966:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  967:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  968:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  969:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  970:                   .&Apache::lonhtmlcommon::row_closure();
  971:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  972:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  973:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  974:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  975:                   .&Apache::lonhtmlcommon::row_closure();
  976: 
  977:     my $submission_options;
  978:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  979: 	$submission_options.=
  980: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  981:     }
  982:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  983:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  984:     $env{'form.Status'} = $saveStatus;
  985:     $submission_options.=
  986:         '<span class="LC_nobreak">'.
  987:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  988:         &mt('last submission only').' </label></span>'."\n".
  989:         '<span class="LC_nobreak">'.
  990:         '<label><input type="radio" name="lastSub" value="last" /> '.
  991:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  992:         '<span class="LC_nobreak">'.
  993:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  994:         &mt('by dates and submissions').'</label></span>'."\n".
  995:         '<span class="LC_nobreak">'.
  996:         '<label><input type="radio" name="lastSub" value="all" /> '.
  997:         &mt('all details').'</label></span>';
  998:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  999:                   .$submission_options
 1000:                   .&Apache::lonhtmlcommon::row_closure();
 1001: 
 1002:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1003:                   .'<select name="increment">'
 1004:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1005:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1006:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1007:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1008:                   .'</select>'
 1009:                   .&Apache::lonhtmlcommon::row_closure();
 1010: 
 1011:     $gradeTable .= 
 1012:         &build_section_inputs().
 1013: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1014: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1015: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1016: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1017: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1018: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1019: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1020: 
 1021:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1022: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1023:     } else {
 1024:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1025:                       .&Apache::lonhtmlcommon::StatusOptions(
 1026:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1027:                       .&Apache::lonhtmlcommon::row_closure();
 1028:     }
 1029: 
 1030:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1031:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1032:                   .&Apache::lonhtmlcommon::row_closure(1)
 1033:                   .&Apache::lonhtmlcommon::end_pick_box();
 1034: 
 1035:     $gradeTable .= '<p>'
 1036:                   .&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"
 1037:                   .'<input type="hidden" name="command" value="processGroup" />'
 1038:                   .'</p>';
 1039: 
 1040: # checkall buttons
 1041:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1042:     $gradeTable.='<input type="button" '."\n".
 1043:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1044:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1045:     $gradeTable.=&check_buttons();
 1046:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1047:     $gradeTable.= &Apache::loncommon::start_data_table().
 1048: 	&Apache::loncommon::start_data_table_header_row();
 1049:     my $loop = 0;
 1050:     while ($loop < 2) {
 1051: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1052: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1053: 	if ($env{'form.showgrading'} eq 'yes' 
 1054: 	    && $submitonly ne 'queued'
 1055: 	    && $submitonly ne 'all') {
 1056: 	    foreach my $part (sort(@$partlist)) {
 1057: 		my $display_part=
 1058: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1059: 		$gradeTable.=
 1060: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1061: 	    }
 1062: 	} elsif ($submitonly eq 'queued') {
 1063: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1064: 	}
 1065: 	$loop++;
 1066: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1067:     }
 1068:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1069: 
 1070:     my $ctr = 0;
 1071:     foreach my $student (sort 
 1072: 			 {
 1073: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1074: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1075: 			     }
 1076: 			     return $a cmp $b;
 1077: 			 }
 1078: 			 (keys(%$fullname))) {
 1079: 	my ($uname,$udom) = split(/:/,$student);
 1080: 
 1081: 	my %status = ();
 1082: 
 1083: 	if ($submitonly eq 'queued') {
 1084: 	    my %queue_status = 
 1085: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1086: 							$udom,$uname);
 1087: 	    next if (!defined($queue_status{'gradingqueue'}));
 1088: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1089: 	}
 1090: 
 1091: 	if ($env{'form.showgrading'} eq 'yes' 
 1092: 	    && $submitonly ne 'queued'
 1093: 	    && $submitonly ne 'all') {
 1094: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1095: 	    my $submitted = 0;
 1096: 	    my $graded = 0;
 1097: 	    my $incorrect = 0;
 1098: 	    foreach (keys(%status)) {
 1099: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1100: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1101: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1102: 		
 1103: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1104: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1105: 		    $submitted = 0;
 1106: 		    my ($part)=split(/\./,$partid);
 1107: 		    $gradeTable.='<input type="hidden" name="'.
 1108: 			$student.':'.$part.':submitted_by" value="'.
 1109: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1110: 		}
 1111: 	    }
 1112: 	    
 1113: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1114: 				     $submitonly eq 'incorrect' ||
 1115: 				     $submitonly eq 'graded'));
 1116: 	    next if (!$graded && ($submitonly eq 'graded'));
 1117: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1118: 	}
 1119: 
 1120: 	$ctr++;
 1121: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1122:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1123: 	if ( $perm{'vgr'} eq 'F' ) {
 1124: 	    if ($ctr%2 ==1) {
 1125: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1126: 	    }
 1127: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1128:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1129:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1130: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1131: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1132: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1133: 
 1134: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1135: 		foreach (sort(keys(%status))) {
 1136: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1137: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1138: 		}
 1139: 	    }
 1140: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1141: 	    if ($ctr%2 ==0) {
 1142: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1143: 	    }
 1144: 	}
 1145:     }
 1146:     if ($ctr%2 ==1) {
 1147: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1148: 	    if ($env{'form.showgrading'} eq 'yes' 
 1149: 		&& $submitonly ne 'queued'
 1150: 		&& $submitonly ne 'all') {
 1151: 		foreach (@$partlist) {
 1152: 		    $gradeTable.='<td>&nbsp;</td>';
 1153: 		}
 1154: 	    } elsif ($submitonly eq 'queued') {
 1155: 		$gradeTable.='<td>&nbsp;</td>';
 1156: 	    }
 1157: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1158:     }
 1159: 
 1160:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1161:         '<input type="button" '.
 1162:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1163:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1164:     if ($ctr == 0) {
 1165: 	my $num_students=(scalar(keys(%$fullname)));
 1166: 	if ($num_students eq 0) {
 1167: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1168: 	} else {
 1169: 	    my $submissions='submissions';
 1170: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1171: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1172: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1173: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1174: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1175: 		    $num_students).
 1176: 		'</span><br />';
 1177: 	}
 1178:     } elsif ($ctr == 1) {
 1179: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1180:     }
 1181:     $gradeTable.=&show_grading_menu_form($symb);
 1182:     $request->print($gradeTable);
 1183:     return '';
 1184: }
 1185: 
 1186: #---- Called from the listStudents routine
 1187: 
 1188: sub check_script {
 1189:     my ($form, $type)=@_;
 1190:     my $chkallscript='<script type="text/javascript">
 1191:     function checkall() {
 1192:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1193:             ele = document.forms.'.$form.'.elements[i];
 1194:             if (ele.name == "'.$type.'") {
 1195:             document.forms.'.$form.'.elements[i].checked=true;
 1196:                                        }
 1197:         }
 1198:     }
 1199: 
 1200:     function checksec() {
 1201:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1202:             ele = document.forms.'.$form.'.elements[i];
 1203:            string = document.forms.'.$form.'.chksec.value;
 1204:            if
 1205:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1206:               document.forms.'.$form.'.elements[i].checked=true;
 1207:             }
 1208:         }
 1209:     }
 1210: 
 1211: 
 1212:     function uncheckall() {
 1213:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1214:             ele = document.forms.'.$form.'.elements[i];
 1215:             if (ele.name == "'.$type.'") {
 1216:             document.forms.'.$form.'.elements[i].checked=false;
 1217:                                        }
 1218:         }
 1219:     }
 1220: 
 1221: </script>'."\n";
 1222:     return $chkallscript;
 1223: }
 1224: 
 1225: sub check_buttons {
 1226:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1227:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1228:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1229:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1230:     return $buttons;
 1231: }
 1232: 
 1233: #     Displays the submissions for one student or a group of students
 1234: sub processGroup {
 1235:     my ($request)  = shift;
 1236:     my $ctr        = 0;
 1237:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1238:     my $total      = scalar(@stuchecked)-1;
 1239: 
 1240:     foreach my $student (@stuchecked) {
 1241: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1242: 	$env{'form.student'}        = $uname;
 1243: 	$env{'form.userdom'}        = $udom;
 1244: 	$env{'form.fullname'}       = $fullname;
 1245: 	&submission($request,$ctr,$total);
 1246: 	$ctr++;
 1247:     }
 1248:     return '';
 1249: }
 1250: 
 1251: #------------------------------------------------------------------------------------
 1252: #
 1253: #-------------------------- Next few routines handles grading by student, essentially
 1254: #                           handles essay response type problem/part
 1255: #
 1256: #--- Javascript to handle the submission page functionality ---
 1257: sub sub_page_js {
 1258:     my $request = shift;
 1259:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1260:     &js_escape(\$alertmsg);
 1261:     $request->print(<<SUBJAVASCRIPT);
 1262: <script type="text/javascript" language="javascript">
 1263:     function updateRadio(formname,id,weight) {
 1264: 	var gradeBox = formname["GD_BOX"+id];
 1265: 	var radioButton = formname["RADVAL"+id];
 1266: 	var oldpts = formname["oldpts"+id].value;
 1267: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1268: 	gradeBox.value = pts;
 1269: 	var resetbox = false;
 1270: 	if (isNaN(pts) || pts < 0) {
 1271: 	    alert("$alertmsg"+pts);
 1272: 	    for (var i=0; i<radioButton.length; i++) {
 1273: 		if (radioButton[i].checked) {
 1274: 		    gradeBox.value = i;
 1275: 		    resetbox = true;
 1276: 		}
 1277: 	    }
 1278: 	    if (!resetbox) {
 1279: 		formtextbox.value = "";
 1280: 	    }
 1281: 	    return;
 1282: 	}
 1283: 
 1284: 	if (pts > weight) {
 1285: 	    var resp = confirm("You entered a value ("+pts+
 1286: 			       ") greater than the weight for the part. Accept?");
 1287: 	    if (resp == false) {
 1288: 		gradeBox.value = oldpts;
 1289: 		return;
 1290: 	    }
 1291: 	}
 1292: 
 1293: 	for (var i=0; i<radioButton.length; i++) {
 1294: 	    radioButton[i].checked=false;
 1295: 	    if (pts == i && pts != "") {
 1296: 		radioButton[i].checked=true;
 1297: 	    }
 1298: 	}
 1299: 	updateSelect(formname,id);
 1300: 	formname["stores"+id].value = "0";
 1301:     }
 1302: 
 1303:     function writeBox(formname,id,pts) {
 1304: 	var gradeBox = formname["GD_BOX"+id];
 1305: 	if (checkSolved(formname,id) == 'update') {
 1306: 	    gradeBox.value = pts;
 1307: 	} else {
 1308: 	    var oldpts = formname["oldpts"+id].value;
 1309: 	    gradeBox.value = oldpts;
 1310: 	    var radioButton = formname["RADVAL"+id];
 1311: 	    for (var i=0; i<radioButton.length; i++) {
 1312: 		radioButton[i].checked=false;
 1313: 		if (i == oldpts) {
 1314: 		    radioButton[i].checked=true;
 1315: 		}
 1316: 	    }
 1317: 	}
 1318: 	formname["stores"+id].value = "0";
 1319: 	updateSelect(formname,id);
 1320: 	return;
 1321:     }
 1322: 
 1323:     function clearRadBox(formname,id) {
 1324: 	if (checkSolved(formname,id) == 'noupdate') {
 1325: 	    updateSelect(formname,id);
 1326: 	    return;
 1327: 	}
 1328: 	gradeSelect = formname["GD_SEL"+id];
 1329: 	for (var i=0; i<gradeSelect.length; i++) {
 1330: 	    if (gradeSelect[i].selected) {
 1331: 		var selectx=i;
 1332: 	    }
 1333: 	}
 1334: 	var stores = formname["stores"+id];
 1335: 	if (selectx == stores.value) { return };
 1336: 	var gradeBox = formname["GD_BOX"+id];
 1337: 	gradeBox.value = "";
 1338: 	var radioButton = formname["RADVAL"+id];
 1339: 	for (var i=0; i<radioButton.length; i++) {
 1340: 	    radioButton[i].checked=false;
 1341: 	}
 1342: 	stores.value = selectx;
 1343:     }
 1344: 
 1345:     function checkSolved(formname,id) {
 1346: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1347: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1348: 	    if (!reply) {return "noupdate";}
 1349: 	    formname.overRideScore.value = 'yes';
 1350: 	}
 1351: 	return "update";
 1352:     }
 1353: 
 1354:     function updateSelect(formname,id) {
 1355: 	formname["GD_SEL"+id][0].selected = true;
 1356: 	return;
 1357:     }
 1358: 
 1359: //=========== Check that a point is assigned for all the parts  ============
 1360:     function checksubmit(formname,val,total,parttot) {
 1361: 	formname.gradeOpt.value = val;
 1362: 	if (val == "Save & Next") {
 1363: 	    for (i=0;i<=total;i++) {
 1364: 		for (j=0;j<parttot;j++) {
 1365: 		    var partid = formname["partid"+i+"_"+j].value;
 1366: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1367: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1368: 			if (points == "") {
 1369: 			    var name = formname["name"+i].value;
 1370: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1371: 			    var resp = confirm("You did not assign a score for "+studentID+
 1372: 					       ", part "+partid+". Continue?");
 1373: 			    if (resp == false) {
 1374: 				formname["GD_BOX"+i+"_"+partid].focus();
 1375: 				return false;
 1376: 			    }
 1377: 			}
 1378: 		    }
 1379: 		}
 1380: 	    }
 1381: 	}
 1382: 	if (val == "Grade Student") {
 1383: 	    formname.showgrading.value = "yes";
 1384: 	    if (formname.Status.value == "") {
 1385: 		formname.Status.value = "Active";
 1386: 	    }
 1387: 	    formname.studentNo.value = total;
 1388: 	}
 1389: 	formname.submit();
 1390:     }
 1391: 
 1392: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1393:     function checkSubmitPage(formname,total) {
 1394: 	noscore = new Array(100);
 1395: 	var ptr = 0;
 1396: 	for (i=1;i<total;i++) {
 1397: 	    var partid = formname["q_"+i].value;
 1398: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1399: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1400: 		var status = formname["solved"+i+"_"+partid].value;
 1401: 		if (points == "" && status != "correct_by_student") {
 1402: 		    noscore[ptr] = i;
 1403: 		    ptr++;
 1404: 		}
 1405: 	    }
 1406: 	}
 1407: 	if (ptr != 0) {
 1408: 	    var sense = ptr == 1 ? ": " : "s: ";
 1409: 	    var prolist = "";
 1410: 	    if (ptr == 1) {
 1411: 		prolist = noscore[0];
 1412: 	    } else {
 1413: 		var i = 0;
 1414: 		while (i < ptr-1) {
 1415: 		    prolist += noscore[i]+", ";
 1416: 		    i++;
 1417: 		}
 1418: 		prolist += "and "+noscore[i];
 1419: 	    }
 1420: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1421: 	    if (resp == false) {
 1422: 		return false;
 1423: 	    }
 1424: 	}
 1425: 
 1426: 	formname.submit();
 1427:     }
 1428: </script>
 1429: SUBJAVASCRIPT
 1430: }
 1431: 
 1432: #--- javascript for essay type problem --
 1433: sub sub_page_kw_js {
 1434:     my $request = shift;
 1435:     my $iconpath = $request->dir_config('lonIconsURL');
 1436:     &commonJSfunctions($request);
 1437: 
 1438:     my $inner_js_msg_central=<<INNERJS;
 1439:     <script text="text/javascript">
 1440:     function checkInput() {
 1441:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1442:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1443:       var usrctr = document.msgcenter.usrctr.value;
 1444:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1445:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1446: 
 1447:       var msgchk = "";
 1448:       if (document.msgcenter.subchk.checked) {
 1449:          msgchk = "msgsub,";
 1450:       }
 1451:       var includemsg = 0;
 1452:       for (var i=1; i<=nmsg; i++) {
 1453:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1454:           var frmmsg = document.msgcenter["msg"+i];
 1455:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1456:           var showflg = opener.document.SCORE["shownOnce"+i];
 1457:           showflg.value = "1";
 1458:           var chkbox = document.msgcenter["msgn"+i];
 1459:           if (chkbox.checked) {
 1460:              msgchk += "savemsg"+i+",";
 1461:              includemsg = 1;
 1462:           }
 1463:       }
 1464:       if (document.msgcenter.newmsgchk.checked) {
 1465:          msgchk += "newmsg"+usrctr;
 1466:          includemsg = 1;
 1467:       }
 1468:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1469:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1470:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1471:       includemsg.value = msgchk;
 1472: 
 1473:       self.close()
 1474: 
 1475:     }
 1476:     </script>
 1477: INNERJS
 1478: 
 1479:     my $inner_js_highlight_central=<<INNERJS;
 1480:  <script type="text/javascript">
 1481:     function updateChoice(flag) {
 1482:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1483:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1484:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1485:       opener.document.SCORE.refresh.value = "on";
 1486:       if (opener.document.SCORE.keywords.value!=""){
 1487:          opener.document.SCORE.submit();
 1488:       }
 1489:       self.close()
 1490:     }
 1491: </script>
 1492: INNERJS
 1493: 
 1494:     my $start_page_msg_central = 
 1495:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1496: 				       {'js_ready'  => 1,
 1497: 					'only_body' => 1,
 1498: 					'bgcolor'   =>'#FFFFFF',});
 1499:     my $end_page_msg_central = 
 1500: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1501: 
 1502: 
 1503:     my $start_page_highlight_central = 
 1504:         &Apache::loncommon::start_page('Highlight Central',
 1505: 				       $inner_js_highlight_central,
 1506: 				       {'js_ready'  => 1,
 1507: 					'only_body' => 1,
 1508: 					'bgcolor'   =>'#FFFFFF',});
 1509:     my $end_page_highlight_central = 
 1510: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1511: 
 1512:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1513:     $docopen=~s/^document\.//;
 1514:     my %js_lt = &Apache::lonlocal::texthash(
 1515:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1516:                 plse => 'Please select a word or group of words from document and then click this link.',
 1517:                 adds => 'Add selection to keyword list? Edit if desired.',
 1518:                 col1 => 'red',
 1519:                 col2 => 'green',
 1520:                 col3 => 'blue',
 1521:                 siz1 => 'normal',
 1522:                 siz2 => '+1',
 1523:                 siz3 => '+2',
 1524:                 sty1 => 'normal',
 1525:                 sty2 => 'italic',
 1526:                 sty3 => 'bold',
 1527:              );
 1528:     my %html_js_lt = &Apache::lonlocal::texthash(
 1529:                 comp => 'Compose Message for: ',
 1530:                 incl => 'Include',
 1531:                 type => 'Type',
 1532:                 subj => 'Subject',
 1533:                 mesa => 'Message',
 1534:                 new  => 'New',
 1535:                 save => 'Save',
 1536:                 canc => 'Cancel',
 1537:                 kehi => 'Keyword Highlight Options',
 1538:                 txtc => 'Text Color',
 1539:                 font => 'Font Size',
 1540:                 fnst => 'Font Style',
 1541:              );
 1542:     &js_escape(\%js_lt);
 1543:     &html_escape(\%html_js_lt);
 1544:     &js_escape(\%html_js_lt);
 1545:     $request->print(<<SUBJAVASCRIPT);
 1546: <script type="text/javascript" language="javascript">
 1547: 
 1548: //===================== Show list of keywords ====================
 1549:   function keywords(formname) {
 1550:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1551:     if (nret==null) return;
 1552:     formname.keywords.value = nret;
 1553: 
 1554:     if (formname.keywords.value != "") {
 1555: 	formname.refresh.value = "on";
 1556: 	formname.submit();
 1557:     }
 1558:     return;
 1559:   }
 1560: 
 1561: //===================== Script to view submitted by ==================
 1562:   function viewSubmitter(submitter) {
 1563:     document.SCORE.refresh.value = "on";
 1564:     document.SCORE.NCT.value = "1";
 1565:     document.SCORE.unamedom0.value = submitter;
 1566:     document.SCORE.submit();
 1567:     return;
 1568:   }
 1569: 
 1570: //===================== Script to add keyword(s) ==================
 1571:   function getSel() {
 1572:     if (document.getSelection) txt = document.getSelection();
 1573:     else if (document.selection) txt = document.selection.createRange().text;
 1574:     else return;
 1575:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1576:     if (cleantxt=="") {
 1577: 	alert("$js_lt{'plse'}");
 1578: 	return;
 1579:     }
 1580:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1581:     if (nret==null) return;
 1582:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1583:     if (document.SCORE.keywords.value != "") {
 1584: 	document.SCORE.refresh.value = "on";
 1585: 	document.SCORE.submit();
 1586:     }
 1587:     return;
 1588:   }
 1589: 
 1590: //====================== Script for composing message ==============
 1591:    // preload images
 1592:    img1 = new Image();
 1593:    img1.src = "$iconpath/mailbkgrd.gif";
 1594:    img2 = new Image();
 1595:    img2.src = "$iconpath/mailto.gif";
 1596: 
 1597:   function msgCenter(msgform,usrctr,fullname) {
 1598:     var Nmsg  = msgform.savemsgN.value;
 1599:     savedMsgHeader(Nmsg,usrctr,fullname);
 1600:     var subject = msgform.msgsub.value;
 1601:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1602:     re = /msgsub/;
 1603:     var shwsel = "";
 1604:     if (re.test(msgchk)) { shwsel = "checked" }
 1605:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1606:     displaySubject(checkEntities(subject),shwsel);
 1607:     for (var i=1; i<=Nmsg; i++) {
 1608: 	var testmsg = "savemsg"+i+",";
 1609: 	re = new RegExp(testmsg,"g");
 1610: 	shwsel = "";
 1611: 	if (re.test(msgchk)) { shwsel = "checked" }
 1612: 	var message = document.SCORE["savemsg"+i].value;
 1613: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1614: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1615: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1616:     }
 1617:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1618:     shwsel = "";
 1619:     re = /newmsg/;
 1620:     if (re.test(msgchk)) { shwsel = "checked" }
 1621:     newMsg(newmsg,shwsel);
 1622:     msgTail(); 
 1623:     return;
 1624:   }
 1625: 
 1626:   function checkEntities(strx) {
 1627:     if (strx.length == 0) return strx;
 1628:     var orgStr = ["&", "<", ">", '"']; 
 1629:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1630:     var counter = 0;
 1631:     while (counter < 4) {
 1632: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1633: 	counter++;
 1634:     }
 1635:     return strx;
 1636:   }
 1637: 
 1638:   function strReplace(strx, orgStr, newStr) {
 1639:     return strx.split(orgStr).join(newStr);
 1640:   }
 1641: 
 1642:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1643:     var height = 70*Nmsg+250;
 1644:     if (height > 600) {
 1645: 	height = 600;
 1646:     }
 1647:     var xpos = (screen.width-600)/2;
 1648:     xpos = (xpos < 0) ? '0' : xpos;
 1649:     var ypos = (screen.height-height)/2-30;
 1650:     ypos = (ypos < 0) ? '0' : ypos;
 1651: 
 1652:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1653:     pWin.focus();
 1654:     pDoc = pWin.document;
 1655:     pDoc.$docopen;
 1656:     pDoc.write('$start_page_msg_central');
 1657: 
 1658:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1659:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1660:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1661: 
 1662:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1663:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1664:     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>");
 1665: }
 1666:     function displaySubject(msg,shwsel) {
 1667:     pDoc = pWin.document;
 1668:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1669:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1670:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1671:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1672: }
 1673: 
 1674:   function displaySavedMsg(ctr,msg,shwsel) {
 1675:     pDoc = pWin.document;
 1676:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1677:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1678:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1679:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1680: }
 1681: 
 1682:   function newMsg(newmsg,shwsel) {
 1683:     pDoc = pWin.document;
 1684:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1685:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1686:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1687:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1688: }
 1689: 
 1690:   function msgTail() {
 1691:     pDoc = pWin.document;
 1692:     pDoc.write("<\\/table>");
 1693:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1694:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1695:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1696:     pDoc.write("<\\/form>");
 1697:     pDoc.write('$end_page_msg_central');
 1698:     pDoc.close();
 1699: }
 1700: 
 1701: //====================== Script for keyword highlight options ==============
 1702:   function kwhighlight() {
 1703:     var kwclr    = document.SCORE.kwclr.value;
 1704:     var kwsize   = document.SCORE.kwsize.value;
 1705:     var kwstyle  = document.SCORE.kwstyle.value;
 1706:     var redsel = "";
 1707:     var grnsel = "";
 1708:     var blusel = "";
 1709:     var txtcol1 = "$js_lt{'col1'}";
 1710:     var txtcol2 = "$js_lt{'col2'}";
 1711:     var txtcol3 = "$js_lt{'col3'}";
 1712:     var txtsiz1 = "$js_lt{'siz1'}";
 1713:     var txtsiz2 = "$js_lt{'siz2'}";
 1714:     var txtsiz3 = "$js_lt{'siz3'}";
 1715:     var txtsty1 = "$js_lt{'sty1'}";
 1716:     var txtsty2 = "$js_lt{'sty2'}";
 1717:     var txtsty3 = "$js_lt{'sty3'}";
 1718:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1719:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1720:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1721:     var sznsel = "";
 1722:     var sz1sel = "";
 1723:     var sz2sel = "";
 1724:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1725:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1726:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1727:     var synsel = "";
 1728:     var syisel = "";
 1729:     var sybsel = "";
 1730:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1731:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1732:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1733:     highlightCentral();
 1734:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1735:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1736:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1737:     highlightend();
 1738:     return;
 1739:   }
 1740: 
 1741:   function highlightCentral() {
 1742: //    if (window.hwdWin) window.hwdWin.close();
 1743:     var xpos = (screen.width-400)/2;
 1744:     xpos = (xpos < 0) ? '0' : xpos;
 1745:     var ypos = (screen.height-330)/2-30;
 1746:     ypos = (ypos < 0) ? '0' : ypos;
 1747: 
 1748:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1749:     hwdWin.focus();
 1750:     var hDoc = hwdWin.document;
 1751:     hDoc.$docopen;
 1752:     hDoc.write('$start_page_highlight_central');
 1753:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1754:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1755: 
 1756:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1757:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1758:   }
 1759: 
 1760:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1761:     var hDoc = hwdWin.document;
 1762:     hDoc.write("<tr>");
 1763:     hDoc.write("<td align=\\"left\\">");
 1764:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1765:     hDoc.write("<td align=\\"left\\">");
 1766:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1767:     hDoc.write("<td align=\\"left\\">");
 1768:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1769:     hDoc.write("<\\/tr>");
 1770:   }
 1771: 
 1772:   function highlightend() { 
 1773:     var hDoc = hwdWin.document;
 1774:     hDoc.write("<\\/table><br \\/>");
 1775:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1776:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1777:     hDoc.write("<\\/form>");
 1778:     hDoc.write('$end_page_highlight_central');
 1779:     hDoc.close();
 1780:   }
 1781: 
 1782: </script>
 1783: SUBJAVASCRIPT
 1784: }
 1785: 
 1786: sub get_increment {
 1787:     my $increment = $env{'form.increment'};
 1788:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1789:         $increment != .1) {
 1790:         $increment = 1;
 1791:     }
 1792:     return $increment;
 1793: }
 1794: 
 1795: sub gradeBox_start {
 1796:     return (
 1797:         &Apache::loncommon::start_data_table()
 1798:        .&Apache::loncommon::start_data_table_header_row()
 1799:        .'<th>'.&mt('Part').'</th>'
 1800:        .'<th>'.&mt('Points').'</th>'
 1801:        .'<th>&nbsp;</th>'
 1802:        .'<th>'.&mt('Assign Grade').'</th>'
 1803:        .'<th>'.&mt('Weight').'</th>'
 1804:        .'<th>'.&mt('Grade Status').'</th>'
 1805:        .&Apache::loncommon::end_data_table_header_row()
 1806:     );
 1807: }
 1808: 
 1809: sub gradeBox_end {
 1810:     return (
 1811:         &Apache::loncommon::end_data_table()
 1812:     );
 1813: }
 1814: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1815: sub gradeBox {
 1816:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1817:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1818: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1819:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1820:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1821:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1822:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1823:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1824: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1825:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1826:     my $display_part= &get_display_part($partid,$symb);
 1827:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1828: 				       [$partid]);
 1829:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1830:     if ($last_resets{$partid}) {
 1831:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1832:     }
 1833:     my $result=&Apache::loncommon::start_data_table_row();
 1834:     my $ctr = 0;
 1835:     my $thisweight = 0;
 1836:     my $increment = &get_increment();
 1837: 
 1838:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1839:     while ($thisweight<=$wgt) {
 1840: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1841:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1842: 	    $thisweight.')" value="'.$thisweight.'" '.
 1843: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1844: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1845:         $thisweight += $increment;
 1846: 	$ctr++;
 1847:     }
 1848:     $radio.='</tr></table>';
 1849: 
 1850:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1851: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1852: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1853: 	$wgt.')" /></td>'."\n";
 1854:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1855: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1856: 	' </td>'."\n";
 1857:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1858: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1859:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1860: 	$line.='<option></option>'.
 1861: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1862:     } else {
 1863: 	$line.='<option selected="selected"></option>'.
 1864: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1865:     }
 1866:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1867: 
 1868: 
 1869:     $result .= 
 1870: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1871:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1872:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1873: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1874: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1875: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1876:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1877:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1878:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1879:         $aggtries.'" />'."\n";
 1880:     my $res_error;
 1881:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1882:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1883:     if ($res_error) {
 1884:         return &navmap_errormsg();
 1885:     }
 1886:     return $result;
 1887: }
 1888: 
 1889: sub handback_box {
 1890:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1891:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1892:     my (@respids);
 1893:     my @part_response_id = &flatten_responseType($responseType);
 1894:     foreach my $part_response_id (@part_response_id) {
 1895:     	my ($part,$resp) = @{ $part_response_id };
 1896:         if ($part eq $partid) {
 1897:             push(@respids,$resp);
 1898:         }
 1899:     }
 1900:     my $result;
 1901:     foreach my $respid (@respids) {
 1902: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1903: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1904: 	next if (!@$files);
 1905: 	my $file_counter = 0;
 1906: 	foreach my $file (@$files) {
 1907: 	    if ($file =~ /\/portfolio\//) {
 1908:                 $file_counter++;
 1909:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1910:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1911:     	        $file_disp = "$name.$ext";
 1912:     	        $file = $file_path.$file_disp;
 1913:     	        $result.=&mt('Return commented version of [_1] to student.',
 1914:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1915:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1916:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1917: 	    }
 1918: 	}
 1919:         if ($file_counter) {
 1920:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1921:                        '<span class="LC_info">'.
 1922:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1923:         }
 1924:     }
 1925:     return $result;    
 1926: }
 1927: 
 1928: sub show_problem {
 1929:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1930:     my $rendered;
 1931:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1932:     &Apache::lonxml::remember_problem_counter();
 1933:     if ($mode eq 'both' or $mode eq 'text') {
 1934: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1935: 						       $env{'request.course.id'},
 1936: 						       undef,\%form);
 1937:     }
 1938:     if ($removeform) {
 1939: 	$rendered=~s|<form(.*?)>||g;
 1940: 	$rendered=~s|</form>||g;
 1941: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1942:     }
 1943:     my $companswer;
 1944:     if ($mode eq 'both' or $mode eq 'answer') {
 1945: 	&Apache::lonxml::restore_problem_counter();
 1946: 	$companswer=
 1947: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1948: 						    $env{'request.course.id'},
 1949: 						    %form);
 1950:     }
 1951:     if ($removeform) {
 1952: 	$companswer=~s|<form(.*?)>||g;
 1953: 	$companswer=~s|</form>||g;
 1954: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1955:     }
 1956:     my $renderheading = &mt('View of the problem');
 1957:     my $answerheading = &mt('Correct answer');
 1958:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1959:         my $stu_fullname = $env{'form.fullname'};
 1960:         if ($stu_fullname eq '') {
 1961:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1962:         }
 1963:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1964:         if ($forwhom ne '') {
 1965:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1966:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1967:         }
 1968:     }
 1969:     $rendered=
 1970:         '<div class="LC_Box">'
 1971:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1972:        .$rendered
 1973:        .'</div>';
 1974:     $companswer=
 1975:         '<div class="LC_Box">'
 1976:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1977:        .$companswer
 1978:        .'</div>';
 1979:     my $result;
 1980:     if ($mode eq 'both') {
 1981:         $result=$rendered.$companswer;
 1982:     } elsif ($mode eq 'text') {
 1983:         $result=$rendered;
 1984:     } elsif ($mode eq 'answer') {
 1985:         $result=$companswer;
 1986:     }
 1987:     return $result;
 1988: }
 1989: 
 1990: sub files_exist {
 1991:     my ($r, $symb) = @_;
 1992:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1993: 
 1994:     foreach my $student (@students) {
 1995:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1996:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1997: 					      $udom,$uname);
 1998:         my ($string,$timestamp)= &get_last_submission(\%record);
 1999:         foreach my $submission (@$string) {
 2000:             my ($partid,$respid) =
 2001: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2002:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2003: 					   \%record);
 2004:             return 1 if (@$files);
 2005:         }
 2006:     }
 2007:     return 0;
 2008: }
 2009: 
 2010: sub download_all_link {
 2011:     my ($r,$symb) = @_;
 2012:     my $all_students = 
 2013: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2014: 
 2015:     my $parts =
 2016: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2017: 
 2018:     my $identifier = &Apache::loncommon::get_cgi_id();
 2019:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2020:                              'cgi.'.$identifier.'.symb' => $symb,
 2021:                              'cgi.'.$identifier.'.parts' => $parts,});
 2022:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2023: 	      &mt('Download All Submitted Documents').'</a>');
 2024:     return
 2025: }
 2026: 
 2027: sub build_section_inputs {
 2028:     my $section_inputs;
 2029:     if ($env{'form.section'} eq '') {
 2030:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2031:     } else {
 2032:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2033:         foreach my $section (@sections) {
 2034:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2035:         }
 2036:     }
 2037:     return $section_inputs;
 2038: }
 2039: 
 2040: # --------------------------- show submissions of a student, option to grade 
 2041: sub submission {
 2042:     my ($request,$counter,$total) = @_;
 2043:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2044:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2045:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2046:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2047:     my ($symb) = &get_symb($request); 
 2048:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2049: 
 2050:     if (!&canview($usec)) {
 2051:         $request->print(
 2052:             '<span class="LC_warning">'.
 2053:             &mt('Unable to view requested student.').
 2054:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2055:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2056:             '</span>');
 2057: 	$request->print(&show_grading_menu_form($symb));
 2058: 	return;
 2059:     }
 2060: 
 2061:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2062:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2063:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2064:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2065:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2066: 	'" src="'.$request->dir_config('lonIconsURL').
 2067: 	'/check.gif" height="16" border="0" />';
 2068: 
 2069:     # header info
 2070:     if ($counter == 0) {
 2071: 	&sub_page_js($request);
 2072: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2073: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2074: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2075: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2076: 	    &download_all_link($request, $symb);
 2077: 	}
 2078: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2079: 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
 2080: 
 2081: 	# option to display problem, only once else it cause problems 
 2082:         # with the form later since the problem has a form.
 2083: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2084: 	    my $mode;
 2085: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2086: 		$mode='both';
 2087: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2088: 		$mode='text';
 2089: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2090: 		$mode='answer';
 2091: 	    }
 2092: 	    &Apache::lonxml::clear_problem_counter();
 2093: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2094: 	}
 2095: 
 2096: 	# kwclr is the only variable that is guaranteed not to be blank 
 2097:         # if this subroutine has been called once.
 2098: 	my %keyhash = ();
 2099: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2100: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2101: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2102: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2103: 
 2104: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2105: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2106: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2107: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2108: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2109: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2110: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2111: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2112: 	}
 2113: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2114: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2115: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2116: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2117: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2118: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2119: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2120: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2121: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2122: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2123: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2124: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2125: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2126: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2127: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2128: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2129: 			&build_section_inputs().
 2130: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2131: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2132: 			'<input type="hidden" name="NCT"'.
 2133: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2134: 	if ($env{'form.handgrade'} eq 'yes') {
 2135: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2136: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2137: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2138: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2139: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2140: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2141: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2142: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2143: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2144: 	    }
 2145: 	}
 2146: 	
 2147: 	my ($cts,$prnmsg) = (1,'');
 2148: 	while ($cts <= $env{'form.savemsgN'}) {
 2149: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2150: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2151: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2152: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2153: 		'" />'."\n".
 2154: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2155: 	    $cts++;
 2156: 	}
 2157: 	$request->print($prnmsg);
 2158: 
 2159: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2160: 
 2161:             my %lt = &Apache::lonlocal::texthash(
 2162:                           keyh => 'Keyword Highlighting for Essays',
 2163:                           keyw => 'Keyword Options',
 2164:                           list => 'List',
 2165:                           past => 'Paste Selection to List',
 2166:                           high => 'Highlight Attribute',
 2167:                      );
 2168: #
 2169: # Print out the keyword options line
 2170: #
 2171:             $request->print(
 2172:                 '<div class="LC_columnSection">'
 2173:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2174:                .&Apache::lonhtmlcommon::funclist_from_array(
 2175:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2176:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2177:  class="page">'.$lt{'past'}.'</a>',
 2178:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2179:                     {legend => $lt{'keyw'}})
 2180:                .'</fieldset></div>'
 2181:             );
 2182: 
 2183: #
 2184: # Load the other essays for similarity check
 2185: #
 2186:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2187: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2188: 	    $apath=&escape($apath);
 2189: 	    $apath=~s/\W/\_/gs;
 2190:             &init_old_essays($symb,$apath,$adom,$aname);
 2191:         }
 2192:     }
 2193: 
 2194: # This is where output for one specific student would start
 2195:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2196:     $request->print(
 2197:         "\n\n"
 2198:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2199:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2200:        ."\n"
 2201:     );
 2202: 
 2203:     # Show additional functions if allowed
 2204:     if ($perm{'vgr'}) {
 2205:         $request->print(
 2206:             &Apache::loncommon::track_student_link(
 2207:                 'View recent activity',
 2208:                 $uname,$udom,'check')
 2209:            .' '
 2210:         );
 2211:     }
 2212:     if ($perm{'opa'}) {
 2213:         $request->print(
 2214:             &Apache::loncommon::pprmlink(
 2215:                 &mt('Set/Change parameters'),
 2216:                 $uname,$udom,$symb,'check'));
 2217:     }
 2218: 
 2219:     # Show Problem
 2220:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2221: 	my $mode;
 2222: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2223: 	    $mode='both';
 2224: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2225: 	    $mode='text';
 2226: 	} elsif ($env{'form.vAns'} eq 'all') {
 2227: 	    $mode='answer';
 2228: 	}
 2229: 	&Apache::lonxml::clear_problem_counter();
 2230: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2231:     }
 2232: 
 2233:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2234:     my $res_error;
 2235:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2236:     if ($res_error) {
 2237:         $request->print(&navmap_errormsg());
 2238:         return;
 2239:     }
 2240: 
 2241:     # Display student info
 2242:     $request->print(($counter == 0 ? '' : '<br />'));
 2243: 
 2244:     my $result='<div class="LC_Box">'
 2245:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2246:     $result.='<input type="hidden" name="name'.$counter.
 2247:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2248:     if ($env{'form.handgrade'} eq 'no') {
 2249:         $result.='<p class="LC_info">'
 2250:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2251:                 ."</p>\n";
 2252:     }
 2253: 
 2254:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2255:     my $fullname;
 2256:     my $col_fullnames = [];
 2257:     if ($env{'form.handgrade'} eq 'yes') {
 2258: 	(my $sub_result,$fullname,$col_fullnames)=
 2259: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2260: 				 $counter);
 2261: 	$result.=$sub_result;
 2262:     }
 2263:     $request->print($result."\n");
 2264: 
 2265:     # print student answer/submission
 2266:     # Options are (1) Handgraded submission only
 2267:     #             (2) Last submission, includes submission that is not handgraded 
 2268:     #                  (for multi-response type part)
 2269:     #             (3) Last submission plus the parts info
 2270:     #             (4) The whole record for this student
 2271: 
 2272: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2273: 	
 2274: 	my $lastsubonly;
 2275: 
 2276:         if ($$timestamp eq '') {
 2277:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2278:         } else {
 2279:             $lastsubonly =
 2280:                 '<div class="LC_grade_submissions_body">'
 2281:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2282: 
 2283: 	    my %seenparts;
 2284: 	    my @part_response_id = &flatten_responseType($responseType);
 2285: 	    foreach my $part (@part_response_id) {
 2286: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2287: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2288: 
 2289: 		my ($partid,$respid) = @{ $part };
 2290: 		my $display_part=&get_display_part($partid,$symb);
 2291: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2292: 		    if (exists($seenparts{$partid})) { next; }
 2293: 		    $seenparts{$partid}=1;
 2294:                     $request->print(
 2295:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2296:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2297:                                    '<a href="javascript:viewSubmitter(\''.
 2298:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2299:                                    '\');" target="_self">'.
 2300:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2301:                         '<br />');
 2302: 		    next;
 2303: 		}
 2304: 		my $responsetype = $responseType->{$partid}->{$respid};
 2305: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2306:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2307:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2308:                         ' <span class="LC_internal_info">'.
 2309:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2310:                         '</span>&nbsp; &nbsp;'.
 2311: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2312: 		    next;
 2313: 		}
 2314: 		foreach my $submission (@$string) {
 2315: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2316: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2317: 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2318: 		    # Similarity check
 2319: 		    my $similar='';
 2320:                     my ($type,$trial,$rndseed);
 2321:                     if ($hide eq 'rand') {
 2322:                         $type = 'randomizetry';
 2323:                         $trial = $record{"resource.$partid.tries"};
 2324:                         $rndseed = $record{"resource.$partid.rndseed"};
 2325:                     }
 2326: 		    if ($env{'form.checkPlag'}) {
 2327: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2328: 			    &most_similar($uname,$udom,$symb,$subval);
 2329: 			if ($osim) {
 2330: 			    $osim=int($osim*100.0);
 2331: 			    my %old_course_desc = 
 2332: 				&Apache::lonnet::coursedescription($ocrsid,
 2333: 								   {'one_time' => 1});
 2334: 
 2335:                             if ($hide eq 'anon') {
 2336:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2337:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2338:                             } else {
 2339: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2340: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2341: 				        $osim,
 2342: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2343: 				        $old_course_desc{'description'},
 2344: 				        $old_course_desc{'num'},
 2345: 				        $old_course_desc{'domain'}).
 2346: 				    '</span></h3><blockquote><i>'.
 2347: 				    &keywords_highlight($oessay).
 2348: 				    '</i></blockquote><hr />';
 2349:                             }
 2350: 			}
 2351: 		    }
 2352: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2353:                                          undef,$type,$trial,$rndseed);
 2354:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2355:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2356: 			my $display_part=&get_display_part($partid,$symb);
 2357:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2358:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2359:                             ' <span class="LC_internal_info">'.
 2360:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2361:                             '</span>&nbsp; &nbsp;';
 2362: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2363: 			if (@$files) {
 2364:                             if ($hide eq 'anon') {
 2365:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2366:                             } else {
 2367:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2368:                                             .'<br /><span class="LC_warning">';
 2369:                                 if(@$files == 1) {
 2370:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2371:                                 } else {
 2372:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2373:                                 }
 2374:                                 $lastsubonly .= '</span>';
 2375: 
 2376:                                 foreach my $file (@$files) {
 2377:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2378:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2379:                                 }
 2380:                             }
 2381: 			    $lastsubonly.='<br />';
 2382: 			}
 2383:                         if ($hide eq 'anon') {
 2384:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2385:                         } else {
 2386: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2387:                             if ($draft) {
 2388:                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2389:                             }
 2390:                             $subval =
 2391: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2392: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2393:                             if ($responsetype eq 'essay') {
 2394:                                 $subval =~ s{\n}{<br />}g;
 2395:                             }
 2396:                             $lastsubonly.=$subval."\n";
 2397:                         }
 2398: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2399: 			$lastsubonly.='</div>';
 2400: 		    }
 2401: 		}
 2402: 	    }
 2403: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2404: 	}
 2405: 	$request->print($lastsubonly);
 2406:    if ($env{'form.lastSub'} eq 'datesub') {
 2407: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2408: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2409:     }
 2410:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2411:         my $identifier = (&canmodify($usec)? $counter : '');
 2412: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2413: 								 $env{'request.course.id'},
 2414: 								 $last,'.submission',
 2415: 								 'Apache::grades::keywords_highlight',
 2416:                                                                  $usec,$identifier));
 2417:     }
 2418: 
 2419:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2420: 	.$udom.'" />'."\n");
 2421:     # return if view submission with no grading option
 2422:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2423: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2424: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2425: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2426: 	$toGrade.='</div>'."\n";
 2427: 	if (($env{'form.command'} eq 'submission') || 
 2428: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2429: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2430: 	}
 2431: 	$request->print($toGrade);
 2432: 	return;
 2433:     } else {
 2434: 	$request->print('</div>'."\n");
 2435:     }
 2436: 
 2437:     # essay grading message center
 2438:     if ($env{'form.handgrade'} eq 'yes') {
 2439: 	my $result='<div class="LC_grade_message_center">';
 2440:     
 2441: 	$result.='<div class="LC_grade_message_center_header">'.
 2442: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2443: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2444: 	my $msgfor = $givenn.' '.$lastname;
 2445: 	if (scalar(@$col_fullnames) > 0) {
 2446: 	    my $lastone = pop(@$col_fullnames);
 2447: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2448: 	}
 2449: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2450: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2451: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2452: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2453: 	    ',\''.$msgfor.'\');" target="_self">'.
 2454: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2455: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2456: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2457: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2458: 	    '<br />&nbsp;('.
 2459: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2460: 	$result.='</div></div>';
 2461: 	$request->print($result);
 2462:     }
 2463: 
 2464:     my %seen = ();
 2465:     my @partlist;
 2466:     my @gradePartRespid;
 2467:     my @part_response_id = &flatten_responseType($responseType);
 2468:     $request->print(
 2469:         '<div class="LC_Box">'
 2470:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2471:     );
 2472:     $request->print(&gradeBox_start());
 2473:     foreach my $part_response_id (@part_response_id) {
 2474:     	my ($partid,$respid) = @{ $part_response_id };
 2475: 	my $part_resp = join('_',@{ $part_response_id });
 2476: 	next if ($seen{$partid} > 0);
 2477: 	$seen{$partid}++;
 2478: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2479: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2480: 	push(@partlist,$partid);
 2481: 	push(@gradePartRespid,$partid.'.'.$respid);
 2482: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2483:     }
 2484:     $request->print(&gradeBox_end()); # </div>
 2485:     $request->print('</div>');
 2486: 
 2487:     $request->print('<div class="LC_grade_info_links">');
 2488:     $request->print('</div>');
 2489: 
 2490:     $result='<input type="hidden" name="partlist'.$counter.
 2491: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2492:     $result.='<input type="hidden" name="gradePartRespid'.
 2493: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2494:     my $ctr = 0;
 2495:     while ($ctr < scalar(@partlist)) {
 2496: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2497: 	    $partlist[$ctr].'" />'."\n";
 2498: 	$ctr++;
 2499:     }
 2500:     $request->print($result.''."\n");
 2501: 
 2502: # Done with printing info for one student
 2503: 
 2504:     $request->print('</div>');#LC_grade_show_user
 2505: 
 2506: 
 2507:     # print end of form
 2508:     if ($counter == $total) {
 2509:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2510: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2511: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2512: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2513: 	my $ntstu ='<select name="NTSTU">'.
 2514: 	    '<option>1</option><option>2</option>'.
 2515: 	    '<option>3</option><option>5</option>'.
 2516: 	    '<option>7</option><option>10</option></select>'."\n";
 2517: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2518: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2519:         $endform.=&mt('[_1]student(s)',$ntstu);
 2520: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2521: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2522: 	    '<input type="button" value="'.&mt('Next').'" '.
 2523: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2524:         $endform.='<span class="LC_warning">'.
 2525:                   &mt('(Next and Previous (student) do not save the scores.)').
 2526:                   '</span>'."\n" ;
 2527:         $endform.="<input type='hidden' value='".&get_increment().
 2528:             "' name='increment' />";
 2529: 	$endform.='</td></tr></table></form>';
 2530: 	$endform.=&show_grading_menu_form($symb);
 2531: 	$request->print($endform);
 2532:     }
 2533:     return '';
 2534: }
 2535: 
 2536: sub check_collaborators {
 2537:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2538:     my ($result,@col_fullnames);
 2539:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2540:     foreach my $part (keys(%$handgrade)) {
 2541: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2542: 					'.maxcollaborators',
 2543: 					$symb,$udom,$uname);
 2544: 	next if ($ncol <= 0);
 2545: 	$part =~ s/\_/\./g;
 2546: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2547: 	my (@good_collaborators, @bad_collaborators);
 2548: 	foreach my $possible_collaborator
 2549: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2550: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2551: 	    next if ($possible_collaborator eq '');
 2552: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2553: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2554: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2555: 	    # Doing this grep allows 'fuzzy' specification
 2556: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2557: 			       keys(%$classlist));
 2558: 	    if (! scalar(@matches)) {
 2559: 		push(@bad_collaborators, $possible_collaborator);
 2560: 	    } else {
 2561: 		push(@good_collaborators, @matches);
 2562: 	    }
 2563: 	}
 2564: 	if (scalar(@good_collaborators) != 0) {
 2565: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2566: 	    foreach my $name (@good_collaborators) {
 2567: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2568: 		push(@col_fullnames, $givenn.' '.$lastname);
 2569: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2570: 	    }
 2571: 	    $result.='</ol><br />'."\n";
 2572: 	    my ($part)=split(/\./,$part);
 2573: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2574: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2575: 		"\n";
 2576: 	}
 2577: 	if (scalar(@bad_collaborators) > 0) {
 2578: 	    $result.='<div class="LC_warning">';
 2579: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2580: 	    $result .= '</div>';
 2581: 	}         
 2582: 	if (scalar(@bad_collaborators > $ncol)) {
 2583: 	    $result .= '<div class="LC_warning">';
 2584: 	    $result .= &mt('This student has submitted too many '.
 2585: 		'collaborators.  Maximum is [_1].',$ncol);
 2586: 	    $result .= '</div>';
 2587: 	}
 2588:     }
 2589:     return ($result,$fullname,\@col_fullnames);
 2590: }
 2591: 
 2592: #--- Retrieve the last submission for all the parts
 2593: sub get_last_submission {
 2594:     my ($returnhash)=@_;
 2595:     my (@string,$timestamp,%lasthidden);
 2596:     if ($$returnhash{'version'}) {
 2597: 	my %lasthash=();
 2598: 	my ($version);
 2599: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2600: 	    foreach my $key (sort(split(/\:/,
 2601: 					$$returnhash{$version.':keys'}))) {
 2602: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2603: 		$timestamp = 
 2604: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2605: 	    }
 2606: 	}
 2607:         my (%typeparts,%randombytry);
 2608:         my $showsurv = 
 2609:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2610:         foreach my $key (sort(keys(%lasthash))) {
 2611:             if ($key =~ /\.type$/) {
 2612:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2613:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2614:                     ($lasthash{$key} eq 'randomizetry')) {
 2615:                     my ($ign,@parts) = split(/\./,$key);
 2616:                     pop(@parts);
 2617:                     my $id = join('.',@parts);
 2618:                     if ($lasthash{$key} eq 'randomizetry') {
 2619:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2620:                     } else {
 2621:                         unless ($showsurv) {
 2622:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2623:                         }
 2624:                     }
 2625:                     delete($lasthash{$key});
 2626:                 }
 2627:             }
 2628:         }
 2629:         my @hidden = keys(%typeparts);
 2630:         my @randomize = keys(%randombytry);
 2631: 	foreach my $key (keys(%lasthash)) {
 2632: 	    next if ($key !~ /\.submission$/);
 2633:             my $hide;
 2634:             if (@hidden) {
 2635:                 foreach my $id (@hidden) {
 2636:                     if ($key =~ /^\Q$id\E/) {
 2637:                         $hide = 'anon';
 2638:                         last;
 2639:                     }
 2640:                 }
 2641:             }
 2642:             unless ($hide) {
 2643:                 if (@randomize) {
 2644:                     foreach my $id (@randomize) {
 2645:                         if ($key =~ /^\Q$id\E/) {
 2646:                             $hide = 'rand';
 2647:                             last;
 2648:                         }
 2649:                     }
 2650:                 }
 2651:             }
 2652: 	    my ($partid,$foo) = split(/submission$/,$key);
 2653: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
 2654:             push(@string, join(':', $key, $hide, $draft, (
 2655:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2656:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2657: 	}
 2658:     }
 2659:     if (!@string) {
 2660: 	$string[0] =
 2661: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2662:     }
 2663:     return (\@string,\$timestamp);
 2664: }
 2665: 
 2666: #--- High light keywords, with style choosen by user.
 2667: sub keywords_highlight {
 2668:     my $string    = shift;
 2669:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2670:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2671:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2672:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2673:     foreach my $keyword (@keylist) {
 2674: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2675:     }
 2676:     return $string;
 2677: }
 2678: 
 2679: # For Tasks provide a mechanism to display previous version for one specific student
 2680: 
 2681: sub show_previous_task_version {
 2682:     my ($request,$symb) = @_;
 2683:     if ($symb eq '') {
 2684:         $request->print(
 2685:             '<span class="LC_error">'.
 2686:             &mt('Unable to handle ambiguous references.').
 2687:             '</span>');
 2688:         return '';
 2689:     }
 2690:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2691:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2692:     if (!&canview($usec)) {
 2693:         $request->print('<span class="LC_warning">'.
 2694:                         &mt('Unable to view previous version for requested student.').
 2695:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2696:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2697:                         '</span>');
 2698:         return;
 2699:     }
 2700:     my $mode = 'both';
 2701:     my $isTask = ($symb =~/\.task$/);
 2702:     if ($isTask) {
 2703:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2704:             if ($env{'form.fullname'} eq '') {
 2705:                 $env{'form.fullname'} =
 2706:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2707:             }
 2708:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2709:             $request->print("\n\n".
 2710:                             '<div class="LC_grade_show_user">'.
 2711:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2712:                             '</h2>'."\n");
 2713:             &Apache::lonxml::clear_problem_counter();
 2714:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2715:                             {'previousversion' => $env{'form.previousversion'} }));
 2716:             $request->print("\n</div>");
 2717:         }
 2718:     }
 2719:     return;
 2720: }
 2721: 
 2722: sub choose_task_version_form {
 2723:     my ($symb,$uname,$udom,$nomenu) = @_;
 2724:     my $isTask = ($symb =~/\.task$/);
 2725:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2726:     if ($isTask) {
 2727:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2728:                                               $udom,$uname);
 2729:         if (($record{'resource.0.version'} eq '') ||
 2730:             ($record{'resource.0.version'} < 2)) {
 2731:             return ($record{'resource.0.version'},
 2732:                     $record{'resource.0.version'},$result,$js);
 2733:         } else {
 2734:             $current = $record{'resource.0.version'};
 2735:         }
 2736:         if ($env{'form.previousversion'}) {
 2737:             $displayed = $env{'form.previousversion'};
 2738:             $rowtitle = &mt('Choose another version:')
 2739:         } else {
 2740:             $displayed = $current;
 2741:             $rowtitle = &mt('Show earlier version:');
 2742:         }
 2743:         $result = '<div class="LC_left_float">';
 2744:         my $list;
 2745:         my $numversions = 0;
 2746:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2747:             if ($i == $current) {
 2748:                 if (!$env{'form.previousversion'} || $nomenu) {
 2749:                     next;
 2750:                 } else {
 2751:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2752:                     $numversions ++;
 2753:                 }
 2754:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2755:                 unless ($i == $env{'form.previousversion'}) {
 2756:                     $numversions ++;
 2757:                 }
 2758:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2759:             }
 2760:         }
 2761:         if ($numversions) {
 2762:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2763:             $result .=
 2764:                 '<form name="getprev" method="post" action=""'.
 2765:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2766:                 &Apache::loncommon::start_data_table().
 2767:                 &Apache::loncommon::start_data_table_row().
 2768:                 '<th align="left">'.$rowtitle.'</th>'.
 2769:                 '<td><select name="version">'.
 2770:                 '<option>'.&mt('Select').'</option>'.
 2771:                 $list.
 2772:                 '</select></td>'.
 2773:                 &Apache::loncommon::end_data_table_row();
 2774:             unless ($nomenu) {
 2775:                 $result .= &Apache::loncommon::start_data_table_row().
 2776:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2777:                 '<td><span class="LC_nobreak">'.
 2778:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2779:                 &mt('Yes').'</label>'.
 2780:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2781:                 '</span></td>'.
 2782:                 &Apache::loncommon::end_data_table_row();
 2783:             }
 2784:             $result .=
 2785:                 &Apache::loncommon::start_data_table_row().
 2786:                 '<th align="left">&nbsp;</th>'.
 2787:                 '<td>'.
 2788:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2789:                 '</td>'.
 2790:                 &Apache::loncommon::end_data_table_row().
 2791:                 &Apache::loncommon::end_data_table().
 2792:                 '</form>';
 2793:             $js = &previous_display_javascript($nomenu,$current);
 2794:         } elsif ($displayed && $nomenu) {
 2795:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2796:         } else {
 2797:             $result .= &mt('No previous versions to show for this student');
 2798:         }
 2799:         $result .= '</div>';
 2800:     }
 2801:     return ($current,$displayed,$result,$js);
 2802: }
 2803: 
 2804: sub previous_display_javascript {
 2805:     my ($nomenu,$current) = @_;
 2806:     my $js = <<"JSONE";
 2807: <script type="text/javascript">
 2808: // <![CDATA[
 2809: function previousVersion(uname,udom,symb) {
 2810:     var current = '$current';
 2811:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2812:     var prevstr = new RegExp("^\\\\d+\$");
 2813:     if (!prevstr.test(version)) {
 2814:         return false;
 2815:     }
 2816:     var url = '';
 2817:     if (version == current) {
 2818:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2819:     } else {
 2820:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2821:     }
 2822: JSONE
 2823:     if ($nomenu) {
 2824:         $js .= <<"JSTWO";
 2825:     document.location.href = url;
 2826: JSTWO
 2827:     } else {
 2828:         $js .= <<"JSTHREE";
 2829:     var newwin = 0;
 2830:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2831:         if (document.getprev.prevwin[i].checked == true) {
 2832:             newwin = document.getprev.prevwin[i].value;
 2833:         }
 2834:     }
 2835:     if (newwin == 1) {
 2836:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2837:         url = url+'&inhibitmenu=yes';
 2838:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2839:             previousWin = window.open(url,'',options,1);
 2840:         } else {
 2841:             previousWin.location.href = url;
 2842:         }
 2843:         previousWin.focus();
 2844:         return false;
 2845:     } else {
 2846:         document.location.href = url;
 2847:         return false;
 2848:     }
 2849: JSTHREE
 2850:     }
 2851:     $js .= <<"ENDJS";
 2852:     return false;
 2853: }
 2854: // ]]>
 2855: </script>
 2856: ENDJS
 2857: 
 2858: }
 2859: 
 2860: #--- Called from submission routine
 2861: sub processHandGrade {
 2862:     my ($request) = shift;
 2863:     my ($symb)   = &get_symb($request);
 2864:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2865:     my $button = $env{'form.gradeOpt'};
 2866:     my $ngrade = $env{'form.NCT'};
 2867:     my $ntstu  = $env{'form.NTSTU'};
 2868:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2869:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2870: 
 2871:     if ($button eq 'Save & Next') {
 2872: 	my $ctr = 0;
 2873: 	while ($ctr < $ngrade) {
 2874: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2875: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2876:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2877: 	    if ($errorflag eq 'no_score') {
 2878: 		$ctr++;
 2879: 		next;
 2880: 	    }
 2881: 	    if ($errorflag eq 'not_allowed') {
 2882:                 $request->print(
 2883:                     '<span class="LC_error">'
 2884:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2885:                    .'</span>');
 2886: 		$ctr++;
 2887: 		next;
 2888: 	    }
 2889:             if ($numhidden) {
 2890:                 $request->print(
 2891:                     '<span class="LC_info">'
 2892:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2893:                    .'</span><br />');
 2894:             }
 2895: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2896: 	    my ($subject,$message,$msgstatus) = ('','','');
 2897: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2898:             my ($feedurl,$showsymb) =
 2899: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2900: 	    my $messagetail;
 2901: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2902: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2903: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2904: 		$subject.=' ['.$restitle.']';
 2905: 		my (@msgnum) = split(/,/,$includemsg);
 2906: 		foreach (@msgnum) {
 2907: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2908: 		}
 2909: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2910: 		if ($env{'form.withgrades'.$ctr}) {
 2911: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2912: 		    $messagetail = " for <a href=\"".
 2913: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2914: 		}
 2915: 		$msgstatus = 
 2916:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2917: 						     $message.$messagetail,
 2918:                                                      undef,$feedurl,undef,
 2919:                                                      undef,undef,$showsymb,
 2920:                                                      $restitle);
 2921: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2922: 				$msgstatus.'<br />');
 2923: 	    }
 2924: 	    if ($env{'form.collaborator'.$ctr}) {
 2925: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2926: 		foreach my $collabstr (@collabstrs) {
 2927: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2928: 		    foreach my $collaborator (@collaborators) {
 2929: 			my ($errorflag,$pts,$wgt) = 
 2930: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2931: 					   $env{'form.unamedom'.$ctr},$part);
 2932: 			if ($errorflag eq 'not_allowed') {
 2933: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2934: 			    next;
 2935: 			} elsif ($message ne '') {
 2936: 			    my ($baseurl,$showsymb) = 
 2937: 				&get_feedurl_and_symb($symb,$collaborator,
 2938: 						      $udom);
 2939: 			    if ($env{'form.withgrades'.$ctr}) {
 2940: 				$messagetail = " for <a href=\"".
 2941:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2942: 			    }
 2943: 			    $msgstatus = 
 2944: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2945: 			}
 2946: 		    }
 2947: 		}
 2948: 	    }
 2949: 	    $ctr++;
 2950: 	}
 2951:     }
 2952: 
 2953:     if ($env{'form.handgrade'} eq 'yes') {
 2954: 	# Keywords sorted in alphabatical order
 2955: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2956: 	my %keyhash = ();
 2957: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2958: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2959: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2960: 	$env{'form.keywords'} = join(' ',@keywords);
 2961: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2962: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2963: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2964: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2965: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2966: 
 2967: 	# message center - Order of message gets changed. Blank line is eliminated.
 2968: 	# New messages are saved in env for the next student.
 2969: 	# All messages are saved in nohist_handgrade.db
 2970: 	my ($ctr,$idx) = (1,1);
 2971: 	while ($ctr <= $env{'form.savemsgN'}) {
 2972: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2973: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2974: 		$idx++;
 2975: 	    }
 2976: 	    $ctr++;
 2977: 	}
 2978: 	$ctr = 0;
 2979: 	while ($ctr < $ngrade) {
 2980: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2981: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2982: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2983: 		$idx++;
 2984: 	    }
 2985: 	    $ctr++;
 2986: 	}
 2987: 	$env{'form.savemsgN'} = --$idx;
 2988: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2989: 	my $putresult = &Apache::lonnet::put
 2990: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2991:     }
 2992:     # Called by Save & Refresh from Highlight Attribute Window
 2993:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2994:     if ($env{'form.refresh'} eq 'on') {
 2995: 	my ($ctr,$total) = (0,0);
 2996: 	while ($ctr < $ngrade) {
 2997: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2998: 	    $ctr++;
 2999: 	}
 3000: 	$env{'form.NTSTU'}=$ngrade;
 3001: 	$ctr = 0;
 3002: 	while ($ctr < $total) {
 3003: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3004: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3005: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3006: 	    &submission($request,$ctr,$total-1);
 3007: 	    $ctr++;
 3008: 	}
 3009: 	return '';
 3010:     }
 3011: 
 3012: # Go directly to grade student - from submission or link from chart page
 3013:     if ($button eq 'Grade Student') {
 3014: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 3015: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 3016: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3017: 	$env{'form.fullname'} = $$fullname{$processUser};
 3018: 	&submission($request,0,0);
 3019: 	return '';
 3020:     }
 3021: 
 3022:     # Get the next/previous one or group of students
 3023:     my $firststu = $env{'form.unamedom0'};
 3024:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3025:     my $ctr = 2;
 3026:     while ($laststu eq '') {
 3027: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3028: 	$ctr++;
 3029: 	$laststu = $firststu if ($ctr > $ngrade);
 3030:     }
 3031: 
 3032:     my (@parsedlist,@nextlist);
 3033:     my ($nextflg) = 0;
 3034:     foreach my $item (sort 
 3035: 	     {
 3036: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3037: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3038: 		 }
 3039: 		 return $a cmp $b;
 3040: 	     } (keys(%$fullname))) {
 3041: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3042: 	    push(@parsedlist,$item);
 3043: 	}
 3044: 	$nextflg = 1 if ($item eq $laststu);
 3045: 	if ($button eq 'Previous') {
 3046: 	    last if ($item eq $firststu);
 3047: 	    push(@parsedlist,$item);
 3048: 	}
 3049:     }
 3050:     $ctr = 0;
 3051:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3052:     my $res_error;
 3053:     my ($partlist) = &response_type($symb,\$res_error);
 3054:     if ($res_error) {
 3055:         $request->print(&navmap_errormsg());
 3056:         return;
 3057:     }
 3058:     foreach my $student (@parsedlist) {
 3059: 	my $submitonly=$env{'form.submitonly'};
 3060: 	my ($uname,$udom) = split(/:/,$student);
 3061: 	
 3062: 	if ($submitonly eq 'queued') {
 3063: 	    my %queue_status = 
 3064: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3065: 							$udom,$uname);
 3066: 	    next if (!defined($queue_status{'gradingqueue'}));
 3067: 	}
 3068: 
 3069: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3070: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3071: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3072: 	    my $submitted = 0;
 3073: 	    my $ungraded = 0;
 3074: 	    my $incorrect = 0;
 3075: 	    foreach my $item (keys(%status)) {
 3076: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3077: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3078: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3079: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3080: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3081: 		    $submitted = 0;
 3082: 		}
 3083: 	    }
 3084: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3085: 				     $submitonly eq 'incorrect' ||
 3086: 				     $submitonly eq 'graded'));
 3087: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3088: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3089: 	}
 3090: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3091: 	last if ($ctr == $ntstu);
 3092: 	$ctr++;
 3093:     }
 3094: 
 3095:     $ctr = 0;
 3096:     my $total = scalar(@nextlist)-1;
 3097: 
 3098:     foreach (sort(@nextlist)) {
 3099: 	my ($uname,$udom,$submitter) = split(/:/);
 3100: 	$env{'form.student'}  = $uname;
 3101: 	$env{'form.userdom'}  = $udom;
 3102: 	$env{'form.fullname'} = $$fullname{$_};
 3103: 	&submission($request,$ctr,$total);
 3104: 	$ctr++;
 3105:     }
 3106:     if ($total < 0) {
 3107: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3108: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3109: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3110: 	$the_end.=&show_grading_menu_form($symb);
 3111: 	$request->print($the_end);
 3112:     }
 3113:     return '';
 3114: }
 3115: 
 3116: #---- Save the score and award for each student, if changed
 3117: sub saveHandGrade {
 3118:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3119:     my @version_parts;
 3120:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3121: 					   $env{'request.course.id'});
 3122:     if (!&canmodify($usec)) { return('not_allowed'); }
 3123:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3124:     my @parts_graded;
 3125:     my %newrecord  = ();
 3126:     my ($pts,$wgt,$totchg) = ('','',0);
 3127:     my %aggregate = ();
 3128:     my $aggregateflag = 0;
 3129:     if ($env{'form.HIDE'.$newflg}) {
 3130:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3131:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3132:         $totchg += $numchgs;
 3133:     }
 3134:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3135:     foreach my $new_part (@parts) {
 3136: 	#collaborator ($submi may vary for different parts
 3137: 	if ($submitter && $new_part ne $part) { next; }
 3138: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3139: 	if ($dropMenu eq 'excused') {
 3140: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3141: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3142: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3143: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3144: 		}
 3145: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3146: 	    }
 3147: 	} elsif ($dropMenu eq 'reset status'
 3148: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3149: 	    foreach my $key (keys(%record)) {
 3150: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3151: 	    }
 3152: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3153: 		"$env{'user.name'}:$env{'user.domain'}";
 3154:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3155: 
 3156:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3157: 					       [$new_part]);
 3158:             my $aggtries =$totaltries;
 3159:             if ($last_resets{$new_part}) {
 3160:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3161: 					   $new_part);
 3162:             }
 3163: 
 3164:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3165:             if ($aggtries > 0) {
 3166:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3167:                 $aggregateflag = 1;
 3168:             }
 3169: 	} elsif ($dropMenu eq '') {
 3170: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3171: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3172: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3173: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3174: 		next;
 3175: 	    }
 3176: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3177: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3178: 	    my $partial= $pts/$wgt;
 3179: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3180: 		#do not update score for part if not changed.
 3181:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3182: 		next;
 3183: 	    } else {
 3184: 	        push(@parts_graded,$new_part);
 3185: 	    }
 3186: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3187: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3188: 	    }
 3189: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3190: 	    if ($partial == 0) {
 3191: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3192: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3193: 		}
 3194: 	    } else {
 3195: 		if ($record{$reckey} ne 'correct_by_override') {
 3196: 		    $newrecord{$reckey} = 'correct_by_override';
 3197: 		}
 3198: 	    }	    
 3199: 	    if ($submitter && 
 3200: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3201: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3202: 	    }
 3203: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3204: 		"$env{'user.name'}:$env{'user.domain'}";
 3205: 	}
 3206: 	# unless problem has been graded, set flag to version the submitted files
 3207: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3208: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3209: 	        $dropMenu eq 'reset status')
 3210: 	   {
 3211: 	    push(@version_parts,$new_part);
 3212: 	}
 3213:     }
 3214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3215:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3216: 
 3217:     if (%newrecord) {
 3218:         if (@version_parts) {
 3219:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3220:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3221: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3222: 	    foreach my $new_part (@version_parts) {
 3223: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3224: 				$new_part,\%newrecord);
 3225: 	    }
 3226:         }
 3227: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3228: 				$env{'request.course.id'},$domain,$stuname);
 3229: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3230: 				     $cdom,$cnum,$domain,$stuname);
 3231:     }
 3232:     if ($aggregateflag) {
 3233:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3234: 			      $cdom,$cnum);
 3235:     }
 3236:     return ('',$pts,$wgt,$totchg);
 3237: }
 3238: 
 3239: sub makehidden {
 3240:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3241:     return unless (ref($record) eq 'HASH');
 3242:     my %modified;
 3243:     my $numchanged = 0;
 3244:     if (exists($record->{$version.':keys'})) {
 3245:         my $partsregexp = $parts;
 3246:         $partsregexp =~ s/,/|/g;
 3247:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3248:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3249:                  my $item = $1;
 3250:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3251:                      $modified{$key} = $record->{$version.':'.$key};
 3252:                  }
 3253:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3254:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3255:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3256:                 $modified{$key} = $record->{$version.':'.$key};
 3257:             }
 3258:         }
 3259:         if (keys(%modified)) {
 3260:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3261:                                           $domain,$stuname,$tolog) eq 'ok') {
 3262:                 $numchanged ++;
 3263:             }
 3264:         }
 3265:     }
 3266:     return $numchanged;
 3267: }
 3268: 
 3269: sub check_and_remove_from_queue {
 3270:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3271:     my @ungraded_parts;
 3272:     foreach my $part (@{$parts}) {
 3273: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3274: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3275: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3276: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3277: 		) {
 3278: 	    push(@ungraded_parts, $part);
 3279: 	}
 3280:     }
 3281:     if ( !@ungraded_parts ) {
 3282: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3283: 					       $cnum,$domain,$stuname);
 3284:     }
 3285: }
 3286: 
 3287: sub handback_files {
 3288:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3289:     my $portfolio_root = '/userfiles/portfolio';
 3290:     my $res_error;
 3291:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3292:     if ($res_error) {
 3293:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3294:         return;
 3295:     }
 3296:     my @handedback;
 3297:     my $file_msg;
 3298:     my @part_response_id = &flatten_responseType($responseType);
 3299:     foreach my $part_response_id (@part_response_id) {
 3300:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3301: 	my $part_resp = join('_',@{ $part_response_id });
 3302:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3303:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3304:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3305: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3306:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3307:                     my ($directory,$answer_file) = 
 3308:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3309:                     my ($answer_name,$answer_ver,$answer_ext) =
 3310: 		        &file_name_version_ext($answer_file);
 3311: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3312:                     my $getpropath = 1;
 3313:                     my ($dir_list,$listerror) =
 3314:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3315:                                                  $domain,$stuname,$getpropath);
 3316: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3317:                     # fix filename
 3318:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3319:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3320:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3321:             	                                $save_file_name);
 3322:                     if ($result !~ m|^/uploaded/|) {
 3323:                         $request->print('<br /><span class="LC_error">'.
 3324:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3325:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3326:                                         '</span>');
 3327:                     } else {
 3328:                         # mark the file as read only
 3329:                         push(@handedback,$save_file_name);
 3330: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3331: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3332: 			}
 3333:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3334: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3335: 
 3336:                     }
 3337:                     $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>'));
 3338:                 }
 3339:             }
 3340:         }
 3341:     }
 3342:     if (@handedback > 0) {
 3343:         $request->print('<br />');
 3344:         my @what = ($symb,$env{'request.course.id'},'handback');
 3345:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3346:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3347:         my ($subject,$message);
 3348:         if (scalar(@handedback) == 1) {
 3349:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3350:         } else {
 3351:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3352:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3353:         }
 3354:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3355:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3356:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3357:         my ($feedurl,$showsymb) =
 3358:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3359:         my $restitle = &Apache::lonnet::gettitle($symb);
 3360:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3361:         my $msgstatus =
 3362:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3363:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3364:                  $restitle);
 3365:         if ($msgstatus) {
 3366:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3367:         }
 3368:     }
 3369:     return;
 3370: }
 3371: 
 3372: sub get_feedurl_and_symb {
 3373:     my ($symb,$uname,$udom) = @_;
 3374:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3375:     $url = &Apache::lonnet::clutter($url);
 3376:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3377: 					$symb,$udom,$uname);
 3378:     if ($encrypturl =~ /^yes$/i) {
 3379: 	&Apache::lonenc::encrypted(\$url,1);
 3380: 	&Apache::lonenc::encrypted(\$symb,1);
 3381:     }
 3382:     return ($url,$symb);
 3383: }
 3384: 
 3385: sub get_submitted_files {
 3386:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3387:     my @files;
 3388:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3389:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3390:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3391:     	    push(@files,$file_url.$file);
 3392:         }
 3393:     }
 3394:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3395:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3396:     }
 3397:     return (\@files);
 3398: }
 3399: 
 3400: # ----------- Provides number of tries since last reset.
 3401: sub get_num_tries {
 3402:     my ($record,$last_reset,$part) = @_;
 3403:     my $timestamp = '';
 3404:     my $num_tries = 0;
 3405:     if ($$record{'version'}) {
 3406:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3407:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3408:                 $timestamp = $$record{$version.':timestamp'};
 3409:                 if ($timestamp > $last_reset) {
 3410:                     $num_tries ++;
 3411:                 } else {
 3412:                     last;
 3413:                 }
 3414:             }
 3415:         }
 3416:     }
 3417:     return $num_tries;
 3418: }
 3419: 
 3420: # ----------- Determine decrements required in aggregate totals 
 3421: sub decrement_aggs {
 3422:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3423:     my %decrement = (
 3424:                         attempts => 0,
 3425:                         users => 0,
 3426:                         correct => 0
 3427:                     );
 3428:     $decrement{'attempts'} = $aggtries;
 3429:     if ($solvedstatus =~ /^correct/) {
 3430:         $decrement{'correct'} = 1;
 3431:     }
 3432:     if ($aggtries == $totaltries) {
 3433:         $decrement{'users'} = 1;
 3434:     }
 3435:     foreach my $type (keys(%decrement)) {
 3436:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3437:     }
 3438:     return;
 3439: }
 3440: 
 3441: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3442: sub get_last_resets {
 3443:     my ($symb,$courseid,$partids) =@_;
 3444:     my %last_resets;
 3445:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3446:     my $cname = $env{'course.'.$courseid.'.num'};
 3447:     my @keys;
 3448:     foreach my $part (@{$partids}) {
 3449: 	push(@keys,"$symb\0$part\0resettime");
 3450:     }
 3451:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3452: 				     $cdom,$cname);
 3453:     foreach my $part (@{$partids}) {
 3454: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3455:     }
 3456:     return %last_resets;
 3457: }
 3458: 
 3459: # ----------- Handles creating versions for portfolio files as answers
 3460: sub version_portfiles {
 3461:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3462:     my $version_parts = join('|',@$v_flag);
 3463:     my @returned_keys;
 3464:     my $parts = join('|', @$parts_graded);
 3465:     my $portfolio_root = '/userfiles/portfolio';
 3466:     foreach my $key (keys(%$record)) {
 3467:         my $new_portfiles;
 3468:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3469:             my @versioned_portfiles;
 3470:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3471:             foreach my $file (@portfiles) {
 3472:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3473:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3474: 		my ($answer_name,$answer_ver,$answer_ext) =
 3475: 		    &file_name_version_ext($answer_file);
 3476:                 my $getpropath = 1;
 3477:                 my ($dir_list,$listerror) =
 3478:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3479:                                              $stu_name,$getpropath);
 3480:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3481:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3482:                 if ($new_answer ne 'problem getting file') {
 3483:                     push(@versioned_portfiles, $directory.$new_answer);
 3484:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3485:                         [$directory.$new_answer],
 3486:                         [$symb,$env{'request.course.id'},'graded']);
 3487:                 }
 3488:             }
 3489:             $$record{$key} = join(',',@versioned_portfiles);
 3490:             push(@returned_keys,$key);
 3491:         }
 3492:     } 
 3493:     return (@returned_keys);   
 3494: }
 3495: 
 3496: sub get_next_version {
 3497:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3498:     my $version;
 3499:     if (ref($dir_list) eq 'ARRAY') {
 3500:         foreach my $row (@{$dir_list}) {
 3501:             my ($file) = split(/\&/,$row,2);
 3502:             my ($file_name,$file_version,$file_ext) =
 3503: 	        &file_name_version_ext($file);
 3504:             if (($file_name eq $answer_name) && 
 3505: 	        ($file_ext eq $answer_ext)) {
 3506:                 # gets here if filename and extension match, 
 3507:                 # regardless of version
 3508:                 if ($file_version ne '') {
 3509:                     # a versioned file is found  so save it for later
 3510:                     if ($file_version > $version) {
 3511: 		        $version = $file_version;
 3512:                     }
 3513: 	        }
 3514:             }
 3515:         }
 3516:     }
 3517:     $version ++;
 3518:     return($version);
 3519: }
 3520: 
 3521: sub version_selected_portfile {
 3522:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3523:     my ($answer_name,$answer_ver,$answer_ext) =
 3524:         &file_name_version_ext($file_name);
 3525:     my $new_answer;
 3526:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3527:     if($env{'form.copy'} eq '-1') {
 3528:         $new_answer = 'problem getting file';
 3529:     } else {
 3530:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3531:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3532:                             $stu_name,$domain,'copy',
 3533: 		        '/portfolio'.$directory.$new_answer);
 3534:     }    
 3535:     return ($new_answer);
 3536: }
 3537: 
 3538: sub file_name_version_ext {
 3539:     my ($file)=@_;
 3540:     my @file_parts = split(/\./, $file);
 3541:     my ($name,$version,$ext);
 3542:     if (@file_parts > 1) {
 3543: 	$ext=pop(@file_parts);
 3544: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3545: 	    $version=pop(@file_parts);
 3546: 	}
 3547: 	$name=join('.',@file_parts);
 3548:     } else {
 3549: 	$name=join('.',@file_parts);
 3550:     }
 3551:     return($name,$version,$ext);
 3552: }
 3553: 
 3554: #--------------------------------------------------------------------------------------
 3555: #
 3556: #-------------------------- Next few routines handles grading by section or whole class
 3557: #
 3558: #--- Javascript to handle grading by section or whole class
 3559: sub viewgrades_js {
 3560:     my ($request) = shift;
 3561: 
 3562:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3563:     &js_escape(\$alertmsg);
 3564:     $request->print(<<VIEWJAVASCRIPT);
 3565: <script type="text/javascript" language="javascript">
 3566:    function writePoint(partid,weight,point) {
 3567: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3568: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3569: 	if (point == "textval") {
 3570: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3571: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3572: 		alert("$alertmsg"+parseFloat(point));
 3573: 		var resetbox = false;
 3574: 		for (var i=0; i<radioButton.length; i++) {
 3575: 		    if (radioButton[i].checked) {
 3576: 			textbox.value = i;
 3577: 			resetbox = true;
 3578: 		    }
 3579: 		}
 3580: 		if (!resetbox) {
 3581: 		    textbox.value = "";
 3582: 		}
 3583: 		return;
 3584: 	    }
 3585: 	    if (parseFloat(point) > parseFloat(weight)) {
 3586: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3587: 				   ") greater than the weight for the part. Accept?");
 3588: 		if (resp == false) {
 3589: 		    textbox.value = "";
 3590: 		    return;
 3591: 		}
 3592: 	    }
 3593: 	    for (var i=0; i<radioButton.length; i++) {
 3594: 		radioButton[i].checked=false;
 3595: 		if (parseFloat(point) == i) {
 3596: 		    radioButton[i].checked=true;
 3597: 		}
 3598: 	    }
 3599: 
 3600: 	} else {
 3601: 	    textbox.value = parseFloat(point);
 3602: 	}
 3603: 	for (i=0;i<document.classgrade.total.value;i++) {
 3604: 	    var user = document.classgrade["ctr"+i].value;
 3605: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3606: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3607: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3608: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3609: 	    if (saveval != "correct") {
 3610: 		scorename.value = point;
 3611: 		if (selname[0].selected != true) {
 3612: 		    selname[0].selected = true;
 3613: 		}
 3614: 	    }
 3615: 	}
 3616: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3617:     }
 3618: 
 3619:     function writeRadText(partid,weight) {
 3620: 	var selval   = document.classgrade["SELVAL_"+partid];
 3621: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3622:         var override = document.classgrade["FORCE_"+partid].checked;
 3623: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3624: 	if (selval[1].selected || selval[2].selected) {
 3625: 	    for (var i=0; i<radioButton.length; i++) {
 3626: 		radioButton[i].checked=false;
 3627: 
 3628: 	    }
 3629: 	    textbox.value = "";
 3630: 
 3631: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3632: 		var user = document.classgrade["ctr"+i].value;
 3633: 		user = user.replace(new RegExp(':', 'g'),"_");
 3634: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3635: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3636: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3637: 		if ((saveval != "correct") || override) {
 3638: 		    scorename.value = "";
 3639: 		    if (selval[1].selected) {
 3640: 			selname[1].selected = true;
 3641: 		    } else {
 3642: 			selname[2].selected = true;
 3643: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3644: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3645: 		    }
 3646: 		}
 3647: 	    }
 3648: 	} else {
 3649: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3650: 		var user = document.classgrade["ctr"+i].value;
 3651: 		user = user.replace(new RegExp(':', 'g'),"_");
 3652: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3653: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3654: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3655: 		if ((saveval != "correct") || override) {
 3656: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3657: 		    selname[0].selected = true;
 3658: 		}
 3659: 	    }
 3660: 	}	    
 3661:     }
 3662: 
 3663:     function changeSelect(partid,user) {
 3664: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3665: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3666: 	var point  = textbox.value;
 3667: 	var weight = document.classgrade["weight_"+partid].value;
 3668: 
 3669: 	if (isNaN(point) || parseFloat(point) < 0) {
 3670: 	    alert("$alertmsg"+parseFloat(point));
 3671: 	    textbox.value = "";
 3672: 	    return;
 3673: 	}
 3674: 	if (parseFloat(point) > parseFloat(weight)) {
 3675: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3676: 			       ") greater than the weight of the part. Accept?");
 3677: 	    if (resp == false) {
 3678: 		textbox.value = "";
 3679: 		return;
 3680: 	    }
 3681: 	}
 3682: 	selval[0].selected = true;
 3683:     }
 3684: 
 3685:     function changeOneScore(partid,user) {
 3686: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3687: 	if (selval[1].selected || selval[2].selected) {
 3688: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3689: 	    if (selval[2].selected) {
 3690: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3691: 	    }
 3692:         }
 3693:     }
 3694: 
 3695:     function resetEntry(numpart) {
 3696: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3697: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3698: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3699: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3700: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3701: 	    for (var i=0; i<radioButton.length; i++) {
 3702: 		radioButton[i].checked=false;
 3703: 
 3704: 	    }
 3705: 	    textbox.value = "";
 3706: 	    selval[0].selected = true;
 3707: 
 3708: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3709: 		var user = document.classgrade["ctr"+i].value;
 3710: 		user = user.replace(new RegExp(':', 'g'),"_");
 3711: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3712: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3713: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3714: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3715: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3716: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3717: 		if (saveselval == "excused") {
 3718: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3719: 		} else {
 3720: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3721: 		}
 3722: 	    }
 3723: 	}
 3724:     }
 3725: 
 3726: </script>
 3727: VIEWJAVASCRIPT
 3728: }
 3729: 
 3730: #--- show scores for a section or whole class w/ option to change/update a score
 3731: sub viewgrades {
 3732:     my ($request) = shift;
 3733:     &viewgrades_js($request);
 3734: 
 3735:     my ($symb) = &get_symb($request);
 3736:     #need to make sure we have the correct data for later EXT calls, 
 3737:     #thus invalidate the cache
 3738:     &Apache::lonnet::devalidatecourseresdata(
 3739:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3740:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3741:     &Apache::lonnet::clear_EXT_cache_status();
 3742: 
 3743:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3744:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3745: 
 3746:     #view individual student submission form - called using Javascript viewOneStudent
 3747:     $result.=&jscriptNform($symb);
 3748: 
 3749:     #beginning of class grading form
 3750:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3751:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3752: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3753: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3754: 	&build_section_inputs().
 3755: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3756: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3757: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3758: 
 3759:     #retrieve selected groups
 3760:     my (@groups,$group_display);
 3761:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3762:     if (grep(/^all$/,@groups)) {
 3763:         @groups = ('all');
 3764:     } elsif (grep(/^none$/,@groups)) {
 3765:         @groups = ('none');
 3766:     } elsif (@groups > 0) {
 3767:         $group_display = join(', ',@groups);
 3768:     }
 3769: 
 3770:     my ($common_header,$specific_header,@sections,$section_display);
 3771:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3772:     if (grep(/^all$/,@sections)) {
 3773:         @sections = ('all');
 3774:         if ($group_display) {
 3775:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3776:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3777:         } elsif (grep(/^none$/,@groups)) {
 3778:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3779:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3780:         } else {
 3781:             $common_header = &mt('Assign Common Grade to Class');
 3782:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3783:         }
 3784:     } elsif (grep(/^none$/,@sections)) {
 3785:         @sections = ('none');
 3786:         if ($group_display) {
 3787:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3788:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3789:         } elsif (grep(/^none$/,@groups)) {
 3790:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3791:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3792:         } else {
 3793:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3794:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3795:         }
 3796:     } else {
 3797:         $section_display = join (", ",@sections);
 3798:         if ($group_display) {
 3799:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3800:                                  $section_display,$group_display);
 3801:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3802:                                    $section_display,$group_display);
 3803:         } elsif (grep(/^none$/,@groups)) {
 3804:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3805:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3806:         } else {
 3807:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3808:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3809:         }
 3810:     }
 3811:     my %submit_types = &substatus_options();
 3812:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3813: 
 3814:     if ($env{'form.submitonly'} eq 'all') {
 3815:         $result.= '<h3>'.$common_header.'</h3>';
 3816:     } else {
 3817:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 3818:     }
 3819:     $result .= &Apache::loncommon::start_data_table();
 3820:     #radio buttons/text box for assigning points for a section or class.
 3821:     #handles different parts of a problem
 3822:     my $res_error;
 3823:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3824:     if ($res_error) {
 3825:         return &navmap_errormsg();
 3826:     }
 3827:     my %weight = ();
 3828:     my $ctsparts = 0;
 3829:     my %seen = ();
 3830:     my @part_response_id = &flatten_responseType($responseType);
 3831:     foreach my $part_response_id (@part_response_id) {
 3832:     	my ($partid,$respid) = @{ $part_response_id };
 3833: 	my $part_resp = join('_',@{ $part_response_id });
 3834: 	next if $seen{$partid};
 3835: 	$seen{$partid}++;
 3836: 	my $handgrade=$$handgrade{$part_resp};
 3837: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3838: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3839: 
 3840: 	my $display_part=&get_display_part($partid,$symb);
 3841: 	my $radio.='<table border="0"><tr>';  
 3842: 	my $ctr = 0;
 3843: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3844: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3845: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3846: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3847: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3848: 	    $ctr++;
 3849: 	}
 3850: 	$radio.='</tr></table>';
 3851: 	my $line = '<input type="text" name="TEXTVAL_'.
 3852: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3853: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3854: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3855: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3856:                 '<select name="SELVAL_'.$partid.'" '.
 3857: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3858: 		$weight{$partid}.')"> '.
 3859: 	    '<option selected="selected"> </option>'.
 3860: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3861: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3862: 	    '</select></td>'.
 3863:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3864: 	$line.='<input type="hidden" name="partid_'.
 3865: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3866: 	$line.='<input type="hidden" name="weight_'.
 3867: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3868: 
 3869: 	$result.=
 3870: 	    &Apache::loncommon::start_data_table_row()."\n".
 3871: 	    '<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>'.
 3872: 	    &Apache::loncommon::end_data_table_row()."\n";
 3873: 	$ctsparts++;
 3874:     }
 3875:     $result.=&Apache::loncommon::end_data_table()."\n".
 3876: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3877:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3878: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3879: 
 3880:     #table listing all the students in a section/class
 3881:     #header of table
 3882:     if ($env{'form.submitonly'} eq 'all') { 
 3883:         $result.= '<h3>'.$specific_header.'</h3>';
 3884:     } else {
 3885:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3886:     }
 3887:     $result.= &Apache::loncommon::start_data_table().
 3888: 	      &Apache::loncommon::start_data_table_header_row().
 3889: 	      '<th>'.&mt('No.').'</th>'.
 3890: 	      '<th>'.&nameUserString('header')."</th>\n";
 3891:     my $partserror;
 3892:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3893:     if ($partserror) {
 3894:         return &navmap_errormsg();
 3895:     }
 3896:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3897:     my @partids = ();
 3898:     foreach my $part (@parts) {
 3899: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3900:         my $narrowtext = &mt('Tries');
 3901: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3902: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3903: 	my ($partid) = &split_part_type($part);
 3904:         push(@partids,$partid);
 3905: 	my $display_part=&get_display_part($partid,$symb);
 3906: 	if ($display =~ /^Partial Credit Factor/) {
 3907: 	    $result.='<th>'.
 3908:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3909:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3910: 	    next;
 3911: 	    
 3912: 	} else {
 3913: 	    if ($display =~ /Problem Status/) {
 3914: 		my $grade_status_mt = &mt('Grade Status');
 3915: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3916: 	    }
 3917: 	    my $part_mt = &mt('Part:');
 3918: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3919: 	}
 3920: 
 3921: 	$result.='<th>'.$display.'</th>'."\n";
 3922:     }
 3923:     $result.=&Apache::loncommon::end_data_table_header_row();
 3924: 
 3925:     my %last_resets = 
 3926: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3927: 
 3928:     #get info for each student
 3929:     #list all the students - with points and grade status
 3930:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3931:     my $ctr = 0;
 3932:     foreach (sort 
 3933: 	     {
 3934: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3935: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3936: 		 }
 3937: 		 return $a cmp $b;
 3938: 	     } (keys(%$fullname))) {
 3939: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3940: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 3941:     }
 3942:     $result.=&Apache::loncommon::end_data_table();
 3943:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3944:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3945: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3946:     if ($ctr == 0) {
 3947:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3948:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3949:                 '<span class="LC_warning">';
 3950:         if ($env{'form.submitonly'} eq 'all') {
 3951:             if (grep(/^all$/,@sections)) {
 3952:                 if (grep(/^all$/,@groups)) {
 3953:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3954:                                    $stu_status);
 3955:                 } elsif (grep(/^none$/,@groups)) {
 3956:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 3957:                                    $stu_status);
 3958:                 } else {
 3959:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3960:                                    $group_display,$stu_status);
 3961:                 }
 3962:             } elsif (grep(/^none$/,@sections)) {
 3963:                 if (grep(/^all$/,@groups)) {
 3964:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 3965:                                    $stu_status);
 3966:                 } elsif (grep(/^none$/,@groups)) {
 3967:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 3968:                                    $stu_status);
 3969:                 } else {
 3970:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3971:                                    $group_display,$stu_status);
 3972:                 }
 3973:             } else {
 3974:                 if (grep(/^all$/,@groups)) {
 3975:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3976:                                    $section_display,$stu_status);
 3977:                 } elsif (grep(/^none$/,@groups)) {
 3978:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 3979:                                    $section_display,$stu_status);
 3980:                 } else {
 3981:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 3982:                                    $section_display,$group_display,$stu_status);
 3983:                 }
 3984:             }
 3985:         } else {
 3986:             if (grep(/^all$/,@sections)) {
 3987:                 if (grep(/^all$/,@groups)) {
 3988:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3989:                                    $stu_status,$submission_status);
 3990:                 } elsif (grep(/^none$/,@groups)) {
 3991:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3992:                                    $stu_status,$submission_status);
 3993:                 } else {
 3994:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3995:                                    $group_display,$stu_status,$submission_status);
 3996:                 }
 3997:             } elsif (grep(/^none$/,@sections)) {
 3998:                 if (grep(/^all$/,@groups)) {
 3999:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4000:                                    $stu_status,$submission_status);
 4001:                 } elsif (grep(/^none$/,@groups)) {
 4002:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4003:                                    $stu_status,$submission_status);
 4004:                 } else {
 4005:                     $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.',
 4006:                                    $group_display,$stu_status,$submission_status);
 4007:                 }
 4008:             } else {
 4009:                 if (grep(/^all$/,@groups)) {
 4010:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4011:                                    $section_display,$stu_status,$submission_status);
 4012:                 } elsif (grep(/^none$/,@groups)) {
 4013:                     $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.',
 4014:                                    $section_display,$stu_status,$submission_status);
 4015:                 } else {
 4016:                     $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.',
 4017:                                    $section_display,$group_display,$stu_status,$submission_status);
 4018:                 }
 4019:             }
 4020: 	}
 4021: 	$result .= '</span><br />';
 4022:     }
 4023:     $result.=&show_grading_menu_form($symb);
 4024:     return $result;
 4025: }
 4026: 
 4027: #--- call by previous routine to display each student who satisfies submission filter.
 4028: sub viewstudentgrade {
 4029:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4030:     my ($uname,$udom) = split(/:/,$student);
 4031:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4032:     my $submitonly = $env{'form.submitonly'};
 4033:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4034:         my %partstatus = ();
 4035:         if (ref($parts) eq 'ARRAY') {
 4036:             foreach my $apart (@{$parts}) {
 4037:                 my ($part,$type) = &split_part_type($apart);
 4038:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4039:                 $status = 'nothing' if ($status eq '');
 4040:                 $partstatus{$part}      = $status;
 4041:                 my $subkey = "resource.$part.submitted_by";
 4042:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4043:             }
 4044:             my $submitted = 0;
 4045:             my $graded = 0;
 4046:             my $incorrect = 0;
 4047:             foreach my $key (keys(%partstatus)) {
 4048:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4049:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4050:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4051: 
 4052:                 my $partid = (split(/\./,$key))[1];
 4053:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4054:                     $submitted = 0;
 4055:                 }
 4056:             }
 4057:             return if (!$submitted && ($submitonly eq 'yes' ||
 4058:                                        $submitonly eq 'incorrect' ||
 4059:                                        $submitonly eq 'graded'));
 4060:             return if (!$graded && ($submitonly eq 'graded'));
 4061:             return if (!$incorrect && $submitonly eq 'incorrect');
 4062:         }
 4063:     }
 4064:     if ($submitonly eq 'queued') {
 4065:         my ($cdom,$cnum) = split(/_/,$courseid);
 4066:         my %queue_status =
 4067:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4068:                                                     $udom,$uname);
 4069:         return if (!defined($queue_status{'gradingqueue'}));
 4070:     }
 4071:     $$ctr++;
 4072:     my %aggregates = ();
 4073:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4074: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4075: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4076: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4077: 	'\');" target="_self">'.$fullname.'</a> '.
 4078: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4079:     $student=~s/:/_/; # colon doen't work in javascript for names
 4080:     foreach my $apart (@$parts) {
 4081: 	my ($part,$type) = &split_part_type($apart);
 4082: 	my $score=$record{"resource.$part.$type"};
 4083:         $result.='<td align="center">';
 4084:         my ($aggtries,$totaltries);
 4085:         unless (exists($aggregates{$part})) {
 4086: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4087: 
 4088: 	    $aggtries = $totaltries;
 4089:             if ($$last_resets{$part}) {  
 4090:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4091: 					   $part);
 4092:             }
 4093:             $result.='<input type="hidden" name="'.
 4094:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4095:             $result.='<input type="hidden" name="'.
 4096:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4097:             $aggregates{$part} = 1;
 4098:         }
 4099: 	if ($type eq 'awarded') {
 4100: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4101: 	    $result.='<input type="hidden" name="'.
 4102: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4103: 	    $result.='<input type="text" name="'.
 4104: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4105:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4106: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4107: 	} elsif ($type eq 'solved') {
 4108: 	    my ($status,$foo)=split(/_/,$score,2);
 4109: 	    $status = 'nothing' if ($status eq '');
 4110: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4111: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4112: 	    $result.='&nbsp;<select name="'.
 4113: 		'GD_'.$student.'_'.$part.'_solved" '.
 4114:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4115: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4116: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4117: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4118: 	    $result.="</select>&nbsp;</td>\n";
 4119: 	} else {
 4120: 	    $result.='<input type="hidden" name="'.
 4121: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4122: 		    "\n";
 4123: 	    $result.='<input type="text" name="'.
 4124: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4125: 		'value="'.$score.'" size="4" /></td>'."\n";
 4126: 	}
 4127:     }
 4128:     $result.=&Apache::loncommon::end_data_table_row();
 4129:     return $result;
 4130: }
 4131: 
 4132: #--- change scores for all the students in a section/class
 4133: #    record does not get update if unchanged
 4134: sub editgrades {
 4135:     my ($request) = @_;
 4136: 
 4137:     my ($symb)=&get_symb($request);
 4138:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4139:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4140:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 4141:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4142: 
 4143:     my $result= &Apache::loncommon::start_data_table().
 4144: 	&Apache::loncommon::start_data_table_header_row().
 4145: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4146: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4147:     my %scoreptr = (
 4148: 		    'correct'  =>'correct_by_override',
 4149: 		    'incorrect'=>'incorrect_by_override',
 4150: 		    'excused'  =>'excused',
 4151: 		    'ungraded' =>'ungraded_attempted',
 4152:                     'credited' =>'credit_attempted',
 4153: 		    'nothing'  => '',
 4154: 		    );
 4155:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4156: 
 4157:     my (@partid);
 4158:     my %weight = ();
 4159:     my %columns = ();
 4160:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4161: 
 4162:     my $partserror;
 4163:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4164:     if ($partserror) {
 4165:         return &navmap_errormsg();
 4166:     }
 4167:     my $header;
 4168:     while ($ctr < $env{'form.totalparts'}) {
 4169: 	my $partid = $env{'form.partid_'.$ctr};
 4170: 	push(@partid,$partid);
 4171: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4172: 	$ctr++;
 4173:     }
 4174:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4175:     foreach my $partid (@partid) {
 4176: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4177: 	    '<th align="center">'.&mt('New Score').'</th>';
 4178: 	$columns{$partid}=2;
 4179: 	foreach my $stores (@parts) {
 4180: 	    my ($part,$type) = &split_part_type($stores);
 4181: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4182: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4183: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4184: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4185:             my $narrowtext = &mt('Tries');
 4186: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4187: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4188: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4189: 	    $columns{$partid}+=2;
 4190: 	}
 4191:     }
 4192:     foreach my $partid (@partid) {
 4193: 	my $display_part=&get_display_part($partid,$symb);
 4194: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4195: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4196: 	    '</th>';
 4197: 
 4198:     }
 4199:     $result .= &Apache::loncommon::end_data_table_header_row().
 4200: 	&Apache::loncommon::start_data_table_header_row().
 4201: 	$header.
 4202: 	&Apache::loncommon::end_data_table_header_row();
 4203:     my @noupdate;
 4204:     my ($updateCtr,$noupdateCtr) = (1,1);
 4205:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4206: 	my $line;
 4207: 	my $user = $env{'form.ctr'.$i};
 4208: 	my ($uname,$udom)=split(/:/,$user);
 4209: 	my %newrecord;
 4210: 	my $updateflag = 0;
 4211: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4212: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4213: 	if (!&canmodify($usec)) {
 4214: 	    my $numcols=scalar(@partid)*4+2;
 4215: 	    push(@noupdate,
 4216: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 4217: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 4218: 	    next;
 4219: 	}
 4220:         my %aggregate = ();
 4221:         my $aggregateflag = 0;
 4222: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4223: 	foreach (@partid) {
 4224: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4225: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4226: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4227: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4228: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4229: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4230: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4231: 	    my $score;
 4232: 	    if ($partial eq '') {
 4233: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4234: 	    } elsif ($partial > 0) {
 4235: 		$score = 'correct_by_override';
 4236: 	    } elsif ($partial == 0) {
 4237: 		$score = 'incorrect_by_override';
 4238: 	    }
 4239: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4240: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4241: 
 4242: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4243: 		"$env{'user.name'}:$env{'user.domain'}";
 4244: 	    if ($dropMenu eq 'reset status' &&
 4245: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4246: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4247: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4248: 		$newrecord{'resource.'.$_.'.award'} = '';
 4249: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4250: 		$updateflag = 1;
 4251:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4252:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4253:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4254:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4255:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4256:                     $aggregateflag = 1;
 4257:                 }
 4258: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4259: 		$updateflag = 1;
 4260: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4261: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4262: 		$rec_update++;
 4263: 	    }
 4264: 
 4265: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4266: 		'<td align="center">'.$awarded.
 4267: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4268: 
 4269: 
 4270: 	    my $partid=$_;
 4271: 	    foreach my $stores (@parts) {
 4272: 		my ($part,$type) = &split_part_type($stores);
 4273: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4274: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4275: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4276: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4277: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4278: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4279: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4280: 		    $updateflag=1;
 4281: 		}
 4282: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4283: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4284: 	    }
 4285: 	}
 4286: 	$line.="\n";
 4287: 
 4288: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4289: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4290: 
 4291: 	if ($updateflag) {
 4292: 	    $count++;
 4293: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4294: 				    $udom,$uname);
 4295: 
 4296: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4297: 					      $cnum,$udom,$uname)) {
 4298: 		# need to figure out if should be in queue.
 4299: 		my %record =  
 4300: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4301: 					     $udom,$uname);
 4302: 		my $all_graded = 1;
 4303: 		my $none_graded = 1;
 4304: 		foreach my $part (@parts) {
 4305: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4306: 			$all_graded = 0;
 4307: 		    } else {
 4308: 			$none_graded = 0;
 4309: 		    }
 4310: 		}
 4311: 
 4312: 		if ($all_graded || $none_graded) {
 4313: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4314: 							   $symb,$cdom,$cnum,
 4315: 							   $udom,$uname);
 4316: 		}
 4317: 	    }
 4318: 
 4319: 	    $result.=&Apache::loncommon::start_data_table_row().
 4320: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4321: 		&Apache::loncommon::end_data_table_row();
 4322: 	    $updateCtr++;
 4323: 	} else {
 4324: 	    push(@noupdate,
 4325: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4326: 	    $noupdateCtr++;
 4327: 	}
 4328:         if ($aggregateflag) {
 4329:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4330: 				  $cdom,$cnum);
 4331:         }
 4332:     }
 4333:     if (@noupdate) {
 4334: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4335: 	my $numcols=scalar(@partid)*4+2;
 4336: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4337: 	    '<td align="center" colspan="'.$numcols.'">'.
 4338: 	    &mt('No Changes Occurred For the Students Below').
 4339: 	    '</td>'.
 4340: 	    &Apache::loncommon::end_data_table_row();
 4341: 	foreach my $line (@noupdate) {
 4342: 	    $result.=
 4343: 		&Apache::loncommon::start_data_table_row().
 4344: 		$line.
 4345: 		&Apache::loncommon::end_data_table_row();
 4346: 	}
 4347:     }
 4348:     $result .= &Apache::loncommon::end_data_table().
 4349: 	&show_grading_menu_form($symb);
 4350:     my $msg = '<p><b>'.
 4351: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4352: 	    $rec_update,$count).'</b><br />'.
 4353: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4354: 	'</b></p>';
 4355:     return $title.$msg.$result;
 4356: }
 4357: 
 4358: sub split_part_type {
 4359:     my ($partstr) = @_;
 4360:     my ($temp,@allparts)=split(/_/,$partstr);
 4361:     my $type=pop(@allparts);
 4362:     my $part=join('_',@allparts);
 4363:     return ($part,$type);
 4364: }
 4365: 
 4366: #------------- end of section for handling grading by section/class ---------
 4367: #
 4368: #----------------------------------------------------------------------------
 4369: 
 4370: 
 4371: #----------------------------------------------------------------------------
 4372: #
 4373: #-------------------------- Next few routines handles grading by csv upload
 4374: #
 4375: #--- Javascript to handle csv upload
 4376: sub csvupload_javascript_reverse_associate {
 4377:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4378:     my $error2=&mt('You need to specify at least one grading field');
 4379:   &js_escape(\$error1);
 4380:   &js_escape(\$error2);
 4381:   return(<<ENDPICK);
 4382:   function verify(vf) {
 4383:     var foundsomething=0;
 4384:     var founduname=0;
 4385:     var foundID=0;
 4386:     for (i=0;i<=vf.nfields.value;i++) {
 4387:       tw=eval('vf.f'+i+'.selectedIndex');
 4388:       if (i==0 && tw!=0) { foundID=1; }
 4389:       if (i==1 && tw!=0) { founduname=1; }
 4390:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4391:     }
 4392:     if (founduname==0 && foundID==0) {
 4393: 	alert('$error1');
 4394: 	return;
 4395:     }
 4396:     if (foundsomething==0) {
 4397: 	alert('$error2');
 4398: 	return;
 4399:     }
 4400:     vf.submit();
 4401:   }
 4402:   function flip(vf,tf) {
 4403:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4404:     var i;
 4405:     for (i=0;i<=vf.nfields.value;i++) {
 4406:       //can not pick the same destination field for both name and domain
 4407:       if (((i ==0)||(i ==1)) && 
 4408:           ((tf==0)||(tf==1)) && 
 4409:           (i!=tf) &&
 4410:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4411:         eval('vf.f'+i+'.selectedIndex=0;')
 4412:       }
 4413:     }
 4414:   }
 4415: ENDPICK
 4416: }
 4417: 
 4418: sub csvupload_javascript_forward_associate {
 4419:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4420:     my $error2=&mt('You need to specify at least one grading field');
 4421:   &js_escape(\$error1);
 4422:   &js_escape(\$error2);
 4423:   return(<<ENDPICK);
 4424:   function verify(vf) {
 4425:     var foundsomething=0;
 4426:     var founduname=0;
 4427:     var foundID=0;
 4428:     for (i=0;i<=vf.nfields.value;i++) {
 4429:       tw=eval('vf.f'+i+'.selectedIndex');
 4430:       if (tw==1) { foundID=1; }
 4431:       if (tw==2) { founduname=1; }
 4432:       if (tw>3) { foundsomething=1; }
 4433:     }
 4434:     if (founduname==0 && foundID==0) {
 4435: 	alert('$error1');
 4436: 	return;
 4437:     }
 4438:     if (foundsomething==0) {
 4439: 	alert('$error2');
 4440: 	return;
 4441:     }
 4442:     vf.submit();
 4443:   }
 4444:   function flip(vf,tf) {
 4445:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4446:     var i;
 4447:     //can not pick the same destination field twice
 4448:     for (i=0;i<=vf.nfields.value;i++) {
 4449:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4450:         eval('vf.f'+i+'.selectedIndex=0;')
 4451:       }
 4452:     }
 4453:   }
 4454: ENDPICK
 4455: }
 4456: 
 4457: sub csvuploadmap_header {
 4458:     my ($request,$symb,$datatoken,$distotal)= @_;
 4459:     my $javascript;
 4460:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4461: 	$javascript=&csvupload_javascript_reverse_associate();
 4462:     } else {
 4463: 	$javascript=&csvupload_javascript_forward_associate();
 4464:     }
 4465: 
 4466:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4467:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4468:     my $ignore=&mt('Ignore First Line');
 4469:     $symb = &Apache::lonenc::check_encrypt($symb);
 4470:     $request->print(<<ENDPICK);
 4471: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4472: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4473: $result
 4474: <hr />
 4475: <h3>Identify fields</h3>
 4476: Total number of records found in file: $distotal <hr />
 4477: Enter as many fields as you can. The system will inform you and bring you back
 4478: to this page if the data selected is insufficient to run your class.<hr />
 4479: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4480: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4481: <input type="hidden" name="associate"  value="" />
 4482: <input type="hidden" name="phase"      value="three" />
 4483: <input type="hidden" name="datatoken"  value="$datatoken" />
 4484: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4485: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4486: <input type="hidden" name="upfile_associate" 
 4487:                                        value="$env{'form.upfile_associate'}" />
 4488: <input type="hidden" name="symb"       value="$symb" />
 4489: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4490: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4491: <input type="hidden" name="command"    value="csvuploadoptions" />
 4492: <hr />
 4493: <script type="text/javascript" language="Javascript">
 4494: $javascript
 4495: </script>
 4496: ENDPICK
 4497:     return '';
 4498: 
 4499: }
 4500: 
 4501: sub csvupload_fields {
 4502:     my ($symb,$errorref) = @_;
 4503:     my (@parts) = &getpartlist($symb,$errorref);
 4504:     if (ref($errorref)) {
 4505:         if ($$errorref) {
 4506:             return;
 4507:         }
 4508:     }
 4509: 
 4510:     my @fields=(['ID','Student/Employee ID'],
 4511: 		['username','Student Username'],
 4512: 		['domain','Student Domain']);
 4513:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4514:     foreach my $part (sort(@parts)) {
 4515: 	my @datum;
 4516: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4517: 	my $name=$part;
 4518: 	if  (!$display) { $display = $name; }
 4519: 	@datum=($name,$display);
 4520: 	if ($name=~/^stores_(.*)_awarded/) {
 4521: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4522: 	}
 4523: 	push(@fields,\@datum);
 4524:     }
 4525:     return (@fields);
 4526: }
 4527: 
 4528: sub csvuploadmap_footer {
 4529:     my ($request,$i,$keyfields) =@_;
 4530:     my $buttontext = &mt('Assign Grades');
 4531:     $request->print(<<ENDPICK);
 4532: </table>
 4533: <input type="hidden" name="nfields" value="$i" />
 4534: <input type="hidden" name="keyfields" value="$keyfields" />
 4535: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4536: </form>
 4537: ENDPICK
 4538: }
 4539: 
 4540: sub checkforfile_js {
 4541:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4542:     &js_escape(\$alertmsg);
 4543:     my $result =<<CSVFORMJS;
 4544: <script type="text/javascript" language="javascript">
 4545:     function checkUpload(formname) {
 4546: 	if (formname.upfile.value == "") {
 4547: 	    alert("$alertmsg");
 4548: 	    return false;
 4549: 	}
 4550: 	formname.submit();
 4551:     }
 4552:     </script>
 4553: CSVFORMJS
 4554:     return $result;
 4555: }
 4556: 
 4557: sub upcsvScores_form {
 4558:     my ($request) = shift;
 4559:     my ($symb)=&get_symb($request);
 4560:     if (!$symb) {return '';}
 4561:     my $result=&checkforfile_js();
 4562:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4563:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4564:     $result.=$table;
 4565:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4566:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4567:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4568: 	'</b></td></tr>'."\n";
 4569:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4570:     my $upload=&mt("Upload Scores");
 4571:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4572:     my $ignore=&mt('Ignore First Line');
 4573:     $symb = &Apache::lonenc::check_encrypt($symb);
 4574:     $result.=<<ENDUPFORM;
 4575: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4576: <input type="hidden" name="symb" value="$symb" />
 4577: <input type="hidden" name="command" value="csvuploadmap" />
 4578: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4579: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4580: $upfile_select
 4581: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4582: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4583: </form>
 4584: ENDUPFORM
 4585:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4586:                            &mt("How do I create a CSV file from a spreadsheet"))
 4587:     .'</td></tr></table>'."\n";
 4588:     $result.='</td></tr></table><br /><br />'."\n";
 4589:     $result.=&show_grading_menu_form($symb);
 4590:     return $result;
 4591: }
 4592: 
 4593: 
 4594: sub csvuploadmap {
 4595:     my ($request)= @_;
 4596:     my ($symb)=&get_symb($request);
 4597:     if (!$symb) {return '';}
 4598: 
 4599:     my $datatoken;
 4600:     if (!$env{'form.datatoken'}) {
 4601: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4602:     } else {
 4603: 	$datatoken=$env{'form.datatoken'};
 4604: 	&Apache::loncommon::load_tmp_file($request);
 4605:     }
 4606:     my @records=&Apache::loncommon::upfile_record_sep();
 4607:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4608:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4609:     my ($i,$keyfields);
 4610:     if (@records) {
 4611:         my $fieldserror;
 4612: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4613:         if ($fieldserror) {
 4614:             $request->print(&navmap_errormsg());
 4615:             return;
 4616:         }
 4617: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4618: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4619: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4620: 							  \@fields);
 4621: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4622: 	    chop($keyfields);
 4623: 	} else {
 4624: 	    unshift(@fields,['none','']);
 4625: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4626: 							    \@fields);
 4627:             foreach my $rec (@records) {
 4628:                 my %temp = &Apache::loncommon::record_sep($rec);
 4629:                 if (%temp) {
 4630:                     $keyfields=join(',',sort(keys(%temp)));
 4631:                     last;
 4632:                 }
 4633:             }
 4634: 	}
 4635:     }
 4636:     &csvuploadmap_footer($request,$i,$keyfields);
 4637:     $request->print(&show_grading_menu_form($symb));
 4638: 
 4639:     return '';
 4640: }
 4641: 
 4642: sub csvuploadoptions {
 4643:     my ($request)= @_;
 4644:     my ($symb)=&get_symb($request);
 4645:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4646:     my $ignore=&mt('Ignore First Line');
 4647:     $request->print(<<ENDPICK);
 4648: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4649: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4650: <input type="hidden" name="command"    value="csvuploadassign" />
 4651: <!--
 4652: <p>
 4653: <label>
 4654:    <input type="checkbox" name="show_full_results" />
 4655:    Show a table of all changes
 4656: </label>
 4657: </p>
 4658: -->
 4659: <p>
 4660: <label>
 4661:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4662:    Overwrite any existing score
 4663: </label>
 4664: </p>
 4665: ENDPICK
 4666:     my %fields=&get_fields();
 4667:     if (!defined($fields{'domain'})) {
 4668: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4669: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4670:     }
 4671:     foreach my $key (sort(keys(%env))) {
 4672: 	if ($key !~ /^form\.(.*)$/) { next; }
 4673: 	my $cleankey=$1;
 4674: 	if ($cleankey eq 'command') { next; }
 4675: 	$request->print('<input type="hidden" name="'.$cleankey.
 4676: 			'"  value="'.$env{$key}.'" />'."\n");
 4677:     }
 4678:     # FIXME do a check for any duplicated user ids...
 4679:     # FIXME do a check for any invalid user ids?...
 4680:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4681: <hr /></form>'."\n");
 4682:     $request->print(&show_grading_menu_form($symb));
 4683:     return '';
 4684: }
 4685: 
 4686: sub get_fields {
 4687:     my %fields;
 4688:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4689:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4690: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4691: 	    if ($env{'form.f'.$i} ne 'none') {
 4692: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4693: 	    }
 4694: 	} else {
 4695: 	    if ($env{'form.f'.$i} ne 'none') {
 4696: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4697: 	    }
 4698: 	}
 4699:     }
 4700:     return %fields;
 4701: }
 4702: 
 4703: sub csvuploadassign {
 4704:     my ($request)= @_;
 4705:     my ($symb)=&get_symb($request);
 4706:     if (!$symb) {return '';}
 4707:     my $error_msg = '';
 4708:     &Apache::loncommon::load_tmp_file($request);
 4709:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4710:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4711:     my %fields=&get_fields();
 4712:     $request->print('<h3>Assigning Grades</h3>');
 4713:     my $courseid=$env{'request.course.id'};
 4714:     my ($classlist) = &getclasslist('all',0);
 4715:     my @notallowed;
 4716:     my @skipped;
 4717:     my @warnings;
 4718:     my $countdone=0;
 4719:     foreach my $grade (@gradedata) {
 4720: 	my %entries=&Apache::loncommon::record_sep($grade);
 4721: 	my $domain;
 4722: 	if ($entries{$fields{'domain'}}) {
 4723: 	    $domain=$entries{$fields{'domain'}};
 4724: 	} else {
 4725: 	    $domain=$env{'form.default_domain'};
 4726: 	}
 4727: 	$domain=~s/\s//g;
 4728: 	my $username=$entries{$fields{'username'}};
 4729: 	$username=~s/\s//g;
 4730: 	if (!$username) {
 4731: 	    my $id=$entries{$fields{'ID'}};
 4732: 	    $id=~s/\s//g;
 4733: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4734: 	    $username=$ids{$id};
 4735: 	}
 4736: 	if (!exists($$classlist{"$username:$domain"})) {
 4737: 	    my $id=$entries{$fields{'ID'}};
 4738: 	    $id=~s/\s//g;
 4739: 	    if ($id) {
 4740: 		push(@skipped,"$id:$domain");
 4741: 	    } else {
 4742: 		push(@skipped,"$username:$domain");
 4743: 	    }
 4744: 	    next;
 4745: 	}
 4746: 	my $usec=$classlist->{"$username:$domain"}[5];
 4747: 	if (!&canmodify($usec)) {
 4748: 	    push(@notallowed,"$username:$domain");
 4749: 	    next;
 4750: 	}
 4751: 	my %points;
 4752: 	my %grades;
 4753: 	foreach my $dest (keys(%fields)) {
 4754: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4755: 		$dest eq 'domain') { next; }
 4756: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4757: 	    if ($dest=~/stores_(.*)_points/) {
 4758: 		my $part=$1;
 4759: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4760: 					      $symb,$domain,$username);
 4761:                 if ($wgt) {
 4762:                     $entries{$fields{$dest}}=~s/\s//g;
 4763:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4764:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4765:                                           : 'correct_by_override';
 4766:                     if ($pcr>1) {
 4767:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4768:                     }
 4769:                     $grades{"resource.$part.awarded"}=$pcr;
 4770:                     $grades{"resource.$part.solved"}=$award;
 4771:                     $points{$part}=1;
 4772:                 } else {
 4773:                     $error_msg = "<br />" .
 4774:                         &mt("Some point values were assigned"
 4775:                             ." for problems with a weight "
 4776:                             ."of zero. These values were "
 4777:                             ."ignored.");
 4778:                 }
 4779: 	    } else {
 4780: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4781: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4782: 		my $store_key=$dest;
 4783: 		$store_key=~s/^stores/resource/;
 4784: 		$store_key=~s/_/\./g;
 4785: 		$grades{$store_key}=$entries{$fields{$dest}};
 4786: 	    }
 4787: 	}
 4788: 	if (! %grades) { 
 4789:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4790:         } else {
 4791: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4792: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4793: 					   $env{'request.course.id'},
 4794: 					   $domain,$username);
 4795: 	   if ($result eq 'ok') {
 4796: 	      $request->print('.');
 4797: # Remove from grading queue
 4798:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4799:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4800:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4801:                                              $domain,$username);
 4802: 	   } else {
 4803: 	      $request->print("<p><span class=\"LC_error\">".
 4804:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4805:                                   "$username:$domain",$result)."</span></p>");
 4806: 	   }
 4807: 	   $request->rflush();
 4808: 	   $countdone++;
 4809:         }
 4810:     }
 4811:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4812:     if (@warnings) {
 4813:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4814:         $request->print(join(', ',@warnings));
 4815:     }
 4816:     if (@skipped) {
 4817: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4818:         $request->print(join(', ',@skipped));
 4819:     }
 4820:     if (@notallowed) {
 4821: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4822: 	$request->print(join(', ',@notallowed));
 4823:     }
 4824:     $request->print("<br />\n");
 4825:     $request->print(&show_grading_menu_form($symb));
 4826:     return $error_msg;
 4827: }
 4828: #------------- end of section for handling csv file upload ---------
 4829: #
 4830: #-------------------------------------------------------------------
 4831: #
 4832: #-------------- Next few routines handle grading by page/sequence
 4833: #
 4834: #--- Select a page/sequence and a student to grade
 4835: sub pickStudentPage {
 4836:     my ($request) = shift;
 4837: 
 4838:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4839:     &js_escape(\$alertmsg);
 4840:     $request->print(<<LISTJAVASCRIPT);
 4841: <script type="text/javascript" language="javascript">
 4842: 
 4843: function checkPickOne(formname) {
 4844:     if (radioSelection(formname.student) == null) {
 4845: 	alert("$alertmsg");
 4846: 	return;
 4847:     }
 4848:     ptr = pullDownSelection(formname.selectpage);
 4849:     formname.page.value = formname["page"+ptr].value;
 4850:     formname.title.value = formname["title"+ptr].value;
 4851:     formname.submit();
 4852: }
 4853: 
 4854: </script>
 4855: LISTJAVASCRIPT
 4856:     &commonJSfunctions($request);
 4857:     my ($symb) = &get_symb($request);
 4858:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4859:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4860:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4861: 
 4862:     my $result='<h3><span class="LC_info">&nbsp;'.
 4863: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4864: 
 4865:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4866:     my $map_error;
 4867:     my ($titles,$symbx) = &getSymbMap($map_error);
 4868:     if ($map_error) {
 4869:         $request->print(&navmap_errormsg());
 4870:         return; 
 4871:     }
 4872:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4873: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4874: #    my $type=($curpage =~ /\.(page|sequence)/);
 4875:     my $select = '<select name="selectpage">'."\n";
 4876:     my $ctr=0;
 4877:     foreach (@$titles) {
 4878: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4879: 	$select.='<option value="'.$ctr.'" '.
 4880: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4881: 	    '>'.$showtitle.'</option>'."\n";
 4882: 	$ctr++;
 4883:     }
 4884:     $select.= '</select>';
 4885:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4886: 
 4887:     $ctr=0;
 4888:     foreach (@$titles) {
 4889: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4890: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4891: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4892: 	$ctr++;
 4893:     }
 4894:     $result.='<input type="hidden" name="page" />'."\n".
 4895: 	'<input type="hidden" name="title" />'."\n";
 4896: 
 4897:     my $options =
 4898: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4899: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4900:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4901: 
 4902:     $options =
 4903: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4904: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4905: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4906:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4907:     
 4908:     $result.=&build_section_inputs();
 4909:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4910:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4911: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4912: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4913: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4914: 
 4915:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4916: 
 4917:     $result.='&nbsp;<input type="button" '.
 4918:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4919: 
 4920:     $request->print($result);
 4921: 
 4922:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4923: 	&Apache::loncommon::start_data_table().
 4924: 	&Apache::loncommon::start_data_table_header_row().
 4925: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4926: 	'<th>'.&nameUserString('header').'</th>'.
 4927: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4928: 	'<th>'.&nameUserString('header').'</th>'.
 4929: 	&Apache::loncommon::end_data_table_header_row();
 4930:  
 4931:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4932:     my $ptr = 1;
 4933:     foreach my $student (sort 
 4934: 			 {
 4935: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4936: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4937: 			     }
 4938: 			     return $a cmp $b;
 4939: 			 } (keys(%$fullname))) {
 4940: 	my ($uname,$udom) = split(/:/,$student);
 4941: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4942:                                   : '</td>');
 4943: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4944: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4945: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4946: 	$studentTable.=
 4947: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4948:                          : '');
 4949: 	$ptr++;
 4950:     }
 4951:     if ($ptr%2 == 0) {
 4952: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4953: 	    &Apache::loncommon::end_data_table_row();
 4954:     }
 4955:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4956:     $studentTable.='<input type="button" '.
 4957:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4958: 
 4959:     $studentTable.=&show_grading_menu_form($symb);
 4960:     $request->print($studentTable);
 4961: 
 4962:     return '';
 4963: }
 4964: 
 4965: sub getSymbMap {
 4966:     my ($map_error) = @_;
 4967:     my $navmap = Apache::lonnavmaps::navmap->new();
 4968:     unless (ref($navmap)) {
 4969:         if (ref($map_error)) {
 4970:             $$map_error = 'navmap';
 4971:         }
 4972:         return;
 4973:     }
 4974:     my %symbx = ();
 4975:     my @titles = ();
 4976:     my $minder = 0;
 4977: 
 4978:     # Gather every sequence that has problems.
 4979:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4980: 					       1,0,1);
 4981:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4982: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4983: 	    my $title = $minder.'.'.
 4984: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4985: 	    push(@titles, $title); # minder in case two titles are identical
 4986: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4987: 	    $minder++;
 4988: 	}
 4989:     }
 4990:     return \@titles,\%symbx;
 4991: }
 4992: 
 4993: #
 4994: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4995: sub displayPage {
 4996:     my ($request) = shift;
 4997: 
 4998:     my ($symb) = &get_symb($request);
 4999:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5000:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5001:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5002:     my $pageTitle = $env{'form.page'};
 5003:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5004:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5005:     my $usec=$classlist->{$env{'form.student'}}[5];
 5006: 
 5007:     #need to make sure we have the correct data for later EXT calls, 
 5008:     #thus invalidate the cache
 5009:     &Apache::lonnet::devalidatecourseresdata(
 5010:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5011:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5012:     &Apache::lonnet::clear_EXT_cache_status();
 5013: 
 5014:     if (!&canview($usec)) {
 5015: 	$request->print('<span class="LC_warning">'.
 5016:                         &mt('Unable to view requested student. ([_1])',
 5017:                             $env{'form.student'}).
 5018:                         '</span>');
 5019:         $request->print(&show_grading_menu_form($symb));
 5020:         return;
 5021:     }
 5022:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5023:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5024: 	'</h3>'."\n";
 5025:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5026:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5027: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5028:     } else {
 5029: 	delete($env{'form.CODE'});
 5030:     }
 5031:     &sub_page_js($request);
 5032:     $request->print($result);
 5033: 
 5034:     my $navmap = Apache::lonnavmaps::navmap->new();
 5035:     unless (ref($navmap)) {
 5036:         $request->print(&navmap_errormsg());
 5037:         $request->print(&show_grading_menu_form($symb));
 5038:         return;
 5039:     }
 5040:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5041:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5042:     if (!$map) {
 5043: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5044: 	$request->print(&show_grading_menu_form($symb));
 5045: 	return; 
 5046:     }
 5047:     my $iterator = $navmap->getIterator($map->map_start(),
 5048: 					$map->map_finish());
 5049: 
 5050:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5051: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5052: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5053: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5054: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5055: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5056: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5057: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 5058: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 5059: 
 5060:     if (defined($env{'form.CODE'})) {
 5061: 	$studentTable.=
 5062: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5063:     }
 5064:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5065: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5066: 
 5067:     $studentTable.='&nbsp;<span class="LC_info">'.
 5068:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5069:         '</span>'."\n".
 5070: 	&Apache::loncommon::start_data_table().
 5071: 	&Apache::loncommon::start_data_table_header_row().
 5072: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 5073: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5074: 	&Apache::loncommon::end_data_table_header_row();
 5075: 
 5076:     &Apache::lonxml::clear_problem_counter();
 5077:     my ($depth,$question,$prob) = (1,1,1);
 5078:     $iterator->next(); # skip the first BEGIN_MAP
 5079:     my $curRes = $iterator->next(); # for "current resource"
 5080:     while ($depth > 0) {
 5081:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5082:         if($curRes == $iterator->END_MAP) { $depth--; }
 5083: 
 5084:         if (ref($curRes) && $curRes->is_problem()) {
 5085: 	    my $parts = $curRes->parts();
 5086:             my $title = $curRes->compTitle();
 5087: 	    my $symbx = $curRes->symb();
 5088: 	    $studentTable.=
 5089: 		&Apache::loncommon::start_data_table_row().
 5090: 		'<td align="center" valign="top" >'.$prob.
 5091: 		(scalar(@{$parts}) == 1 ? '' 
 5092: 		                        : '<br />('.&mt('[_1]parts',
 5093: 							scalar(@{$parts}).'&nbsp;').')'
 5094: 		 ).
 5095: 		 '</td>';
 5096: 	    $studentTable.='<td valign="top">';
 5097: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5098: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5099: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5100: 					     undef,'both',\%form);
 5101: 	    } else {
 5102: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5103: 		$companswer =~ s|<form(.*?)>||g;
 5104: 		$companswer =~ s|</form>||g;
 5105: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5106: #		    $companswer =~ s/$1/ /ms;
 5107: #		    $request->print('match='.$1."<br />\n");
 5108: #		}
 5109: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5110: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5111: 	    }
 5112: 
 5113: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5114: 
 5115: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5116: 		if ($record{'version'} eq '') {
 5117: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5118: 		} else {
 5119: 		    my %responseType = ();
 5120: 		    foreach my $partid (@{$parts}) {
 5121: 			my @responseIds =$curRes->responseIds($partid);
 5122: 			my @responseType =$curRes->responseType($partid);
 5123: 			my %responseIds;
 5124: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5125: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5126: 			}
 5127: 			$responseType{$partid} = \%responseIds;
 5128: 		    }
 5129: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5130: 
 5131: 		}
 5132: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5133: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5134:                 my $identifier = (&canmodify($usec)? $prob : '');
 5135: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5136: 									$env{'request.course.id'},
 5137: 									'','.submission',undef,
 5138:                                                                         $usec,$identifier);
 5139:  
 5140: 	    }
 5141: 	    if (&canmodify($usec)) {
 5142:             $studentTable.=&gradeBox_start();
 5143: 		foreach my $partid (@{$parts}) {
 5144: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5145: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5146: 		    $question++;
 5147: 		}
 5148:             $studentTable.=&gradeBox_end();
 5149: 		$prob++;
 5150: 	    }
 5151: 	    $studentTable.='</td></tr>';
 5152: 
 5153: 	}
 5154:         $curRes = $iterator->next();
 5155:     }
 5156: 
 5157:     $studentTable.=
 5158:         '</table>'."\n".
 5159:         '<input type="button" value="'.&mt('Save').'" '.
 5160:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5161:         '</form>'."\n";
 5162:     $studentTable.=&show_grading_menu_form($symb);
 5163:     $request->print($studentTable);
 5164: 
 5165:     return '';
 5166: }
 5167: 
 5168: sub displaySubByDates {
 5169:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5170:     my $isCODE=0;
 5171:     my $isTask = ($symb =~/\.task$/);
 5172:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5173:     my $studentTable=&Apache::loncommon::start_data_table().
 5174: 	&Apache::loncommon::start_data_table_header_row().
 5175: 	'<th>'.&mt('Date/Time').'</th>'.
 5176: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5177:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5178: 	'<th>'.&mt('Submission').'</th>'.
 5179: 	'<th>'.&mt('Status').'</th>'.
 5180: 	&Apache::loncommon::end_data_table_header_row();
 5181:     my ($version);
 5182:     my %mark;
 5183:     my %orders;
 5184:     $mark{'correct_by_student'} = $checkIcon;
 5185:     if (!exists($$record{'1:timestamp'})) {
 5186: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5187:     }
 5188: 
 5189:     my $interaction;
 5190:     my $no_increment = 1;
 5191:     my (%lastrndseed,%lasttype);
 5192:     for ($version=1;$version<=$$record{'version'};$version++) {
 5193: 	my $timestamp = 
 5194: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5195: 	if (exists($$record{$version.':resource.0.version'})) {
 5196: 	    $interaction = $$record{$version.':resource.0.version'};
 5197: 	}
 5198:         if ($isTask && $env{'form.previousversion'}) {
 5199:             next unless ($interaction == $env{'form.previousversion'});
 5200:         }
 5201: 	my $where = ($isTask ? "$version:resource.$interaction"
 5202: 		             : "$version:resource");
 5203: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5204: 	    '<td>'.$timestamp.'</td>';
 5205: 	if ($isCODE) {
 5206: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5207: 	}
 5208:         if ($isTask) {
 5209:             $studentTable.='<td>'.$interaction.'</td>';
 5210:         }
 5211: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5212: 	my @displaySub = ();
 5213: 	foreach my $partid (@{$parts}) {
 5214:             my ($hidden,$type);
 5215:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5216:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5217:                 $hidden = 1;
 5218:             }
 5219: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5220: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5221: 	    
 5222: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5223: 	    my $display_part=&get_display_part($partid,$symb);
 5224: 	    foreach my $matchKey (@matchKey) {
 5225: 		if (exists($$record{$version.':'.$matchKey}) &&
 5226: 		    $$record{$version.':'.$matchKey} ne '') {
 5227:                     
 5228: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5229: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5230:                     $displaySub[0].='<span class="LC_nobreak">';
 5231:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5232:                                    .' <span class="LC_internal_info">'
 5233:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5234:                                    .'</span>'
 5235:                                    .' <b>';
 5236:                     if ($hidden) {
 5237:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5238:                     } else {
 5239:                         my ($trial,$rndseed,$newvariation);
 5240:                         if ($type eq 'randomizetry') {
 5241:                             $trial = $$record{"$where.$partid.tries"};
 5242:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5243:                         }
 5244: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5245: 			    $displaySub[0].=&mt('Trial not counted');
 5246: 		        } else {
 5247: 			    $displaySub[0].=&mt('Trial: [_1]',
 5248: 					    $$record{"$where.$partid.tries"});
 5249:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5250:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5251:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5252:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5253:                                 }
 5254:                             }
 5255:                             $lastrndseed{$partid} = $rndseed;
 5256:                             $lasttype{$partid} = $type;
 5257: 		        }
 5258: 		        my $responseType=($isTask ? 'Task'
 5259:                                               : $responseType->{$partid}->{$responseId});
 5260: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5261: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5262: 			    $orders{$partid}->{$responseId}=
 5263: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5264:                                            $no_increment,$type,$trial,$rndseed);
 5265: 		        }
 5266: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5267: 		        $displaySub[0].='&nbsp; '.
 5268: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5269:                     }
 5270: 		}
 5271: 	    }
 5272: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5273: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5274: 				    $$record{"$where.$partid.checkedin"},
 5275: 				    $$record{"$where.$partid.checkedin.slot"}).
 5276: 					'<br />';
 5277: 	    }
 5278: 	    if (exists $$record{"$where.$partid.award"}) {
 5279: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5280: 		    lc($$record{"$where.$partid.award"}).' '.
 5281: 		    $mark{$$record{"$where.$partid.solved"}}.
 5282: 		    '<br />';
 5283: 	    }
 5284: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5285: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5286: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5287: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5288: 		$displaySub[2].=
 5289: 		    $$record{"$version:resource.$partid.regrader"}.
 5290: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5291: 	    }
 5292: 	}
 5293: 	# needed because old essay regrader has not parts info
 5294: 	if (exists $$record{"$version:resource.regrader"}) {
 5295: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5296: 	}
 5297: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5298: 	if ($displaySub[2]) {
 5299: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5300: 	}
 5301: 	$studentTable.='&nbsp;</td>'.
 5302: 	    &Apache::loncommon::end_data_table_row();
 5303:     }
 5304:     $studentTable.=&Apache::loncommon::end_data_table();
 5305:     return $studentTable;
 5306: }
 5307: 
 5308: sub updateGradeByPage {
 5309:     my ($request) = shift;
 5310: 
 5311:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5312:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5313:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5314:     my $pageTitle = $env{'form.page'};
 5315:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5316:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5317:     my $usec=$classlist->{$env{'form.student'}}[5];
 5318:     if (!&canmodify($usec)) {
 5319: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5320: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5321: 	return;
 5322:     }
 5323:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5324:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5325: 	'</h3>'."\n";
 5326: 
 5327:     $request->print($result);
 5328: 
 5329: 
 5330:     my $navmap = Apache::lonnavmaps::navmap->new();
 5331:     unless (ref($navmap)) {
 5332:         $request->print(&navmap_errormsg());
 5333:         return;
 5334:     }
 5335:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5336:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5337:     if (!$map) {
 5338: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5339: 	my ($symb)=&get_symb($request);
 5340: 	$request->print(&show_grading_menu_form($symb));
 5341: 	return; 
 5342:     }
 5343:     my $iterator = $navmap->getIterator($map->map_start(),
 5344: 					$map->map_finish());
 5345: 
 5346:     my $studentTable=
 5347: 	&Apache::loncommon::start_data_table().
 5348: 	&Apache::loncommon::start_data_table_header_row().
 5349: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5350: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5351: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5352: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5353: 	&Apache::loncommon::end_data_table_header_row();
 5354: 
 5355:     $iterator->next(); # skip the first BEGIN_MAP
 5356:     my $curRes = $iterator->next(); # for "current resource"
 5357:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5358:     while ($depth > 0) {
 5359:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5360:         if($curRes == $iterator->END_MAP) { $depth--; }
 5361: 
 5362:         if (ref($curRes) && $curRes->is_problem()) {
 5363: 	    my $parts = $curRes->parts();
 5364:             my $title = $curRes->compTitle();
 5365: 	    my $symbx = $curRes->symb();
 5366: 	    $studentTable.=
 5367: 		&Apache::loncommon::start_data_table_row().
 5368: 		'<td align="center" valign="top" >'.$prob.
 5369: 		(scalar(@{$parts}) == 1 ? '' 
 5370:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5371: 		.')').'</td>';
 5372: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5373: 
 5374: 	    my %newrecord=();
 5375: 	    my @displayPts=();
 5376:             my %aggregate = ();
 5377:             my $aggregateflag = 0;
 5378:             if ($env{'form.HIDE'.$prob}) {
 5379:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5380:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5381:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5382:                 $hideflag += $numchgs;
 5383:             }
 5384: 	    foreach my $partid (@{$parts}) {
 5385: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5386: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5387: 
 5388: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5389: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5390: 		my $partial = $newpts/$wgt;
 5391: 		my $score;
 5392: 		if ($partial > 0) {
 5393: 		    $score = 'correct_by_override';
 5394: 		} elsif ($newpts ne '') { #empty is taken as 0
 5395: 		    $score = 'incorrect_by_override';
 5396: 		}
 5397: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5398: 		if ($dropMenu eq 'excused') {
 5399: 		    $partial = '';
 5400: 		    $score = 'excused';
 5401: 		} elsif ($dropMenu eq 'reset status'
 5402: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5403: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5404: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5405: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5406: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5407: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5408: 		    $changeflag++;
 5409: 		    $newpts = '';
 5410:                     
 5411:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5412:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5413:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5414:                     if ($aggtries > 0) {
 5415:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5416:                         $aggregateflag = 1;
 5417:                     }
 5418: 		}
 5419: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5420: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5421: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5422: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5423: 		    '&nbsp;<br />';
 5424: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5425: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5426: 		    '&nbsp;<br />';
 5427: 		$question++;
 5428: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5429: 
 5430: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5431: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5432: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5433: 		    if (scalar(keys(%newrecord)) > 0);
 5434: 
 5435: 		$changeflag++;
 5436: 	    }
 5437: 	    if (scalar(keys(%newrecord)) > 0) {
 5438: 		my %record = 
 5439: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5440: 					     $udom,$uname);
 5441: 
 5442: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5443: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5444: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5445: 		    $newrecord{'resource.CODE'} = '';
 5446: 		}
 5447: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5448: 					$udom,$uname);
 5449: 		%record = &Apache::lonnet::restore($symbx,
 5450: 						   $env{'request.course.id'},
 5451: 						   $udom,$uname);
 5452: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5453: 					     $cdom,$cnum,$udom,$uname);
 5454: 	    }
 5455: 	    
 5456:             if ($aggregateflag) {
 5457:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5458:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5459:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5460:             }
 5461: 
 5462: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5463: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5464: 		&Apache::loncommon::end_data_table_row();
 5465: 
 5466: 	    $prob++;
 5467: 	}
 5468:         $curRes = $iterator->next();
 5469:     }
 5470: 
 5471:     $studentTable.=&Apache::loncommon::end_data_table();
 5472:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5473:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5474: 		  &mt('The scores were changed for [quant,_1,problem].',
 5475: 		  $changeflag).'<br />');
 5476:     my $hidemsg=($hideflag == 0 ? '' :
 5477:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5478:                      $hideflag).'<br />');
 5479:     $request->print($hidemsg.$grademsg.$studentTable);
 5480: 
 5481:     return '';
 5482: }
 5483: 
 5484: #-------- end of section for handling grading by page/sequence ---------
 5485: #
 5486: #-------------------------------------------------------------------
 5487: 
 5488: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5489: #
 5490: #------ start of section for handling grading by page/sequence ---------
 5491: 
 5492: =pod
 5493: 
 5494: =head1 Bubble sheet grading routines
 5495: 
 5496:   For this documentation:
 5497: 
 5498:    'scanline' refers to the full line of characters
 5499:    from the file that we are parsing that represents one entire sheet
 5500: 
 5501:    'bubble line' refers to the data
 5502:    representing the line of bubbles that are on the physical bubblesheet
 5503: 
 5504: 
 5505: The overall process is that a scanned in bubblesheet data is uploaded
 5506: into a course. When a user wants to grade, they select a
 5507: sequence/folder of resources, a file of bubblesheet info, and pick
 5508: one of the predefined configurations for what each scanline looks
 5509: like.
 5510: 
 5511: Next each scanline is checked for any errors of either 'missing
 5512: bubbles' (it's an error because it may have been mis-scanned
 5513: because too light bubbling), 'double bubble' (each bubble line should
 5514: have no more than one letter picked), invalid or duplicated CODE,
 5515: invalid student/employee ID
 5516: 
 5517: If the CODE option is used that determines the randomization of the
 5518: homework problems, either way the student/employee ID is looked up into a
 5519: username:domain.
 5520: 
 5521: During the validation phase the instructor can choose to skip scanlines. 
 5522: 
 5523: After the validation phase, there are now 3 bubblesheet files
 5524: 
 5525:   scantron_original_filename (unmodified original file)
 5526:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5527:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5528: 
 5529: Also there is a separate hash nohist_scantrondata that contains extra
 5530: correction information that isn't representable in the bubblesheet
 5531: file (see &scantron_getfile() for more information)
 5532: 
 5533: After all scanlines are either valid, marked as valid or skipped, then
 5534: foreach line foreach problem in the picked sequence, an ssi request is
 5535: made that simulates a user submitting their selected letter(s) against
 5536: the homework problem.
 5537: 
 5538: =over 4
 5539: 
 5540: 
 5541: 
 5542: =item defaultFormData
 5543: 
 5544:   Returns html hidden inputs used to hold context/default values.
 5545: 
 5546:  Arguments:
 5547:   $symb - $symb of the current resource 
 5548: 
 5549: =cut
 5550: 
 5551: sub defaultFormData {
 5552:     my ($symb)=@_;
 5553:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5554:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5555:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5556: }
 5557: 
 5558: 
 5559: =pod 
 5560: 
 5561: =item getSequenceDropDown
 5562: 
 5563:    Return html dropdown of possible sequences to grade
 5564:  
 5565:  Arguments:
 5566:    $symb - $symb of the current resource
 5567:    $map_error - ref to scalar which will container error if
 5568:                 $navmap object is unavailable in &getSymbMap().
 5569: 
 5570: =cut
 5571: 
 5572: sub getSequenceDropDown {
 5573:     my ($symb,$map_error)=@_;
 5574:     my $result='<select name="selectpage">'."\n";
 5575:     my ($titles,$symbx) = &getSymbMap($map_error);
 5576:     if (ref($map_error)) {
 5577:         return if ($$map_error);
 5578:     }
 5579:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5580:     my $ctr=0;
 5581:     foreach (@$titles) {
 5582: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5583: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5584: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5585: 	    '>'.$showtitle.'</option>'."\n";
 5586: 	$ctr++;
 5587:     }
 5588:     $result.= '</select>';
 5589:     return $result;
 5590: }
 5591: 
 5592: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5593:                                    # key is zero-based index - 0, 1, 2 ...
 5594: 
 5595: my %first_bubble_line;             # First bubble line no. for each bubble.
 5596: 
 5597: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5598:                                    # matchresponse or rankresponse, where 
 5599:                                    # an individual response can have multiple 
 5600:                                    # lines
 5601: 
 5602: my %responsetype_per_response;     # responsetype for each response
 5603: 
 5604: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5605:                                    # numbered response. Needed when randomorder
 5606:                                    # or randompick are in use. Key is ID, value 
 5607:                                    # is response number.
 5608: 
 5609: # Save and restore the bubble lines array to the form env.
 5610: 
 5611: 
 5612: sub save_bubble_lines {
 5613:     foreach my $line (keys(%bubble_lines_per_response)) {
 5614: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5615: 	$env{"form.scantron.first_bubble_line.$line"} =
 5616: 	    $first_bubble_line{$line};
 5617:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5618:             $subdivided_bubble_lines{$line};
 5619:         $env{"form.scantron.responsetype.$line"} =
 5620:             $responsetype_per_response{$line};
 5621:     }
 5622:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5623:         my $line = $masterseq_id_responsenum{$resid};
 5624:         $env{"form.scantron.residpart.$line"} = $resid;
 5625:     }
 5626: }
 5627: 
 5628: 
 5629: sub restore_bubble_lines {
 5630:     my $line = 0;
 5631:     %bubble_lines_per_response = ();
 5632:     %masterseq_id_responsenum = ();
 5633:     while ($env{"form.scantron.bubblelines.$line"}) {
 5634: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5635: 	$bubble_lines_per_response{$line} = $value;
 5636: 	$first_bubble_line{$line}  =
 5637: 	    $env{"form.scantron.first_bubble_line.$line"};
 5638:         $subdivided_bubble_lines{$line} =
 5639:             $env{"form.scantron.sub_bubblelines.$line"};
 5640:         $responsetype_per_response{$line} =
 5641:             $env{"form.scantron.responsetype.$line"};
 5642:         my $id = $env{"form.scantron.residpart.$line"};
 5643:         $masterseq_id_responsenum{$id} = $line;
 5644: 	$line++;
 5645:     }
 5646: }
 5647: 
 5648: =pod 
 5649: 
 5650: =item scantron_filenames
 5651: 
 5652:    Returns a list of the scantron files in the current course 
 5653: 
 5654: =cut
 5655: 
 5656: sub scantron_filenames {
 5657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5658:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5659:     my $getpropath = 1;
 5660:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5661:                                                         $cname,$getpropath);
 5662:     my @possiblenames;
 5663:     if (ref($dirlist) eq 'ARRAY') {
 5664:         foreach my $filename (sort(@{$dirlist})) {
 5665: 	    ($filename)=split(/&/,$filename);
 5666: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5667: 	    $filename=~s/^scantron_orig_//;
 5668: 	    push(@possiblenames,$filename);
 5669:         }
 5670:     }
 5671:     return @possiblenames;
 5672: }
 5673: 
 5674: =pod 
 5675: 
 5676: =item scantron_uploads
 5677: 
 5678:    Returns  html drop-down list of scantron files in current course.
 5679: 
 5680:  Arguments:
 5681:    $file2grade - filename to set as selected in the dropdown
 5682: 
 5683: =cut
 5684: 
 5685: sub scantron_uploads {
 5686:     my ($file2grade) = @_;
 5687:     my $result=	'<select name="scantron_selectfile">';
 5688:     $result.="<option></option>";
 5689:     foreach my $filename (sort(&scantron_filenames())) {
 5690: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5691:     }
 5692:     $result.="</select>";
 5693:     return $result;
 5694: }
 5695: 
 5696: =pod 
 5697: 
 5698: =item scantron_scantab
 5699: 
 5700:   Returns html drop down of the scantron formats in the scantronformat.tab
 5701:   file.
 5702: 
 5703: =cut
 5704: 
 5705: sub scantron_scantab {
 5706:     my $result='<select name="scantron_format">'."\n";
 5707:     $result.='<option></option>'."\n";
 5708:     my @lines = &get_scantronformat_file();
 5709:     if (@lines > 0) {
 5710:         foreach my $line (@lines) {
 5711:             next if (($line =~ /^\#/) || ($line eq ''));
 5712: 	    my ($name,$descrip)=split(/:/,$line);
 5713: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5714:         }
 5715:     }
 5716:     $result.='</select>'."\n";
 5717:     return $result;
 5718: }
 5719: 
 5720: =pod
 5721: 
 5722: =item get_scantronformat_file
 5723: 
 5724:   Returns an array containing lines from the scantron format file for
 5725:   the domain of the course.
 5726: 
 5727:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5728:   lines are from this file.
 5729: 
 5730:   Otherwise, if a default.tab has been published in RES space by the 
 5731:   domainconfig user, lines are from this file.
 5732: 
 5733:   Otherwise, fall back to getting lines from the legacy file on the
 5734:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5735: 
 5736: =cut
 5737: 
 5738: sub get_scantronformat_file {
 5739:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5740:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5741:     my $gottab = 0;
 5742:     my @lines;
 5743:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5744:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5745:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5746:             if ($formatfile ne '-1') {
 5747:                 @lines = split("\n",$formatfile,-1);
 5748:                 $gottab = 1;
 5749:             }
 5750:         }
 5751:     }
 5752:     if (!$gottab) {
 5753:         my $confname = $cdom.'-domainconfig';
 5754:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5755:         my $formatfile =  &Apache::lonnet::getfile($default);
 5756:         if ($formatfile ne '-1') {
 5757:             @lines = split("\n",$formatfile,-1);
 5758:             $gottab = 1;
 5759:         }
 5760:     }
 5761:     if (!$gottab) {
 5762:         my @domains = &Apache::lonnet::current_machine_domains();
 5763:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5764:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5765:             @lines = <$fh>;
 5766:             close($fh);
 5767:         } else {
 5768:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5769:             @lines = <$fh>;
 5770:             close($fh);
 5771:         }
 5772:     }
 5773:     return @lines;
 5774: }
 5775: 
 5776: =pod 
 5777: 
 5778: =item scantron_CODElist
 5779: 
 5780:   Returns html drop down of the saved CODE lists from current course,
 5781:   generated from earlier printings.
 5782: 
 5783: =cut
 5784: 
 5785: sub scantron_CODElist {
 5786:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5787:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5788:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5789:     my $namechoice='<option></option>';
 5790:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5791: 	if ($name =~ /^error: 2 /) { next; }
 5792: 	if ($name =~ /^type\0/) { next; }
 5793: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5794:     }
 5795:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5796:     return $namechoice;
 5797: }
 5798: 
 5799: =pod 
 5800: 
 5801: =item scantron_CODEunique
 5802: 
 5803:   Returns the html for "Each CODE to be used once" radio.
 5804: 
 5805: =cut
 5806: 
 5807: sub scantron_CODEunique {
 5808:     my $result='<span class="LC_nobreak">
 5809:                  <label><input type="radio" name="scantron_CODEunique"
 5810:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5811:                 </span>
 5812:                 <span class="LC_nobreak">
 5813:                  <label><input type="radio" name="scantron_CODEunique"
 5814:                         value="no" />'.&mt('No').' </label>
 5815:                 </span>';
 5816:     return $result;
 5817: }
 5818: 
 5819: =pod 
 5820: 
 5821: =item scantron_selectphase
 5822: 
 5823:   Generates the initial screen to start the bubblesheet process.
 5824:   Allows for - starting a grading run.
 5825:              - downloading existing scan data (original, corrected
 5826:                                                 or skipped info)
 5827: 
 5828:              - uploading new scan data
 5829: 
 5830:  Arguments:
 5831:   $r          - The Apache request object
 5832:   $file2grade - name of the file that contain the scanned data to score
 5833: 
 5834: =cut
 5835: 
 5836: sub scantron_selectphase {
 5837:     my ($r,$file2grade) = @_;
 5838:     my ($symb)=&get_symb($r);
 5839:     if (!$symb) {return '';}
 5840:     my $map_error;
 5841:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5842:     if ($map_error) {
 5843:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5844:         return;
 5845:     }
 5846:     my $default_form_data=&defaultFormData($symb);
 5847:     my $grading_menu_button=&show_grading_menu_form($symb);
 5848:     my $file_selector=&scantron_uploads($file2grade);
 5849:     my $format_selector=&scantron_scantab();
 5850:     my $CODE_selector=&scantron_CODElist();
 5851:     my $CODE_unique=&scantron_CODEunique();
 5852:     my $result;
 5853: 
 5854:     $ssi_error = 0;
 5855: 
 5856:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5857:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5858: 
 5859:         # Chunk of form to prompt for a scantron file upload.
 5860: 
 5861:         $r->print('
 5862:     <br />
 5863:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5864:        '.&Apache::loncommon::start_data_table_header_row().'
 5865:             <th>
 5866:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5867:             </th>
 5868:        '.&Apache::loncommon::end_data_table_header_row().'
 5869:        '.&Apache::loncommon::start_data_table_row().'
 5870:             <td>
 5871: ');
 5872:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5873:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5874:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5875:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5876:     &js_escape(\$alertmsg);
 5877:     $r->print('
 5878:               <script type="text/javascript" language="javascript">
 5879:     function checkUpload(formname) {
 5880:         if (formname.upfile.value == "") {
 5881:             alert("'.$alertmsg.'");
 5882:             return false;
 5883:         }
 5884:         formname.submit();
 5885:     }
 5886:               </script>
 5887: 
 5888:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5889:                 '.$default_form_data.'
 5890:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5891:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5892:                 <input name="command" value="scantronupload_save" type="hidden" />
 5893:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5894:                 <br />
 5895:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5896:               </form>
 5897: ');
 5898: 
 5899:         $r->print('
 5900:             </td>
 5901:        '.&Apache::loncommon::end_data_table_row().'
 5902:        '.&Apache::loncommon::end_data_table().'
 5903: ');
 5904:     }
 5905: 
 5906:     # Chunk of form to prompt for a file to grade and how:
 5907: 
 5908:     $result.= '
 5909:     <br />
 5910:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5911:     <input type="hidden" name="command" value="scantron_warning" />
 5912:     '.$default_form_data.'
 5913:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5914:        '.&Apache::loncommon::start_data_table_header_row().'
 5915:             <th colspan="2">
 5916:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5917:             </th>
 5918:        '.&Apache::loncommon::end_data_table_header_row().'
 5919:        '.&Apache::loncommon::start_data_table_row().'
 5920:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5921:        '.&Apache::loncommon::end_data_table_row().'
 5922:        '.&Apache::loncommon::start_data_table_row().'
 5923:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5924:        '.&Apache::loncommon::end_data_table_row().'
 5925:        '.&Apache::loncommon::start_data_table_row().'
 5926:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5927:        '.&Apache::loncommon::end_data_table_row().'
 5928:        '.&Apache::loncommon::start_data_table_row().'
 5929:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5930:        '.&Apache::loncommon::end_data_table_row().'
 5931:        '.&Apache::loncommon::start_data_table_row().'
 5932:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5933:        '.&Apache::loncommon::end_data_table_row().'
 5934:        '.&Apache::loncommon::start_data_table_row().'
 5935: 	    <td> '.&mt('Options:').' </td>
 5936:             <td>
 5937: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5938:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5939:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5940: 	    </td>
 5941:        '.&Apache::loncommon::end_data_table_row().'
 5942:        '.&Apache::loncommon::start_data_table_row().'
 5943:             <td colspan="2">
 5944:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5945:             </td>
 5946:        '.&Apache::loncommon::end_data_table_row().'
 5947:     '.&Apache::loncommon::end_data_table().'
 5948:     </form>
 5949: ';
 5950:    
 5951:     $r->print($result);
 5952: 
 5953:     # Chunk of the form that prompts to view a scoring office file,
 5954:     # corrected file, skipped records in a file.
 5955: 
 5956:     $r->print('
 5957:    <br />
 5958:    <form action="/adm/grades" name="scantron_download">
 5959:      '.$default_form_data.'
 5960:      <input type="hidden" name="command" value="scantron_download" />
 5961:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5962:        '.&Apache::loncommon::start_data_table_header_row().'
 5963:               <th>
 5964:                 &nbsp;'.&mt('Download a scoring office file').'
 5965:               </th>
 5966:        '.&Apache::loncommon::end_data_table_header_row().'
 5967:        '.&Apache::loncommon::start_data_table_row().'
 5968:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5969:                 <br />
 5970:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5971:        '.&Apache::loncommon::end_data_table_row().'
 5972:      '.&Apache::loncommon::end_data_table().'
 5973:    </form>
 5974:    <br />
 5975: ');
 5976: 
 5977:     &Apache::lonpickcode::code_list($r,2);
 5978: 
 5979:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5980:              $default_form_data."\n".
 5981:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5982:              &Apache::loncommon::start_data_table_header_row()."\n".
 5983:              '<th colspan="2">
 5984:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5985:              '</th>'."\n".
 5986:               &Apache::loncommon::end_data_table_header_row()."\n".
 5987:               &Apache::loncommon::start_data_table_row()."\n".
 5988:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5989:               '<td> '.$sequence_selector.' </td>'.
 5990:               &Apache::loncommon::end_data_table_row()."\n".
 5991:               &Apache::loncommon::start_data_table_row()."\n".
 5992:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5993:               '<td> '.$file_selector.' </td>'."\n".
 5994:               &Apache::loncommon::end_data_table_row()."\n".
 5995:               &Apache::loncommon::start_data_table_row()."\n".
 5996:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5997:               '<td> '.$format_selector.' </td>'."\n".
 5998:               &Apache::loncommon::end_data_table_row()."\n".
 5999:               &Apache::loncommon::start_data_table_row()."\n".
 6000:               '<td> '.&mt('Options').' </td>'."\n".
 6001:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6002:               &Apache::loncommon::end_data_table_row()."\n".
 6003:               &Apache::loncommon::start_data_table_row()."\n".
 6004:               '<td colspan="2">'."\n".
 6005:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6006:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6007:               '</td>'."\n".
 6008:               &Apache::loncommon::end_data_table_row()."\n".
 6009:               &Apache::loncommon::end_data_table()."\n".
 6010:               '</form><br />');
 6011:     $r->print($grading_menu_button);
 6012:     return;
 6013: }
 6014: 
 6015: =pod
 6016: 
 6017: =item get_scantron_config
 6018: 
 6019:    Parse and return the scantron configuration line selected as a
 6020:    hash of configuration file fields.
 6021: 
 6022:  Arguments:
 6023:     which - the name of the configuration to parse from the file.
 6024: 
 6025: 
 6026:  Returns:
 6027:             If the named configuration is not in the file, an empty
 6028:             hash is returned.
 6029:     a hash with the fields
 6030:       name         - internal name for the this configuration setup
 6031:       description  - text to display to operator that describes this config
 6032:       CODElocation - if 0 or the string 'none'
 6033:                           - no CODE exists for this config
 6034:                      if -1 || the string 'letter'
 6035:                           - a CODE exists for this config and is
 6036:                             a string of letters
 6037:                      Unsupported value (but planned for future support)
 6038:                           if a positive integer
 6039:                                - The CODE exists as the first n items from
 6040:                                  the question section of the form
 6041:                           if the string 'number'
 6042:                                - The CODE exists for this config and is
 6043:                                  a string of numbers
 6044:       CODEstart   - (only matter if a CODE exists) column in the line where
 6045:                      the CODE starts
 6046:       CODElength  - length of the CODE
 6047:       IDstart     - column where the student/employee ID starts
 6048:       IDlength    - length of the student/employee ID info
 6049:       Qstart      - column where the information from the bubbled
 6050:                     'questions' start
 6051:       Qlength     - number of columns comprising a single bubble line from
 6052:                     the sheet. (usually either 1 or 10)
 6053:       Qon         - either a single character representing the character used
 6054:                     to signal a bubble was chosen in the positional setup, or
 6055:                     the string 'letter' if the letter of the chosen bubble is
 6056:                     in the final, or 'number' if a number representing the
 6057:                     chosen bubble is in the file (1->A 0->J)
 6058:       Qoff        - the character used to represent that a bubble was
 6059:                     left blank
 6060:       PaperID     - if the scanning process generates a unique number for each
 6061:                     sheet scanned the column that this ID number starts in
 6062:       PaperIDlength - number of columns that comprise the unique ID number
 6063:                       for the sheet of paper
 6064:       FirstName   - column that the first name starts in
 6065:       FirstNameLength - number of columns that the first name spans
 6066:  
 6067:       LastName    - column that the last name starts in
 6068:       LastNameLength - number of columns that the last name spans
 6069:       BubblesPerRow - number of bubbles available in each row used to
 6070:                       bubble an answer. (If not specified, 10 assumed).
 6071: 
 6072: =cut
 6073: 
 6074: sub get_scantron_config {
 6075:     my ($which) = @_;
 6076:     my @lines = &get_scantronformat_file();
 6077:     my %config;
 6078:     #FIXME probably should move to XML it has already gotten a bit much now
 6079:     foreach my $line (@lines) {
 6080: 	my ($name,$descrip)=split(/:/,$line);
 6081: 	if ($name ne $which ) { next; }
 6082: 	chomp($line);
 6083: 	my @config=split(/:/,$line);
 6084: 	$config{'name'}=$config[0];
 6085: 	$config{'description'}=$config[1];
 6086: 	$config{'CODElocation'}=$config[2];
 6087: 	$config{'CODEstart'}=$config[3];
 6088: 	$config{'CODElength'}=$config[4];
 6089: 	$config{'IDstart'}=$config[5];
 6090: 	$config{'IDlength'}=$config[6];
 6091: 	$config{'Qstart'}=$config[7];
 6092:  	$config{'Qlength'}=$config[8];
 6093: 	$config{'Qoff'}=$config[9];
 6094: 	$config{'Qon'}=$config[10];
 6095: 	$config{'PaperID'}=$config[11];
 6096: 	$config{'PaperIDlength'}=$config[12];
 6097: 	$config{'FirstName'}=$config[13];
 6098: 	$config{'FirstNamelength'}=$config[14];
 6099: 	$config{'LastName'}=$config[15];
 6100: 	$config{'LastNamelength'}=$config[16];
 6101:         $config{'BubblesPerRow'}=$config[17];
 6102: 	last;
 6103:     }
 6104:     return %config;
 6105: }
 6106: 
 6107: =pod 
 6108: 
 6109: =item username_to_idmap
 6110: 
 6111:     creates a hash keyed by student/employee ID with values of the corresponding
 6112:     student username:domain.
 6113: 
 6114:   Arguments:
 6115: 
 6116:     $classlist - reference to the class list hash. This is a hash
 6117:                  keyed by student name:domain  whose elements are references
 6118:                  to arrays containing various chunks of information
 6119:                  about the student. (See loncoursedata for more info).
 6120: 
 6121:   Returns
 6122:     %idmap - the constructed hash
 6123: 
 6124: =cut
 6125: 
 6126: sub username_to_idmap {
 6127:     my ($classlist)= @_;
 6128:     my %idmap;
 6129:     foreach my $student (keys(%$classlist)) {
 6130:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6131:         unless ($id eq '') {
 6132:             if (!exists($idmap{$id})) {
 6133:                 $idmap{$id} = $student;
 6134:             } else {
 6135:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6136:                 if ($status eq 'Active') {
 6137:                     $idmap{$id} = $student;
 6138:                 }
 6139:             }
 6140:         }
 6141:     }
 6142:     return %idmap;
 6143: }
 6144: 
 6145: =pod
 6146: 
 6147: =item scantron_fixup_scanline
 6148: 
 6149:    Process a requested correction to a scanline.
 6150: 
 6151:   Arguments:
 6152:     $scantron_config   - hash from &get_scantron_config()
 6153:     $scan_data         - hash of correction information 
 6154:                           (see &scantron_getfile())
 6155:     $line              - existing scanline
 6156:     $whichline         - line number of the passed in scanline
 6157:     $field             - type of change to process 
 6158:                          (either 
 6159:                           'ID'     -> correct the student/employee ID
 6160:                           'CODE'   -> correct the CODE
 6161:                           'answer' -> fixup the submitted answers)
 6162:     
 6163:    $args               - hash of additional info,
 6164:                           - 'ID' 
 6165:                                'newid' -> studentID to use in replacement
 6166:                                           of existing one
 6167:                           - 'CODE' 
 6168:                                'CODE_ignore_dup' - set to true if duplicates
 6169:                                                    should be ignored.
 6170: 	                       'CODE' - is new code or 'use_unfound'
 6171:                                         if the existing unfound code should
 6172:                                         be used as is
 6173:                           - 'answer'
 6174:                                'response' - new answer or 'none' if blank
 6175:                                'question' - the bubble line to change
 6176:                                'questionnum' - the question identifier,
 6177:                                                may include subquestion. 
 6178: 
 6179:   Returns:
 6180:     $line - the modified scanline
 6181: 
 6182:   Side effects: 
 6183:     $scan_data - may be updated
 6184: 
 6185: =cut
 6186: 
 6187: 
 6188: sub scantron_fixup_scanline {
 6189:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6190:     if ($field eq 'ID') {
 6191: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6192: 	    return ($line,1,'New value too large');
 6193: 	}
 6194: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6195: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6196: 				     $args->{'newid'});
 6197: 	}
 6198: 	substr($line,$$scantron_config{'IDstart'}-1,
 6199: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6200: 	if ($args->{'newid'}=~/^\s*$/) {
 6201: 	    &scan_data($scan_data,"$whichline.user",
 6202: 		       $args->{'username'}.':'.$args->{'domain'});
 6203: 	}
 6204:     } elsif ($field eq 'CODE') {
 6205: 	if ($args->{'CODE_ignore_dup'}) {
 6206: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6207: 	}
 6208: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6209: 	if ($args->{'CODE'} ne 'use_unfound') {
 6210: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6211: 		return ($line,1,'New CODE value too large');
 6212: 	    }
 6213: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6214: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6215: 	    }
 6216: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6217: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6218: 	}
 6219:     } elsif ($field eq 'answer') {
 6220: 	my $length=$scantron_config->{'Qlength'};
 6221: 	my $off=$scantron_config->{'Qoff'};
 6222: 	my $on=$scantron_config->{'Qon'};
 6223: 	my $answer=${off}x$length;
 6224: 	if ($args->{'response'} eq 'none') {
 6225: 	    &scan_data($scan_data,
 6226: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6227: 	} else {
 6228: 	    if ($on eq 'letter') {
 6229: 		my @alphabet=('A'..'Z');
 6230: 		$answer=$alphabet[$args->{'response'}];
 6231: 	    } elsif ($on eq 'number') {
 6232: 		$answer=$args->{'response'}+1;
 6233: 		if ($answer == 10) { $answer = '0'; }
 6234: 	    } else {
 6235: 		substr($answer,$args->{'response'},1)=$on;
 6236: 	    }
 6237: 	    &scan_data($scan_data,
 6238: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6239: 	}
 6240: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6241: 	substr($line,$where-1,$length)=$answer;
 6242:     }
 6243:     return $line;
 6244: }
 6245: 
 6246: =pod
 6247: 
 6248: =item scan_data
 6249: 
 6250:     Edit or look up  an item in the scan_data hash.
 6251: 
 6252:   Arguments:
 6253:     $scan_data  - The hash (see scantron_getfile)
 6254:     $key        - shorthand of the key to edit (actual key is
 6255:                   scantronfilename_key).
 6256:     $data        - New value of the hash entry.
 6257:     $delete      - If true, the entry is removed from the hash.
 6258: 
 6259:   Returns:
 6260:     The new value of the hash table field (undefined if deleted).
 6261: 
 6262: =cut
 6263: 
 6264: 
 6265: sub scan_data {
 6266:     my ($scan_data,$key,$value,$delete)=@_;
 6267:     my $filename=$env{'form.scantron_selectfile'};
 6268:     if (defined($value)) {
 6269: 	$scan_data->{$filename.'_'.$key} = $value;
 6270:     }
 6271:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6272:     return $scan_data->{$filename.'_'.$key};
 6273: }
 6274: 
 6275: # ----- These first few routines are general use routines.----
 6276: 
 6277: # Return the number of occurences of a pattern in a string.
 6278: 
 6279: sub occurence_count {
 6280:     my ($string, $pattern) = @_;
 6281: 
 6282:     my @matches = ($string =~ /$pattern/g);
 6283: 
 6284:     return scalar(@matches);
 6285: }
 6286: 
 6287: 
 6288: # Take a string known to have digits and convert all the
 6289: # digits into letters in the range J,A..I.
 6290: 
 6291: sub digits_to_letters {
 6292:     my ($input) = @_;
 6293: 
 6294:     my @alphabet = ('J', 'A'..'I');
 6295: 
 6296:     my @input    = split(//, $input);
 6297:     my $output ='';
 6298:     for (my $i = 0; $i < scalar(@input); $i++) {
 6299: 	if ($input[$i] =~ /\d/) {
 6300: 	    $output .= $alphabet[$input[$i]];
 6301: 	} else {
 6302: 	    $output .= $input[$i];
 6303: 	}
 6304:     }
 6305:     return $output;
 6306: }
 6307: 
 6308: =pod 
 6309: 
 6310: =item scantron_parse_scanline
 6311: 
 6312:   Decodes a scanline from the selected scantron file
 6313: 
 6314:  Arguments:
 6315:     line             - The text of the scantron file line to process
 6316:     whichline        - Line number
 6317:     scantron_config  - Hash describing the format of the scantron lines.
 6318:     scan_data        - Hash of extra information about the scanline
 6319:                        (see scantron_getfile for more information)
 6320:     just_header      - True if should not process question answers but only
 6321:                        the stuff to the left of the answers.
 6322:     randomorder      - True if randomorder in use
 6323:     randompick       - True if randompick in use
 6324:     sequence         - Exam folder URL
 6325:     master_seq       - Ref to array containing symbs in exam folder
 6326:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6327:                        (corresponding values are resource objects)
 6328:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6329:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6330:                        are refs to an array of resource objects, ordered
 6331:                        according to order used for CODE, when randomorder
 6332:                        and or randompick are in use.
 6333:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6334:                        for current line to question number used for same question
 6335:                         in "Master Sequence" (as seen by Course Coordinator).
 6336:     startline        - Ref to hash where key is question number (0 is first)
 6337:                        and value is number of first bubble line for current 
 6338:                        student or code-based randompick and/or randomorder.
 6339:     totalref         - Ref of scalar used to score total number of bubble
 6340:                        lines needed for responses in a scan line (used when
 6341:                        randompick in use. 
 6342: 
 6343:  Returns:
 6344:    Hash containing the result of parsing the scanline
 6345: 
 6346:    Keys are all proceeded by the string 'scantron.'
 6347: 
 6348:        CODE    - the CODE in use for this scanline
 6349:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6350:                  by the operator
 6351:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6352:                             CODEs were selected, but the usage has been
 6353:                             forced by the operator
 6354:        ID  - student/employee ID
 6355:        PaperID - if used, the ID number printed on the sheet when the 
 6356:                  paper was scanned
 6357:        FirstName - first name from the sheet
 6358:        LastName  - last name from the sheet
 6359: 
 6360:      if just_header was not true these key may also exist
 6361: 
 6362:        missingerror - a list of bubble ranges that are considered to be answers
 6363:                       to a single question that don't have any bubbles filled in.
 6364:                       Of the form questionnumber:firstbubblenumber:count.
 6365:        doubleerror  - a list of bubble ranges that are considered to be answers
 6366:                       to a single question that have more than one bubble filled in.
 6367:                       Of the form questionnumber::firstbubblenumber:count
 6368:    
 6369:                 In the above, count is the number of bubble responses in the
 6370:                 input line needed to represent the possible answers to the question.
 6371:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6372:                 per line would have count = 2.
 6373: 
 6374:        maxquest     - the number of the last bubble line that was parsed
 6375: 
 6376:        (<number> starts at 1)
 6377:        <number>.answer - zero or more letters representing the selected
 6378:                          letters from the scanline for the bubble line 
 6379:                          <number>.
 6380:                          if blank there was either no bubble or there where
 6381:                          multiple bubbles, (consult the keys missingerror and
 6382:                          doubleerror if this is an error condition)
 6383: 
 6384: =cut
 6385: 
 6386: sub scantron_parse_scanline {
 6387:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6388:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6389:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6390: 
 6391:     my %record;
 6392:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6393:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6394: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6395: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6396: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6397: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6398: 	    $record{'scantron.CODE'}=substr($data,
 6399: 					    $$scantron_config{'CODEstart'}-1,
 6400: 					    $$scantron_config{'CODElength'});
 6401: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6402: 		$record{'scantron.useCODE'}=1;
 6403: 	    }
 6404: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6405: 		$record{'scantron.CODE_ignore_dup'}=1;
 6406: 	    }
 6407: 	} else {
 6408: 	    #FIXME interpret first N questions
 6409: 	}
 6410:     }
 6411:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6412: 				  $$scantron_config{'IDlength'});
 6413:     $record{'scantron.PaperID'}=
 6414: 	substr($data,$$scantron_config{'PaperID'}-1,
 6415: 	       $$scantron_config{'PaperIDlength'});
 6416:     $record{'scantron.FirstName'}=
 6417: 	substr($data,$$scantron_config{'FirstName'}-1,
 6418: 	       $$scantron_config{'FirstNamelength'});
 6419:     $record{'scantron.LastName'}=
 6420: 	substr($data,$$scantron_config{'LastName'}-1,
 6421: 	       $$scantron_config{'LastNamelength'});
 6422:     if ($just_header) { return \%record; }
 6423: 
 6424:     my @alphabet=('A'..'Z');
 6425:     my $questnum=0;
 6426:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6427: 
 6428:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6429:     if ($randompick || $randomorder) {
 6430:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6431:                                          $master_seq,$symb_to_resource,
 6432:                                          $partids_by_symb,$orderedforcode,
 6433:                                          $respnumlookup,$startline);
 6434:         if ($total) {
 6435:             $lastpos = $total*$$scantron_config{'Qlength'};
 6436:         }
 6437:         if (ref($totalref)) {
 6438:             $$totalref = $total;
 6439:         }
 6440:     }
 6441:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6442:     chomp($questions);		# Get rid of any trailing \n.
 6443:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6444:     while (length($questions)) {
 6445:         my $answers_needed;
 6446:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6447:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6448:         } else {
 6449:             $answers_needed = $bubble_lines_per_response{$questnum};
 6450:         }
 6451:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6452:                              || 1;
 6453:         $questnum++;
 6454:         my $quest_id = $questnum;
 6455:         my $currentquest = substr($questions,0,$answer_length);
 6456:         $questions       = substr($questions,$answer_length);
 6457:         if (length($currentquest) < $answer_length) { next; }
 6458: 
 6459:         my $subdivided;
 6460:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6461:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6462:         } else {
 6463:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6464:         }
 6465:         if ($subdivided =~ /,/) {
 6466:             my $subquestnum = 1;
 6467:             my $subquestions = $currentquest;
 6468:             my @subanswers_needed = split(/,/,$subdivided);
 6469:             foreach my $subans (@subanswers_needed) {
 6470:                 my $subans_length =
 6471:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6472:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6473:                 $subquestions   = substr($subquestions,$subans_length);
 6474:                 $quest_id = "$questnum.$subquestnum";
 6475:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6476:                     ($$scantron_config{'Qon'} eq 'number')) {
 6477:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6478:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6479:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6480:                         $randomorder,$randompick,$respnumlookup);
 6481:                 } else {
 6482:                     $ansnum = &scantron_validator_positional($ansnum,
 6483:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6484:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6485:                         $randomorder,$randompick,$respnumlookup);
 6486:                 }
 6487:                 $subquestnum ++;
 6488:             }
 6489:         } else {
 6490:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6491:                 ($$scantron_config{'Qon'} eq 'number')) {
 6492:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6493:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6494:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6495:                     $randomorder,$randompick,$respnumlookup);
 6496:             } else {
 6497:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6498:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6499:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6500:                     $randomorder,$randompick,$respnumlookup);
 6501:             }
 6502:         }
 6503:     }
 6504:     $record{'scantron.maxquest'}=$questnum;
 6505:     return \%record;
 6506: }
 6507: 
 6508: sub get_master_seq {
 6509:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6510:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6511:                    (ref($symb_to_resource) eq 'HASH'));
 6512:     my $resource_error;
 6513:     foreach my $resource (@{$resources}) {
 6514:         my $ressymb;
 6515:         if (ref($resource)) {
 6516:             $ressymb = $resource->symb();
 6517:             push(@{$master_seq},$ressymb);
 6518:             $symb_to_resource->{$ressymb} = $resource;
 6519:         } else {
 6520:             $resource_error = 1;
 6521:             last;
 6522:         }
 6523:     }
 6524:     return $resource_error;
 6525: }
 6526: 
 6527: sub get_respnum_lookups {
 6528:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6529:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6530:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6531:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6532:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6533:                    (ref($startline) eq 'HASH'));
 6534:     my ($user,$scancode);
 6535:     if ((exists($record->{'scantron.CODE'})) &&
 6536:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6537:         $scancode = $record->{'scantron.CODE'};
 6538:     } else {
 6539:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6540:     }
 6541:     my @mapresources =
 6542:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6543:                      $orderedforcode);
 6544:     my $total = 0;
 6545:     my $count = 0;
 6546:     foreach my $resource (@mapresources) {
 6547:         my $id = $resource->id();
 6548:         my $symb = $resource->symb();
 6549:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6550:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6551:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6552:                 if ($respnum ne '') {
 6553:                     $respnumlookup->{$count} = $respnum;
 6554:                     $startline->{$count} = $total;
 6555:                     $total += $bubble_lines_per_response{$respnum};
 6556:                     $count ++;
 6557:                 }
 6558:             }
 6559:         }
 6560:     }
 6561:     return $total;
 6562: }
 6563: 
 6564: sub scantron_validator_lettnum {
 6565:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6566:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6567:         $randompick,$respnumlookup) = @_;
 6568: 
 6569:     # Qon 'letter' implies for each slot in currquest we have:
 6570:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6571:     #    about anything else (esp. a value of Qoff) for missing
 6572:     #    bubbles.
 6573:     #
 6574:     # Qon 'number' implies each slot gives a digit that indexes the
 6575:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6576:     #    and * or ? for double bubbles on a single line.
 6577:     #
 6578: 
 6579:     my $matchon;
 6580:     if ($$scantron_config{'Qon'} eq 'letter') {
 6581:         $matchon = '[A-Z]';
 6582:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6583:         $matchon = '\d';
 6584:     }
 6585:     my $occurrences = 0;
 6586:     my $responsenum = $questnum-1;
 6587:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6588:        $responsenum = $respnumlookup->{$questnum-1}
 6589:     }
 6590:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6591:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6592:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6593:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6594:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6595:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6596:         my @singlelines = split('',$currquest);
 6597:         foreach my $entry (@singlelines) {
 6598:             $occurrences = &occurence_count($entry,$matchon);
 6599:             if ($occurrences > 1) {
 6600:                 last;
 6601:             }
 6602:         }
 6603:     } else {
 6604:         $occurrences = &occurence_count($currquest,$matchon); 
 6605:     }
 6606:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6607:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6608:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6609:             my $bubble = substr($currquest,$ans,1);
 6610:             if ($bubble =~ /$matchon/ ) {
 6611:                 if ($$scantron_config{'Qon'} eq 'number') {
 6612:                     if ($bubble == 0) {
 6613:                         $bubble = 10; 
 6614:                     }
 6615:                     $record->{"scantron.$ansnum.answer"} = 
 6616:                         $alphabet->[$bubble-1];
 6617:                 } else {
 6618:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6619:                 }
 6620:             } else {
 6621:                 $record->{"scantron.$ansnum.answer"}='';
 6622:             }
 6623:             $ansnum++;
 6624:         }
 6625:     } elsif (!defined($currquest)
 6626:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6627:             || (&occurence_count($currquest,$matchon) == 0)) {
 6628:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6629:             $record->{"scantron.$ansnum.answer"}='';
 6630:             $ansnum++;
 6631:         }
 6632:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6633:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6634:         }
 6635:     } else {
 6636:         if ($$scantron_config{'Qon'} eq 'number') {
 6637:             $currquest = &digits_to_letters($currquest);            
 6638:         }
 6639:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6640:             my $bubble = substr($currquest,$ans,1);
 6641:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6642:             $ansnum++;
 6643:         }
 6644:     }
 6645:     return $ansnum;
 6646: }
 6647: 
 6648: sub scantron_validator_positional {
 6649:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6650:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6651:         $randomorder,$randompick,$respnumlookup) = @_;
 6652: 
 6653:     # Otherwise there's a positional notation;
 6654:     # each bubble line requires Qlength items, and there are filled in
 6655:     # bubbles for each case where there 'Qon' characters.
 6656:     #
 6657: 
 6658:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6659: 
 6660:     # If the split only gives us one element.. the full length of the
 6661:     # answer string, no bubbles are filled in:
 6662: 
 6663:     if ($answers_needed eq '') {
 6664:         return;
 6665:     }
 6666: 
 6667:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6668:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6669:             $record->{"scantron.$ansnum.answer"}='';
 6670:             $ansnum++;
 6671:         }
 6672:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6673:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6674:         }
 6675:     } elsif (scalar(@array) == 2) {
 6676:         my $location = length($array[0]);
 6677:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6678:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6679:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6680:             if ($ans eq $line_num) {
 6681:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6682:             } else {
 6683:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6684:             }
 6685:             $ansnum++;
 6686:          }
 6687:     } else {
 6688:         #  If there's more than one instance of a bubble character
 6689:         #  That's a double bubble; with positional notation we can
 6690:         #  record all the bubbles filled in as well as the
 6691:         #  fact this response consists of multiple bubbles.
 6692:         #
 6693:         my $responsenum = $questnum-1;
 6694:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6695:             $responsenum = $respnumlookup->{$questnum-1}
 6696:         }
 6697:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6698:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6699:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6700:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6701:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6702:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6703:             my $doubleerror = 0;
 6704:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6705:                    (!$doubleerror)) {
 6706:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6707:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6708:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6709:                if (length(@currarray) > 2) {
 6710:                    $doubleerror = 1;
 6711:                } 
 6712:             }
 6713:             if ($doubleerror) {
 6714:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6715:             }
 6716:         } else {
 6717:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6718:         }
 6719:         my $item = $ansnum;
 6720:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6721:             $record->{"scantron.$item.answer"} = '';
 6722:             $item ++;
 6723:         }
 6724: 
 6725:         my @ans=@array;
 6726:         my $i=0;
 6727:         my $increment = 0;
 6728:         while ($#ans) {
 6729:             $i+=length($ans[0]) + $increment;
 6730:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6731:             my $bubble = $i%$$scantron_config{'Qlength'};
 6732:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6733:             shift(@ans);
 6734:             $increment = 1;
 6735:         }
 6736:         $ansnum += $answers_needed;
 6737:     }
 6738:     return $ansnum;
 6739: }
 6740: 
 6741: =pod
 6742: 
 6743: =item scantron_add_delay
 6744: 
 6745:    Adds an error message that occurred during the grading phase to a
 6746:    queue of messages to be shown after grading pass is complete
 6747: 
 6748:  Arguments:
 6749:    $delayqueue  - arrary ref of hash ref of error messages
 6750:    $scanline    - the scanline that caused the error
 6751:    $errormesage - the error message
 6752:    $errorcode   - a numeric code for the error
 6753: 
 6754:  Side Effects:
 6755:    updates the $delayqueue to have a new hash ref of the error
 6756: 
 6757: =cut
 6758: 
 6759: sub scantron_add_delay {
 6760:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6761:     push(@$delayqueue,
 6762: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6763: 	  'ecode' => $errorcode }
 6764: 	 );
 6765: }
 6766: 
 6767: =pod
 6768: 
 6769: =item scantron_find_student
 6770: 
 6771:    Finds the username for the current scanline
 6772: 
 6773:   Arguments:
 6774:    $scantron_record - hash result from scantron_parse_scanline
 6775:    $scan_data       - hash of correction information 
 6776:                       (see &scantron_getfile() form more information)
 6777:    $idmap           - hash from &username_to_idmap()
 6778:    $line            - number of current scanline
 6779:  
 6780:   Returns:
 6781:    Either 'username:domain' or undef if unknown
 6782: 
 6783: =cut
 6784: 
 6785: sub scantron_find_student {
 6786:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6787:     my $scanID=$$scantron_record{'scantron.ID'};
 6788:     if ($scanID =~ /^\s*$/) {
 6789:  	return &scan_data($scan_data,"$line.user");
 6790:     }
 6791:     foreach my $id (keys(%$idmap)) {
 6792:  	if (lc($id) eq lc($scanID)) {
 6793:  	    return $$idmap{$id};
 6794:  	}
 6795:     }
 6796:     return undef;
 6797: }
 6798: 
 6799: =pod
 6800: 
 6801: =item scantron_filter
 6802: 
 6803:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6804:    hidden resources was selected
 6805: 
 6806: =cut
 6807: 
 6808: sub scantron_filter {
 6809:     my ($curres)=@_;
 6810: 
 6811:     if (ref($curres) && $curres->is_problem()) {
 6812: 	# if the user has asked to not have either hidden
 6813: 	# or 'randomout' controlled resources to be graded
 6814: 	# don't include them
 6815: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6816: 	    && $curres->randomout) {
 6817: 	    return 0;
 6818: 	}
 6819: 	return 1;
 6820:     }
 6821:     return 0;
 6822: }
 6823: 
 6824: =pod
 6825: 
 6826: =item scantron_process_corrections
 6827: 
 6828:    Gets correction information out of submitted form data and corrects
 6829:    the scanline
 6830: 
 6831: =cut
 6832: 
 6833: sub scantron_process_corrections {
 6834:     my ($r) = @_;
 6835:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6836:     my ($scanlines,$scan_data)=&scantron_getfile();
 6837:     my $classlist=&Apache::loncoursedata::get_classlist();
 6838:     my $which=$env{'form.scantron_line'};
 6839:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6840:     my ($skip,$err,$errmsg);
 6841:     if ($env{'form.scantron_skip_record'}) {
 6842: 	$skip=1;
 6843:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6844: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6845: 	    $env{'form.scantron_domain'};
 6846: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6847: 	($line,$err,$errmsg)=
 6848: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6849: 				     'ID',{'newid'=>$newid,
 6850: 				    'username'=>$env{'form.scantron_username'},
 6851: 				    'domain'=>$env{'form.scantron_domain'}});
 6852:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6853: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6854: 	my $newCODE;
 6855: 	my %args;
 6856: 	if      ($resolution eq 'use_unfound') {
 6857: 	    $newCODE='use_unfound';
 6858: 	} elsif ($resolution eq 'use_found') {
 6859: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6860: 	} elsif ($resolution eq 'use_typed') {
 6861: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6862: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6863: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6864: 	}
 6865: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6866: 	    $args{'CODE_ignore_dup'}=1;
 6867: 	}
 6868: 	$args{'CODE'}=$newCODE;
 6869: 	($line,$err,$errmsg)=
 6870: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6871: 				     'CODE',\%args);
 6872:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6873: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6874: 	    ($line,$err,$errmsg)=
 6875: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6876: 					 $which,'answer',
 6877: 					 { 'question'=>$question,
 6878: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6879:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6880: 	    if ($err) { last; }
 6881: 	}
 6882:     }
 6883:     if ($err) {
 6884: 	$r->print(
 6885:             '<p class="LC_error">'
 6886:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6887:                 $errmsg)
 6888:            .'</p>');
 6889:     } else {
 6890: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6891: 	&scantron_putfile($scanlines,$scan_data);
 6892:     }
 6893: }
 6894: 
 6895: =pod
 6896: 
 6897: =item reset_skipping_status
 6898: 
 6899:    Forgets the current set of remember skipped scanlines (and thus
 6900:    reverts back to considering all lines in the
 6901:    scantron_skipped_<filename> file)
 6902: 
 6903: =cut
 6904: 
 6905: sub reset_skipping_status {
 6906:     my ($scanlines,$scan_data)=&scantron_getfile();
 6907:     &scan_data($scan_data,'remember_skipping',undef,1);
 6908:     &scantron_putfile(undef,$scan_data);
 6909: }
 6910: 
 6911: =pod
 6912: 
 6913: =item start_skipping
 6914: 
 6915:    Marks a scanline to be skipped. 
 6916: 
 6917: =cut
 6918: 
 6919: sub start_skipping {
 6920:     my ($scan_data,$i)=@_;
 6921:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6922:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6923: 	$remembered{$i}=2;
 6924:     } else {
 6925: 	$remembered{$i}=1;
 6926:     }
 6927:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6928: }
 6929: 
 6930: =pod
 6931: 
 6932: =item should_be_skipped
 6933: 
 6934:    Checks whether a scanline should be skipped.
 6935: 
 6936: =cut
 6937: 
 6938: sub should_be_skipped {
 6939:     my ($scanlines,$scan_data,$i)=@_;
 6940:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6941: 	# not redoing old skips
 6942: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6943: 	return 0;
 6944:     }
 6945:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6946: 
 6947:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6948: 	return 0;
 6949:     }
 6950:     return 1;
 6951: }
 6952: 
 6953: =pod
 6954: 
 6955: =item remember_current_skipped
 6956: 
 6957:    Discovers what scanlines are in the scantron_skipped_<filename>
 6958:    file and remembers them into scan_data for later use.
 6959: 
 6960: =cut
 6961: 
 6962: sub remember_current_skipped {
 6963:     my ($scanlines,$scan_data)=&scantron_getfile();
 6964:     my %to_remember;
 6965:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6966: 	if ($scanlines->{'skipped'}[$i]) {
 6967: 	    $to_remember{$i}=1;
 6968: 	}
 6969:     }
 6970: 
 6971:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6972:     &scantron_putfile(undef,$scan_data);
 6973: }
 6974: 
 6975: =pod
 6976: 
 6977: =item check_for_error
 6978: 
 6979:     Checks if there was an error when attempting to remove a specific
 6980:     scantron_.. bubblesheet data file. Prints out an error if
 6981:     something went wrong.
 6982: 
 6983: =cut
 6984: 
 6985: sub check_for_error {
 6986:     my ($r,$result)=@_;
 6987:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6988: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6989:     }
 6990: }
 6991: 
 6992: =pod
 6993: 
 6994: =item scantron_warning_screen
 6995: 
 6996:    Interstitial screen to make sure the operator has selected the
 6997:    correct options before we start the validation phase.
 6998: 
 6999: =cut
 7000: 
 7001: sub scantron_warning_screen {
 7002:     my ($button_text)=@_;
 7003:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7004:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7005:     my $CODElist;
 7006:     if ($scantron_config{'CODElocation'} &&
 7007: 	$scantron_config{'CODEstart'} &&
 7008: 	$scantron_config{'CODElength'}) {
 7009: 	$CODElist=$env{'form.scantron_CODElist'};
 7010: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7011: 	$CODElist=
 7012: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7013: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7014:     }
 7015:     my $lastbubblepoints;
 7016:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7017:         $lastbubblepoints =
 7018:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7019:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7020:     }
 7021:     return ('
 7022: <p>
 7023: <span class="LC_warning">
 7024: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7025: </p>
 7026: <table>
 7027: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7028: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7029: '.$CODElist.$lastbubblepoints.'
 7030: </table>
 7031: <br />
 7032: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 7033: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 7034: 
 7035: <br />
 7036: ');
 7037: }
 7038: 
 7039: =pod
 7040: 
 7041: =item scantron_do_warning
 7042: 
 7043:    Check if the operator has picked something for all required
 7044:    fields. Error out if something is missing.
 7045: 
 7046: =cut
 7047: 
 7048: sub scantron_do_warning {
 7049:     my ($r)=@_;
 7050:     my ($symb)=&get_symb($r);
 7051:     if (!$symb) {return '';}
 7052:     my $default_form_data=&defaultFormData($symb);
 7053:     $r->print(&scantron_form_start().$default_form_data);
 7054:     if ( $env{'form.selectpage'} eq '' ||
 7055: 	 $env{'form.scantron_selectfile'} eq '' ||
 7056: 	 $env{'form.scantron_format'} eq '' ) {
 7057: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7058: 	if ( $env{'form.selectpage'} eq '') {
 7059: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7060: 	} 
 7061: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7062: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7063: 	} 
 7064: 	if ( $env{'form.scantron_format'} eq '') {
 7065: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7066: 	} 
 7067:     } else {
 7068: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 7069:         my $bubbledbyhand=&hand_bubble_option();
 7070: 	$r->print('
 7071: '.$warning.$bubbledbyhand.'
 7072: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7073: <input type="hidden" name="command" value="scantron_validate" />
 7074: ');
 7075:     }
 7076:     $r->print("</form><br />".&show_grading_menu_form($symb));
 7077:     return '';
 7078: }
 7079: 
 7080: =pod
 7081: 
 7082: =item scantron_form_start
 7083: 
 7084:     html hidden input for remembering all selected grading options
 7085: 
 7086: =cut
 7087: 
 7088: sub scantron_form_start {
 7089:     my ($max_bubble)=@_;
 7090:     my $result= <<SCANTRONFORM;
 7091: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7092:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7093:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7094:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7095:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7096:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7097:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7098:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7099:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7100:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7101: SCANTRONFORM
 7102: 
 7103:   my $line = 0;
 7104:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7105:        my $chunk =
 7106: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7107:        $chunk .=
 7108: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7109:        $chunk .= 
 7110:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7111:        $chunk .=
 7112:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7113:        $chunk .=
 7114:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7115:        $result .= $chunk;
 7116:        $line++;
 7117:     }
 7118:     return $result;
 7119: }
 7120: 
 7121: =pod
 7122: 
 7123: =item scantron_validate_file
 7124: 
 7125:     Dispatch routine for doing validation of a bubblesheet data file.
 7126: 
 7127:     Also processes any necessary information resets that need to
 7128:     occur before validation begins (ignore previous corrections,
 7129:     restarting the skipped records processing)
 7130: 
 7131: =cut
 7132: 
 7133: sub scantron_validate_file {
 7134:     my ($r) = @_;
 7135:     my ($symb)=&get_symb($r);
 7136:     if (!$symb) {return '';}
 7137:     my $default_form_data=&defaultFormData($symb);
 7138:     
 7139:     # do the detection of only doing skipped records first before we delete
 7140:     # them when doing the corrections reset
 7141:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7142: 	&reset_skipping_status();
 7143:     }
 7144:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7145: 	&remember_current_skipped();
 7146: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7147:     }
 7148: 
 7149:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7150: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7151: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7152: 	&check_for_error($r,&scantron_remove_scan_data());
 7153: 	$env{'form.scantron_options_ignore'}='done';
 7154:     }
 7155: 
 7156:     if ($env{'form.scantron_corrections'}) {
 7157: 	&scantron_process_corrections($r);
 7158:     }
 7159:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7160:     #get the student pick code ready
 7161:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7162:     my $nav_error;
 7163:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7164:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7165:     if ($nav_error) {
 7166:         $r->print(&navmap_errormsg());
 7167:         return '';
 7168:     }
 7169:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7170:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7171:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7172:     }
 7173:     $r->print($result);
 7174:     
 7175:     my @validate_phases=( 'sequence',
 7176: 			  'ID',
 7177: 			  'CODE',
 7178: 			  'doublebubble',
 7179: 			  'missingbubbles');
 7180:     if (!$env{'form.validatepass'}) {
 7181: 	$env{'form.validatepass'} = 0;
 7182:     }
 7183:     my $currentphase=$env{'form.validatepass'};
 7184: 
 7185: 
 7186:     my $stop=0;
 7187:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7188: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7189: 	$r->rflush();
 7190: 
 7191: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7192: 	{
 7193: 	    no strict 'refs';
 7194: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7195: 	}
 7196:     }
 7197:     if (!$stop) {
 7198: 	my $warning=&scantron_warning_screen('Start Grading');
 7199: 	$r->print(&mt('Validation process complete.').'<br />'.
 7200:                   $warning.
 7201:                   &mt('Perform verification for each student after storage of submissions?').
 7202:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7203:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7204:                   ('&nbsp;'x3).'<label>'.
 7205:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7206:                   '</label></span><br />'.
 7207:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7208:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 7209:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7210:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7211:     } else {
 7212: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7213: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7214:     }
 7215:     if ($stop) {
 7216: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7217: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7218: 	    $r->print(' '.&mt('this error').' <br />');
 7219: 
 7220: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 7221: 	} else {
 7222:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7223: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7224:             } else {
 7225:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7226:             }
 7227: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7228: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7229: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7230: 	}
 7231:     }
 7232:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 7233:     return '';
 7234: }
 7235: 
 7236: 
 7237: =pod
 7238: 
 7239: =item scantron_remove_file
 7240: 
 7241:    Removes the requested bubblesheet data file, makes sure that
 7242:    scantron_original_<filename> is never removed
 7243: 
 7244: 
 7245: =cut
 7246: 
 7247: sub scantron_remove_file {
 7248:     my ($which)=@_;
 7249:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7250:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7251:     my $file='scantron_';
 7252:     if ($which eq 'corrected' || $which eq 'skipped') {
 7253: 	$file.=$which.'_';
 7254:     } else {
 7255: 	return 'refused';
 7256:     }
 7257:     $file.=$env{'form.scantron_selectfile'};
 7258:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7259: }
 7260: 
 7261: 
 7262: =pod
 7263: 
 7264: =item scantron_remove_scan_data
 7265: 
 7266:    Removes all scan_data correction for the requested bubblesheet
 7267:    data file.  (In the case that both the are doing skipped records we need
 7268:    to remember the old skipped lines for the time being so that element
 7269:    persists for a while.)
 7270: 
 7271: =cut
 7272: 
 7273: sub scantron_remove_scan_data {
 7274:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7275:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7276:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7277:     my @todelete;
 7278:     my $filename=$env{'form.scantron_selectfile'};
 7279:     foreach my $key (@keys) {
 7280: 	if ($key=~/^\Q$filename\E_/) {
 7281: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7282: 		$key=~/remember_skipping/) {
 7283: 		next;
 7284: 	    }
 7285: 	    push(@todelete,$key);
 7286: 	}
 7287:     }
 7288:     my $result;
 7289:     if (@todelete) {
 7290: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7291: 				       \@todelete,$cdom,$cname);
 7292:     } else {
 7293: 	$result = 'ok';
 7294:     }
 7295:     return $result;
 7296: }
 7297: 
 7298: 
 7299: =pod
 7300: 
 7301: =item scantron_getfile
 7302: 
 7303:     Fetches the requested bubblesheet data file (all 3 versions), and
 7304:     the scan_data hash
 7305:   
 7306:   Arguments:
 7307:     None
 7308: 
 7309:   Returns:
 7310:     2 hash references
 7311: 
 7312:      - first one has 
 7313:          orig      -
 7314:          corrected -
 7315:          skipped   -  each of which points to an array ref of the specified
 7316:                       file broken up into individual lines
 7317:          count     - number of scanlines
 7318:  
 7319:      - second is the scan_data hash possible keys are
 7320:        ($number refers to scanline numbered $number and thus the key affects
 7321:         only that scanline
 7322:         $bubline refers to the specific bubble line element and the aspects
 7323:         refers to that specific bubble line element)
 7324: 
 7325:        $number.user - username:domain to use
 7326:        $number.CODE_ignore_dup 
 7327:                     - ignore the duplicate CODE error 
 7328:        $number.useCODE
 7329:                     - use the CODE in the scanline as is
 7330:        $number.no_bubble.$bubline
 7331:                     - it is valid that there is no bubbled in bubble
 7332:                       at $number $bubline
 7333:        remember_skipping
 7334:                     - a frozen hash containing keys of $number and values
 7335:                       of either 
 7336:                         1 - we are on a 'do skipped records pass' and plan
 7337:                             on processing this line
 7338:                         2 - we are on a 'do skipped records pass' and this
 7339:                             scanline has been marked to skip yet again
 7340: 
 7341: =cut
 7342: 
 7343: sub scantron_getfile {
 7344:     #FIXME really would prefer a scantron directory
 7345:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7346:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7347:     my $lines;
 7348:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7349: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7350:     my %scanlines;
 7351:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7352:     my $temp=$scanlines{'orig'};
 7353:     $scanlines{'count'}=$#$temp;
 7354: 
 7355:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7356: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7357:     if ($lines eq '-1') {
 7358: 	$scanlines{'corrected'}=[];
 7359:     } else {
 7360: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7361:     }
 7362:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7363: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7364:     if ($lines eq '-1') {
 7365: 	$scanlines{'skipped'}=[];
 7366:     } else {
 7367: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7368:     }
 7369:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7370:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7371:     my %scan_data = @tmp;
 7372:     return (\%scanlines,\%scan_data);
 7373: }
 7374: 
 7375: =pod
 7376: 
 7377: =item lonnet_putfile
 7378: 
 7379:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7380: 
 7381:  Arguments:
 7382:    $contents - data to store
 7383:    $filename - filename to store $contents into
 7384: 
 7385:  Returns:
 7386:    result value from &Apache::lonnet::finishuserfileupload
 7387: 
 7388: =cut
 7389: 
 7390: sub lonnet_putfile {
 7391:     my ($contents,$filename)=@_;
 7392:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7393:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7394:     $env{'form.sillywaytopassafilearound'}=$contents;
 7395:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7396: 
 7397: }
 7398: 
 7399: =pod
 7400: 
 7401: =item scantron_putfile
 7402: 
 7403:     Stores the current version of the bubblesheet data files, and the
 7404:     scan_data hash. (Does not modify the original version only the
 7405:     corrected and skipped versions.
 7406: 
 7407:  Arguments:
 7408:     $scanlines - hash ref that looks like the first return value from
 7409:                  &scantron_getfile()
 7410:     $scan_data - hash ref that looks like the second return value from
 7411:                  &scantron_getfile()
 7412: 
 7413: =cut
 7414: 
 7415: sub scantron_putfile {
 7416:     my ($scanlines,$scan_data) = @_;
 7417:     #FIXME really would prefer a scantron directory
 7418:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7419:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7420:     if ($scanlines) {
 7421: 	my $prefix='scantron_';
 7422: # no need to update orig, shouldn't change
 7423: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7424: #		    $env{'form.scantron_selectfile'});
 7425: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7426: 			$prefix.'corrected_'.
 7427: 			$env{'form.scantron_selectfile'});
 7428: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7429: 			$prefix.'skipped_'.
 7430: 			$env{'form.scantron_selectfile'});
 7431:     }
 7432:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7433: }
 7434: 
 7435: =pod
 7436: 
 7437: =item scantron_get_line
 7438: 
 7439:    Returns the correct version of the scanline
 7440: 
 7441:  Arguments:
 7442:     $scanlines - hash ref that looks like the first return value from
 7443:                  &scantron_getfile()
 7444:     $scan_data - hash ref that looks like the second return value from
 7445:                  &scantron_getfile()
 7446:     $i         - number of the requested line (starts at 0)
 7447: 
 7448:  Returns:
 7449:    A scanline, (either the original or the corrected one if it
 7450:    exists), or undef if the requested scanline should be
 7451:    skipped. (Either because it's an skipped scanline, or it's an
 7452:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7453:    pass.
 7454: 
 7455: =cut
 7456: 
 7457: sub scantron_get_line {
 7458:     my ($scanlines,$scan_data,$i)=@_;
 7459:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7460:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7461:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7462:     return $scanlines->{'orig'}[$i]; 
 7463: }
 7464: 
 7465: =pod
 7466: 
 7467: =item scantron_todo_count
 7468: 
 7469:     Counts the number of scanlines that need processing.
 7470: 
 7471:  Arguments:
 7472:     $scanlines - hash ref that looks like the first return value from
 7473:                  &scantron_getfile()
 7474:     $scan_data - hash ref that looks like the second return value from
 7475:                  &scantron_getfile()
 7476: 
 7477:  Returns:
 7478:     $count - number of scanlines to process
 7479: 
 7480: =cut
 7481: 
 7482: sub get_todo_count {
 7483:     my ($scanlines,$scan_data)=@_;
 7484:     my $count=0;
 7485:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7486: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7487: 	if ($line=~/^[\s\cz]*$/) { next; }
 7488: 	$count++;
 7489:     }
 7490:     return $count;
 7491: }
 7492: 
 7493: =pod
 7494: 
 7495: =item scantron_put_line
 7496: 
 7497:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7498:     data file.
 7499: 
 7500:  Arguments:
 7501:     $scanlines - hash ref that looks like the first return value from
 7502:                  &scantron_getfile()
 7503:     $scan_data - hash ref that looks like the second return value from
 7504:                  &scantron_getfile()
 7505:     $i         - line number to update
 7506:     $newline   - contents of the updated scanline
 7507:     $skip      - if true make the line for skipping and update the
 7508:                  'skipped' file
 7509: 
 7510: =cut
 7511: 
 7512: sub scantron_put_line {
 7513:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7514:     if ($skip) {
 7515: 	$scanlines->{'skipped'}[$i]=$newline;
 7516: 	&start_skipping($scan_data,$i);
 7517: 	return;
 7518:     }
 7519:     $scanlines->{'corrected'}[$i]=$newline;
 7520: }
 7521: 
 7522: =pod
 7523: 
 7524: =item scantron_clear_skip
 7525: 
 7526:    Remove a line from the 'skipped' file
 7527: 
 7528:  Arguments:
 7529:     $scanlines - hash ref that looks like the first return value from
 7530:                  &scantron_getfile()
 7531:     $scan_data - hash ref that looks like the second return value from
 7532:                  &scantron_getfile()
 7533:     $i         - line number to update
 7534: 
 7535: =cut
 7536: 
 7537: sub scantron_clear_skip {
 7538:     my ($scanlines,$scan_data,$i)=@_;
 7539:     if (exists($scanlines->{'skipped'}[$i])) {
 7540: 	undef($scanlines->{'skipped'}[$i]);
 7541: 	return 1;
 7542:     }
 7543:     return 0;
 7544: }
 7545: 
 7546: =pod
 7547: 
 7548: =item scantron_filter_not_exam
 7549: 
 7550:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7551:    filter out resources that are not marked as 'exam' mode
 7552: 
 7553: =cut
 7554: 
 7555: sub scantron_filter_not_exam {
 7556:     my ($curres)=@_;
 7557:     
 7558:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7559: 	# if the user has asked to not have either hidden
 7560: 	# or 'randomout' controlled resources to be graded
 7561: 	# don't include them
 7562: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7563: 	    && $curres->randomout) {
 7564: 	    return 0;
 7565: 	}
 7566: 	return 1;
 7567:     }
 7568:     return 0;
 7569: }
 7570: 
 7571: =pod
 7572: 
 7573: =item scantron_validate_sequence
 7574: 
 7575:     Validates the selected sequence, checking for resource that are
 7576:     not set to exam mode.
 7577: 
 7578: =cut
 7579: 
 7580: sub scantron_validate_sequence {
 7581:     my ($r,$currentphase) = @_;
 7582: 
 7583:     my $navmap=Apache::lonnavmaps::navmap->new();
 7584:     unless (ref($navmap)) {
 7585:         $r->print(&navmap_errormsg());
 7586:         return (1,$currentphase);
 7587:     }
 7588:     my (undef,undef,$sequence)=
 7589: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7590: 
 7591:     my $map=$navmap->getResourceByUrl($sequence);
 7592: 
 7593:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7594:                                     value="ignore" />');
 7595:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7596: 	my @resources=
 7597: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7598: 	if (@resources) {
 7599: 	    $r->print('<p class="LC_warning">'
 7600:                .&mt('Some resources in the sequence currently are not set to'
 7601:                    .' exam mode. Grading these resources currently may not'
 7602:                    .' work correctly.')
 7603:                .'</p>'
 7604:             );
 7605: 	    return (1,$currentphase);
 7606: 	}
 7607:     }
 7608: 
 7609:     return (0,$currentphase+1);
 7610: }
 7611: 
 7612: 
 7613: 
 7614: sub scantron_validate_ID {
 7615:     my ($r,$currentphase) = @_;
 7616:     
 7617:     #get student info
 7618:     my $classlist=&Apache::loncoursedata::get_classlist();
 7619:     my %idmap=&username_to_idmap($classlist);
 7620: 
 7621:     #get scantron line setup
 7622:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7623:     my ($scanlines,$scan_data)=&scantron_getfile();
 7624: 
 7625:     my $nav_error;
 7626:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7627:     if ($nav_error) {
 7628:         $r->print(&navmap_errormsg());
 7629:         return(1,$currentphase);
 7630:     }
 7631: 
 7632:     my %found=('ids'=>{},'usernames'=>{});
 7633:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7634: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7635: 	if ($line=~/^[\s\cz]*$/) { next; }
 7636: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7637: 						 $scan_data);
 7638: 	my $id=$$scan_record{'scantron.ID'};
 7639: 	my $found;
 7640: 	foreach my $checkid (keys(%idmap)) {
 7641: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7642: 	}
 7643: 	if ($found) {
 7644: 	    my $username=$idmap{$found};
 7645: 	    if ($found{'ids'}{$found}) {
 7646: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7647: 					 $line,'duplicateID',$found);
 7648: 		return(1,$currentphase);
 7649: 	    } elsif ($found{'usernames'}{$username}) {
 7650: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7651: 					 $line,'duplicateID',$username);
 7652: 		return(1,$currentphase);
 7653: 	    }
 7654: 	    #FIXME store away line we previously saw the ID on to use above
 7655: 	    $found{'ids'}{$found}++;
 7656: 	    $found{'usernames'}{$username}++;
 7657: 	} else {
 7658: 	    if ($id =~ /^\s*$/) {
 7659: 		my $username=&scan_data($scan_data,"$i.user");
 7660: 		if (defined($username) && $found{'usernames'}{$username}) {
 7661: 		    &scantron_get_correction($r,$i,$scan_record,
 7662: 					     \%scantron_config,
 7663: 					     $line,'duplicateID',$username);
 7664: 		    return(1,$currentphase);
 7665: 		} elsif (!defined($username)) {
 7666: 		    &scantron_get_correction($r,$i,$scan_record,
 7667: 					     \%scantron_config,
 7668: 					     $line,'incorrectID');
 7669: 		    return(1,$currentphase);
 7670: 		}
 7671: 		$found{'usernames'}{$username}++;
 7672: 	    } else {
 7673: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7674: 					 $line,'incorrectID');
 7675: 		return(1,$currentphase);
 7676: 	    }
 7677: 	}
 7678:     }
 7679: 
 7680:     return (0,$currentphase+1);
 7681: }
 7682: 
 7683: 
 7684: sub scantron_get_correction {
 7685:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7686:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7687: #FIXME in the case of a duplicated ID the previous line, probably need
 7688: #to show both the current line and the previous one and allow skipping
 7689: #the previous one or the current one
 7690: 
 7691:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7692:         $r->print(
 7693:             '<p class="LC_warning">'
 7694:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7695:                 "<b>$error</b>",
 7696:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7697:            ."</p> \n");
 7698:     } else {
 7699:         $r->print(
 7700:             '<p class="LC_warning">'
 7701:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7702:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7703:            ."</p> \n");
 7704:     }
 7705:     my $message =
 7706:         '<p>'
 7707:        .&mt('The ID on the form is [_1]',
 7708:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7709:        .'<br />'
 7710:        .&mt('The name on the paper is [_1], [_2]',
 7711:             $$scan_record{'scantron.LastName'},
 7712:             $$scan_record{'scantron.FirstName'})
 7713:        .'</p>';
 7714: 
 7715:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7716:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7717:                            # Array populated for doublebubble or
 7718:     my @lines_to_correct;  # missingbubble errors to build javascript
 7719:                            # to validate radio button checking   
 7720: 
 7721:     if ($error =~ /ID$/) {
 7722: 	if ($error eq 'incorrectID') {
 7723: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7724: 		      "</p>\n");
 7725: 	} elsif ($error eq 'duplicateID') {
 7726: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7727: 	}
 7728: 	$r->print($message);
 7729: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7730: 	$r->print("\n<ul><li> ");
 7731: 	#FIXME it would be nice if this sent back the user ID and
 7732: 	#could do partial userID matches
 7733: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7734: 				       'scantron_username','scantron_domain'));
 7735: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7736: 	$r->print("\n:\n".
 7737: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7738: 
 7739: 	$r->print('</li>');
 7740:     } elsif ($error =~ /CODE$/) {
 7741: 	if ($error eq 'incorrectCODE') {
 7742: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7743: 	} elsif ($error eq 'duplicateCODE') {
 7744: 	    $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");
 7745: 	}
 7746:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7747:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7748:                  ."</p>\n");
 7749: 	$r->print($message);
 7750: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7751: 	$r->print("\n<br /> ");
 7752: 	my $i=0;
 7753: 	if ($error eq 'incorrectCODE' 
 7754: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7755: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7756: 	    if ($closest > 0) {
 7757: 		foreach my $testcode (@{$closest}) {
 7758: 		    my $checked='';
 7759: 		    if (!$i) { $checked=' checked="checked"'; }
 7760: 		    $r->print("
 7761:    <label>
 7762:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7763:        ".&mt("Use the similar CODE [_1] instead.",
 7764: 	    "<b><tt>".$testcode."</tt></b>")."
 7765:     </label>
 7766:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7767: 		    $r->print("\n<br />");
 7768: 		    $i++;
 7769: 		}
 7770: 	    }
 7771: 	}
 7772: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7773: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7774: 	    $r->print("
 7775:     <label>
 7776:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7777:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7778: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7779:     </label>");
 7780: 	    $r->print("\n<br />");
 7781: 	}
 7782: 
 7783: 	$r->print(<<ENDSCRIPT);
 7784: <script type="text/javascript">
 7785: function change_radio(field) {
 7786:     var slct=document.scantronupload.scantron_CODE_resolution;
 7787:     var i;
 7788:     for (i=0;i<slct.length;i++) {
 7789:         if (slct[i].value==field) { slct[i].checked=true; }
 7790:     }
 7791: }
 7792: </script>
 7793: ENDSCRIPT
 7794: 	my $href="/adm/pickcode?".
 7795: 	   "form=".&escape("scantronupload").
 7796: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7797: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7798: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7799: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7800: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7801: 	    $r->print("
 7802:     <label>
 7803:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7804:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7805: 	     "<a target='_blank' href='$href'>","</a>")."
 7806:     </label> 
 7807:     ".&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\')" />'));
 7808: 	    $r->print("\n<br />");
 7809: 	}
 7810: 	$r->print("
 7811:     <label>
 7812:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7813:        ".&mt("Use [_1] as the CODE.",
 7814: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7815: 	$r->print("\n<br /><br />");
 7816:     } elsif ($error eq 'doublebubble') {
 7817: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7818: 
 7819: 	# The form field scantron_questions is acutally a list of line numbers.
 7820: 	# represented by this form so:
 7821: 
 7822: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7823:                                                 $respnumlookup,$startline);
 7824: 
 7825: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7826: 		  $line_list.'" />');
 7827: 	$r->print($message);
 7828: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7829: 	foreach my $question (@{$arg}) {
 7830: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7831:                                                    $scan_record, $error,
 7832:                                                    $randomorder,$randompick,
 7833:                                                    $respnumlookup,$startline);
 7834:             push(@lines_to_correct,@linenums);
 7835: 	}
 7836:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7837:     } elsif ($error eq 'missingbubble') {
 7838: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7839: 	$r->print($message);
 7840: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7841: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7842: 
 7843: 	# The form field scantron_questions is actually a list of line numbers not
 7844: 	# a list of question numbers. Therefore:
 7845: 	#
 7846: 	
 7847: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7848:                                                 $respnumlookup,$startline);
 7849: 
 7850: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7851: 		  $line_list.'" />');
 7852: 	foreach my $question (@{$arg}) {
 7853: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7854:                                                    $scan_record, $error,
 7855:                                                    $randomorder,$randompick,
 7856:                                                    $respnumlookup,$startline);
 7857:             push(@lines_to_correct,@linenums);
 7858: 	}
 7859:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7860:     } else {
 7861: 	$r->print("\n<ul>");
 7862:     }
 7863:     $r->print("\n</li></ul>");
 7864: }
 7865: 
 7866: sub verify_bubbles_checked {
 7867:     my (@ansnums) = @_;
 7868:     my $ansnumstr = join('","',@ansnums);
 7869:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7870:     &js_escape(\$warning);
 7871:     my $output = (<<ENDSCRIPT);
 7872: <script type="text/javascript">
 7873: function verify_bubble_radio(form) {
 7874:     var ansnumArray = new Array ("$ansnumstr");
 7875:     var need_bubble_count = 0;
 7876:     for (var i=0; i<ansnumArray.length; i++) {
 7877:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7878:             var bubble_picked = 0; 
 7879:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7880:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7881:                     bubble_picked = 1;
 7882:                 }
 7883:             }
 7884:             if (bubble_picked == 0) {
 7885:                 need_bubble_count ++;
 7886:             }
 7887:         }
 7888:     }
 7889:     if (need_bubble_count) {
 7890:         alert("$warning");
 7891:         return;
 7892:     }
 7893:     form.submit(); 
 7894: }
 7895: </script>
 7896: ENDSCRIPT
 7897:     return $output;
 7898: }
 7899: 
 7900: =pod
 7901: 
 7902: =item  questions_to_line_list
 7903: 
 7904: Converts a list of questions into a string of comma separated
 7905: line numbers in the answer sheet used by the questions.  This is
 7906: used to fill in the scantron_questions form field.
 7907: 
 7908:   Arguments:
 7909:      questions    - Reference to an array of questions.
 7910:      randomorder  - True if randomorder in use.
 7911:      randompick   - True if randompick in use.
 7912:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7913:                      for current line to question number used for same question
 7914:                      in "Master Seqence" (as seen by Course Coordinator).
 7915:      startline    - Reference to hash where key is question number (0 is first)
 7916:                     and key is number of first bubble line for current student
 7917:                     or code-based randompick and/or randomorder.
 7918: 
 7919: =cut
 7920: 
 7921: 
 7922: sub questions_to_line_list {
 7923:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7924:     my @lines;
 7925: 
 7926:     foreach my $item (@{$questions}) {
 7927:         my $question = $item;
 7928:         my ($first,$count,$last);
 7929:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7930:             $question = $1;
 7931:             my $subquestion = $2;
 7932:             my $responsenum = $question-1;
 7933:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7934:                 $responsenum = $respnumlookup->{$question-1};
 7935:                 if (ref($startline) eq 'HASH') {
 7936:                     $first = $startline->{$question-1} + 1;
 7937:                 }
 7938:             } else {
 7939:                 $first = $first_bubble_line{$responsenum} + 1;
 7940:             }
 7941:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7942:             my $subcount = 1;
 7943:             while ($subcount<$subquestion) {
 7944:                 $first += $subans[$subcount-1];
 7945:                 $subcount ++;
 7946:             }
 7947:             $count = $subans[$subquestion-1];
 7948:         } else {
 7949:             my $responsenum = $question-1;
 7950:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7951:                 $responsenum = $respnumlookup->{$question-1};
 7952:                 if (ref($startline) eq 'HASH') {
 7953:                     $first = $startline->{$question-1} + 1;
 7954:                 }
 7955:             } else {
 7956:                 $first = $first_bubble_line{$responsenum} + 1;
 7957:             }
 7958:             $count   = $bubble_lines_per_response{$responsenum};
 7959:         }
 7960:         $last = $first+$count-1;
 7961:         push(@lines, ($first..$last));
 7962:     }
 7963:     return join(',', @lines);
 7964: }
 7965: 
 7966: =pod 
 7967: 
 7968: =item prompt_for_corrections
 7969: 
 7970: Prompts for a potentially multiline correction to the
 7971: user's bubbling (factors out common code from scantron_get_correction
 7972: for multi and missing bubble cases).
 7973: 
 7974:  Arguments:
 7975:    $r           - Apache request object.
 7976:    $question    - The question number to prompt for.
 7977:    $scan_config - The scantron file configuration hash.
 7978:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7979:    $error       - Type of error
 7980:    $randomorder - True if randomorder in use.
 7981:    $randompick  - True if randompick in use.
 7982:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7983:                     for current line to question number used for same question
 7984:                     in "Master Seqence" (as seen by Course Coordinator).
 7985:    $startline   - Reference to hash where key is question number (0 is first)
 7986:                   and value is number of first bubble line for current student
 7987:                   or code-based randompick and/or randomorder.
 7988: 
 7989:  Implicit inputs:
 7990:    %bubble_lines_per_response   - Starting line numbers for each question.
 7991:                                   Numbered from 0 (but question numbers are from
 7992:                                   1.
 7993:    %first_bubble_line           - Starting bubble line for each question.
 7994:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7995:                                   type problems render as separate sub-questions, 
 7996:                                   in exam mode. This hash contains a 
 7997:                                   comma-separated list of the lines per 
 7998:                                   sub-question.
 7999:    %responsetype_per_response   - essayresponse, formularesponse,
 8000:                                   stringresponse, imageresponse, reactionresponse,
 8001:                                   and organicresponse type problem parts can have
 8002:                                   multiple lines per response if the weight
 8003:                                   assigned exceeds 10.  In this case, only
 8004:                                   one bubble per line is permitted, but more 
 8005:                                   than one line might contain bubbles, e.g.
 8006:                                   bubbling of: line 1 - J, line 2 - J, 
 8007:                                   line 3 - B would assign 22 points.  
 8008: 
 8009: =cut
 8010: 
 8011: sub prompt_for_corrections {
 8012:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8013:         $randompick, $respnumlookup, $startline) = @_;
 8014:     my ($current_line,$lines);
 8015:     my @linenums;
 8016:     my $questionnum = $question;
 8017:     my ($first,$responsenum);
 8018:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8019:         $question = $1;
 8020:         my $subquestion = $2;
 8021:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8022:             $responsenum = $respnumlookup->{$question-1};
 8023:             if (ref($startline) eq 'HASH') {
 8024:                 $first = $startline->{$question-1};
 8025:             }
 8026:         } else {
 8027:             $responsenum = $question-1;
 8028:             $first = $first_bubble_line{$responsenum};
 8029:         }
 8030:         $current_line = $first + 1 ;
 8031:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8032:         my $subcount = 1;
 8033:         while ($subcount<$subquestion) {
 8034:             $current_line += $subans[$subcount-1];
 8035:             $subcount ++;
 8036:         }
 8037:         $lines = $subans[$subquestion-1];
 8038:     } else {
 8039:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8040:             $responsenum = $respnumlookup->{$question-1};
 8041:             if (ref($startline) eq 'HASH') {
 8042:                 $first = $startline->{$question-1};
 8043:             }
 8044:         } else {
 8045:             $responsenum = $question-1;
 8046:             $first = $first_bubble_line{$responsenum};
 8047:         }
 8048:         $current_line = $first + 1;
 8049:         $lines        = $bubble_lines_per_response{$responsenum};
 8050:     }
 8051:     if ($lines > 1) {
 8052:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8053:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8054:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8055:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8056:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8057:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8058:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8059:             $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 />');
 8060:         } else {
 8061:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8062:         }
 8063:     }
 8064:     for (my $i =0; $i < $lines; $i++) {
 8065:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8066: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8067: 	        		  $questionnum,$error,split('', $selected));
 8068:         push(@linenums,$current_line);
 8069: 	$current_line++;
 8070:     }
 8071:     if ($lines > 1) {
 8072: 	$r->print("<hr /><br />");
 8073:     }
 8074:     return @linenums;
 8075: }
 8076: 
 8077: =pod
 8078: 
 8079: =item scantron_bubble_selector
 8080:   
 8081:    Generates the html radiobuttons to correct a single bubble line
 8082:    possibly showing the existing the selected bubbles if known
 8083: 
 8084:  Arguments:
 8085:     $r           - Apache request object
 8086:     $scan_config - hash from &get_scantron_config()
 8087:     $line        - Number of the line being displayed.
 8088:     $questionnum - Question number (may include subquestion)
 8089:     $error       - Type of error.
 8090:     @selected    - Array of bubbles picked on this line.
 8091: 
 8092: =cut
 8093: 
 8094: sub scantron_bubble_selector {
 8095:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8096:     my $max=$$scan_config{'Qlength'};
 8097: 
 8098:     my $scmode=$$scan_config{'Qon'};
 8099:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8100:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8101:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8102:             $max=$$scan_config{'BubblesPerRow'};
 8103:             if (($scmode eq 'number') && ($max > 10)) {
 8104:                 $max = 10;
 8105:             } elsif (($scmode eq 'letter') && $max > 26) {
 8106:                 $max = 26;
 8107:             }
 8108:         } else {
 8109:             $max = 10;
 8110:         }
 8111:     }
 8112: 
 8113:     my @alphabet=('A'..'Z');
 8114:     $r->print(&Apache::loncommon::start_data_table().
 8115:               &Apache::loncommon::start_data_table_row());
 8116:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8117:     for (my $i=0;$i<$max+1;$i++) {
 8118: 	$r->print("\n".'<td align="center">');
 8119: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8120: 	else { $r->print('&nbsp;'); }
 8121: 	$r->print('</td>');
 8122:     }
 8123:     $r->print(&Apache::loncommon::end_data_table_row().
 8124:               &Apache::loncommon::start_data_table_row());
 8125:     for (my $i=0;$i<$max;$i++) {
 8126: 	$r->print("\n".
 8127: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8128: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8129:     }
 8130:     my $nobub_checked = ' ';
 8131:     if ($error eq 'missingbubble') {
 8132:         $nobub_checked = ' checked = "checked" ';
 8133:     }
 8134:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8135: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8136:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8137:               $line.'" value="'.$questionnum.'" /></td>');
 8138:     $r->print(&Apache::loncommon::end_data_table_row().
 8139:               &Apache::loncommon::end_data_table());
 8140: }
 8141: 
 8142: =pod
 8143: 
 8144: =item num_matches
 8145: 
 8146:    Counts the number of characters that are the same between the two arguments.
 8147: 
 8148:  Arguments:
 8149:    $orig - CODE from the scanline
 8150:    $code - CODE to match against
 8151: 
 8152:  Returns:
 8153:    $count - integer count of the number of same characters between the
 8154:             two arguments
 8155: 
 8156: =cut
 8157: 
 8158: sub num_matches {
 8159:     my ($orig,$code) = @_;
 8160:     my @code=split(//,$code);
 8161:     my @orig=split(//,$orig);
 8162:     my $same=0;
 8163:     for (my $i=0;$i<scalar(@code);$i++) {
 8164: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8165:     }
 8166:     return $same;
 8167: }
 8168: 
 8169: =pod
 8170: 
 8171: =item scantron_get_closely_matching_CODEs
 8172: 
 8173:    Cycles through all CODEs and finds the set that has the greatest
 8174:    number of same characters as the provided CODE
 8175: 
 8176:  Arguments:
 8177:    $allcodes - hash ref returned by &get_codes()
 8178:    $CODE     - CODE from the current scanline
 8179: 
 8180:  Returns:
 8181:    2 element list
 8182:     - first elements is number of how closely matching the best fit is 
 8183:       (5 means best set has 5 matching characters)
 8184:     - second element is an arrary ref containing the set of valid CODEs
 8185:       that best fit the passed in CODE
 8186: 
 8187: =cut
 8188: 
 8189: sub scantron_get_closely_matching_CODEs {
 8190:     my ($allcodes,$CODE)=@_;
 8191:     my @CODEs;
 8192:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8193: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8194:     }
 8195: 
 8196:     return ($#CODEs,$CODEs[-1]);
 8197: }
 8198: 
 8199: =pod
 8200: 
 8201: =item get_codes
 8202: 
 8203:    Builds a hash which has keys of all of the valid CODEs from the selected
 8204:    set of remembered CODEs.
 8205: 
 8206:  Arguments:
 8207:   $old_name - name of the set of remembered CODEs
 8208:   $cdom     - domain of the course
 8209:   $cnum     - internal course name
 8210: 
 8211:  Returns:
 8212:   %allcodes - keys are the valid CODEs, values are all 1
 8213: 
 8214: =cut
 8215: 
 8216: sub get_codes {
 8217:     my ($old_name, $cdom, $cnum) = @_;
 8218:     if (!$old_name) {
 8219: 	$old_name=$env{'form.scantron_CODElist'};
 8220:     }
 8221:     if (!$cdom) {
 8222: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8223:     }
 8224:     if (!$cnum) {
 8225: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8226:     }
 8227:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8228: 				    $cdom,$cnum);
 8229:     my %allcodes;
 8230:     if ($result{"type\0$old_name"} eq 'number') {
 8231: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8232:     } else {
 8233: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8234:     }
 8235:     return %allcodes;
 8236: }
 8237: 
 8238: =pod
 8239: 
 8240: =item scantron_validate_CODE
 8241: 
 8242:    Validates all scanlines in the selected file to not have any
 8243:    invalid or underspecified CODEs and that none of the codes are
 8244:    duplicated if this was requested.
 8245: 
 8246: =cut
 8247: 
 8248: sub scantron_validate_CODE {
 8249:     my ($r,$currentphase) = @_;
 8250:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8251:     if ($scantron_config{'CODElocation'} &&
 8252: 	$scantron_config{'CODEstart'} &&
 8253: 	$scantron_config{'CODElength'}) {
 8254: 	if (!defined($env{'form.scantron_CODElist'})) {
 8255: 	    &FIXME_blow_up()
 8256: 	}
 8257:     } else {
 8258: 	return (0,$currentphase+1);
 8259:     }
 8260:     
 8261:     my %usedCODEs;
 8262: 
 8263:     my %allcodes=&get_codes();
 8264: 
 8265:     my $nav_error;
 8266:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8267:     if ($nav_error) {
 8268:         $r->print(&navmap_errormsg());
 8269:         return(1,$currentphase);
 8270:     }
 8271: 
 8272:     my ($scanlines,$scan_data)=&scantron_getfile();
 8273:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8274: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8275: 	if ($line=~/^[\s\cz]*$/) { next; }
 8276: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8277: 						 $scan_data);
 8278: 	my $CODE=$$scan_record{'scantron.CODE'};
 8279: 	my $error=0;
 8280: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8281: 	    &scantron_get_correction($r,$i,$scan_record,
 8282: 				     \%scantron_config,
 8283: 				     $line,'incorrectCODE',\%allcodes);
 8284: 	    return(1,$currentphase);
 8285: 	}
 8286: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8287: 	    && !$$scan_record{'scantron.useCODE'}) {
 8288: 	    &scantron_get_correction($r,$i,$scan_record,
 8289: 				     \%scantron_config,
 8290: 				     $line,'incorrectCODE',\%allcodes);
 8291: 	    return(1,$currentphase);
 8292: 	}
 8293: 	if (exists($usedCODEs{$CODE}) 
 8294: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8295: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8296: 	    &scantron_get_correction($r,$i,$scan_record,
 8297: 				     \%scantron_config,
 8298: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8299: 	    return(1,$currentphase);
 8300: 	}
 8301: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8302:     }
 8303:     return (0,$currentphase+1);
 8304: }
 8305: 
 8306: =pod
 8307: 
 8308: =item scantron_validate_doublebubble
 8309: 
 8310:    Validates all scanlines in the selected file to not have any
 8311:    bubble lines with multiple bubbles marked.
 8312: 
 8313: =cut
 8314: 
 8315: sub scantron_validate_doublebubble {
 8316:     my ($r,$currentphase) = @_;
 8317:     #get student info
 8318:     my $classlist=&Apache::loncoursedata::get_classlist();
 8319:     my %idmap=&username_to_idmap($classlist);
 8320:     my (undef,undef,$sequence)=
 8321:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8322: 
 8323:     #get scantron line setup
 8324:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8325:     my ($scanlines,$scan_data)=&scantron_getfile();
 8326: 
 8327:     my $navmap = Apache::lonnavmaps::navmap->new();
 8328:     unless (ref($navmap)) {
 8329:         $r->print(&navmap_errormsg());
 8330:         return(1,$currentphase);
 8331:     }
 8332:     my $map=$navmap->getResourceByUrl($sequence);
 8333:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8334:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8335:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8336:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8337: 
 8338:     my $nav_error;
 8339:     if (ref($map)) {
 8340:         $randomorder = $map->randomorder();
 8341:         $randompick = $map->randompick();
 8342:         if ($randomorder || $randompick) {
 8343:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8344:             if ($nav_error) {
 8345:                 $r->print(&navmap_errormsg());
 8346:                 return(1,$currentphase);
 8347:             }
 8348:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8349:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8350:         }
 8351:     } else {
 8352:         $r->print(&navmap_errormsg());
 8353:         return(1,$currentphase);
 8354:     }
 8355: 
 8356:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8357:     if ($nav_error) {
 8358:         $r->print(&navmap_errormsg());
 8359:         return(1,$currentphase);
 8360:     }
 8361: 
 8362:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8363: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8364: 	if ($line=~/^[\s\cz]*$/) { next; }
 8365: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8366: 						 $scan_data,undef,\%idmap,$randomorder,
 8367:                                                  $randompick,$sequence,\@master_seq,
 8368:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8369:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8370: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8371: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8372: 				 'doublebubble',
 8373: 				 $$scan_record{'scantron.doubleerror'},
 8374:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8375:     	return (1,$currentphase);
 8376:     }
 8377:     return (0,$currentphase+1);
 8378: }
 8379: 
 8380: 
 8381: sub scantron_get_maxbubble {
 8382:     my ($nav_error,$scantron_config) = @_;
 8383:     if (defined($env{'form.scantron_maxbubble'}) &&
 8384: 	$env{'form.scantron_maxbubble'}) {
 8385: 	&restore_bubble_lines();
 8386: 	return $env{'form.scantron_maxbubble'};
 8387:     }
 8388: 
 8389:     my (undef, undef, $sequence) =
 8390: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8391: 
 8392:     my $navmap=Apache::lonnavmaps::navmap->new();
 8393:     unless (ref($navmap)) {
 8394:         if (ref($nav_error)) {
 8395:             $$nav_error = 1;
 8396:         }
 8397:         return;
 8398:     }
 8399:     my $map=$navmap->getResourceByUrl($sequence);
 8400:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8401:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8402: 
 8403:     &Apache::lonxml::clear_problem_counter();
 8404: 
 8405:     my $uname       = $env{'user.name'};
 8406:     my $udom        = $env{'user.domain'};
 8407:     my $cid         = $env{'request.course.id'};
 8408:     my $total_lines = 0;
 8409:     %bubble_lines_per_response = ();
 8410:     %first_bubble_line         = ();
 8411:     %subdivided_bubble_lines   = ();
 8412:     %responsetype_per_response = ();
 8413:     %masterseq_id_responsenum  = ();
 8414: 
 8415:     my $response_number = 0;
 8416:     my $bubble_line     = 0;
 8417:     foreach my $resource (@resources) {
 8418:         my $resid = $resource->id();
 8419:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8420:                                                           $udom,undef,$bubbles_per_row);
 8421:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8422: 	    foreach my $part_id (@{$parts}) {
 8423:                 my $lines;
 8424: 
 8425: 	        # TODO - make this a persistent hash not an array.
 8426: 
 8427:                 # optionresponse, matchresponse and rankresponse type items 
 8428:                 # render as separate sub-questions in exam mode.
 8429:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8430:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8431:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8432:                     my ($numbub,$numshown);
 8433:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8434:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8435:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8436:                         }
 8437:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8438:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8439:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8440:                         }
 8441:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8442:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8443:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8444:                         }
 8445:                     }
 8446:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8447:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8448:                     }
 8449:                     my $bubbles_per_row =
 8450:                         &bubblesheet_bubbles_per_row($scantron_config);
 8451:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8452:                     if (($numbub % $bubbles_per_row) != 0) {
 8453:                         $inner_bubble_lines++;
 8454:                     }
 8455:                     for (my $i=0; $i<$numshown; $i++) {
 8456:                         $subdivided_bubble_lines{$response_number} .= 
 8457:                             $inner_bubble_lines.',';
 8458:                     }
 8459:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8460:                     $lines = $numshown * $inner_bubble_lines;
 8461:                 } else {
 8462:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8463:                 }
 8464: 
 8465:                 $first_bubble_line{$response_number} = $bubble_line;
 8466: 	        $bubble_lines_per_response{$response_number} = $lines;
 8467:                 $responsetype_per_response{$response_number} = 
 8468:                     $analysis->{$part_id.'.type'};
 8469:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8470: 	        $response_number++;
 8471: 
 8472: 	        $bubble_line +=  $lines;
 8473: 	        $total_lines +=  $lines;
 8474: 	    }
 8475:         }
 8476:     }
 8477:     &Apache::lonnet::delenv('scantron.');
 8478: 
 8479:     &save_bubble_lines();
 8480:     $env{'form.scantron_maxbubble'} =
 8481: 	$total_lines;
 8482:     return $env{'form.scantron_maxbubble'};
 8483: }
 8484: 
 8485: sub bubblesheet_bubbles_per_row {
 8486:     my ($scantron_config) = @_;
 8487:     my $bubbles_per_row;
 8488:     if (ref($scantron_config) eq 'HASH') {
 8489:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8490:     }
 8491:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8492:         $bubbles_per_row = 10;
 8493:     }
 8494:     return $bubbles_per_row;
 8495: }
 8496: 
 8497: sub scantron_validate_missingbubbles {
 8498:     my ($r,$currentphase) = @_;
 8499:     #get student info
 8500:     my $classlist=&Apache::loncoursedata::get_classlist();
 8501:     my %idmap=&username_to_idmap($classlist);
 8502:     my (undef,undef,$sequence)=
 8503:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8504: 
 8505:     #get scantron line setup
 8506:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8507:     my ($scanlines,$scan_data)=&scantron_getfile();
 8508: 
 8509:     my $navmap = Apache::lonnavmaps::navmap->new();
 8510:     unless (ref($navmap)) {
 8511:         $r->print(&navmap_errormsg());
 8512:         return(1,$currentphase);
 8513:     }
 8514: 
 8515:     my $map=$navmap->getResourceByUrl($sequence);
 8516:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8517:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8518:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8519:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8520: 
 8521:     my $nav_error;
 8522:     if (ref($map)) {
 8523:         $randomorder = $map->randomorder();
 8524:         $randompick = $map->randompick();
 8525:         if ($randomorder || $randompick) {
 8526:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8527:             if ($nav_error) {
 8528:                 $r->print(&navmap_errormsg());
 8529:                 return(1,$currentphase);
 8530:             }
 8531:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8532:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8533:         }
 8534:     } else {
 8535:         $r->print(&navmap_errormsg());
 8536:         return(1,$currentphase);
 8537:     }
 8538: 
 8539: 
 8540:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8541:     if ($nav_error) {
 8542:         $r->print(&navmap_errormsg());
 8543:         return(1,$currentphase);
 8544:     }
 8545: 
 8546:     if (!$max_bubble) { $max_bubble=2**31; }
 8547:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8548: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8549: 	if ($line=~/^[\s\cz]*$/) { next; }
 8550:         my $scan_record =
 8551:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8552:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8553:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8554:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8555: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8556: 	my @to_correct;
 8557: 	
 8558: 	# Probably here's where the error is...
 8559: 
 8560: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8561:             my $lastbubble;
 8562:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8563:                 my $question = $1;
 8564:                 my $subquestion = $2;
 8565:                 my ($first,$responsenum);
 8566:                 if ($randomorder || $randompick) {
 8567:                     $responsenum = $respnumlookup{$question-1};
 8568:                     $first = $startline{$question-1};
 8569:                 } else {
 8570:                     $responsenum = $question-1;
 8571:                     $first = $first_bubble_line{$responsenum};
 8572:                 }
 8573:                 if (!defined($first)) { next; }
 8574:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8575:                 my $subcount = 1;
 8576:                 while ($subcount<$subquestion) {
 8577:                     $first += $subans[$subcount-1];
 8578:                     $subcount ++;
 8579:                 }
 8580:                 my $count = $subans[$subquestion-1];
 8581:                 $lastbubble = $first + $count;
 8582:             } else {
 8583:                 my ($first,$responsenum);
 8584:                 if ($randomorder || $randompick) {
 8585:                     $responsenum = $respnumlookup{$missing-1};
 8586:                     $first = $startline{$missing-1};
 8587:                 } else {
 8588:                     $responsenum = $missing-1;
 8589:                     $first = $first_bubble_line{$responsenum};
 8590:                 }
 8591:                 if (!defined($first)) { next; }
 8592:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8593:             }
 8594:             if ($lastbubble > $max_bubble) { next; }
 8595: 	    push(@to_correct,$missing);
 8596: 	}
 8597: 	if (@to_correct) {
 8598: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8599: 				     $line,'missingbubble',\@to_correct,
 8600:                                      $randomorder,$randompick,\%respnumlookup,
 8601:                                      \%startline);
 8602: 	    return (1,$currentphase);
 8603: 	}
 8604: 
 8605:     }
 8606:     return (0,$currentphase+1);
 8607: }
 8608: 
 8609: sub hand_bubble_option {
 8610:     my (undef, undef, $sequence) =
 8611:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8612:     return if ($sequence eq '');
 8613:     my $navmap = Apache::lonnavmaps::navmap->new();
 8614:     unless (ref($navmap)) {
 8615:         return;
 8616:     }
 8617:     my $needs_hand_bubbles;
 8618:     my $map=$navmap->getResourceByUrl($sequence);
 8619:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8620:     foreach my $res (@resources) {
 8621:         if (ref($res)) {
 8622:             if ($res->is_problem()) {
 8623:                 my $partlist = $res->parts();
 8624:                 foreach my $part (@{ $partlist }) {
 8625:                     my @types = $res->responseType($part);
 8626:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8627:                         $needs_hand_bubbles = 1;
 8628:                         last;
 8629:                     }
 8630:                 }
 8631:             }
 8632:         }
 8633:     }
 8634:     if ($needs_hand_bubbles) {
 8635:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8636:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8637:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8638:                &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 />').
 8639:                '<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;'.
 8640:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8641:     }
 8642:     return;
 8643: }
 8644: 
 8645: sub scantron_process_students {
 8646:     my ($r) = @_;
 8647: 
 8648:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8649:     my ($symb)=&get_symb($r);
 8650:     if (!$symb) {
 8651: 	return '';
 8652:     }
 8653:     my $default_form_data=&defaultFormData($symb);
 8654: 
 8655:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8656:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8657:     my ($scanlines,$scan_data)=&scantron_getfile();
 8658:     my $classlist=&Apache::loncoursedata::get_classlist();
 8659:     my %idmap=&username_to_idmap($classlist);
 8660:     my $navmap=Apache::lonnavmaps::navmap->new();
 8661:     unless (ref($navmap)) {
 8662:         $r->print(&navmap_errormsg());
 8663:         return '';
 8664:     }
 8665:     my $map=$navmap->getResourceByUrl($sequence);
 8666:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8667:         %grader_randomlists_by_symb);
 8668:     if (ref($map)) {
 8669:         $randomorder = $map->randomorder();
 8670:         $randompick = $map->randompick();
 8671:     } else {
 8672:         $r->print(&navmap_errormsg());
 8673:         return '';
 8674:     }
 8675:     my $nav_error;
 8676:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8677:     if ($randomorder || $randompick) {
 8678:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8679:         if ($nav_error) {
 8680:             $r->print(&navmap_errormsg());
 8681:             return '';
 8682:         }
 8683:     }
 8684:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8685:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8686: 
 8687:     my ($uname,$udom);
 8688:     my $result= <<SCANTRONFORM;
 8689: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8690:   <input type="hidden" name="command" value="scantron_configphase" />
 8691:   $default_form_data
 8692: SCANTRONFORM
 8693:     $r->print($result);
 8694: 
 8695:     my @delayqueue;
 8696:     my (%completedstudents,%scandata);
 8697:     
 8698:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8699:     my $count=&get_todo_count($scanlines,$scan_data);
 8700:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8701:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8702: 					  'Processing first student');
 8703:     $r->print('<br />');
 8704:     my $start=&Time::HiRes::time();
 8705:     my $i=-1;
 8706:     my $started;
 8707: 
 8708:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8709:     if ($nav_error) {
 8710:         $r->print(&navmap_errormsg());
 8711:         return '';
 8712:     }
 8713: 
 8714:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8715:     # the user and return.
 8716: 
 8717:     if ($ssi_error) {
 8718: 	$r->print("</form>");
 8719: 	&ssi_print_error($r);
 8720: 	$r->print(&show_grading_menu_form($symb));
 8721:         &Apache::lonnet::remove_lock($lock);
 8722: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8723:     }
 8724: 
 8725:     my %lettdig = &letter_to_digits();
 8726:     my $numletts = scalar(keys(%lettdig));
 8727:     my %orderedforcode;
 8728: 
 8729:     while ($i<$scanlines->{'count'}) {
 8730:  	($uname,$udom)=('','');
 8731:  	$i++;
 8732:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8733:  	if ($line=~/^[\s\cz]*$/) { next; }
 8734: 	if ($started) {
 8735: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8736: 						     'last student');
 8737: 	}
 8738: 	$started=1;
 8739:         my %respnumlookup = ();
 8740:         my %startline = ();
 8741:         my $total;
 8742:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8743:  						 $scan_data,undef,\%idmap,$randomorder,
 8744:                                                  $randompick,$sequence,\@master_seq,
 8745:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8746:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8747:                                                  \$total);
 8748:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8749:  					      \%idmap,$i)) {
 8750:   	    &scantron_add_delay(\@delayqueue,$line,
 8751:  				'Unable to find a student that matches',1);
 8752:  	    next;
 8753:   	}
 8754:  	if (exists $completedstudents{$uname}) {
 8755:  	    &scantron_add_delay(\@delayqueue,$line,
 8756:  				'Student '.$uname.' has multiple sheets',2);
 8757:  	    next;
 8758:  	}
 8759:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8760:         my $user = $uname.':'.$usec;
 8761:   	($uname,$udom)=split(/:/,$uname);
 8762: 
 8763:         my $scancode;
 8764:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8765:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8766:             $scancode = $scan_record->{'scantron.CODE'};
 8767:         } else {
 8768:             $scancode = '';
 8769:         }
 8770: 
 8771:         my @mapresources = @resources;
 8772:         if ($randomorder || $randompick) {
 8773:             @mapresources =
 8774:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8775:                              \%orderedforcode);
 8776:         }
 8777:         my (%partids_by_symb,$res_error);
 8778:         foreach my $resource (@mapresources) {
 8779:             my $ressymb;
 8780:             if (ref($resource)) {
 8781:                 $ressymb = $resource->symb();
 8782:             } else {
 8783:                 $res_error = 1;
 8784:                 last;
 8785:             }
 8786:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8787:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8788:                 my ($analysis,$parts) =
 8789:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8790:                                               $uname,$udom,undef,$bubbles_per_row);
 8791:                 $partids_by_symb{$ressymb} = $parts;
 8792:             } else {
 8793:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8794:             }
 8795:         }
 8796: 
 8797:         if ($res_error) {
 8798:             &scantron_add_delay(\@delayqueue,$line,
 8799:                                 'An error occurred while grading student '.$uname,2);
 8800:             next;
 8801:         }
 8802: 
 8803: 	&Apache::lonxml::clear_problem_counter();
 8804:   	&Apache::lonnet::appenv($scan_record);
 8805: 
 8806: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8807: 	    &scantron_putfile($scanlines,$scan_data);
 8808: 	}
 8809: 	
 8810:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8811:                                    \@mapresources,\%partids_by_symb,
 8812:                                    $bubbles_per_row,$randomorder,$randompick,
 8813:                                    \%respnumlookup,\%startline) 
 8814:             eq 'ssi_error') {
 8815:             $ssi_error = 0; # So end of handler error message does not trigger.
 8816:             $r->print("</form>");
 8817:             &ssi_print_error($r);
 8818:             $r->print(&show_grading_menu_form($symb));
 8819:             &Apache::lonnet::remove_lock($lock);
 8820:             return '';      # Why return ''?  Beats me.
 8821:         }
 8822: 
 8823:         if (($scancode) && ($randomorder || $randompick)) {
 8824:             my $parmresult =
 8825:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8826:                                                        '0_examcode',2,$scancode,
 8827:                                                        'string_examcode',$uname,
 8828:                                                        $udom);
 8829:         }
 8830: 	$completedstudents{$uname}={'line'=>$line};
 8831:         if ($env{'form.verifyrecord'}) {
 8832:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8833:             if ($randompick) {
 8834:                 if ($total) {
 8835:                     $lastpos = $total*$scantron_config{'Qlength'};
 8836:                 }
 8837:             }
 8838: 
 8839:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8840:             chomp($studentdata);
 8841:             $studentdata =~ s/\r$//;
 8842:             my $studentrecord = '';
 8843:             my $counter = -1;
 8844:             foreach my $resource (@mapresources) {
 8845:                 my $ressymb = $resource->symb();
 8846:                 ($counter,my $recording) =
 8847:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8848:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8849:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8850:                                              $randompick,\%respnumlookup,\%startline);
 8851:                 $studentrecord .= $recording;
 8852:             }
 8853:             if ($studentrecord ne $studentdata) {
 8854:                 &Apache::lonxml::clear_problem_counter();
 8855:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8856:                                            \@mapresources,\%partids_by_symb,
 8857:                                            $bubbles_per_row,$randomorder,$randompick,
 8858:                                            \%respnumlookup,\%startline)
 8859:                     eq 'ssi_error') {
 8860:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8861:                     $r->print("</form>");
 8862:                     &ssi_print_error($r);
 8863:                     $r->print(&show_grading_menu_form($symb));
 8864:                     &Apache::lonnet::remove_lock($lock);
 8865:                     delete($completedstudents{$uname});
 8866:                     return '';
 8867:                 }
 8868:                 $counter = -1;
 8869:                 $studentrecord = '';
 8870:                 foreach my $resource (@mapresources) {
 8871:                     my $ressymb = $resource->symb();
 8872:                     ($counter,my $recording) =
 8873:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8874:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8875:                                                  \%scantron_config,\%lettdig,$numletts,
 8876:                                                  $randomorder,$randompick,\%respnumlookup,
 8877:                                                  \%startline);
 8878:                     $studentrecord .= $recording;
 8879:                 }
 8880:                 if ($studentrecord ne $studentdata) {
 8881:                     $r->print('<p><span class="LC_warning">');
 8882:                     if ($scancode eq '') {
 8883:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8884:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8885:                     } else {
 8886:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8887:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8888:                     }
 8889:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8890:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8891:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8892:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8893:                               &Apache::loncommon::start_data_table_row().
 8894:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8895:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8896:                               &Apache::loncommon::end_data_table_row().
 8897:                               &Apache::loncommon::start_data_table_row().
 8898:                               '<td>'.&mt('Stored submissions').'</td>'.
 8899:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8900:                               &Apache::loncommon::end_data_table_row().
 8901:                               &Apache::loncommon::end_data_table().'</p>');
 8902:                 } else {
 8903:                     $r->print('<br /><span class="LC_warning">'.
 8904:                              &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 />'.
 8905:                              &mt("As a consequence, this user's submission history records two tries.").
 8906:                                  '</span><br />');
 8907:                 }
 8908:             }
 8909:         }
 8910:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8911:     } continue {
 8912: 	&Apache::lonxml::clear_problem_counter();
 8913: 	&Apache::lonnet::delenv('scantron.');
 8914:     }
 8915:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8916:     &Apache::lonnet::remove_lock($lock);
 8917: #    my $lasttime = &Time::HiRes::time()-$start;
 8918: #    $r->print("<p>took $lasttime</p>");
 8919: 
 8920:     $r->print("</form>");
 8921:     $r->print(&show_grading_menu_form($symb));
 8922:     return '';
 8923: }
 8924: 
 8925: sub graders_resources_pass {
 8926:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8927:         $bubbles_per_row) = @_;
 8928:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8929:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8930:         foreach my $resource (@{$resources}) {
 8931:             my $ressymb = $resource->symb();
 8932:             my ($analysis,$parts) =
 8933:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8934:                                           $env{'user.name'},$env{'user.domain'},
 8935:                                           1,$bubbles_per_row);
 8936:             $grader_partids_by_symb->{$ressymb} = $parts;
 8937:             if (ref($analysis) eq 'HASH') {
 8938:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8939:                     $grader_randomlists_by_symb->{$ressymb} =
 8940:                         $analysis->{'parts_withrandomlist'};
 8941:                 }
 8942:             }
 8943:         }
 8944:     }
 8945:     return;
 8946: }
 8947: 
 8948: =pod
 8949: 
 8950: =item users_order
 8951: 
 8952:   Returns array of resources in current map, ordered based on either CODE,
 8953:   if this is a CODEd exam, or based on student's identity if this is a
 8954:   "NAMEd" exam.
 8955: 
 8956:   Should be used when randomorder and/or randompick applied when the 
 8957:   corresponding exam was printed, prior to students completing bubblesheets 
 8958:   for the version of the exam the student received.
 8959: 
 8960: =cut
 8961: 
 8962: sub users_order  {
 8963:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8964:     my @mapresources;
 8965:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8966:         return @mapresources;
 8967:     }
 8968:     if ($scancode) {
 8969:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8970:             @mapresources = @{$orderedforcode->{$scancode}};
 8971:         } else {
 8972:             $env{'form.CODE'} = $scancode;
 8973:             my $actual_seq =
 8974:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8975:                                                                $master_seq,
 8976:                                                                $user,$scancode,1);
 8977:             if (ref($actual_seq) eq 'ARRAY') {
 8978:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8979:                 if (ref($orderedforcode) eq 'HASH') {
 8980:                     if (@mapresources > 0) {
 8981:                         $orderedforcode->{$scancode} = \@mapresources;
 8982:                     }
 8983:                 }
 8984:             }
 8985:             delete($env{'form.CODE'});
 8986:         }
 8987:     } else {
 8988:         my $actual_seq =
 8989:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8990:                                                            $master_seq,
 8991:                                                            $user,undef,1);
 8992:         if (ref($actual_seq) eq 'ARRAY') {
 8993:             @mapresources =
 8994:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8995:         }
 8996:     }
 8997:     return @mapresources;
 8998: }
 8999: 
 9000: sub grade_student_bubbles {
 9001:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9002:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9003:     my $uselookup = 0;
 9004:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9005:         (ref($startline) eq 'HASH')) {
 9006:         $uselookup = 1;
 9007:     }
 9008: 
 9009:     if (ref($resources) eq 'ARRAY') {
 9010:         my $count = 0;
 9011:         foreach my $resource (@{$resources}) {
 9012:             my $ressymb = $resource->symb();
 9013:             my %form = ('submitted'      => 'scantron',
 9014:                         'grade_target'   => 'grade',
 9015:                         'grade_username' => $uname,
 9016:                         'grade_domain'   => $udom,
 9017:                         'grade_courseid' => $env{'request.course.id'},
 9018:                         'grade_symb'     => $ressymb,
 9019:                         'CODE'           => $scancode
 9020:                        );
 9021:             if ($bubbles_per_row ne '') {
 9022:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9023:             }
 9024:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9025:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9026:             }
 9027:             if (ref($parts) eq 'HASH') {
 9028:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9029:                     foreach my $part (@{$parts->{$ressymb}}) {
 9030:                         if ($uselookup) {
 9031:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9032:                         } else {
 9033:                             $form{'scantron_questnum_start.'.$part} =
 9034:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9035:                         }
 9036:                         $count++;
 9037:                     }
 9038:                 }
 9039:             }
 9040:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9041:             return 'ssi_error' if ($ssi_error);
 9042:             last if (&Apache::loncommon::connection_aborted($r));
 9043:         }
 9044:     }
 9045:     return;
 9046: }
 9047: 
 9048: sub scantron_upload_scantron_data {
 9049:     my ($r)=@_;
 9050:     my $dom = $env{'request.role.domain'};
 9051:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9052:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9053:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9054: 							  'domainid',
 9055: 							  'coursename',$dom);
 9056:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9057:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9058:     my ($symb) = &get_symb($r,1);
 9059:     my $default_form_data=&defaultFormData($symb);
 9060:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9061:     &js_escape(\$nofile_alert);
 9062:     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.");
 9063:     &js_escape(\$nocourseid_alert);
 9064:     $r->print('
 9065: <script type="text/javascript" language="javascript">
 9066:     function checkUpload(formname) {
 9067: 	if (formname.upfile.value == "") {
 9068: 	    alert("'.$nofile_alert.'");
 9069: 	    return false;
 9070: 	}
 9071:         if (formname.courseid.value == "") {
 9072:             alert("'.$nocourseid_alert.'");
 9073:             return false;
 9074:         }
 9075: 	formname.submit();
 9076:     }
 9077: 
 9078:     function ToSyllabus() {
 9079:         var cdom = '."'$dom'".';
 9080:         var cnum = document.rules.courseid.value;
 9081:         if (cdom == "" || cdom == null) {
 9082:             return;
 9083:         }
 9084:         if (cnum == "" || cnum == null) {
 9085:            return;
 9086:         }
 9087:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9088:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9089:         return;
 9090:     }
 9091: 
 9092: </script>
 9093: 
 9094: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9095: 
 9096: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9097: '.$default_form_data.
 9098:   &Apache::lonhtmlcommon::start_pick_box().
 9099:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9100:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9101:   &Apache::lonhtmlcommon::row_closure().
 9102:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9103:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9104:   &Apache::lonhtmlcommon::row_closure().
 9105:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9106:   '<input name="domainid" type="hidden" />'.$domdesc.
 9107:   &Apache::lonhtmlcommon::row_closure().
 9108:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9109:   '<input type="file" name="upfile" size="50" />'.
 9110:   &Apache::lonhtmlcommon::row_closure(1).
 9111:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9112: 
 9113: <input name="command" value="scantronupload_save" type="hidden" />
 9114: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9115: </form>
 9116: ');
 9117:     return '';
 9118: }
 9119: 
 9120: 
 9121: sub scantron_upload_scantron_data_save {
 9122:     my($r)=@_;
 9123:     my ($symb)=&get_symb($r,1);
 9124:     my $doanotherupload=
 9125: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9126: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9127: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9128: 	'</form>'."\n";
 9129:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9130: 	!&Apache::lonnet::allowed('usc',
 9131: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9132: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9133: 	if ($symb) {
 9134: 	    $r->print(&show_grading_menu_form($symb));
 9135: 	} else {
 9136: 	    $r->print($doanotherupload);
 9137: 	}
 9138: 	return '';
 9139:     }
 9140:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9141:     my $uploadedfile;
 9142:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9143:     if (length($env{'form.upfile'}) < 2) {
 9144:         $r->print(
 9145:             &Apache::lonhtmlcommon::confirm_success(
 9146:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9147:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9148:     } else {
 9149:         my $result = 
 9150:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 9151:                                             $env{'form.courseid'},$env{'form.domainid'});
 9152: 	if ($result =~ m{^/uploaded/}) {
 9153:             $r->print(
 9154:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9155:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9156:                         (length($env{'form.upfile'})-1),
 9157:                         '<span class="LC_filename">'.$result.'</span>'));
 9158:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9159:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9160:                                                        $env{'form.courseid'},$uploadedfile));
 9161: 	} else {
 9162:             $r->print(
 9163:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9164:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9165:                           $result,
 9166: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9167: 	}
 9168:     }
 9169:     if ($symb) {
 9170: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 9171:     } else {
 9172: 	$r->print($doanotherupload);
 9173:     }
 9174:     return '';
 9175: }
 9176: 
 9177: sub validate_uploaded_scantron_file {
 9178:     my ($cdom,$cname,$fname) = @_;
 9179:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9180:     my @lines;
 9181:     if ($scanlines ne '-1') {
 9182:         @lines=split("\n",$scanlines,-1);
 9183:     }
 9184:     my $output;
 9185:     if (@lines) {
 9186:         my (%counts,$max_match_format);
 9187:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9188:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9189:         my %idmap = &username_to_idmap($classlist);
 9190:         foreach my $key (keys(%idmap)) {
 9191:             my $lckey = lc($key);
 9192:             $idmap{$lckey} = $idmap{$key};
 9193:         }
 9194:         my %unique_formats;
 9195:         my @formatlines = &get_scantronformat_file();
 9196:         foreach my $line (@formatlines) {
 9197:             chomp($line);
 9198:             my @config = split(/:/,$line);
 9199:             my $idstart = $config[5];
 9200:             my $idlength = $config[6];
 9201:             if (($idstart ne '') && ($idlength > 0)) {
 9202:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9203:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9204:                 } else {
 9205:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9206:                 }
 9207:             }
 9208:         }
 9209:         foreach my $key (keys(%unique_formats)) {
 9210:             my ($idstart,$idlength) = split(':',$key);
 9211:             %{$counts{$key}} = (
 9212:                                'found'   => 0,
 9213:                                'total'   => 0,
 9214:                               );
 9215:             foreach my $line (@lines) {
 9216:                 next if ($line =~ /^#/);
 9217:                 next if ($line =~ /^[\s\cz]*$/);
 9218:                 my $id = substr($line,$idstart-1,$idlength);
 9219:                 $id = lc($id);
 9220:                 if (exists($idmap{$id})) {
 9221:                     $counts{$key}{'found'} ++;
 9222:                 }
 9223:                 $counts{$key}{'total'} ++;
 9224:             }
 9225:             if ($counts{$key}{'total'}) {
 9226:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9227:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9228:                     $max_match_pct = $percent_match;
 9229:                     $max_match_format = $key;
 9230:                     $found_match_count = $counts{$key}{'found'};
 9231:                     $max_match_count = $counts{$key}{'total'};
 9232:                 }
 9233:             }
 9234:         }
 9235:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9236:             my $format_descs;
 9237:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9238:             for (my $i=0; $i<$numwithformat; $i++) {
 9239:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9240:                 if ($i<$numwithformat-2) {
 9241:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9242:                 } elsif ($i==$numwithformat-2) {
 9243:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9244:                 } elsif ($i==$numwithformat-1) {
 9245:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9246:                 }
 9247:             }
 9248:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9249:             $output .= '<br />';
 9250:             if ($found_match_count == $max_match_count) {
 9251:                 # 100% matching entries
 9252:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9253:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9254:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9255:                 &mt('Comparison of student IDs in the uploaded file with'.
 9256:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9257:                     ' in the file (for the format defined for [_3]).',
 9258:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9259:             } else {
 9260:                 # Not all entries matching? -> Show warning and additional info
 9261:                 $output .=
 9262:                     &Apache::lonhtmlcommon::confirm_success(
 9263:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9264:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9265:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9266:                     &mt('Comparison of student IDs in the uploaded file with'.
 9267:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9268:                         ' in the file (for the format defined for [_3]).',
 9269:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9270:                     '<p class="LC_info">'.
 9271:                     &mt('A low percentage of matches results from one of the following:').
 9272:                     '</p><ul>'.
 9273:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9274:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9275:                                '<i>'.$cdom.'</i>').'</li>'.
 9276:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9277:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9278:                     '</ul>';
 9279:             }
 9280:         }
 9281:     } else {
 9282:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9283:     }
 9284:     return $output;
 9285: }
 9286: 
 9287: sub valid_file {
 9288:     my ($requested_file)=@_;
 9289:     foreach my $filename (sort(&scantron_filenames())) {
 9290: 	if ($requested_file eq $filename) { return 1; }
 9291:     }
 9292:     return 0;
 9293: }
 9294: 
 9295: sub scantron_download_scantron_data {
 9296:     my ($r)=@_;
 9297:     my ($symb) = &get_symb($r,1);
 9298:     my $default_form_data=&defaultFormData($symb);
 9299:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9300:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9301:     my $file=$env{'form.scantron_selectfile'};
 9302:     if (! &valid_file($file)) {
 9303: 	$r->print('
 9304: 	<p>
 9305: 	    '.&mt('The requested filename was invalid.').'
 9306:         </p>
 9307: ');
 9308: 	$r->print(&show_grading_menu_form($symb));
 9309: 	return;
 9310:     }
 9311:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9312:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9313:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9314:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9315:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9316:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9317:     $r->print('
 9318:     <p>
 9319: 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
 9320: 	      '<a href="'.$orig.'">','</a>').'
 9321:     </p>
 9322:     <p>
 9323: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9324: 	      '<a href="'.$corrected.'">','</a>').'
 9325:     </p>
 9326:     <p>
 9327: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9328: 	      '<a href="'.$skipped.'">','</a>').'
 9329:     </p>
 9330: ');
 9331:     $r->print(&show_grading_menu_form($symb));
 9332:     return '';
 9333: }
 9334: 
 9335: sub checkscantron_results {
 9336:     my ($r) = @_;
 9337:     my ($symb)=&get_symb($r);
 9338:     if (!$symb) {return '';}
 9339:     my $grading_menu_button=&show_grading_menu_form($symb);
 9340:     my $cid = $env{'request.course.id'};
 9341:     my %lettdig = &letter_to_digits();
 9342:     my $numletts = scalar(keys(%lettdig));
 9343:     my $cnum = $env{'course.'.$cid.'.num'};
 9344:     my $cdom = $env{'course.'.$cid.'.domain'};
 9345:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9346:     my %record;
 9347:     my %scantron_config =
 9348:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9349:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9350:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9351:     my $classlist=&Apache::loncoursedata::get_classlist();
 9352:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9353:     my $navmap=Apache::lonnavmaps::navmap->new();
 9354:     unless (ref($navmap)) {
 9355:         $r->print(&navmap_errormsg());
 9356:         return '';
 9357:     }
 9358:     my $map=$navmap->getResourceByUrl($sequence);
 9359:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9360:         %grader_randomlists_by_symb,%orderedforcode);
 9361:     if (ref($map)) {
 9362:         $randomorder=$map->randomorder();
 9363:         $randompick=$map->randompick();
 9364:     }
 9365:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9366:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9367:     if ($nav_error) {
 9368:         $r->print(&navmap_errormsg());
 9369:         return '';
 9370:     }
 9371:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9372:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9373:     my ($uname,$udom);
 9374:     my (%scandata,%lastname,%bylast);
 9375:     $r->print('
 9376: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9377: 
 9378:     my @delayqueue;
 9379:     my %completedstudents;
 9380: 
 9381:     my $count=&get_todo_count($scanlines,$scan_data);
 9382:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9383:     my ($username,$domain,$started);
 9384:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9385:     if ($nav_error) {
 9386:         $r->print(&navmap_errormsg());
 9387:         return '';
 9388:     }
 9389: 
 9390:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9391:                                           'Processing first student');
 9392:     my $start=&Time::HiRes::time();
 9393:     my $i=-1;
 9394: 
 9395:     while ($i<$scanlines->{'count'}) {
 9396:         ($username,$domain,$uname)=('','','');
 9397:         $i++;
 9398:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9399:         if ($line=~/^[\s\cz]*$/) { next; }
 9400:         if ($started) {
 9401:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9402:                                                      'last student');
 9403:         }
 9404:         $started=1;
 9405:         my $scan_record=
 9406:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9407:                                                      $scan_data);
 9408:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9409:                                               \%idmap,$i)) {
 9410:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9411:                                 'Unable to find a student that matches',1);
 9412:             next;
 9413:         }
 9414:         if (exists $completedstudents{$uname}) {
 9415:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9416:                                 'Student '.$uname.' has multiple sheets',2);
 9417:             next;
 9418:         }
 9419:         my $pid = $scan_record->{'scantron.ID'};
 9420:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9421:         push(@{$bylast{$lastname{$pid}}},$pid);
 9422:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9423:         my $user = $uname.':'.$usec;
 9424:         ($username,$domain)=split(/:/,$uname);
 9425: 
 9426:         my $scancode;
 9427:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9428:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9429:             $scancode = $scan_record->{'scantron.CODE'};
 9430:         } else {
 9431:             $scancode = '';
 9432:         }
 9433: 
 9434:         my @mapresources = @resources;
 9435:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9436:         my %respnumlookup=();
 9437:         my %startline=();
 9438:         if ($randomorder || $randompick) {
 9439:             @mapresources =
 9440:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9441:                              \%orderedforcode);
 9442:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9443:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9444:                                              \%grader_partids_by_symb,\%orderedforcode,
 9445:                                              \%respnumlookup,\%startline);
 9446:             if ($randompick && $total) {
 9447:                 $lastpos = $total*$scantron_config{'Qlength'};
 9448:             }
 9449:         }
 9450:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9451:         chomp($scandata{$pid});
 9452:         $scandata{$pid} =~ s/\r$//;
 9453: 
 9454:         my $counter = -1;
 9455:         foreach my $resource (@mapresources) {
 9456:             my $parts;
 9457:             my $ressymb = $resource->symb();
 9458:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9459:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9460:                 (my $analysis,$parts) =
 9461:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9462:                                               $username,$domain,undef,
 9463:                                               $bubbles_per_row);
 9464:             } else {
 9465:                 $parts = $grader_partids_by_symb{$ressymb};
 9466:             }
 9467:             ($counter,my $recording) =
 9468:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9469:                                          $scandata{$pid},$parts,
 9470:                                          \%scantron_config,\%lettdig,$numletts,
 9471:                                          $randomorder,$randompick,
 9472:                                          \%respnumlookup,\%startline);
 9473:             $record{$pid} .= $recording;
 9474:         }
 9475:     }
 9476:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9477:     $r->print('<br />');
 9478:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9479:     $passed = 0;
 9480:     $failed = 0;
 9481:     $numstudents = 0;
 9482:     foreach my $last (sort(keys(%bylast))) {
 9483:         if (ref($bylast{$last}) eq 'ARRAY') {
 9484:             foreach my $pid (sort(@{$bylast{$last}})) {
 9485:                 my $showscandata = $scandata{$pid};
 9486:                 my $showrecord = $record{$pid};
 9487:                 $showscandata =~ s/\s/&nbsp;/g;
 9488:                 $showrecord =~ s/\s/&nbsp;/g;
 9489:                 if ($scandata{$pid} eq $record{$pid}) {
 9490:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9491:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9492: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9493: '</tr>'."\n".
 9494: '<tr class="'.$css_class.'">'."\n".
 9495: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9496:                     $passed ++;
 9497:                 } else {
 9498:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9499:                     $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".
 9500: '</tr>'."\n".
 9501: '<tr class="'.$css_class.'">'."\n".
 9502: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9503: '</tr>'."\n";
 9504:                     $failed ++;
 9505:                 }
 9506:                 $numstudents ++;
 9507:             }
 9508:         }
 9509:     }
 9510:     $r->print('<p>'.
 9511:               &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).',
 9512:                   '<b>',
 9513:                   $numstudents,
 9514:                   '</b>',
 9515:                   $env{'form.scantron_maxbubble'}).
 9516:               '</p>'
 9517:     );
 9518:     $r->print('<p>'
 9519:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9520:              .'<br />'
 9521:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9522:              .'</p>');
 9523:     if ($passed) {
 9524:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9525:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9526:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9527:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9528:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9529:                  $okstudents."\n".
 9530:                  &Apache::loncommon::end_data_table().'<br />');
 9531:     }
 9532:     if ($failed) {
 9533:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9534:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9535:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9536:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9537:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9538:                  $badstudents."\n".
 9539:                  &Apache::loncommon::end_data_table()).'<br />'.
 9540:                  &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.');  
 9541:     }
 9542:     $r->print('</form><br />'.$grading_menu_button);
 9543:     return;
 9544: }
 9545: 
 9546: sub verify_scantron_grading {
 9547:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9548:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9549:         $respnumlookup,$startline) = @_;
 9550:     my ($record,%expected,%startpos);
 9551:     return ($counter,$record) if (!ref($resource));
 9552:     return ($counter,$record) if (!$resource->is_problem());
 9553:     my $symb = $resource->symb();
 9554:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9555:     foreach my $part_id (@{$partids}) {
 9556:         $counter ++;
 9557:         $expected{$part_id} = 0;
 9558:         my $respnum = $counter;
 9559:         if ($randomorder || $randompick) {
 9560:             $respnum = $respnumlookup->{$counter};
 9561:             $startpos{$part_id} = $startline->{$counter} + 1;
 9562:         } else {
 9563:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9564:         }
 9565:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9566:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9567:             foreach my $item (@sub_lines) {
 9568:                 $expected{$part_id} += $item;
 9569:             }
 9570:         } else {
 9571:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9572:         }
 9573:     }
 9574:     if ($symb) {
 9575:         my %recorded;
 9576:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9577:         if ($returnhash{'version'}) {
 9578:             my %lasthash=();
 9579:             my $version;
 9580:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9581:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9582:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9583:                 }
 9584:             }
 9585:             foreach my $key (keys(%lasthash)) {
 9586:                 if ($key =~ /\.scantron$/) {
 9587:                     my $value = &unescape($lasthash{$key});
 9588:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9589:                     if ($value eq '') {
 9590:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9591:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9592:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9593:                             }
 9594:                         }
 9595:                     } else {
 9596:                         my @tocheck;
 9597:                         my @items = split(//,$value);
 9598:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9599:                             ($scantron_config->{'Qon'} eq 'number')) {
 9600:                             if (@items < $expected{$part_id}) {
 9601:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9602:                                 my @singles = split(//,$fragment);
 9603:                                 foreach my $pos (@singles) {
 9604:                                     if ($pos eq ' ') {
 9605:                                         push(@tocheck,$pos);
 9606:                                     } else {
 9607:                                         my $next = shift(@items);
 9608:                                         push(@tocheck,$next);
 9609:                                     }
 9610:                                 }
 9611:                             } else {
 9612:                                 @tocheck = @items;
 9613:                             }
 9614:                             foreach my $letter (@tocheck) {
 9615:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9616:                                     if ($letter !~ /^[A-J]$/) {
 9617:                                         $letter = $scantron_config->{'Qoff'};
 9618:                                     }
 9619:                                     $recorded{$part_id} .= $letter;
 9620:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9621:                                     my $digit;
 9622:                                     if ($letter !~ /^[A-J]$/) {
 9623:                                         $digit = $scantron_config->{'Qoff'};
 9624:                                     } else {
 9625:                                         $digit = $lettdig->{$letter};
 9626:                                     }
 9627:                                     $recorded{$part_id} .= $digit;
 9628:                                 }
 9629:                             }
 9630:                         } else {
 9631:                             @tocheck = @items;
 9632:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9633:                                 my $curr_sub = shift(@tocheck);
 9634:                                 my $digit;
 9635:                                 if ($curr_sub =~ /^[A-J]$/) {
 9636:                                     $digit = $lettdig->{$curr_sub}-1;
 9637:                                 }
 9638:                                 if ($curr_sub eq 'J') {
 9639:                                     $digit += scalar($numletts);
 9640:                                 }
 9641:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9642:                                     if ($j == $digit) {
 9643:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9644:                                     } else {
 9645:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9646:                                     }
 9647:                                 }
 9648:                             }
 9649:                         }
 9650:                     }
 9651:                 }
 9652:             }
 9653:         }
 9654:         foreach my $part_id (@{$partids}) {
 9655:             if ($recorded{$part_id} eq '') {
 9656:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9657:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9658:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9659:                     }
 9660:                 }
 9661:             }
 9662:             $record .= $recorded{$part_id};
 9663:         }
 9664:     }
 9665:     return ($counter,$record);
 9666: }
 9667: 
 9668: sub letter_to_digits {
 9669:     my %lettdig = (
 9670:                     A => 1,
 9671:                     B => 2,
 9672:                     C => 3,
 9673:                     D => 4,
 9674:                     E => 5,
 9675:                     F => 6,
 9676:                     G => 7,
 9677:                     H => 8,
 9678:                     I => 9,
 9679:                     J => 0,
 9680:                   );
 9681:     return %lettdig;
 9682: }
 9683: 
 9684: 
 9685: #-------- end of section for handling grading scantron forms -------
 9686: #
 9687: #-------------------------------------------------------------------
 9688: 
 9689: #-------------------------- Menu interface -------------------------
 9690: #
 9691: #--- Show a Grading Menu button - Calls the next routine ---
 9692: sub show_grading_menu_form {
 9693:     my ($symb)=@_;
 9694:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9695: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9696: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9697: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9698: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9699: 	'</form>'."\n";
 9700:     return $result;
 9701: }
 9702: 
 9703: # -- Retrieve choices for grading form
 9704: sub savedState {
 9705:     my %savedState = ();
 9706:     if ($env{'form.saveState'}) {
 9707: 	foreach (split(/:/,$env{'form.saveState'})) {
 9708: 	    my ($key,$value) = split(/=/,$_,2);
 9709: 	    $savedState{$key} = $value;
 9710: 	}
 9711:     }
 9712:     return \%savedState;
 9713: }
 9714: 
 9715: #--- Href with symb and command ---
 9716: 
 9717: sub href_symb_cmd {
 9718:     my ($symb,$cmd)=@_;
 9719:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9720: }
 9721: 
 9722: sub grading_menu {
 9723:     my ($request) = @_;
 9724:     my ($symb)=&get_symb($request);
 9725:     if (!$symb) {return '';}
 9726:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9727:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9728: 
 9729:     $request->print($table);
 9730:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9731:                   'handgrade'=>$hdgrade,
 9732:                   'probTitle'=>$probTitle,
 9733:                   'command'=>'submit_options',
 9734:                   'saveState'=>"",
 9735:                   'gradingMenu'=>1,
 9736:                   'showgrading'=>"yes");
 9737:     
 9738:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9739:     
 9740:     $fields{'command'} = 'csvform';
 9741:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9742:     
 9743:     $fields{'command'} = 'processclicker';
 9744:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9745:     
 9746:     $fields{'command'} = 'scantron_selectphase';
 9747:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9748:     
 9749:     my @menu = ({	categorytitle=>'Course Grading',
 9750:             items =>[
 9751:                         {	linktext => 'Manual Grading/View Submissions',
 9752:                     		url => $url1,
 9753:                     		permission => 'F',
 9754:                     		icon => 'edit-find-replace.png',
 9755:                     		linktitle => 'Start the process of hand grading submissions.'
 9756:                         },
 9757:                 	    {	linktext => 'Upload Scores',
 9758:                     		url => $url2,
 9759:                     		permission => 'F',
 9760:                     		icon => 'uploadscores.png',
 9761:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9762:                 	    },
 9763:                 	    {	linktext => 'Process Clicker',
 9764:                     		url => $url3,
 9765:                     		permission => 'F',
 9766:                     		icon => 'addClickerInfoFile.png',
 9767:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9768:                 	    },
 9769:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9770:                     		url => $url4,
 9771:                     		permission => 'F',
 9772:                     		icon => 'stat.png',
 9773:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9774:                 	    }
 9775:                     ]
 9776:             });
 9777: 
 9778:     #$fields{'command'} = 'verify';
 9779:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9780:     #
 9781:     # Create the menu
 9782:     my $Str;
 9783:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9784:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9785:     $Str .= '<input type="hidden" name="command" value="" />'.
 9786:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9787: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9788: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9789: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9790: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9791: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9792: 
 9793:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9794:     #$menudata->{'jscript'}
 9795:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9796:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9797:         ' /> '.
 9798:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9799:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9800: 
 9801:     $Str .="</form>\n";
 9802:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9803:     $request->print(<<GRADINGMENUJS);
 9804: <script type="text/javascript" language="javascript">
 9805:     function checkChoice(formname,val,cmdx) {
 9806: 	if (val <= 2) {
 9807: 	    var cmd = radioSelection(formname.radioChoice);
 9808: 	    var cmdsave = cmd;
 9809: 	} else {
 9810: 	    cmd = cmdx;
 9811: 	    cmdsave = 'submission';
 9812: 	}
 9813: 	formname.command.value = cmd;
 9814: 	if (val < 5) formname.submit();
 9815: 	if (val == 5) {
 9816: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9817: 	        return false;
 9818: 	    } else {
 9819: 	        formname.submit();
 9820: 	    }
 9821: 	}
 9822:     }
 9823: 
 9824:     function checkReceiptNo(formname,nospace) {
 9825: 	var receiptNo = formname.receipt.value;
 9826: 	var checkOpt = false;
 9827: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9828: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9829: 	if (checkOpt) {
 9830: 	    alert("$receiptalert");
 9831: 	    formname.receipt.value = "";
 9832: 	    formname.receipt.focus();
 9833: 	    return false;
 9834: 	}
 9835: 	return true;
 9836:     }
 9837: </script>
 9838: GRADINGMENUJS
 9839:     &commonJSfunctions($request);
 9840:     return $Str;    
 9841: }
 9842: 
 9843: 
 9844: #--- Displays the submissions first page -------
 9845: sub submit_options {
 9846:     my ($request) = @_;
 9847:     my ($symb)=&get_symb($request);
 9848:     if (!$symb) {return '';}
 9849:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9850: 
 9851:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9852:     $request->print(<<GRADINGMENUJS);
 9853: <script type="text/javascript" language="javascript">
 9854:     function checkChoice(formname,val,cmdx) {
 9855: 	if (val <= 2) {
 9856: 	    var cmd = radioSelection(formname.radioChoice);
 9857: 	    var cmdsave = cmd;
 9858: 	} else {
 9859: 	    cmd = cmdx;
 9860: 	    cmdsave = 'submission';
 9861: 	}
 9862: 	formname.command.value = cmd;
 9863: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9864: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9865: 	if (val < 5) formname.submit();
 9866: 	if (val == 5) {
 9867: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9868: 	    formname.submit();
 9869: 	}
 9870: 	if (val < 7) formname.submit();
 9871:     }
 9872: 
 9873:     function checkReceiptNo(formname,nospace) {
 9874: 	var receiptNo = formname.receipt.value;
 9875: 	var checkOpt = false;
 9876: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9877: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9878: 	if (checkOpt) {
 9879: 	    alert("$receiptalert");
 9880: 	    formname.receipt.value = "";
 9881: 	    formname.receipt.focus();
 9882: 	    return false;
 9883: 	}
 9884: 	return true;
 9885:     }
 9886: </script>
 9887: GRADINGMENUJS
 9888:     &commonJSfunctions($request);
 9889:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9890:     my $result;
 9891:     my (undef,$sections) = &getclasslist('all','0');
 9892:     my $savedState = &savedState();
 9893:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9894:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9895:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9896:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9897: 
 9898:     # Preselect sections
 9899:     my $selsec="";
 9900:     if (ref($sections)) {
 9901:         foreach my $section (sort(@$sections)) {
 9902:             $selsec.='<option value="'.$section.'" '.
 9903:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9904:         }
 9905:     }
 9906: 
 9907:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9908: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9909: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9910: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9911: 	'<input type="hidden" name="command"     value="" />'."\n".
 9912: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9913: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9914: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9915: 
 9916:     $result.='
 9917: <h2>
 9918:   '.&mt('Grade Current Resource').'
 9919: </h2>
 9920: <div>
 9921:   '.$table.'
 9922: </div>
 9923: 
 9924: <div class="LC_columnSection">
 9925:   
 9926:     <fieldset>
 9927:       <legend>
 9928:        '.&mt('Sections').'
 9929:       </legend>
 9930:       <select name="section" multiple="multiple" size="5">'."\n";
 9931:     $result.= $selsec;
 9932:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9933:     $result.='
 9934:     </fieldset>
 9935:   
 9936:     <fieldset>
 9937:       <legend>
 9938:         '.&mt('Groups').'
 9939:       </legend>
 9940:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9941:     </fieldset>
 9942:   
 9943:     <fieldset>
 9944:       <legend>
 9945:         '.&mt('Access Status').'
 9946:       </legend>
 9947:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9948:     </fieldset>
 9949:   
 9950:     <fieldset>
 9951:       <legend>
 9952:         '.&mt('Submission Status').'
 9953:       </legend>
 9954:       <select name="submitonly" size="5">
 9955: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9956: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9957: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9958: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9959:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9960:       </select>
 9961:     </fieldset>
 9962:   
 9963: </div>
 9964: 
 9965: <br />
 9966:           <div>
 9967:             <div>
 9968:               <label>
 9969:                 <input type="radio" name="radioChoice" value="submission" '.
 9970:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9971:              &mt('Select individual students to grade and view submissions.').'
 9972: 	      </label> 
 9973:             </div>
 9974:             <div>
 9975: 	      <label>
 9976:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9977:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9978:                     &mt('Grade all selected students in a grading table.').'
 9979:               </label>
 9980:             </div>
 9981:             <div>
 9982: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9983:             </div>
 9984:           </div>
 9985: 
 9986: 
 9987:         <h2>
 9988:          '.&mt('Grade Complete Folder for One Student').'
 9989:         </h2>
 9990:         <div>
 9991:             <div>
 9992:               <label>
 9993:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9994: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9995:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9996:               </label>
 9997:             </div>
 9998:             <div>
 9999: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10000:             </div>
10001:         </div>
10002:   </form>';
10003:     $result .= &show_grading_menu_form($symb);
10004:     return $result;
10005: }
10006: 
10007: sub substatus_options {
10008:     return &Apache::lonlocal::texthash(
10009:                                       'yes'       => 'with submissions',
10010:                                       'queued'    => 'in grading queue',
10011:                                       'graded'    => 'with ungraded submissions',
10012:                                       'incorrect' => 'with incorrect submissions',
10013:                                       'all'       => 'with any status',
10014:                                       );
10015: }
10016: 
10017: sub reset_perm {
10018:     undef(%perm);
10019: }
10020: 
10021: sub init_perm {
10022:     &reset_perm();
10023:     foreach my $test_perm ('vgr','mgr','opa') {
10024: 
10025: 	my $scope = $env{'request.course.id'};
10026: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10027: 
10028: 	    $scope .= '/'.$env{'request.course.sec'};
10029: 	    if ( $perm{$test_perm}=
10030: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10031: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10032: 	    } else {
10033: 		delete($perm{$test_perm});
10034: 	    }
10035: 	}
10036:     }
10037: }
10038: 
10039: sub init_old_essays {
10040:     my ($symb,$apath,$adom,$aname) = @_;
10041:     if ($symb ne '') {
10042:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10043:         if (keys(%essays) > 0) {
10044:             $old_essays{$symb} = \%essays;
10045:         }
10046:     }
10047:     return;
10048: }
10049: 
10050: sub reset_old_essays {
10051:     undef(%old_essays);
10052: }
10053: 
10054: sub gather_clicker_ids {
10055:     my %clicker_ids;
10056: 
10057:     my $classlist = &Apache::loncoursedata::get_classlist();
10058: 
10059:     # Set up a couple variables.
10060:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10061:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10062:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10063: 
10064:     foreach my $student (keys(%$classlist)) {
10065:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10066:         my $username = $classlist->{$student}->[$username_idx];
10067:         my $domain   = $classlist->{$student}->[$domain_idx];
10068:         my $clickers =
10069: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10070:         foreach my $id (split(/\,/,$clickers)) {
10071:             $id=~s/^[\#0]+//;
10072:             $id=~s/[\-\:]//g;
10073:             if (exists($clicker_ids{$id})) {
10074: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10075:             } else {
10076: 		$clicker_ids{$id}=$username.':'.$domain;
10077:             }
10078:         }
10079:     }
10080:     return %clicker_ids;
10081: }
10082: 
10083: sub gather_adv_clicker_ids {
10084:     my %clicker_ids;
10085:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10086:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10087:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10088:     foreach my $element (sort(keys(%coursepersonnel))) {
10089:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10090:             my ($puname,$pudom)=split(/\:/,$person);
10091:             my $clickers =
10092: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10093:             foreach my $id (split(/\,/,$clickers)) {
10094: 		$id=~s/^[\#0]+//;
10095:                 $id=~s/[\-\:]//g;
10096: 		if (exists($clicker_ids{$id})) {
10097: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10098: 		} else {
10099: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10100: 		}
10101:             }
10102:         }
10103:     }
10104:     return %clicker_ids;
10105: }
10106: 
10107: sub clicker_grading_parameters {
10108:     return ('gradingmechanism' => 'scalar',
10109:             'upfiletype' => 'scalar',
10110:             'specificid' => 'scalar',
10111:             'pcorrect' => 'scalar',
10112:             'pincorrect' => 'scalar');
10113: }
10114: 
10115: sub process_clicker {
10116:     my ($r)=@_;
10117:     my ($symb)=&get_symb($r);
10118:     if (!$symb) {return '';}
10119:     my $result=&checkforfile_js();
10120:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
10121:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
10122:     $result.=$table;
10123:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
10124:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
10125:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
10126:         '</b></td></tr>'."\n";
10127:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
10128: # Attempt to restore parameters from last session, set defaults if not present
10129:     my %Saveable_Parameters=&clicker_grading_parameters();
10130:     &Apache::loncommon::restore_course_settings('grades_clicker',
10131:                                                  \%Saveable_Parameters);
10132:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10133:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10134:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10135:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10136: 
10137:     my %checked;
10138:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10139:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10140:           $checked{$gradingmechanism}=' checked="checked"';
10141:        }
10142:     }
10143: 
10144:     my $upload=&mt("Upload File");
10145:     my $type=&mt("Type");
10146:     my $attendance=&mt("Award points just for participation");
10147:     my $personnel=&mt("Correctness determined from response by course personnel");
10148:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10149:     my $given=&mt("Correctness determined from given list of answers").' '.
10150:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10151:     my $pcorrect=&mt("Percentage points for correct solution");
10152:     my $pincorrect=&mt("Percentage points for incorrect solution");
10153:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10154:                                                    {'iclicker' => 'i>clicker',
10155:                                                     'interwrite' => 'interwrite PRS',
10156:                                                     'turning' => 'Turning Technologies'});
10157:     $symb = &Apache::lonenc::check_encrypt($symb);
10158:     $result.=<<ENDUPFORM;
10159: <script type="text/javascript">
10160: function sanitycheck() {
10161: // Accept only integer percentages
10162:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10163:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10164: // Find out grading choice
10165:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10166:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10167:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10168:       }
10169:    }
10170: // By default, new choice equals user selection
10171:    newgradingchoice=gradingchoice;
10172: // Not good to give more points for false answers than correct ones
10173:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10174:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10175:    }
10176: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10177:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10178:       document.forms.gradesupload.pcorrect.value=100;
10179:       document.forms.gradesupload.pincorrect.value=100;
10180:    }
10181: // If the values are different, cannot be attendance only
10182:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10183:        (gradingchoice=='attendance')) {
10184:        newgradingchoice='personnel';
10185:    }
10186: // Change grading choice to new one
10187:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10188:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10189:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10190:       } else {
10191:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10192:       }
10193:    }
10194: // Remember the old state
10195:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10196: }
10197: </script>
10198: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10199: <input type="hidden" name="symb" value="$symb" />
10200: <input type="hidden" name="command" value="processclickerfile" />
10201: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10202: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10203: <input type="file" name="upfile" size="50" />
10204: <br /><label>$type: $selectform</label>
10205: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10206: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10207: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10208: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10209: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10210: <br />&nbsp;&nbsp;&nbsp;
10211: <input type="text" name="givenanswer" size="50" />
10212: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10213: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10214: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10215: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10216: </form>
10217: ENDUPFORM
10218:     $result.='</td></tr></table>'."\n".
10219:              '</td></tr></table><br /><br />'."\n";
10220:     $result.=&show_grading_menu_form($symb);
10221:     return $result;
10222: }
10223: 
10224: sub process_clicker_file {
10225:     my ($r)=@_;
10226:     my ($symb)=&get_symb($r);
10227:     if (!$symb) {return '';}
10228: 
10229:     my %Saveable_Parameters=&clicker_grading_parameters();
10230:     &Apache::loncommon::store_course_settings('grades_clicker',
10231:                                               \%Saveable_Parameters);
10232: 
10233:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10234:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10235: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10236: 	return $result.&show_grading_menu_form($symb);
10237:     }
10238:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10239:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10240:         return $result.&show_grading_menu_form($symb);
10241:     }
10242:     my $foundgiven=0;
10243:     if ($env{'form.gradingmechanism'} eq 'given') {
10244:         $env{'form.givenanswer'}=~s/^\s*//gs;
10245:         $env{'form.givenanswer'}=~s/\s*$//gs;
10246:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10247:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10248:         my @answers=split(/\,/,$env{'form.givenanswer'});
10249:         $foundgiven=$#answers+1;
10250:     }
10251:     my %clicker_ids=&gather_clicker_ids();
10252:     my %correct_ids;
10253:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10254: 	%correct_ids=&gather_adv_clicker_ids();
10255:     }
10256:     if ($env{'form.gradingmechanism'} eq 'specific') {
10257: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10258: 	   $correct_id=~tr/a-z/A-Z/;
10259: 	   $correct_id=~s/\s//gs;
10260: 	   $correct_id=~s/^[\#0]+//;
10261:            $correct_id=~s/[\-\:]//g;
10262:            if ($correct_id) {
10263: 	      $correct_ids{$correct_id}='specified';
10264:            }
10265:         }
10266:     }
10267:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10268: 	$result.=&mt('Score based on attendance only');
10269:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10270:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10271:     } else {
10272: 	my $number=0;
10273: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10274: 	foreach my $id (sort(keys(%correct_ids))) {
10275: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10276: 	    if ($correct_ids{$id} eq 'specified') {
10277: 		$result.=&mt('specified');
10278: 	    } else {
10279: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10280: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10281: 	    }
10282: 	    $number++;
10283: 	}
10284:         $result.="</p>\n";
10285:         if ($number==0) {
10286:             $result .=
10287:                  &Apache::lonhtmlcommon::confirm_success(
10288:                      &mt('No IDs found to determine correct answer'),1);
10289:             return $result,.&show_grading_menu_form($symb);
10290:         }
10291:     }
10292:     if (length($env{'form.upfile'}) < 2) {
10293:         $result .=
10294:             &Apache::lonhtmlcommon::confirm_success(
10295:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10296:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10297:         return $result.&show_grading_menu_form($symb);
10298:     }
10299: 
10300: # Were able to get all the info needed, now analyze the file
10301: 
10302:     $result.=&Apache::loncommon::studentbrowser_javascript();
10303:     $symb = &Apache::lonenc::check_encrypt($symb);
10304:     my $heading=&mt('Scanning clicker file');
10305:     $result.=(<<ENDHEADER);
10306: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10307: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10308: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10309: <form method="post" action="/adm/grades" name="clickeranalysis">
10310: <input type="hidden" name="symb" value="$symb" />
10311: <input type="hidden" name="command" value="assignclickergrades" />
10312: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10313: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10314: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10315: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10316: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10317: ENDHEADER
10318:     if ($env{'form.gradingmechanism'} eq 'given') {
10319:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10320:     } 
10321:     my %responses;
10322:     my @questiontitles;
10323:     my $errormsg='';
10324:     my $number=0;
10325:     if ($env{'form.upfiletype'} eq 'iclicker') {
10326: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10327:     }
10328:     if ($env{'form.upfiletype'} eq 'interwrite') {
10329:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10330:     }
10331:     if ($env{'form.upfiletype'} eq 'turning') {
10332:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10333:     }
10334:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10335:              '<input type="hidden" name="number" value="'.$number.'" />'.
10336:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10337:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10338:              '<br />';
10339:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10340:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10341:        return $result.&show_grading_menu_form($symb);
10342:     } 
10343: # Remember Question Titles
10344: # FIXME: Possibly need delimiter other than ":"
10345:     for (my $i=0;$i<$number;$i++) {
10346:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10347:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10348:     }
10349:     my $correct_count=0;
10350:     my $student_count=0;
10351:     my $unknown_count=0;
10352: # Match answers with usernames
10353: # FIXME: Possibly need delimiter other than ":"
10354:     foreach my $id (keys(%responses)) {
10355:        if ($correct_ids{$id}) {
10356:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10357:           $correct_count++;
10358:        } elsif ($clicker_ids{$id}) {
10359:           if ($clicker_ids{$id}=~/\,/) {
10360: # More than one user with the same clicker!
10361:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10362:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10363:                            "<select name='multi".$id."'>";
10364:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10365:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10366:              }
10367:              $result.='</select>';
10368:              $unknown_count++;
10369:           } else {
10370: # Good: found one and only one user with the right clicker
10371:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10372:              $student_count++;
10373:           }
10374:        } else {
10375:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10376:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10377:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10378:                    "\n".&mt("Domain").": ".
10379:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10380:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10381:           $unknown_count++;
10382:        }
10383:     }
10384:     $result.='<hr />'.
10385:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10386:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10387:        if ($correct_count==0) {
10388:           $errormsg.="Found no correct answers for grading!";
10389:        } elsif ($correct_count>1) {
10390:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10391:        }
10392:     }
10393:     if ($number<1) {
10394:        $errormsg.="Found no questions.";
10395:     }
10396:     if ($errormsg) {
10397:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10398:     } else {
10399:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10400:     }
10401:     $result.='</form></td></tr></table>'."\n".
10402:              '</td></tr></table><br /><br />'."\n";
10403:     return $result.&show_grading_menu_form($symb);
10404: }
10405: 
10406: sub iclicker_eval {
10407:     my ($questiontitles,$responses)=@_;
10408:     my $number=0;
10409:     my $errormsg='';
10410:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10411:         my %components=&Apache::loncommon::record_sep($line);
10412:         my @entries=map {$components{$_}} (sort(keys(%components)));
10413: 	if ($entries[0] eq 'Question') {
10414: 	    for (my $i=3;$i<$#entries;$i+=6) {
10415: 		$$questiontitles[$number]=$entries[$i];
10416: 		$number++;
10417: 	    }
10418: 	}
10419: 	if ($entries[0]=~/^\#/) {
10420: 	    my $id=$entries[0];
10421: 	    my @idresponses;
10422: 	    $id=~s/^[\#0]+//;
10423: 	    for (my $i=0;$i<$number;$i++) {
10424: 		my $idx=3+$i*6;
10425:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10426: 		push(@idresponses,$entries[$idx]);
10427: 	    }
10428: 	    $$responses{$id}=join(',',@idresponses);
10429: 	}
10430:     }
10431:     return ($errormsg,$number);
10432: }
10433: 
10434: sub interwrite_eval {
10435:     my ($questiontitles,$responses)=@_;
10436:     my $number=0;
10437:     my $errormsg='';
10438:     my $skipline=1;
10439:     my $questionnumber=0;
10440:     my %idresponses=();
10441:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10442:         my %components=&Apache::loncommon::record_sep($line);
10443:         my @entries=map {$components{$_}} (sort(keys(%components)));
10444:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10445:         if ($entries[1] eq 'Response') { $skipline=1; }
10446:         next if $skipline;
10447:         if ($entries[0]!=$questionnumber) {
10448:            $questionnumber=$entries[0];
10449:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10450:            $number++;
10451:         }
10452:         my $id=$entries[4];
10453:         $id=~s/^[\#0]+//;
10454:         $id=~s/^v\d*\://i;
10455:         $id=~s/[\-\:]//g;
10456:         $idresponses{$id}[$number]=$entries[6];
10457:     }
10458:     foreach my $id (keys(%idresponses)) {
10459:        $$responses{$id}=join(',',@{$idresponses{$id}});
10460:        $$responses{$id}=~s/^\s*\,//;
10461:     }
10462:     return ($errormsg,$number);
10463: }
10464: 
10465: sub turning_eval {
10466:     my ($questiontitles,$responses)=@_;
10467:     my $number=0;
10468:     my $errormsg='';
10469:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10470:         my %components=&Apache::loncommon::record_sep($line);
10471:         my @entries=map {$components{$_}} (sort(keys(%components)));
10472:         if ($#entries>$number) { $number=$#entries; }
10473:         my $id=$entries[0];
10474:         my @idresponses;
10475:         $id=~s/^[\#0]+//;
10476:         unless ($id) { next; }
10477:         for (my $idx=1;$idx<=$#entries;$idx++) {
10478:             $entries[$idx]=~s/\,/\;/g;
10479:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10480:             push(@idresponses,$entries[$idx]);
10481:         }
10482:         $$responses{$id}=join(',',@idresponses);
10483:     }
10484:     for (my $i=1; $i<=$number; $i++) {
10485:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10486:     }
10487:     return ($errormsg,$number);
10488: }
10489: 
10490: sub assign_clicker_grades {
10491:     my ($r)=@_;
10492:     my ($symb)=&get_symb($r);
10493:     if (!$symb) {return '';}
10494: # See which part we are saving to
10495:     my $res_error;
10496:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10497:     if ($res_error) {
10498:         return &navmap_errormsg();
10499:     }
10500: # FIXME: This should probably look for the first handgradeable part
10501:     my $part=$$partlist[0];
10502: # Start screen output
10503:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10504: 
10505:     $result .= '<br />'.
10506:                &Apache::loncommon::start_data_table().
10507:                &Apache::loncommon::start_data_table_header_row().
10508:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10509:                &Apache::loncommon::end_data_table_header_row().
10510:                &Apache::loncommon::start_data_table_row().'<td>';
10511: 
10512: # Get correct result
10513: # FIXME: Possibly need delimiter other than ":"
10514:     my @correct=();
10515:     my $gradingmechanism=$env{'form.gradingmechanism'};
10516:     my $number=$env{'form.number'};
10517:     if ($gradingmechanism ne 'attendance') {
10518:        foreach my $key (keys(%env)) {
10519:           if ($key=~/^form\.correct\:/) {
10520:              my @input=split(/\,/,$env{$key});
10521:              for (my $i=0;$i<=$#input;$i++) {
10522:                  if (($correct[$i]) && ($input[$i]) &&
10523:                      ($correct[$i] ne $input[$i])) {
10524:                     $result.='<br /><span class="LC_warning">'.
10525:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10526:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10527:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10528:                     $correct[$i]=$input[$i];
10529:                  }
10530:              }
10531:           }
10532:        }
10533:        for (my $i=0;$i<$number;$i++) {
10534:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10535:              $result.='<br /><span class="LC_error">'.
10536:                       &mt('No correct result given for question "[_1]"!',
10537:                           $env{'form.question:'.$i}).'</span>';
10538:           }
10539:        }
10540:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10541:     }
10542: # Start grading
10543:     my $pcorrect=$env{'form.pcorrect'};
10544:     my $pincorrect=$env{'form.pincorrect'};
10545:     my $storecount=0;
10546:     my %users=();
10547:     foreach my $key (keys(%env)) {
10548:        my $user='';
10549:        if ($key=~/^form\.student\:(.*)$/) {
10550:           $user=$1;
10551:        }
10552:        if ($key=~/^form\.unknown\:(.*)$/) {
10553:           my $id=$1;
10554:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10555:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10556:           } elsif ($env{'form.multi'.$id}) {
10557:              $user=$env{'form.multi'.$id};
10558:           }
10559:        }
10560:        if ($user) {
10561:           if ($users{$user}) {
10562:              $result.='<br /><span class="LC_warning">'.
10563:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10564:                       '</span><br />';
10565:           }
10566:           $users{$user}=1;
10567:           my @answer=split(/\,/,$env{$key});
10568:           my $sum=0;
10569:           my $realnumber=$number;
10570:           for (my $i=0;$i<$number;$i++) {
10571:              if  ($correct[$i] eq '-') {
10572:                 $realnumber--;
10573:              } elsif ($answer[$i]) {
10574:                 if ($gradingmechanism eq 'attendance') {
10575:                    $sum+=$pcorrect;
10576:                 } elsif ($correct[$i] eq '*') {
10577:                    $sum+=$pcorrect;
10578:                 } else {
10579: # We actually grade if correct or not
10580:                    my $increment=$pincorrect;
10581: # Special case: numerical answer "0"
10582:                    if ($correct[$i] eq '0') {
10583:                       if ($answer[$i]=~/^[0\.]+$/) {
10584:                          $increment=$pcorrect;
10585:                       }
10586: # General numerical answer, both evaluate to something non-zero
10587:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10588:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10589:                          $increment=$pcorrect;
10590:                       }
10591: # Must be just alphanumeric
10592:                    } elsif ($answer[$i] eq $correct[$i]) {
10593:                       $increment=$pcorrect;
10594:                    }
10595:                    $sum+=$increment;
10596:                 }
10597:              }
10598:           }
10599:           my $ave=$sum/(100*$realnumber);
10600: # Store
10601:           my ($username,$domain)=split(/\:/,$user);
10602:           my %grades=();
10603:           $grades{"resource.$part.solved"}='correct_by_override';
10604:           $grades{"resource.$part.awarded"}=$ave;
10605:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10606:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10607:                                                  $env{'request.course.id'},
10608:                                                  $domain,$username);
10609:           if ($returncode ne 'ok') {
10610:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10611:           } else {
10612:              $storecount++;
10613:           }
10614:        }
10615:     }
10616: # We are done
10617:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10618:              '</td>'.
10619:              &Apache::loncommon::end_data_table_row().
10620:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10621:     return $result.&show_grading_menu_form($symb);
10622: }
10623: 
10624: sub navmap_errormsg {
10625:     return '<div class="LC_error">'.
10626:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10627:            &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>').
10628:            '</div>';
10629: }
10630: 
10631: sub startpage {
10632:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10633:     if ($nomenu) {
10634:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10635:     } else {
10636:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10637:                                                  {'bread_crumbs' => $crumbs}));
10638:     }
10639:     unless ($nodisplayflag) {
10640:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10641:     }
10642: }
10643: 
10644: sub handler {
10645:     my $request=$_[0];
10646:     &reset_caches();
10647:     if ($request->header_only) {
10648:         &Apache::loncommon::content_type($request,'text/html');
10649:         $request->send_http_header;
10650:         return OK;
10651:     }
10652:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10653: 
10654:     my $symb=&get_symb($request,1);
10655:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10656:     my $command=$commands[0];
10657: 
10658:     if ($#commands > 0) {
10659: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10660:     }
10661: 
10662:     $ssi_error = 0;
10663:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10664:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10665:                                                     {'bread_crumbs' => $brcrum});
10666:     if ($symb eq '' && $command eq '') {
10667: 	if ($env{'user.adv'}) {
10668:             &Apache::loncommon::content_type($request,'text/html');
10669:             $request->send_http_header;
10670:             $request->print($start_page);
10671: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10672: 		($env{'form.codethree'})) {
10673: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10674: 		    $env{'form.codethree'};
10675: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10676: 		    &Apache::lonnet::checkin($token);
10677: 		if ($tsymb) {
10678: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10679: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10680: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10681: 					  ('grade_username' => $tuname,
10682: 					   'grade_domain' => $tudom,
10683: 					   'grade_courseid' => $tcrsid,
10684: 					   'grade_symb' => $tsymb)));
10685: 		    } else {
10686: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10687: 		    }
10688: 		} else {
10689: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10690: 		}
10691: 	    } else {
10692: 		$request->print(&Apache::lonxml::tokeninputfield());
10693: 	    }
10694:         } elsif ($env{'request.course.id'}) {
10695:             &init_perm(); 
10696:             if (!%perm) {
10697:                 $request->internal_redirect('/adm/quickgrades');
10698:                 return OK;
10699:             } else {
10700:                 &Apache::loncommon::content_type($request,'text/html');
10701:                 $request->send_http_header;
10702:                 $request->print($start_page);
10703:             }
10704:         }
10705:     } else {
10706:         &init_perm();
10707:         if (!$env{'request.course.id'}) {
10708:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10709:                     ($command =~ /^scantronupload/)) {
10710:                 # Not in a course.
10711:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10712:                 return HTTP_NOT_ACCEPTABLE;
10713:             }
10714:         } elsif (!%perm) {
10715:             $request->internal_redirect('/adm/quickgrades');
10716:         }
10717:         &Apache::loncommon::content_type($request,'text/html');
10718:         $request->send_http_header;
10719:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10720:             $request->print($start_page); 
10721:         }
10722: 	if ($command eq 'submission' && $perm{'vgr'}) {
10723:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10724:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10725:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10726:                     &choose_task_version_form($symb,$env{'form.student'},
10727:                                               $env{'form.userdom'});
10728:             }
10729:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10730:             if ($versionform) {
10731:                 $request->print($versionform);
10732:             }
10733:             $request->print('<br clear="all" />');
10734: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10735:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10736:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10737:                 &choose_task_version_form($symb,$env{'form.student'},
10738:                                           $env{'form.userdom'},
10739:                                           $env{'form.inhibitmenu'});
10740:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10741:             if ($versionform) {
10742:                 $request->print($versionform);
10743:             }
10744:             $request->print('<br clear="all" />');
10745:             $request->print(&show_previous_task_version($request,$symb));
10746: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10747: 	    &pickStudentPage($request);
10748: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10749: 	    &displayPage($request);
10750: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10751: 	    &updateGradeByPage($request);
10752: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10753: 	    &processGroup($request);
10754: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10755: 	    $request->print(&grading_menu($request));
10756: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10757: 	    $request->print(&submit_options($request));
10758: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10759: 	    $request->print(&viewgrades($request));
10760: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10761: 	    $request->print(&processHandGrade($request));
10762: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10763: 	    $request->print(&editgrades($request));
10764: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10765: 	    $request->print(&verifyreceipt($request));
10766:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10767:             $request->print(&process_clicker($request));
10768:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10769:             $request->print(&process_clicker_file($request));
10770:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10771:             $request->print(&assign_clicker_grades($request));
10772: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10773: 	    $request->print(&upcsvScores_form($request));
10774: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10775: 	    $request->print(&csvupload($request));
10776: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10777: 	    $request->print(&csvuploadmap($request));
10778: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10779: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10780: 		$request->print(&csvuploadoptions($request));
10781: 	    } else {
10782: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10783: 		    $env{'form.upfile_associate'} = 'reverse';
10784: 		} else {
10785: 		    $env{'form.upfile_associate'} = 'forward';
10786: 		}
10787: 		$request->print(&csvuploadmap($request));
10788: 	    }
10789: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10790: 	    $request->print(&csvuploadassign($request));
10791: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10792: 	    $request->print(&scantron_selectphase($request));
10793:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10794:  	    $request->print(&scantron_do_warning($request));
10795: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10796: 	    $request->print(&scantron_validate_file($request));
10797: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10798: 	    $request->print(&scantron_process_students($request));
10799:  	} elsif ($command eq 'scantronupload' && 
10800:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10801: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10802:  	    $request->print(&scantron_upload_scantron_data($request)); 
10803:  	} elsif ($command eq 'scantronupload_save' &&
10804:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10805: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10806:  	    $request->print(&scantron_upload_scantron_data_save($request));
10807:  	} elsif ($command eq 'scantron_download' &&
10808: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10809:  	    $request->print(&scantron_download_scantron_data($request));
10810:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10811:             $request->print(&checkscantron_results($request));     
10812: 	} elsif ($command) {
10813: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10814: 	}
10815:     }
10816:     if ($ssi_error) {
10817: 	&ssi_print_error($request);
10818:     }
10819:     $request->print(&Apache::loncommon::end_page());
10820:     &reset_caches();
10821:     return OK;
10822: }
10823: 
10824: 1;
10825: 
10826: __END__;
10827: 
10828: 
10829: =head1 NAME
10830: 
10831: Apache::grades
10832: 
10833: =head1 SYNOPSIS
10834: 
10835: Handles the viewing of grades.
10836: 
10837: This is part of the LearningOnline Network with CAPA project
10838: described at http://www.lon-capa.org.
10839: 
10840: =head1 OVERVIEW
10841: 
10842: Do an ssi with retries:
10843: While I'd love to factor out this with the vesrion in lonprintout,
10844: 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
10845: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10846: 
10847: At least the logic that drives this has been pulled out into loncommon.
10848: 
10849: 
10850: 
10851: ssi_with_retries - Does the server side include of a resource.
10852:                      if the ssi call returns an error we'll retry it up to
10853:                      the number of times requested by the caller.
10854:                      If we still have a problem, no text is appended to the
10855:                      output and we set some global variables.
10856:                      to indicate to the caller an SSI error occurred.  
10857:                      All of this is supposed to deal with the issues described
10858:                      in LON-CAPA BZ 5631 see:
10859:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10860:                      by informing the user that this happened.
10861: 
10862: Parameters:
10863:   resource   - The resource to include.  This is passed directly, without
10864:                interpretation to lonnet::ssi.
10865:   form       - The form hash parameters that guide the interpretation of the resource
10866:                
10867:   retries    - Number of retries allowed before giving up completely.
10868: Returns:
10869:   On success, returns the rendered resource identified by the resource parameter.
10870: Side Effects:
10871:   The following global variables can be set:
10872:    ssi_error                - If an unrecoverable error occurred this becomes true.
10873:                               It is up to the caller to initialize this to false
10874:                               if desired.
10875:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10876:                               of the resource that could not be rendered by the ssi
10877:                               call.
10878:    ssi_error_message   - The error string fetched from the ssi response
10879:                               in the event of an error.
10880: 
10881: 
10882: =head1 HANDLER SUBROUTINE
10883: 
10884: ssi_with_retries()
10885: 
10886: =head1 SUBROUTINES
10887: 
10888: =over
10889: 
10890: =item scantron_get_correction() : 
10891: 
10892:    Builds the interface screen to interact with the operator to fix a
10893:    specific error condition in a specific scanline
10894: 
10895:  Arguments:
10896:     $r           - Apache request object
10897:     $i           - number of the current scanline
10898:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10899:     $scan_config - hash ref as returned from &get_scantron_config()
10900:     $line        - full contents of the current scanline
10901:     $error       - error condition, valid values are
10902:                    'incorrectCODE', 'duplicateCODE',
10903:                    'doublebubble', 'missingbubble',
10904:                    'duplicateID', 'incorrectID'
10905:     $arg         - extra information needed
10906:        For errors:
10907:          - duplicateID   - paper number that this studentID was seen before on
10908:          - duplicateCODE - array ref of the paper numbers this CODE was
10909:                            seen on before
10910:          - incorrectCODE - current incorrect CODE 
10911:          - doublebubble  - array ref of the bubble lines that have double
10912:                            bubble errors
10913:          - missingbubble - array ref of the bubble lines that have missing
10914:                            bubble errors
10915: 
10916:    $randomorder - True if exam folder has randomorder set
10917:    $randompick  - True if exam folder has randompick set
10918:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10919:                      for current line to question number used for same question
10920:                      in "Master Seqence" (as seen by Course Coordinator).
10921:    $startline   - Reference to hash where key is question number (0 is first)
10922:                   and value is number of first bubble line for current student
10923:                   or code-based randompick and/or randomorder.
10924: 
10925: 
10926: =item  scantron_get_maxbubble() : 
10927: 
10928:    Arguments:
10929:        $nav_error  - Reference to scalar which is a flag to indicate a
10930:                       failure to retrieve a navmap object.
10931:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10932:        calling routine should trap the error condition and display the warning
10933:        found in &navmap_errormsg().
10934: 
10935:        $scantron_config - Reference to bubblesheet format configuration hash.
10936: 
10937:    Returns the maximum number of bubble lines that are expected to
10938:    occur. Does this by walking the selected sequence rendering the
10939:    resource and then checking &Apache::lonxml::get_problem_counter()
10940:    for what the current value of the problem counter is.
10941: 
10942:    Caches the results to $env{'form.scantron_maxbubble'},
10943:    $env{'form.scantron.bubble_lines.n'}, 
10944:    $env{'form.scantron.first_bubble_line.n'} and
10945:    $env{"form.scantron.sub_bubblelines.n"}
10946:    which are the total number of bubble lines, the number of bubble
10947:    lines for response n and number of the first bubble line for response n,
10948:    and a comma separated list of numbers of bubble lines for sub-questions
10949:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10950: 
10951: 
10952: =item  scantron_validate_missingbubbles() : 
10953: 
10954:    Validates all scanlines in the selected file to not have any
10955:     answers that don't have bubbles that have not been verified
10956:     to be bubble free.
10957: 
10958: =item  scantron_process_students() : 
10959: 
10960:    Routine that does the actual grading of the bubblesheet information.
10961: 
10962:    The parsed scanline hash is added to %env 
10963: 
10964:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10965:    foreach resource , with the form data of
10966: 
10967: 	'submitted'     =>'scantron' 
10968: 	'grade_target'  =>'grade',
10969: 	'grade_username'=> username of student
10970: 	'grade_domain'  => domain of student
10971: 	'grade_courseid'=> of course
10972: 	'grade_symb'    => symb of resource to grade
10973: 
10974:     This triggers a grading pass. The problem grading code takes care
10975:     of converting the bubbled letter information (now in %env) into a
10976:     valid submission.
10977: 
10978: =item  scantron_upload_scantron_data() :
10979: 
10980:     Creates the screen for adding a new bubblesheet data file to a course.
10981: 
10982: =item  scantron_upload_scantron_data_save() : 
10983: 
10984:    Adds a provided bubble information data file to the course if user
10985:    has the correct privileges to do so. 
10986: 
10987: =item  valid_file() :
10988: 
10989:    Validates that the requested bubble data file exists in the course.
10990: 
10991: =item  scantron_download_scantron_data() : 
10992: 
10993:    Shows a list of the three internal files (original, corrected,
10994:    skipped) for a specific bubblesheet data file that exists in the
10995:    course.
10996: 
10997: =item  scantron_validate_ID() : 
10998: 
10999:    Validates all scanlines in the selected file to not have any
11000:    invalid or underspecified student/employee IDs
11001: 
11002: =item navmap_errormsg() :
11003: 
11004:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11005:    Should be called whenever the request to instantiate a navmap object fails.  
11006: 
11007: =back
11008: 
11009: =cut

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