File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.36: download - view: text, annotated - select for diffs
Thu Aug 4 18:47:52 2016 UTC (7 years, 8 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  - Backport 1.736

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.36 2016/08/04 18:47:52 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::bridgetask();
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: my %old_essays=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: sub getpartlist {
  102:     my ($symb,$errorref) = @_;
  103: 
  104:     my $navmap   = Apache::lonnavmaps::navmap->new();
  105:     unless (ref($navmap)) {
  106:         if (ref($errorref)) { 
  107:             $$errorref = 'navmap';
  108:             return;
  109:         }
  110:     }
  111:     my $res      = $navmap->getBySymb($symb);
  112:     my $partlist = $res->parts();
  113:     my $url      = $res->src();
  114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  115: 
  116:     my @stores;
  117:     foreach my $part (@{ $partlist }) {
  118: 	foreach my $key (@metakeys) {
  119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  120: 	}
  121:     }
  122:     return @stores;
  123: }
  124: 
  125: # --- Get the symbolic name of a problem and the url
  126: sub get_symb {
  127:     my ($request,$silent) = @_;
  128:     my $symb=$env{'form.symb'};
  129:     unless ($symb) {
  130:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  131:         $symb = &Apache::lonnet::symbread($url);
  132:         if ($symb eq '') { 
  133: 	    if (!$silent) {
  134:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  135: 	        return ();
  136: 	    }
  137:         }
  138:     }
  139:     &Apache::lonenc::check_decrypt(\$symb);
  140:     return ($symb);
  141: }
  142: 
  143: #--- Format fullname, username:domain if different for display
  144: #--- Use anywhere where the student names are listed
  145: sub nameUserString {
  146:     my ($type,$fullname,$uname,$udom) = @_;
  147:     if ($type eq 'header') {
  148: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  149:     } else {
  150: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  151: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  152:     }
  153: }
  154: 
  155: #--- Get the partlist and the response type for a given problem. ---
  156: #--- Indicate if a response type is coded handgraded or not. ---
  157: sub response_type {
  158:     my ($symb,$response_error) = @_;
  159: 
  160:     my $navmap = Apache::lonnavmaps::navmap->new();
  161:     unless (ref($navmap)) {
  162:         if (ref($response_error)) {
  163:             $$response_error = 1;
  164:         }
  165:         return;
  166:     }
  167:     my $res = $navmap->getBySymb($symb);
  168:     unless (ref($res)) {
  169:         $$response_error = 1;
  170:         return;
  171:     }
  172:     my $partlist = $res->parts();
  173:     my %vPart = 
  174: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  175:     my (%response_types,%handgrade);
  176:     foreach my $part (@{ $partlist }) {
  177: 	next if (%vPart && !exists($vPart{$part}));
  178: 
  179: 	my @types = $res->responseType($part);
  180: 	my @ids = $res->responseIds($part);
  181: 	for (my $i=0; $i < scalar(@ids); $i++) {
  182: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  183: 	    $handgrade{$part.'_'.$ids[$i]} = 
  184: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  185: 				     '.handgrade',$symb);
  186: 	}
  187:     }
  188:     return ($partlist,\%handgrade,\%response_types);
  189: }
  190: 
  191: sub flatten_responseType {
  192:     my ($responseType) = @_;
  193:     my @part_response_id =
  194: 	map { 
  195: 	    my $part = $_;
  196: 	    map {
  197: 		[$part,$_]
  198: 		} sort(keys(%{ $responseType->{$part} }));
  199: 	} sort(keys(%$responseType));
  200:     return @part_response_id;
  201: }
  202: 
  203: sub get_display_part {
  204:     my ($partID,$symb)=@_;
  205:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  206:     if (defined($display) and $display ne '') {
  207:         $display.= ' (<span class="LC_internal_info">'
  208:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  209:     } else {
  210: 	$display=$partID;
  211:     }
  212:     return $display;
  213: }
  214: 
  215: #--- Show resource title
  216: #--- and parts and response type
  217: sub showResourceInfo {
  218:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  219:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  220:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  221:     if (ref($res_error)) {
  222:         if ($$res_error) {
  223:             return;
  224:         }
  225:     }
  226:     $result.=&Apache::loncommon::start_data_table()
  227:             .&Apache::loncommon::start_data_table_header_row();
  228:     if ($checkboxes) {
  229:         $result.='<th>&nbsp;</th>';
  230:     }
  231:     $result.='<th>'.&mt('Problem Part').'</th>'
  232:             .'<th>'.&mt('Res. ID').'</th>'
  233:             .'<th>'.&mt('Type').'</th>'
  234:             .&Apache::loncommon::end_data_table_header_row();
  235:     my %resptype = ();
  236:     my $hdgrade='no';
  237:     my %partsseen;
  238:     foreach my $partID (sort(keys(%$responseType))) {
  239:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  240:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  241:             my $responsetype = $responseType->{$partID}->{$resID};
  242:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  243:             $result.=&Apache::loncommon::start_data_table_row();
  244:             if ($checkboxes) {
  245:                 if (exists($partsseen{$partID})) {
  246:                     $result.="<td>&nbsp;</td>";
  247:                 } else {
  248:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  249:                 }
  250:                 $partsseen{$partID}=1;
  251:             }
  252:             my $display_part=&get_display_part($partID,$symb);
  253:             $result.='<td>'.$display_part.'</td>'
  254:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  255:                     .'<td>'.&mt($responsetype).'</td>'
  256: #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
  257:                     .&Apache::loncommon::end_data_table_row();
  258:         }
  259:     }
  260:     $result.=&Apache::loncommon::end_data_table();
  261:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  262: }
  263: 
  264: sub reset_caches {
  265:     &reset_analyze_cache();
  266:     &reset_perm();
  267:     &reset_old_essays();
  268: }
  269: 
  270: {
  271:     my %analyze_cache;
  272:     my %analyze_cache_formkeys;
  273: 
  274:     sub reset_analyze_cache {
  275: 	undef(%analyze_cache);
  276:         undef(%analyze_cache_formkeys);
  277:     }
  278: 
  279:     sub get_analyze {
  280: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  281: 	my $key = "$symb\0$uname\0$udom";
  282:         if ($type eq 'randomizetry') {
  283:             if ($trial ne '') {
  284:                 $key .= "\0".$trial;
  285:             }
  286:         }
  287: 	if (exists($analyze_cache{$key})) {
  288:             my $getupdate = 0;
  289:             if (ref($add_to_hash) eq 'HASH') {
  290:                 foreach my $item (keys(%{$add_to_hash})) {
  291:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  292:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  293:                             $getupdate = 1;
  294:                             last;
  295:                         }
  296:                     } else {
  297:                         $getupdate = 1;
  298:                     }
  299:                 }
  300:             }
  301:             if (!$getupdate) {
  302:                 return $analyze_cache{$key};
  303:             }
  304:         }
  305: 
  306: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  307: 	$url=&Apache::lonnet::clutter($url);
  308:         my %form = ('grade_target'      => 'analyze',
  309:                     'grade_domain'      => $udom,
  310:                     'grade_symb'        => $symb,
  311:                     'grade_courseid'    =>  $env{'request.course.id'},
  312:                     'grade_username'    => $uname,
  313:                     'grade_noincrement' => $no_increment);
  314:         if ($bubbles_per_row ne '') {
  315:             $form{'bubbles_per_row'} = $bubbles_per_row;
  316:         }
  317:         if ($type eq 'randomizetry') {
  318:             $form{'grade_questiontype'} = $type;
  319:             if ($rndseed ne '') {
  320:                 $form{'grade_rndseed'} = $rndseed;
  321:             }
  322:         }
  323:         if (ref($add_to_hash)) {
  324:             %form = (%form,%{$add_to_hash});
  325:         }
  326: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  327: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  328: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  329:         if (ref($add_to_hash) eq 'HASH') {
  330:             $analyze_cache_formkeys{$key} = $add_to_hash;
  331:         } else {
  332:             $analyze_cache_formkeys{$key} = {};
  333:         }
  334: 	return $analyze_cache{$key} = \%analyze;
  335:     }
  336: 
  337:     sub get_order {
  338: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  339: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  340: 	return $analyze->{"$partid.$respid.shown"};
  341:     }
  342: 
  343:     sub get_radiobutton_correct_foil {
  344: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  345: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  346:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  347:         if (ref($foils) eq 'ARRAY') {
  348: 	    foreach my $foil (@{$foils}) {
  349: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  350: 		    return $foil;
  351: 	        }
  352: 	    }
  353: 	}
  354:     }
  355: 
  356:     sub scantron_partids_tograde {
  357:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  358:         my (%analysis,@parts);
  359:         if (ref($resource)) {
  360:             my $symb = $resource->symb();
  361:             my $add_to_form;
  362:             if ($check_for_randomlist) {
  363:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  364:             }
  365:             my $analyze =
  366:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  367:                              undef,undef,undef,$bubbles_per_row);
  368:             if (ref($analyze) eq 'HASH') {
  369:                 %analysis = %{$analyze};
  370:             }
  371:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  372:                 foreach my $part (@{$analysis{'parts'}}) {
  373:                     my ($id,$respid) = split(/\./,$part);
  374:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  375:                         push(@parts,$part);
  376:                     }
  377:                 }
  378:             }
  379:         }
  380:         return (\%analysis,\@parts);
  381:     }
  382: 
  383: }
  384: 
  385: #--- Clean response type for display
  386: #--- Currently filters option/rank/radiobutton/match/essay/Task
  387: #        response types only.
  388: sub cleanRecord {
  389:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  390: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  391:     my $grayFont = '<span class="LC_internal_info">';
  392:     if ($response =~ /^(option|rank)$/) {
  393: 	my %answer=&Apache::lonnet::str2hash($answer);
  394:         my @answer = %answer;
  395:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  396: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  397: 	my ($toprow,$bottomrow);
  398: 	foreach my $foil (@$order) {
  399: 	    if ($grading{$foil} == 1) {
  400: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  401: 	    } else {
  402: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  403: 	    }
  404: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  405: 	}
  406: 	return '<blockquote><table border="1">'.
  407: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  408: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  409: 	    $bottomrow.'</tr></table></blockquote>';
  410:     } elsif ($response eq 'match') {
  411: 	my %answer=&Apache::lonnet::str2hash($answer);
  412:         my @answer = %answer;
  413:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  414: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  415: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  416: 	my ($toprow,$middlerow,$bottomrow);
  417: 	foreach my $foil (@$order) {
  418: 	    my $item=shift(@items);
  419: 	    if ($grading{$foil} == 1) {
  420: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  421: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  422: 	    } else {
  423: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  424: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  425: 	    }
  426: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  427: 	}
  428: 	return '<blockquote><table border="1">'.
  429: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  430: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  431: 	    $middlerow.'</tr>'.
  432: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  433: 	    $bottomrow.'</tr></table></blockquote>';
  434:     } elsif ($response eq 'radiobutton') {
  435: 	my %answer=&Apache::lonnet::str2hash($answer);
  436: 	my ($toprow,$bottomrow);
  437: 	my $correct = 
  438: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  439: 	foreach my $foil (@$order) {
  440: 	    if (exists($answer{$foil})) {
  441: 		if ($foil eq $correct) {
  442: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  443: 		} else {
  444: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  445: 		}
  446: 	    } else {
  447: 		$toprow.='<td>'.&mt('false').'</td>';
  448: 	    }
  449: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  450: 	}
  451: 	return '<blockquote><table border="1">'.
  452: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  453: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  454: 	    $bottomrow.'</tr></table></blockquote>';
  455:     } elsif ($response eq 'essay') {
  456: 	if (! exists ($env{'form.'.$symb})) {
  457: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  458: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  459: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  460: 
  461: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  462: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  463: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  464: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  465: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  466: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  467: 	}
  468: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  469:     } elsif ( $response eq 'organic') {
  470:         my $result=&mt('Smile representation: [_1]',
  471:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  472: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  473: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  474: 	return $result;
  475:     } elsif ( $response eq 'Task') {
  476: 	if ( $answer eq 'SUBMITTED') {
  477: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  478: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  479: 	    return $result;
  480: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  481: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  482: 			       keys(%{$record}));
  483: 	    return join('<br />',($version,@matches));
  484: 			       
  485: 			       
  486: 	} else {
  487: 	    my $result =
  488: 		'<p>'
  489: 		.&mt('Overall result: [_1]',
  490: 		     $record->{$version."resource.$respid.$partid.status"})
  491: 		.'</p>';
  492: 	    
  493: 	    $result .= '<ul>';
  494: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  495: 			     keys(%{$record}));
  496: 	    foreach my $grade (sort(@grade)) {
  497: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  498: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  499: 				     $dim, $record->{$grade}).
  500: 			  '</li>';
  501: 	    }
  502: 	    $result.='</ul>';
  503: 	    return $result;
  504: 	}
  505:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  506:         # Respect multiple input fields, see Bug #5409 
  507: 	$answer = 
  508: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  509: 							      $answer);
  510:         return $answer;
  511:     }
  512:     return &HTML::Entities::encode($answer, '"<>&');
  513: }
  514: 
  515: #-- A couple of common js functions
  516: sub commonJSfunctions {
  517:     my $request = shift;
  518:     $request->print(<<COMMONJSFUNCTIONS);
  519: <script type="text/javascript" language="javascript">
  520:     function radioSelection(radioButton) {
  521: 	var selection=null;
  522: 	if (radioButton.length > 1) {
  523: 	    for (var i=0; i<radioButton.length; i++) {
  524: 		if (radioButton[i].checked) {
  525: 		    return radioButton[i].value;
  526: 		}
  527: 	    }
  528: 	} else {
  529: 	    if (radioButton.checked) return radioButton.value;
  530: 	}
  531: 	return selection;
  532:     }
  533: 
  534:     function pullDownSelection(selectOne) {
  535: 	var selection="";
  536: 	if (selectOne.length > 1) {
  537: 	    for (var i=0; i<selectOne.length; i++) {
  538: 		if (selectOne[i].selected) {
  539: 		    return selectOne[i].value;
  540: 		}
  541: 	    }
  542: 	} else {
  543:             // only one value it must be the selected one
  544: 	    return selectOne.value;
  545: 	}
  546:     }
  547: </script>
  548: COMMONJSFUNCTIONS
  549: }
  550: 
  551: #--- Dumps the class list with usernames,list of sections,
  552: #--- section, ids and fullnames for each user.
  553: sub getclasslist {
  554:     my ($getsec,$filterlist,$getgroup) = @_;
  555:     my @getsec;
  556:     my @getgroup;
  557:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  558:     if (!ref($getsec)) {
  559: 	if ($getsec ne '' && $getsec ne 'all') {
  560: 	    @getsec=($getsec);
  561: 	}
  562:     } else {
  563: 	@getsec=@{$getsec};
  564:     }
  565:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  566:     if (!ref($getgroup)) {
  567: 	if ($getgroup ne '' && $getgroup ne 'all') {
  568: 	    @getgroup=($getgroup);
  569: 	}
  570:     } else {
  571: 	@getgroup=@{$getgroup};
  572:     }
  573:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  574: 
  575:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  576:     # Bail out if we were unable to get the classlist
  577:     return if (! defined($classlist));
  578:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  579:     #
  580:     my %sections;
  581:     my %fullnames;
  582:     foreach my $student (keys(%$classlist)) {
  583:         my $end      = 
  584:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  585:         my $start    = 
  586:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  587:         my $id       = 
  588:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  589:         my $section  = 
  590:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  591:         my $fullname = 
  592:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  593:         my $status   = 
  594:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  595:         my $group   = 
  596:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  597: 	# filter students according to status selected
  598: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  599: 	    if (!($stu_status =~ $status)) {
  600: 		delete($classlist->{$student});
  601: 		next;
  602: 	    }
  603: 	}
  604: 	# filter students according to groups selected
  605: 	my @stu_groups = split(/,/,$group);
  606: 	if (@getgroup) {
  607: 	    my $exclude = 1;
  608: 	    foreach my $grp (@getgroup) {
  609: 	        foreach my $stu_group (@stu_groups) {
  610: 	            if ($stu_group eq $grp) {
  611: 	                $exclude = 0;
  612:     	            } 
  613: 	        }
  614:     	        if (($grp eq 'none') && !$group) {
  615:         	        $exclude = 0;
  616:         	}
  617: 	    }
  618: 	    if ($exclude) {
  619: 	        delete($classlist->{$student});
  620: 	    }
  621: 	}
  622: 	$section = ($section ne '' ? $section : 'none');
  623: 	if (&canview($section)) {
  624: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  625: 		$sections{$section}++;
  626: 		if ($classlist->{$student}) {
  627: 		    $fullnames{$student}=$fullname;
  628: 		}
  629: 	    } else {
  630: 		delete($classlist->{$student});
  631: 	    }
  632: 	} else {
  633: 	    delete($classlist->{$student});
  634: 	}
  635:     }
  636:     my %seen = ();
  637:     my @sections = sort(keys(%sections));
  638:     return ($classlist,\@sections,\%fullnames);
  639: }
  640: 
  641: sub canmodify {
  642:     my ($sec)=@_;
  643:     if ($perm{'mgr'}) {
  644: 	if (!defined($perm{'mgr_section'})) {
  645: 	    # can modify whole class
  646: 	    return 1;
  647: 	} else {
  648: 	    if ($sec eq $perm{'mgr_section'}) {
  649: 		#can modify the requested section
  650: 		return 1;
  651: 	    } else {
  652: 		# can't modify the request section
  653: 		return 0;
  654: 	    }
  655: 	}
  656:     }
  657:     #can't modify
  658:     return 0;
  659: }
  660: 
  661: sub canview {
  662:     my ($sec)=@_;
  663:     if ($perm{'vgr'}) {
  664: 	if (!defined($perm{'vgr_section'})) {
  665: 	    # can modify whole class
  666: 	    return 1;
  667: 	} else {
  668: 	    if ($sec eq $perm{'vgr_section'}) {
  669: 		#can modify the requested section
  670: 		return 1;
  671: 	    } else {
  672: 		# can't modify the request section
  673: 		return 0;
  674: 	    }
  675: 	}
  676:     }
  677:     #can't modify
  678:     return 0;
  679: }
  680: 
  681: #--- Retrieve the grade status of a student for all the parts
  682: sub student_gradeStatus {
  683:     my ($symb,$udom,$uname,$partlist) = @_;
  684:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  685:     my %partstatus = ();
  686:     foreach (@$partlist) {
  687: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  688: 	$status              = 'nothing' if ($status eq '');
  689: 	$partstatus{$_}      = $status;
  690: 	my $subkey           = "resource.$_.submitted_by";
  691: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  692:     }
  693:     return %partstatus;
  694: }
  695: 
  696: # hidden form and javascript that calls the form
  697: # Use by verifyscript and viewgrades
  698: # Shows a student's view of problem and submission
  699: sub jscriptNform {
  700:     my ($symb) = @_;
  701:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  702:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  703: 	'    function viewOneStudent(user,domain) {'."\n".
  704: 	'	document.onestudent.student.value = user;'."\n".
  705: 	'	document.onestudent.userdom.value = domain;'."\n".
  706: 	'	document.onestudent.submit();'."\n".
  707: 	'    }'."\n".
  708: 	'</script>'."\n";
  709:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  710: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  711: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  712: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  713: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  714: 	'<input type="hidden" name="command" value="submission" />'."\n".
  715: 	'<input type="hidden" name="student" value="" />'."\n".
  716: 	'<input type="hidden" name="userdom" value="" />'."\n".
  717: 	'</form>'."\n";
  718:     return $jscript;
  719: }
  720: 
  721: 
  722: 
  723: # Given the score (as a number [0-1] and the weight) what is the final
  724: # point value? This function will round to the nearest tenth, third,
  725: # or quarter if one of those is within the tolerance of .00001.
  726: sub compute_points {
  727:     my ($score, $weight) = @_;
  728:     
  729:     my $tolerance = .00001;
  730:     my $points = $score * $weight;
  731: 
  732:     # Check for nearness to 1/x.
  733:     my $check_for_nearness = sub {
  734:         my ($factor) = @_;
  735:         my $num = ($points * $factor) + $tolerance;
  736:         my $floored_num = floor($num);
  737:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  738:             return $floored_num / $factor;
  739:         }
  740:         return $points;
  741:     };
  742: 
  743:     $points = $check_for_nearness->(10);
  744:     $points = $check_for_nearness->(3);
  745:     $points = $check_for_nearness->(4);
  746:     
  747:     return $points;
  748: }
  749: 
  750: #------------------ End of general use routines --------------------
  751: 
  752: #
  753: # Find most similar essay
  754: #
  755: 
  756: sub most_similar {
  757:     my ($uname,$udom,$symb,$uessay)=@_;
  758: 
  759:     unless ($symb) { return ''; }
  760: 
  761:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  762: 
  763: # ignore spaces and punctuation
  764: 
  765:     $uessay=~s/\W+/ /gs;
  766: 
  767: # ignore empty submissions (occuring when only files are sent)
  768: 
  769:     unless ($uessay=~/\w+/s) { return ''; }
  770: 
  771: # these will be returned. Do not care if not at least 50 percent similar
  772:     my $limit=0.6;
  773:     my $sname='';
  774:     my $sdom='';
  775:     my $scrsid='';
  776:     my $sessay='';
  777: # go through all essays ...
  778:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  779: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  780: # ... except the same student
  781:         next if (($tname eq $uname) && ($tdom eq $udom));
  782: 	my $tessay=$old_essays{$symb}{$tkey};
  783: 	$tessay=~s/\W+/ /gs;
  784: # String similarity gives up if not even limit
  785: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  786: # Found one
  787: 	if ($tsimilar>$limit) {
  788: 	    $limit=$tsimilar;
  789: 	    $sname=$tname;
  790: 	    $sdom=$tdom;
  791: 	    $scrsid=$tcrsid;
  792: 	    $sessay=$old_essays{$symb}{$tkey};
  793: 	}
  794:     }
  795:     if ($limit>0.6) {
  796:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  797:     } else {
  798:        return ('','','','',0);
  799:     }
  800: }
  801: 
  802: #-------------------------------------------------------------------
  803: 
  804: #------------------------------------ Receipt Verification Routines
  805: #
  806: #--- Check whether a receipt number is valid.---
  807: sub verifyreceipt {
  808:     my $request  = shift;
  809: 
  810:     my $courseid = $env{'request.course.id'};
  811:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  812: 	$env{'form.receipt'};
  813:     $receipt     =~ s/[^\-\d]//g;
  814:     my ($symb)   = &get_symb($request);
  815: 
  816:     my $title.=
  817: 	'<h3><span class="LC_info">'.
  818: 	&mt('Verifying Receipt No. [_1]',$receipt).
  819: 	'</span></h3>'."\n".
  820: 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
  821: 	'</h4>'."\n";
  822: 
  823:     my ($string,$contents,$matches) = ('','',0);
  824:     my (undef,undef,$fullname) = &getclasslist('all','0');
  825:     
  826:     my $receiptparts=0;
  827:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  828: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  829:     my $parts=['0'];
  830:     if ($receiptparts) {
  831:         my $res_error; 
  832:         ($parts)=&response_type($symb,\$res_error);
  833:         if ($res_error) {
  834:             return &navmap_errormsg();
  835:         } 
  836:     }
  837:     
  838:     my $header = 
  839: 	&Apache::loncommon::start_data_table().
  840: 	&Apache::loncommon::start_data_table_header_row().
  841: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  842: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  843: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  844:     if ($receiptparts) {
  845: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  846:     }
  847:     $header.=
  848: 	&Apache::loncommon::end_data_table_header_row();
  849: 
  850:     foreach (sort 
  851: 	     {
  852: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  853: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  854: 		 }
  855: 		 return $a cmp $b;
  856: 	     } (keys(%$fullname))) {
  857: 	my ($uname,$udom)=split(/\:/);
  858: 	foreach my $part (@$parts) {
  859: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  860: 		$contents.=
  861: 		    &Apache::loncommon::start_data_table_row().
  862: 		    '<td>&nbsp;'."\n".
  863: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  864: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  865: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  866: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  867: 		if ($receiptparts) {
  868: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  869: 		}
  870: 		$contents.= 
  871: 		    &Apache::loncommon::end_data_table_row()."\n";
  872: 		
  873: 		$matches++;
  874: 	    }
  875: 	}
  876:     }
  877:     if ($matches == 0) {
  878:         $string = $title
  879:                  .'<p class="LC_warning">'
  880:                  .&mt('No match found for the above receipt number.')
  881:                  .'</p>';
  882:     } else {
  883: 	$string = &jscriptNform($symb).$title.
  884: 	    '<p>'.
  885: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  886: 	    '</p>'.
  887: 	    $header.
  888: 	    $contents.
  889: 	    &Apache::loncommon::end_data_table()."\n";
  890:     }
  891:     return $string.&show_grading_menu_form($symb);
  892: }
  893: 
  894: #--- This is called by a number of programs.
  895: #--- Called from the Grading Menu - View/Grade an individual student
  896: #--- Also called directly when one clicks on the subm button 
  897: #    on the problem page.
  898: sub listStudents {
  899:     my ($request) = shift;
  900: 
  901:     my ($symb) = &get_symb($request);
  902:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  903:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  904:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  905:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  906:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  907:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  908:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  909: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  910: 
  911:     my $result='<h3><span class="LC_info">&nbsp;'
  912: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  913: 	.'</span></h3>';
  914: 
  915:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  916: 
  917:     my %js_lt = &Apache::lonlocal::texthash (
  918: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  919: 		'single'   => 'Please select the student before clicking on the Next button.',
  920: 	     );
  921:     &js_escape(\%js_lt);
  922:     $request->print(<<LISTJAVASCRIPT);
  923: <script type="text/javascript" language="javascript">
  924:     function checkSelect(checkBox) {
  925: 	var ctr=0;
  926: 	var sense="";
  927: 	if (checkBox.length > 1) {
  928: 	    for (var i=0; i<checkBox.length; i++) {
  929: 		if (checkBox[i].checked) {
  930: 		    ctr++;
  931: 		}
  932: 	    }
  933: 	    sense = '$js_lt{'multiple'}';
  934: 	} else {
  935: 	    if (checkBox.checked) {
  936: 		ctr = 1;
  937: 	    }
  938: 	    sense = '$js_lt{'single'}';
  939: 	}
  940: 	if (ctr == 0) {
  941: 	    alert(sense);
  942: 	    return false;
  943: 	}
  944: 	document.gradesub.submit();
  945:     }
  946: 
  947:     function reLoadList(formname) {
  948: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  949: 	formname.command.value = 'submission';
  950: 	formname.submit();
  951:     }
  952: </script>
  953: LISTJAVASCRIPT
  954: 
  955:     &commonJSfunctions($request);
  956:     $request->print($result);
  957: 
  958:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  959:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  960:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  961: 	"\n".$table;
  962: 	
  963:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  964:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  965:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  966:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  967:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  968:                   .&Apache::lonhtmlcommon::row_closure();
  969:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  970:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  971:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  972:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  973:                   .&Apache::lonhtmlcommon::row_closure();
  974: 
  975:     my $submission_options;
  976:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  977: 	$submission_options.=
  978: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  979:     }
  980:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  981:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  982:     $env{'form.Status'} = $saveStatus;
  983:     $submission_options.=
  984:         '<span class="LC_nobreak">'.
  985:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  986:         &mt('last submission only').' </label></span>'."\n".
  987:         '<span class="LC_nobreak">'.
  988:         '<label><input type="radio" name="lastSub" value="last" /> '.
  989:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  990:         '<span class="LC_nobreak">'.
  991:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  992:         &mt('by dates and submissions').'</label></span>'."\n".
  993:         '<span class="LC_nobreak">'.
  994:         '<label><input type="radio" name="lastSub" value="all" /> '.
  995:         &mt('all details').'</label></span>';
  996:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  997:                   .$submission_options
  998:                   .&Apache::lonhtmlcommon::row_closure();
  999: 
 1000:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1001:                   .'<select name="increment">'
 1002:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1003:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1004:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1005:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1006:                   .'</select>'
 1007:                   .&Apache::lonhtmlcommon::row_closure();
 1008: 
 1009:     $gradeTable .= 
 1010:         &build_section_inputs().
 1011: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1012: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1013: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1014: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1015: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1016: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1017: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1018: 
 1019:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1020: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1021:     } else {
 1022:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1023:                       .&Apache::lonhtmlcommon::StatusOptions(
 1024:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1025:                       .&Apache::lonhtmlcommon::row_closure();
 1026:     }
 1027: 
 1028:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1029:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1030:                   .&Apache::lonhtmlcommon::row_closure(1)
 1031:                   .&Apache::lonhtmlcommon::end_pick_box();
 1032: 
 1033:     $gradeTable .= '<p>'
 1034:                   .&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"
 1035:                   .'<input type="hidden" name="command" value="processGroup" />'
 1036:                   .'</p>';
 1037: 
 1038: # checkall buttons
 1039:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1040:     $gradeTable.='<input type="button" '."\n".
 1041:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1042:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1043:     $gradeTable.=&check_buttons();
 1044:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1045:     $gradeTable.= &Apache::loncommon::start_data_table().
 1046: 	&Apache::loncommon::start_data_table_header_row();
 1047:     my $loop = 0;
 1048:     while ($loop < 2) {
 1049: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1050: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1051: 	if ($env{'form.showgrading'} eq 'yes' 
 1052: 	    && $submitonly ne 'queued'
 1053: 	    && $submitonly ne 'all') {
 1054: 	    foreach my $part (sort(@$partlist)) {
 1055: 		my $display_part=
 1056: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1057: 		$gradeTable.=
 1058: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1059: 	    }
 1060: 	} elsif ($submitonly eq 'queued') {
 1061: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1062: 	}
 1063: 	$loop++;
 1064: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1065:     }
 1066:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1067: 
 1068:     my $ctr = 0;
 1069:     foreach my $student (sort 
 1070: 			 {
 1071: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1072: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1073: 			     }
 1074: 			     return $a cmp $b;
 1075: 			 }
 1076: 			 (keys(%$fullname))) {
 1077: 	my ($uname,$udom) = split(/:/,$student);
 1078: 
 1079: 	my %status = ();
 1080: 
 1081: 	if ($submitonly eq 'queued') {
 1082: 	    my %queue_status = 
 1083: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1084: 							$udom,$uname);
 1085: 	    next if (!defined($queue_status{'gradingqueue'}));
 1086: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1087: 	}
 1088: 
 1089: 	if ($env{'form.showgrading'} eq 'yes' 
 1090: 	    && $submitonly ne 'queued'
 1091: 	    && $submitonly ne 'all') {
 1092: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1093: 	    my $submitted = 0;
 1094: 	    my $graded = 0;
 1095: 	    my $incorrect = 0;
 1096: 	    foreach (keys(%status)) {
 1097: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1098: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1099: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1100: 		
 1101: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1102: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1103: 		    $submitted = 0;
 1104: 		    my ($part)=split(/\./,$partid);
 1105: 		    $gradeTable.='<input type="hidden" name="'.
 1106: 			$student.':'.$part.':submitted_by" value="'.
 1107: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1108: 		}
 1109: 	    }
 1110: 	    
 1111: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1112: 				     $submitonly eq 'incorrect' ||
 1113: 				     $submitonly eq 'graded'));
 1114: 	    next if (!$graded && ($submitonly eq 'graded'));
 1115: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1116: 	}
 1117: 
 1118: 	$ctr++;
 1119: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1120:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1121: 	if ( $perm{'vgr'} eq 'F' ) {
 1122: 	    if ($ctr%2 ==1) {
 1123: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1124: 	    }
 1125: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1126:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1127:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1128: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1129: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1130: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1131: 
 1132: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1133: 		foreach (sort(keys(%status))) {
 1134: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1135: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1136: 		}
 1137: 	    }
 1138: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1139: 	    if ($ctr%2 ==0) {
 1140: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1141: 	    }
 1142: 	}
 1143:     }
 1144:     if ($ctr%2 ==1) {
 1145: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1146: 	    if ($env{'form.showgrading'} eq 'yes' 
 1147: 		&& $submitonly ne 'queued'
 1148: 		&& $submitonly ne 'all') {
 1149: 		foreach (@$partlist) {
 1150: 		    $gradeTable.='<td>&nbsp;</td>';
 1151: 		}
 1152: 	    } elsif ($submitonly eq 'queued') {
 1153: 		$gradeTable.='<td>&nbsp;</td>';
 1154: 	    }
 1155: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1156:     }
 1157: 
 1158:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1159:         '<input type="button" '.
 1160:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1161:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1162:     if ($ctr == 0) {
 1163: 	my $num_students=(scalar(keys(%$fullname)));
 1164: 	if ($num_students eq 0) {
 1165: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1166: 	} else {
 1167: 	    my $submissions='submissions';
 1168: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1169: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1170: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1171: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1172: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1173: 		    $num_students).
 1174: 		'</span><br />';
 1175: 	}
 1176:     } elsif ($ctr == 1) {
 1177: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1178:     }
 1179:     $gradeTable.=&show_grading_menu_form($symb);
 1180:     $request->print($gradeTable);
 1181:     return '';
 1182: }
 1183: 
 1184: #---- Called from the listStudents routine
 1185: 
 1186: sub check_script {
 1187:     my ($form, $type)=@_;
 1188:     my $chkallscript='<script type="text/javascript">
 1189:     function checkall() {
 1190:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1191:             ele = document.forms.'.$form.'.elements[i];
 1192:             if (ele.name == "'.$type.'") {
 1193:             document.forms.'.$form.'.elements[i].checked=true;
 1194:                                        }
 1195:         }
 1196:     }
 1197: 
 1198:     function checksec() {
 1199:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1200:             ele = document.forms.'.$form.'.elements[i];
 1201:            string = document.forms.'.$form.'.chksec.value;
 1202:            if
 1203:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1204:               document.forms.'.$form.'.elements[i].checked=true;
 1205:             }
 1206:         }
 1207:     }
 1208: 
 1209: 
 1210:     function uncheckall() {
 1211:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1212:             ele = document.forms.'.$form.'.elements[i];
 1213:             if (ele.name == "'.$type.'") {
 1214:             document.forms.'.$form.'.elements[i].checked=false;
 1215:                                        }
 1216:         }
 1217:     }
 1218: 
 1219: </script>'."\n";
 1220:     return $chkallscript;
 1221: }
 1222: 
 1223: sub check_buttons {
 1224:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1225:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1226:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1227:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1228:     return $buttons;
 1229: }
 1230: 
 1231: #     Displays the submissions for one student or a group of students
 1232: sub processGroup {
 1233:     my ($request)  = shift;
 1234:     my $ctr        = 0;
 1235:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1236:     my $total      = scalar(@stuchecked)-1;
 1237: 
 1238:     foreach my $student (@stuchecked) {
 1239: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1240: 	$env{'form.student'}        = $uname;
 1241: 	$env{'form.userdom'}        = $udom;
 1242: 	$env{'form.fullname'}       = $fullname;
 1243: 	&submission($request,$ctr,$total);
 1244: 	$ctr++;
 1245:     }
 1246:     return '';
 1247: }
 1248: 
 1249: #------------------------------------------------------------------------------------
 1250: #
 1251: #-------------------------- Next few routines handles grading by student, essentially
 1252: #                           handles essay response type problem/part
 1253: #
 1254: #--- Javascript to handle the submission page functionality ---
 1255: sub sub_page_js {
 1256:     my $request = shift;
 1257:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1258:     &js_escape(\$alertmsg); 
 1259:     $request->print(<<SUBJAVASCRIPT);
 1260: <script type="text/javascript" language="javascript">
 1261:     function updateRadio(formname,id,weight) {
 1262: 	var gradeBox = formname["GD_BOX"+id];
 1263: 	var radioButton = formname["RADVAL"+id];
 1264: 	var oldpts = formname["oldpts"+id].value;
 1265: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1266: 	gradeBox.value = pts;
 1267: 	var resetbox = false;
 1268: 	if (isNaN(pts) || pts < 0) {
 1269: 	    alert("$alertmsg"+pts);
 1270: 	    for (var i=0; i<radioButton.length; i++) {
 1271: 		if (radioButton[i].checked) {
 1272: 		    gradeBox.value = i;
 1273: 		    resetbox = true;
 1274: 		}
 1275: 	    }
 1276: 	    if (!resetbox) {
 1277: 		formtextbox.value = "";
 1278: 	    }
 1279: 	    return;
 1280: 	}
 1281: 
 1282: 	if (pts > weight) {
 1283: 	    var resp = confirm("You entered a value ("+pts+
 1284: 			       ") greater than the weight for the part. Accept?");
 1285: 	    if (resp == false) {
 1286: 		gradeBox.value = oldpts;
 1287: 		return;
 1288: 	    }
 1289: 	}
 1290: 
 1291: 	for (var i=0; i<radioButton.length; i++) {
 1292: 	    radioButton[i].checked=false;
 1293: 	    if (pts == i && pts != "") {
 1294: 		radioButton[i].checked=true;
 1295: 	    }
 1296: 	}
 1297: 	updateSelect(formname,id);
 1298: 	formname["stores"+id].value = "0";
 1299:     }
 1300: 
 1301:     function writeBox(formname,id,pts) {
 1302: 	var gradeBox = formname["GD_BOX"+id];
 1303: 	if (checkSolved(formname,id) == 'update') {
 1304: 	    gradeBox.value = pts;
 1305: 	} else {
 1306: 	    var oldpts = formname["oldpts"+id].value;
 1307: 	    gradeBox.value = oldpts;
 1308: 	    var radioButton = formname["RADVAL"+id];
 1309: 	    for (var i=0; i<radioButton.length; i++) {
 1310: 		radioButton[i].checked=false;
 1311: 		if (i == oldpts) {
 1312: 		    radioButton[i].checked=true;
 1313: 		}
 1314: 	    }
 1315: 	}
 1316: 	formname["stores"+id].value = "0";
 1317: 	updateSelect(formname,id);
 1318: 	return;
 1319:     }
 1320: 
 1321:     function clearRadBox(formname,id) {
 1322: 	if (checkSolved(formname,id) == 'noupdate') {
 1323: 	    updateSelect(formname,id);
 1324: 	    return;
 1325: 	}
 1326: 	gradeSelect = formname["GD_SEL"+id];
 1327: 	for (var i=0; i<gradeSelect.length; i++) {
 1328: 	    if (gradeSelect[i].selected) {
 1329: 		var selectx=i;
 1330: 	    }
 1331: 	}
 1332: 	var stores = formname["stores"+id];
 1333: 	if (selectx == stores.value) { return };
 1334: 	var gradeBox = formname["GD_BOX"+id];
 1335: 	gradeBox.value = "";
 1336: 	var radioButton = formname["RADVAL"+id];
 1337: 	for (var i=0; i<radioButton.length; i++) {
 1338: 	    radioButton[i].checked=false;
 1339: 	}
 1340: 	stores.value = selectx;
 1341:     }
 1342: 
 1343:     function checkSolved(formname,id) {
 1344: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1345: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1346: 	    if (!reply) {return "noupdate";}
 1347: 	    formname.overRideScore.value = 'yes';
 1348: 	}
 1349: 	return "update";
 1350:     }
 1351: 
 1352:     function updateSelect(formname,id) {
 1353: 	formname["GD_SEL"+id][0].selected = true;
 1354: 	return;
 1355:     }
 1356: 
 1357: //=========== Check that a point is assigned for all the parts  ============
 1358:     function checksubmit(formname,val,total,parttot) {
 1359: 	formname.gradeOpt.value = val;
 1360: 	if (val == "Save & Next") {
 1361: 	    for (i=0;i<=total;i++) {
 1362: 		for (j=0;j<parttot;j++) {
 1363: 		    var partid = formname["partid"+i+"_"+j].value;
 1364: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1365: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1366: 			if (points == "") {
 1367: 			    var name = formname["name"+i].value;
 1368: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1369: 			    var resp = confirm("You did not assign a score for "+studentID+
 1370: 					       ", part "+partid+". Continue?");
 1371: 			    if (resp == false) {
 1372: 				formname["GD_BOX"+i+"_"+partid].focus();
 1373: 				return false;
 1374: 			    }
 1375: 			}
 1376: 		    }
 1377: 		}
 1378: 	    }
 1379: 	}
 1380: 	if (val == "Grade Student") {
 1381: 	    formname.showgrading.value = "yes";
 1382: 	    if (formname.Status.value == "") {
 1383: 		formname.Status.value = "Active";
 1384: 	    }
 1385: 	    formname.studentNo.value = total;
 1386: 	}
 1387: 	formname.submit();
 1388:     }
 1389: 
 1390: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1391:     function checkSubmitPage(formname,total) {
 1392: 	noscore = new Array(100);
 1393: 	var ptr = 0;
 1394: 	for (i=1;i<total;i++) {
 1395: 	    var partid = formname["q_"+i].value;
 1396: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1397: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1398: 		var status = formname["solved"+i+"_"+partid].value;
 1399: 		if (points == "" && status != "correct_by_student") {
 1400: 		    noscore[ptr] = i;
 1401: 		    ptr++;
 1402: 		}
 1403: 	    }
 1404: 	}
 1405: 	if (ptr != 0) {
 1406: 	    var sense = ptr == 1 ? ": " : "s: ";
 1407: 	    var prolist = "";
 1408: 	    if (ptr == 1) {
 1409: 		prolist = noscore[0];
 1410: 	    } else {
 1411: 		var i = 0;
 1412: 		while (i < ptr-1) {
 1413: 		    prolist += noscore[i]+", ";
 1414: 		    i++;
 1415: 		}
 1416: 		prolist += "and "+noscore[i];
 1417: 	    }
 1418: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1419: 	    if (resp == false) {
 1420: 		return false;
 1421: 	    }
 1422: 	}
 1423: 
 1424: 	formname.submit();
 1425:     }
 1426: </script>
 1427: SUBJAVASCRIPT
 1428: }
 1429: 
 1430: #--- javascript for essay type problem --
 1431: sub sub_page_kw_js {
 1432:     my $request = shift;
 1433:     my $iconpath = $request->dir_config('lonIconsURL');
 1434:     &commonJSfunctions($request);
 1435: 
 1436:     my $inner_js_msg_central=<<INNERJS;
 1437:     <script text="text/javascript">
 1438:     function checkInput() {
 1439:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1440:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1441:       var usrctr = document.msgcenter.usrctr.value;
 1442:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1443:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1444: 
 1445:       var msgchk = "";
 1446:       if (document.msgcenter.subchk.checked) {
 1447:          msgchk = "msgsub,";
 1448:       }
 1449:       var includemsg = 0;
 1450:       for (var i=1; i<=nmsg; i++) {
 1451:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1452:           var frmmsg = document.msgcenter["msg"+i];
 1453:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1454:           var showflg = opener.document.SCORE["shownOnce"+i];
 1455:           showflg.value = "1";
 1456:           var chkbox = document.msgcenter["msgn"+i];
 1457:           if (chkbox.checked) {
 1458:              msgchk += "savemsg"+i+",";
 1459:              includemsg = 1;
 1460:           }
 1461:       }
 1462:       if (document.msgcenter.newmsgchk.checked) {
 1463:          msgchk += "newmsg"+usrctr;
 1464:          includemsg = 1;
 1465:       }
 1466:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1467:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1468:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1469:       includemsg.value = msgchk;
 1470: 
 1471:       self.close()
 1472: 
 1473:     }
 1474:     </script>
 1475: INNERJS
 1476: 
 1477:     my $inner_js_highlight_central=<<INNERJS;
 1478:  <script type="text/javascript">
 1479:     function updateChoice(flag) {
 1480:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1481:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1482:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1483:       opener.document.SCORE.refresh.value = "on";
 1484:       if (opener.document.SCORE.keywords.value!=""){
 1485:          opener.document.SCORE.submit();
 1486:       }
 1487:       self.close()
 1488:     }
 1489: </script>
 1490: INNERJS
 1491: 
 1492:     my $start_page_msg_central = 
 1493:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1494: 				       {'js_ready'  => 1,
 1495: 					'only_body' => 1,
 1496: 					'bgcolor'   =>'#FFFFFF',});
 1497:     my $end_page_msg_central = 
 1498: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1499: 
 1500: 
 1501:     my $start_page_highlight_central = 
 1502:         &Apache::loncommon::start_page('Highlight Central',
 1503: 				       $inner_js_highlight_central,
 1504: 				       {'js_ready'  => 1,
 1505: 					'only_body' => 1,
 1506: 					'bgcolor'   =>'#FFFFFF',});
 1507:     my $end_page_highlight_central = 
 1508: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1509: 
 1510:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1511:     $docopen=~s/^document\.//;
 1512:     my %js_lt = &Apache::lonlocal::texthash(
 1513:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1514:                 plse => 'Please select a word or group of words from document and then click this link.',
 1515:                 adds => 'Add selection to keyword list? Edit if desired.',
 1516:                 col1 => 'red',
 1517:                 col2 => 'green',
 1518:                 col3 => 'blue',
 1519:                 siz1 => 'normal',
 1520:                 siz2 => '+1',
 1521:                 siz3 => '+2',
 1522:                 sty1 => 'normal',
 1523:                 sty2 => 'italic',
 1524:                 sty3 => 'bold',
 1525:              );
 1526:     my %html_js_lt = &Apache::lonlocal::texthash(
 1527:                 comp => 'Compose Message for: ',
 1528:                 incl => 'Include',
 1529:                 type => 'Type',
 1530:                 subj => 'Subject',
 1531:                 mesa => 'Message',
 1532:                 new  => 'New',
 1533:                 save => 'Save',
 1534:                 canc => 'Cancel',
 1535:                 kehi => 'Keyword Highlight Options',
 1536:                 txtc => 'Text Color',
 1537:                 font => 'Font Size',
 1538:                 fnst => 'Font Style',
 1539:              );
 1540:     &js_escape(\%js_lt);
 1541:     &html_escape(\%html_js_lt);
 1542:     &js_escape(\%html_js_lt);
 1543:     $request->print(<<SUBJAVASCRIPT);
 1544: <script type="text/javascript" language="javascript">
 1545: 
 1546: //===================== Show list of keywords ====================
 1547:   function keywords(formname) {
 1548:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1549:     if (nret==null) return;
 1550:     formname.keywords.value = nret;
 1551: 
 1552:     if (formname.keywords.value != "") {
 1553: 	formname.refresh.value = "on";
 1554: 	formname.submit();
 1555:     }
 1556:     return;
 1557:   }
 1558: 
 1559: //===================== Script to view submitted by ==================
 1560:   function viewSubmitter(submitter) {
 1561:     document.SCORE.refresh.value = "on";
 1562:     document.SCORE.NCT.value = "1";
 1563:     document.SCORE.unamedom0.value = submitter;
 1564:     document.SCORE.submit();
 1565:     return;
 1566:   }
 1567: 
 1568: //===================== Script to add keyword(s) ==================
 1569:   function getSel() {
 1570:     if (document.getSelection) txt = document.getSelection();
 1571:     else if (document.selection) txt = document.selection.createRange().text;
 1572:     else return;
 1573:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1574:     if (cleantxt=="") {
 1575: 	alert("$js_lt{'plse'}");
 1576: 	return;
 1577:     }
 1578:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1579:     if (nret==null) return;
 1580:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1581:     if (document.SCORE.keywords.value != "") {
 1582: 	document.SCORE.refresh.value = "on";
 1583: 	document.SCORE.submit();
 1584:     }
 1585:     return;
 1586:   }
 1587: 
 1588: //====================== Script for composing message ==============
 1589:    // preload images
 1590:    img1 = new Image();
 1591:    img1.src = "$iconpath/mailbkgrd.gif";
 1592:    img2 = new Image();
 1593:    img2.src = "$iconpath/mailto.gif";
 1594: 
 1595:   function msgCenter(msgform,usrctr,fullname) {
 1596:     var Nmsg  = msgform.savemsgN.value;
 1597:     savedMsgHeader(Nmsg,usrctr,fullname);
 1598:     var subject = msgform.msgsub.value;
 1599:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1600:     re = /msgsub/;
 1601:     var shwsel = "";
 1602:     if (re.test(msgchk)) { shwsel = "checked" }
 1603:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1604:     displaySubject(checkEntities(subject),shwsel);
 1605:     for (var i=1; i<=Nmsg; i++) {
 1606: 	var testmsg = "savemsg"+i+",";
 1607: 	re = new RegExp(testmsg,"g");
 1608: 	shwsel = "";
 1609: 	if (re.test(msgchk)) { shwsel = "checked" }
 1610: 	var message = document.SCORE["savemsg"+i].value;
 1611: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1612: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1613: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1614:     }
 1615:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1616:     shwsel = "";
 1617:     re = /newmsg/;
 1618:     if (re.test(msgchk)) { shwsel = "checked" }
 1619:     newMsg(newmsg,shwsel);
 1620:     msgTail(); 
 1621:     return;
 1622:   }
 1623: 
 1624:   function checkEntities(strx) {
 1625:     if (strx.length == 0) return strx;
 1626:     var orgStr = ["&", "<", ">", '"']; 
 1627:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1628:     var counter = 0;
 1629:     while (counter < 4) {
 1630: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1631: 	counter++;
 1632:     }
 1633:     return strx;
 1634:   }
 1635: 
 1636:   function strReplace(strx, orgStr, newStr) {
 1637:     return strx.split(orgStr).join(newStr);
 1638:   }
 1639: 
 1640:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1641:     var height = 70*Nmsg+250;
 1642:     if (height > 600) {
 1643: 	height = 600;
 1644:     }
 1645:     var xpos = (screen.width-600)/2;
 1646:     xpos = (xpos < 0) ? '0' : xpos;
 1647:     var ypos = (screen.height-height)/2-30;
 1648:     ypos = (ypos < 0) ? '0' : ypos;
 1649: 
 1650:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1651:     pWin.focus();
 1652:     pDoc = pWin.document;
 1653:     pDoc.$docopen;
 1654:     pDoc.write('$start_page_msg_central');
 1655: 
 1656:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1657:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1658:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1659: 
 1660:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1661:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1662:     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>");
 1663: }
 1664:     function displaySubject(msg,shwsel) {
 1665:     pDoc = pWin.document;
 1666:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1667:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1668:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1669:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1670: }
 1671: 
 1672:   function displaySavedMsg(ctr,msg,shwsel) {
 1673:     pDoc = pWin.document;
 1674:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1675:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1676:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1677:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1678: }
 1679: 
 1680:   function newMsg(newmsg,shwsel) {
 1681:     pDoc = pWin.document;
 1682:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1683:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1684:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1685:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1686: }
 1687: 
 1688:   function msgTail() {
 1689:     pDoc = pWin.document;
 1690:     pDoc.write("<\\/table>");
 1691:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1692:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1693:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1694:     pDoc.write("<\\/form>");
 1695:     pDoc.write('$end_page_msg_central');
 1696:     pDoc.close();
 1697: }
 1698: 
 1699: //====================== Script for keyword highlight options ==============
 1700:   function kwhighlight() {
 1701:     var kwclr    = document.SCORE.kwclr.value;
 1702:     var kwsize   = document.SCORE.kwsize.value;
 1703:     var kwstyle  = document.SCORE.kwstyle.value;
 1704:     var redsel = "";
 1705:     var grnsel = "";
 1706:     var blusel = "";
 1707:     var txtcol1 = "$js_lt{'col1'}";
 1708:     var txtcol2 = "$js_lt{'col2'}";
 1709:     var txtcol3 = "$js_lt{'col3'}";
 1710:     var txtsiz1 = "$js_lt{'siz1'}";
 1711:     var txtsiz2 = "$js_lt{'siz2'}";
 1712:     var txtsiz3 = "$js_lt{'siz3'}";
 1713:     var txtsty1 = "$js_lt{'sty1'}";
 1714:     var txtsty2 = "$js_lt{'sty2'}";
 1715:     var txtsty3 = "$js_lt{'sty3'}";
 1716:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1717:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1718:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1719:     var sznsel = "";
 1720:     var sz1sel = "";
 1721:     var sz2sel = "";
 1722:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1723:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1724:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1725:     var synsel = "";
 1726:     var syisel = "";
 1727:     var sybsel = "";
 1728:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1729:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1730:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1731:     highlightCentral();
 1732:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1733:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1734:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1735:     highlightend();
 1736:     return;
 1737:   }
 1738: 
 1739:   function highlightCentral() {
 1740: //    if (window.hwdWin) window.hwdWin.close();
 1741:     var xpos = (screen.width-400)/2;
 1742:     xpos = (xpos < 0) ? '0' : xpos;
 1743:     var ypos = (screen.height-330)/2-30;
 1744:     ypos = (ypos < 0) ? '0' : ypos;
 1745: 
 1746:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1747:     hwdWin.focus();
 1748:     var hDoc = hwdWin.document;
 1749:     hDoc.$docopen;
 1750:     hDoc.write('$start_page_highlight_central');
 1751:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1752:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1753: 
 1754:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1755:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1756:   }
 1757: 
 1758:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1759:     var hDoc = hwdWin.document;
 1760:     hDoc.write("<tr>");
 1761:     hDoc.write("<td align=\\"left\\">");
 1762:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1763:     hDoc.write("<td align=\\"left\\">");
 1764:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1765:     hDoc.write("<td align=\\"left\\">");
 1766:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1767:     hDoc.write("<\\/tr>");
 1768:   }
 1769: 
 1770:   function highlightend() { 
 1771:     var hDoc = hwdWin.document;
 1772:     hDoc.write("<\\/table><br \\/>");
 1773:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1774:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1775:     hDoc.write("<\\/form>");
 1776:     hDoc.write('$end_page_highlight_central');
 1777:     hDoc.close();
 1778:   }
 1779: 
 1780: </script>
 1781: SUBJAVASCRIPT
 1782: }
 1783: 
 1784: sub get_increment {
 1785:     my $increment = $env{'form.increment'};
 1786:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1787:         $increment != .1) {
 1788:         $increment = 1;
 1789:     }
 1790:     return $increment;
 1791: }
 1792: 
 1793: sub gradeBox_start {
 1794:     return (
 1795:         &Apache::loncommon::start_data_table()
 1796:        .&Apache::loncommon::start_data_table_header_row()
 1797:        .'<th>'.&mt('Part').'</th>'
 1798:        .'<th>'.&mt('Points').'</th>'
 1799:        .'<th>&nbsp;</th>'
 1800:        .'<th>'.&mt('Assign Grade').'</th>'
 1801:        .'<th>'.&mt('Weight').'</th>'
 1802:        .'<th>'.&mt('Grade Status').'</th>'
 1803:        .&Apache::loncommon::end_data_table_header_row()
 1804:     );
 1805: }
 1806: 
 1807: sub gradeBox_end {
 1808:     return (
 1809:         &Apache::loncommon::end_data_table()
 1810:     );
 1811: }
 1812: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1813: sub gradeBox {
 1814:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1815:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1816: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1817:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1818:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1819:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1820:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1821:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1822: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1823:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1824:     my $display_part= &get_display_part($partid,$symb);
 1825:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1826: 				       [$partid]);
 1827:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1828:     if ($last_resets{$partid}) {
 1829:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1830:     }
 1831:     my $result=&Apache::loncommon::start_data_table_row();
 1832:     my $ctr = 0;
 1833:     my $thisweight = 0;
 1834:     my $increment = &get_increment();
 1835: 
 1836:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1837:     while ($thisweight<=$wgt) {
 1838: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1839:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1840: 	    $thisweight.')" value="'.$thisweight.'" '.
 1841: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1842: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1843:         $thisweight += $increment;
 1844: 	$ctr++;
 1845:     }
 1846:     $radio.='</tr></table>';
 1847: 
 1848:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1849: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1850: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1851: 	$wgt.')" /></td>'."\n";
 1852:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1853: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1854: 	' </td>'."\n";
 1855:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1856: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1857:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1858: 	$line.='<option></option>'.
 1859: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1860:     } else {
 1861: 	$line.='<option selected="selected"></option>'.
 1862: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1863:     }
 1864:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1865: 
 1866: 
 1867:     $result .= 
 1868: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1869:     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
 1870:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1871: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1872: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1873: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1874:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1875:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1876:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1877:         $aggtries.'" />'."\n";
 1878:     my $res_error;
 1879:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1880:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1881:     if ($res_error) {
 1882:         return &navmap_errormsg();
 1883:     }
 1884:     return $result;
 1885: }
 1886: 
 1887: sub handback_box {
 1888:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1889:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1890:     my (@respids);
 1891:     my @part_response_id = &flatten_responseType($responseType);
 1892:     foreach my $part_response_id (@part_response_id) {
 1893:     	my ($part,$resp) = @{ $part_response_id };
 1894:         if ($part eq $partid) {
 1895:             push(@respids,$resp);
 1896:         }
 1897:     }
 1898:     my $result;
 1899:     foreach my $respid (@respids) {
 1900: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1901: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1902: 	next if (!@$files);
 1903: 	my $file_counter = 0;
 1904: 	foreach my $file (@$files) {
 1905: 	    if ($file =~ /\/portfolio\//) {
 1906:                 $file_counter++;
 1907:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1908:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1909:     	        $file_disp = "$name.$ext";
 1910:     	        $file = $file_path.$file_disp;
 1911:     	        $result.=&mt('Return commented version of [_1] to student.',
 1912:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1913:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1914:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1915: 	    }
 1916: 	}
 1917:         if ($file_counter) {
 1918:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1919:                        '<span class="LC_info">'.
 1920:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1921:         }
 1922:     }
 1923:     return $result;    
 1924: }
 1925: 
 1926: sub show_problem {
 1927:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1928:     my $rendered;
 1929:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1930:     &Apache::lonxml::remember_problem_counter();
 1931:     if ($mode eq 'both' or $mode eq 'text') {
 1932: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1933: 						       $env{'request.course.id'},
 1934: 						       undef,\%form);
 1935:     }
 1936:     if ($removeform) {
 1937: 	$rendered=~s|<form(.*?)>||g;
 1938: 	$rendered=~s|</form>||g;
 1939: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1940:     }
 1941:     my $companswer;
 1942:     if ($mode eq 'both' or $mode eq 'answer') {
 1943: 	&Apache::lonxml::restore_problem_counter();
 1944: 	$companswer=
 1945: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1946: 						    $env{'request.course.id'},
 1947: 						    %form);
 1948:     }
 1949:     if ($removeform) {
 1950: 	$companswer=~s|<form(.*?)>||g;
 1951: 	$companswer=~s|</form>||g;
 1952: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1953:     }
 1954:     my $renderheading = &mt('View of the problem');
 1955:     my $answerheading = &mt('Correct answer');
 1956:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1957:         my $stu_fullname = $env{'form.fullname'};
 1958:         if ($stu_fullname eq '') {
 1959:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1960:         }
 1961:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1962:         if ($forwhom ne '') {
 1963:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1964:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1965:         }
 1966:     }
 1967:     $rendered=
 1968:         '<div class="LC_Box">'
 1969:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1970:        .$rendered
 1971:        .'</div>';
 1972:     $companswer=
 1973:         '<div class="LC_Box">'
 1974:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1975:        .$companswer
 1976:        .'</div>';
 1977:     my $result;
 1978:     if ($mode eq 'both') {
 1979:         $result=$rendered.$companswer;
 1980:     } elsif ($mode eq 'text') {
 1981:         $result=$rendered;
 1982:     } elsif ($mode eq 'answer') {
 1983:         $result=$companswer;
 1984:     }
 1985:     return $result;
 1986: }
 1987: 
 1988: sub files_exist {
 1989:     my ($r, $symb) = @_;
 1990:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1991: 
 1992:     foreach my $student (@students) {
 1993:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1994:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1995: 					      $udom,$uname);
 1996:         my ($string,$timestamp)= &get_last_submission(\%record);
 1997:         foreach my $submission (@$string) {
 1998:             my ($partid,$respid) =
 1999: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2000:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2001: 					   \%record);
 2002:             return 1 if (@$files);
 2003:         }
 2004:     }
 2005:     return 0;
 2006: }
 2007: 
 2008: sub download_all_link {
 2009:     my ($r,$symb) = @_;
 2010:     my $all_students = 
 2011: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2012: 
 2013:     my $parts =
 2014: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2015: 
 2016:     my $identifier = &Apache::loncommon::get_cgi_id();
 2017:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2018:                              'cgi.'.$identifier.'.symb' => $symb,
 2019:                              'cgi.'.$identifier.'.parts' => $parts,});
 2020:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2021: 	      &mt('Download All Submitted Documents').'</a>');
 2022:     return
 2023: }
 2024: 
 2025: sub build_section_inputs {
 2026:     my $section_inputs;
 2027:     if ($env{'form.section'} eq '') {
 2028:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2029:     } else {
 2030:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2031:         foreach my $section (@sections) {
 2032:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2033:         }
 2034:     }
 2035:     return $section_inputs;
 2036: }
 2037: 
 2038: # --------------------------- show submissions of a student, option to grade 
 2039: sub submission {
 2040:     my ($request,$counter,$total) = @_;
 2041:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2042:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2043:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2044:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2045:     my ($symb) = &get_symb($request); 
 2046:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2047: 
 2048:     if (!&canview($usec)) {
 2049:         $request->print(
 2050:             '<span class="LC_warning">'.
 2051:             &mt('Unable to view requested student.').
 2052:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2053:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2054:             '</span>');
 2055: 	$request->print(&show_grading_menu_form($symb));
 2056: 	return;
 2057:     }
 2058: 
 2059:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2060:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2061:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2062:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2063:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2064: 	'" src="'.$request->dir_config('lonIconsURL').
 2065: 	'/check.gif" height="16" border="0" />';
 2066: 
 2067:     # header info
 2068:     if ($counter == 0) {
 2069: 	&sub_page_js($request);
 2070: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2071: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2072: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2073: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2074: 	    &download_all_link($request, $symb);
 2075: 	}
 2076: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2077: 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
 2078: 
 2079: 	# option to display problem, only once else it cause problems 
 2080:         # with the form later since the problem has a form.
 2081: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2082: 	    my $mode;
 2083: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2084: 		$mode='both';
 2085: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2086: 		$mode='text';
 2087: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2088: 		$mode='answer';
 2089: 	    }
 2090: 	    &Apache::lonxml::clear_problem_counter();
 2091: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2092: 	}
 2093: 
 2094: 	# kwclr is the only variable that is guaranteed not to be blank 
 2095:         # if this subroutine has been called once.
 2096: 	my %keyhash = ();
 2097: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2098: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2099: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2100: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2101: 
 2102: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2103: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2104: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2105: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2106: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2107: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2108: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2109: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2110: 	}
 2111: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2112: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2113: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2114: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2115: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2116: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2117: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2118: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2119: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2120: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2121: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2122: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2123: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2124: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2125: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2126: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2127: 			&build_section_inputs().
 2128: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2129: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2130: 			'<input type="hidden" name="NCT"'.
 2131: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2132: 	if ($env{'form.handgrade'} eq 'yes') {
 2133: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2134: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2135: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2136: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2137: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2138: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2139: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2140: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2141: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2142: 	    }
 2143: 	}
 2144: 	
 2145: 	my ($cts,$prnmsg) = (1,'');
 2146: 	while ($cts <= $env{'form.savemsgN'}) {
 2147: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2148: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2149: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2150: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2151: 		'" />'."\n".
 2152: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2153: 	    $cts++;
 2154: 	}
 2155: 	$request->print($prnmsg);
 2156: 
 2157: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2158: 
 2159:             my %lt = &Apache::lonlocal::texthash(
 2160:                           keyh => 'Keyword Highlighting for Essays',
 2161:                           keyw => 'Keyword Options',
 2162:                           list => 'List',
 2163:                           past => 'Paste Selection to List',
 2164:                           high => 'Highlight Attribute',
 2165:                      );
 2166: #
 2167: # Print out the keyword options line
 2168: #
 2169:             $request->print(
 2170:                 '<div class="LC_columnSection">'
 2171:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2172:                .&Apache::lonhtmlcommon::funclist_from_array(
 2173:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2174:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2175:  class="page">'.$lt{'past'}.'</a>',
 2176:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2177:                     {legend => $lt{'keyw'}})
 2178:                .'</fieldset></div>'
 2179:             );
 2180: 
 2181: #
 2182: # Load the other essays for similarity check
 2183: #
 2184:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2185: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2186: 	    $apath=&escape($apath);
 2187: 	    $apath=~s/\W/\_/gs;
 2188:             &init_old_essays($symb,$apath,$adom,$aname);
 2189:         }
 2190:     }
 2191: 
 2192: # This is where output for one specific student would start
 2193:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2194:     $request->print(
 2195:         "\n\n"
 2196:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2197:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2198:        ."\n"
 2199:     );
 2200: 
 2201:     # Show additional functions if allowed
 2202:     if ($perm{'vgr'}) {
 2203:         $request->print(
 2204:             &Apache::loncommon::track_student_link(
 2205:                 'View recent activity',
 2206:                 $uname,$udom,'check')
 2207:            .' '
 2208:         );
 2209:     }
 2210:     if ($perm{'opa'}) {
 2211:         $request->print(
 2212:             &Apache::loncommon::pprmlink(
 2213:                 &mt('Set/Change parameters'),
 2214:                 $uname,$udom,$symb,'check'));
 2215:     }
 2216: 
 2217:     # Show Problem
 2218:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2219: 	my $mode;
 2220: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2221: 	    $mode='both';
 2222: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2223: 	    $mode='text';
 2224: 	} elsif ($env{'form.vAns'} eq 'all') {
 2225: 	    $mode='answer';
 2226: 	}
 2227: 	&Apache::lonxml::clear_problem_counter();
 2228: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2229:     }
 2230: 
 2231:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2232:     my $res_error;
 2233:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2234:     if ($res_error) {
 2235:         $request->print(&navmap_errormsg());
 2236:         return;
 2237:     }
 2238: 
 2239:     # Display student info
 2240:     $request->print(($counter == 0 ? '' : '<br />'));
 2241: 
 2242:     my $result='<div class="LC_Box">'
 2243:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2244:     $result.='<input type="hidden" name="name'.$counter.
 2245:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2246:     if ($env{'form.handgrade'} eq 'no') {
 2247:         $result.='<p class="LC_info">'
 2248:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2249:                 ."</p>\n";
 2250:     }
 2251: 
 2252:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2253:     my $fullname;
 2254:     my $col_fullnames = [];
 2255:     if ($env{'form.handgrade'} eq 'yes') {
 2256: 	(my $sub_result,$fullname,$col_fullnames)=
 2257: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2258: 				 $counter);
 2259: 	$result.=$sub_result;
 2260:     }
 2261:     $request->print($result."\n");
 2262: 
 2263:     # print student answer/submission
 2264:     # Options are (1) Handgraded submission only
 2265:     #             (2) Last submission, includes submission that is not handgraded 
 2266:     #                  (for multi-response type part)
 2267:     #             (3) Last submission plus the parts info
 2268:     #             (4) The whole record for this student
 2269: 
 2270: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2271: 	
 2272: 	my $lastsubonly;
 2273: 
 2274:         if ($$timestamp eq '') {
 2275:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2276:         } else {
 2277:             $lastsubonly =
 2278:                 '<div class="LC_grade_submissions_body">'
 2279:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2280: 
 2281: 	    my %seenparts;
 2282: 	    my @part_response_id = &flatten_responseType($responseType);
 2283: 	    foreach my $part (@part_response_id) {
 2284: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2285: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2286: 
 2287: 		my ($partid,$respid) = @{ $part };
 2288: 		my $display_part=&get_display_part($partid,$symb);
 2289: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2290: 		    if (exists($seenparts{$partid})) { next; }
 2291: 		    $seenparts{$partid}=1;
 2292:                     $request->print(
 2293:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2294:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2295:                                    '<a href="javascript:viewSubmitter(\''.
 2296:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2297:                                    '\');" target="_self">'.
 2298:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2299:                         '<br />');
 2300: 		    next;
 2301: 		}
 2302: 		my $responsetype = $responseType->{$partid}->{$respid};
 2303: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2304:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2305:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2306:                         ' <span class="LC_internal_info">'.
 2307:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2308:                         '</span>&nbsp; &nbsp;'.
 2309: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2310: 		    next;
 2311: 		}
 2312: 		foreach my $submission (@$string) {
 2313: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2314: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2315: 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2316: 		    # Similarity check
 2317: 		    my $similar='';
 2318:                     my ($type,$trial,$rndseed);
 2319:                     if ($hide eq 'rand') {
 2320:                         $type = 'randomizetry';
 2321:                         $trial = $record{"resource.$partid.tries"};
 2322:                         $rndseed = $record{"resource.$partid.rndseed"};
 2323:                     }
 2324: 		    if ($env{'form.checkPlag'}) {
 2325: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2326: 			    &most_similar($uname,$udom,$symb,$subval);
 2327: 			if ($osim) {
 2328: 			    $osim=int($osim*100.0);
 2329: 			    my %old_course_desc = 
 2330: 				&Apache::lonnet::coursedescription($ocrsid,
 2331: 								   {'one_time' => 1});
 2332: 
 2333:                             if ($hide eq 'anon') {
 2334:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2335:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2336:                             } else {
 2337: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2338: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2339: 				        $osim,
 2340: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2341: 				        $old_course_desc{'description'},
 2342: 				        $old_course_desc{'num'},
 2343: 				        $old_course_desc{'domain'}).
 2344: 				    '</span></h3><blockquote><i>'.
 2345: 				    &keywords_highlight($oessay).
 2346: 				    '</i></blockquote><hr />';
 2347:                             }
 2348: 			}
 2349: 		    }
 2350: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2351:                                          undef,$type,$trial,$rndseed);
 2352:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2353:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2354: 			my $display_part=&get_display_part($partid,$symb);
 2355:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2356:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2357:                             ' <span class="LC_internal_info">'.
 2358:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2359:                             '</span>&nbsp; &nbsp;';
 2360: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2361: 			if (@$files) {
 2362:                             if ($hide eq 'anon') {
 2363:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2364:                             } else {
 2365:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2366:                                             .'<br /><span class="LC_warning">';
 2367:                                 if(@$files == 1) {
 2368:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2369:                                 } else {
 2370:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2371:                                 }
 2372:                                 $lastsubonly .= '</span>';
 2373: 
 2374:                                 foreach my $file (@$files) {
 2375:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2376:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2377:                                 }
 2378:                             }
 2379: 			    $lastsubonly.='<br />';
 2380: 			}
 2381:                         if ($hide eq 'anon') {
 2382:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2383:                         } else {
 2384: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2385:                             if ($draft) {
 2386:                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2387:                             }
 2388:                             $subval =
 2389: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2390: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2391:                             if ($responsetype eq 'essay') {
 2392:                                 $subval =~ s{\n}{<br />}g;
 2393:                             }
 2394:                             $lastsubonly.=$subval."\n";
 2395:                         }
 2396: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2397: 			$lastsubonly.='</div>';
 2398: 		    }
 2399: 		}
 2400: 	    }
 2401: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2402: 	}
 2403: 	$request->print($lastsubonly);
 2404:    if ($env{'form.lastSub'} eq 'datesub') {
 2405: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2406: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2407:     }
 2408:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2409:         my $identifier = (&canmodify($usec)? $counter : '');
 2410: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2411: 								 $env{'request.course.id'},
 2412: 								 $last,'.submission',
 2413: 								 'Apache::grades::keywords_highlight',
 2414:                                                                  $usec,$identifier));
 2415:     }
 2416: 
 2417:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2418: 	.$udom.'" />'."\n");
 2419:     # return if view submission with no grading option
 2420:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2421: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2422: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2423: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2424: 	$toGrade.='</div>'."\n";
 2425: 	if (($env{'form.command'} eq 'submission') || 
 2426: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2427: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2428: 	}
 2429: 	$request->print($toGrade);
 2430: 	return;
 2431:     } else {
 2432: 	$request->print('</div>'."\n");
 2433:     }
 2434: 
 2435:     # essay grading message center
 2436:     if ($env{'form.handgrade'} eq 'yes') {
 2437: 	my $result='<div class="LC_grade_message_center">';
 2438:     
 2439: 	$result.='<div class="LC_grade_message_center_header">'.
 2440: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2441: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2442: 	my $msgfor = $givenn.' '.$lastname;
 2443: 	if (scalar(@$col_fullnames) > 0) {
 2444: 	    my $lastone = pop(@$col_fullnames);
 2445: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2446: 	}
 2447: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2448: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2449: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2450: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2451: 	    ',\''.$msgfor.'\');" target="_self">'.
 2452: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2453: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2454: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2455: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2456: 	    '<br />&nbsp;('.
 2457: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2458: 	$result.='</div></div>';
 2459: 	$request->print($result);
 2460:     }
 2461: 
 2462:     my %seen = ();
 2463:     my @partlist;
 2464:     my @gradePartRespid;
 2465:     my @part_response_id = &flatten_responseType($responseType);
 2466:     $request->print(
 2467:         '<div class="LC_Box">'
 2468:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2469:     );
 2470:     $request->print(&gradeBox_start());
 2471:     foreach my $part_response_id (@part_response_id) {
 2472:     	my ($partid,$respid) = @{ $part_response_id };
 2473: 	my $part_resp = join('_',@{ $part_response_id });
 2474: 	next if ($seen{$partid} > 0);
 2475: 	$seen{$partid}++;
 2476: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2477: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2478: 	push(@partlist,$partid);
 2479: 	push(@gradePartRespid,$partid.'.'.$respid);
 2480: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2481:     }
 2482:     $request->print(&gradeBox_end()); # </div>
 2483:     $request->print('</div>');
 2484: 
 2485:     $request->print('<div class="LC_grade_info_links">');
 2486:     $request->print('</div>');
 2487: 
 2488:     $result='<input type="hidden" name="partlist'.$counter.
 2489: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2490:     $result.='<input type="hidden" name="gradePartRespid'.
 2491: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2492:     my $ctr = 0;
 2493:     while ($ctr < scalar(@partlist)) {
 2494: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2495: 	    $partlist[$ctr].'" />'."\n";
 2496: 	$ctr++;
 2497:     }
 2498:     $request->print($result.''."\n");
 2499: 
 2500: # Done with printing info for one student
 2501: 
 2502:     $request->print('</div>');#LC_grade_show_user
 2503: 
 2504: 
 2505:     # print end of form
 2506:     if ($counter == $total) {
 2507:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2508: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2509: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2510: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2511: 	my $ntstu ='<select name="NTSTU">'.
 2512: 	    '<option>1</option><option>2</option>'.
 2513: 	    '<option>3</option><option>5</option>'.
 2514: 	    '<option>7</option><option>10</option></select>'."\n";
 2515: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2516: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2517:         $endform.=&mt('[_1]student(s)',$ntstu);
 2518: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2519: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2520: 	    '<input type="button" value="'.&mt('Next').'" '.
 2521: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2522:         $endform.='<span class="LC_warning">'.
 2523:                   &mt('(Next and Previous (student) do not save the scores.)').
 2524:                   '</span>'."\n" ;
 2525:         $endform.="<input type='hidden' value='".&get_increment().
 2526:             "' name='increment' />";
 2527: 	$endform.='</td></tr></table></form>';
 2528: 	$endform.=&show_grading_menu_form($symb);
 2529: 	$request->print($endform);
 2530:     }
 2531:     return '';
 2532: }
 2533: 
 2534: sub check_collaborators {
 2535:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2536:     my ($result,@col_fullnames);
 2537:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2538:     foreach my $part (keys(%$handgrade)) {
 2539: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2540: 					'.maxcollaborators',
 2541: 					$symb,$udom,$uname);
 2542: 	next if ($ncol <= 0);
 2543: 	$part =~ s/\_/\./g;
 2544: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2545: 	my (@good_collaborators, @bad_collaborators);
 2546: 	foreach my $possible_collaborator
 2547: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2548: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2549: 	    next if ($possible_collaborator eq '');
 2550: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2551: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2552: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2553: 	    # Doing this grep allows 'fuzzy' specification
 2554: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2555: 			       keys(%$classlist));
 2556: 	    if (! scalar(@matches)) {
 2557: 		push(@bad_collaborators, $possible_collaborator);
 2558: 	    } else {
 2559: 		push(@good_collaborators, @matches);
 2560: 	    }
 2561: 	}
 2562: 	if (scalar(@good_collaborators) != 0) {
 2563: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2564: 	    foreach my $name (@good_collaborators) {
 2565: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2566: 		push(@col_fullnames, $givenn.' '.$lastname);
 2567: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2568: 	    }
 2569: 	    $result.='</ol><br />'."\n";
 2570: 	    my ($part)=split(/\./,$part);
 2571: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2572: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2573: 		"\n";
 2574: 	}
 2575: 	if (scalar(@bad_collaborators) > 0) {
 2576: 	    $result.='<div class="LC_warning">';
 2577: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2578: 	    $result .= '</div>';
 2579: 	}         
 2580: 	if (scalar(@bad_collaborators > $ncol)) {
 2581: 	    $result .= '<div class="LC_warning">';
 2582: 	    $result .= &mt('This student has submitted too many '.
 2583: 		'collaborators.  Maximum is [_1].',$ncol);
 2584: 	    $result .= '</div>';
 2585: 	}
 2586:     }
 2587:     return ($result,$fullname,\@col_fullnames);
 2588: }
 2589: 
 2590: #--- Retrieve the last submission for all the parts
 2591: sub get_last_submission {
 2592:     my ($returnhash)=@_;
 2593:     my (@string,$timestamp,%lasthidden);
 2594:     if ($$returnhash{'version'}) {
 2595: 	my %lasthash=();
 2596: 	my ($version);
 2597: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2598: 	    foreach my $key (sort(split(/\:/,
 2599: 					$$returnhash{$version.':keys'}))) {
 2600: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2601: 		$timestamp = 
 2602: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2603: 	    }
 2604: 	}
 2605:         my (%typeparts,%randombytry);
 2606:         my $showsurv = 
 2607:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2608:         foreach my $key (sort(keys(%lasthash))) {
 2609:             if ($key =~ /\.type$/) {
 2610:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2611:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2612:                     ($lasthash{$key} eq 'randomizetry')) {
 2613:                     my ($ign,@parts) = split(/\./,$key);
 2614:                     pop(@parts);
 2615:                     my $id = join('.',@parts);
 2616:                     if ($lasthash{$key} eq 'randomizetry') {
 2617:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2618:                     } else {
 2619:                         unless ($showsurv) {
 2620:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2621:                         }
 2622:                     }
 2623:                     delete($lasthash{$key});
 2624:                 }
 2625:             }
 2626:         }
 2627:         my @hidden = keys(%typeparts);
 2628:         my @randomize = keys(%randombytry);
 2629: 	foreach my $key (keys(%lasthash)) {
 2630: 	    next if ($key !~ /\.submission$/);
 2631:             my $hide;
 2632:             if (@hidden) {
 2633:                 foreach my $id (@hidden) {
 2634:                     if ($key =~ /^\Q$id\E/) {
 2635:                         $hide = 'anon';
 2636:                         last;
 2637:                     }
 2638:                 }
 2639:             }
 2640:             unless ($hide) {
 2641:                 if (@randomize) {
 2642:                     foreach my $id (@randomize) {
 2643:                         if ($key =~ /^\Q$id\E/) {
 2644:                             $hide = 'rand';
 2645:                             last;
 2646:                         }
 2647:                     }
 2648:                 }
 2649:             }
 2650: 	    my ($partid,$foo) = split(/submission$/,$key);
 2651: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
 2652:             push(@string, join(':', $key, $hide, $draft, (
 2653:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2654:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2655: 	}
 2656:     }
 2657:     if (!@string) {
 2658: 	$string[0] =
 2659: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2660:     }
 2661:     return (\@string,\$timestamp);
 2662: }
 2663: 
 2664: #--- High light keywords, with style choosen by user.
 2665: sub keywords_highlight {
 2666:     my $string    = shift;
 2667:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2668:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2669:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2670:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2671:     foreach my $keyword (@keylist) {
 2672: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2673:     }
 2674:     return $string;
 2675: }
 2676: 
 2677: # For Tasks provide a mechanism to display previous version for one specific student
 2678: 
 2679: sub show_previous_task_version {
 2680:     my ($request,$symb) = @_;
 2681:     if ($symb eq '') {
 2682:         $request->print(
 2683:             '<span class="LC_error">'.
 2684:             &mt('Unable to handle ambiguous references.').
 2685:             '</span>');
 2686:         return '';
 2687:     }
 2688:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2689:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2690:     if (!&canview($usec)) {
 2691:         $request->print('<span class="LC_warning">'.
 2692:                         &mt('Unable to view previous version for requested student.').
 2693:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2694:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2695:                         '</span>');
 2696:         return;
 2697:     }
 2698:     my $mode = 'both';
 2699:     my $isTask = ($symb =~/\.task$/);
 2700:     if ($isTask) {
 2701:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2702:             if ($env{'form.fullname'} eq '') {
 2703:                 $env{'form.fullname'} =
 2704:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2705:             }
 2706:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2707:             $request->print("\n\n".
 2708:                             '<div class="LC_grade_show_user">'.
 2709:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2710:                             '</h2>'."\n");
 2711:             &Apache::lonxml::clear_problem_counter();
 2712:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2713:                             {'previousversion' => $env{'form.previousversion'} }));
 2714:             $request->print("\n</div>");
 2715:         }
 2716:     }
 2717:     return;
 2718: }
 2719: 
 2720: sub choose_task_version_form {
 2721:     my ($symb,$uname,$udom,$nomenu) = @_;
 2722:     my $isTask = ($symb =~/\.task$/);
 2723:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2724:     if ($isTask) {
 2725:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2726:                                               $udom,$uname);
 2727:         if (($record{'resource.0.version'} eq '') ||
 2728:             ($record{'resource.0.version'} < 2)) {
 2729:             return ($record{'resource.0.version'},
 2730:                     $record{'resource.0.version'},$result,$js);
 2731:         } else {
 2732:             $current = $record{'resource.0.version'};
 2733:         }
 2734:         if ($env{'form.previousversion'}) {
 2735:             $displayed = $env{'form.previousversion'};
 2736:             $rowtitle = &mt('Choose another version:')
 2737:         } else {
 2738:             $displayed = $current;
 2739:             $rowtitle = &mt('Show earlier version:');
 2740:         }
 2741:         $result = '<div class="LC_left_float">';
 2742:         my $list;
 2743:         my $numversions = 0;
 2744:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2745:             if ($i == $current) {
 2746:                 if (!$env{'form.previousversion'} || $nomenu) {
 2747:                     next;
 2748:                 } else {
 2749:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2750:                     $numversions ++;
 2751:                 }
 2752:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2753:                 unless ($i == $env{'form.previousversion'}) {
 2754:                     $numversions ++;
 2755:                 }
 2756:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2757:             }
 2758:         }
 2759:         if ($numversions) {
 2760:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2761:             $result .=
 2762:                 '<form name="getprev" method="post" action=""'.
 2763:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2764:                 &Apache::loncommon::start_data_table().
 2765:                 &Apache::loncommon::start_data_table_row().
 2766:                 '<th align="left">'.$rowtitle.'</th>'.
 2767:                 '<td><select name="version">'.
 2768:                 '<option>'.&mt('Select').'</option>'.
 2769:                 $list.
 2770:                 '</select></td>'.
 2771:                 &Apache::loncommon::end_data_table_row();
 2772:             unless ($nomenu) {
 2773:                 $result .= &Apache::loncommon::start_data_table_row().
 2774:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2775:                 '<td><span class="LC_nobreak">'.
 2776:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2777:                 &mt('Yes').'</label>'.
 2778:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2779:                 '</span></td>'.
 2780:                 &Apache::loncommon::end_data_table_row();
 2781:             }
 2782:             $result .=
 2783:                 &Apache::loncommon::start_data_table_row().
 2784:                 '<th align="left">&nbsp;</th>'.
 2785:                 '<td>'.
 2786:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2787:                 '</td>'.
 2788:                 &Apache::loncommon::end_data_table_row().
 2789:                 &Apache::loncommon::end_data_table().
 2790:                 '</form>';
 2791:             $js = &previous_display_javascript($nomenu,$current);
 2792:         } elsif ($displayed && $nomenu) {
 2793:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2794:         } else {
 2795:             $result .= &mt('No previous versions to show for this student');
 2796:         }
 2797:         $result .= '</div>';
 2798:     }
 2799:     return ($current,$displayed,$result,$js);
 2800: }
 2801: 
 2802: sub previous_display_javascript {
 2803:     my ($nomenu,$current) = @_;
 2804:     my $js = <<"JSONE";
 2805: <script type="text/javascript">
 2806: // <![CDATA[
 2807: function previousVersion(uname,udom,symb) {
 2808:     var current = '$current';
 2809:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2810:     var prevstr = new RegExp("^\\\\d+\$");
 2811:     if (!prevstr.test(version)) {
 2812:         return false;
 2813:     }
 2814:     var url = '';
 2815:     if (version == current) {
 2816:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2817:     } else {
 2818:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2819:     }
 2820: JSONE
 2821:     if ($nomenu) {
 2822:         $js .= <<"JSTWO";
 2823:     document.location.href = url;
 2824: JSTWO
 2825:     } else {
 2826:         $js .= <<"JSTHREE";
 2827:     var newwin = 0;
 2828:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2829:         if (document.getprev.prevwin[i].checked == true) {
 2830:             newwin = document.getprev.prevwin[i].value;
 2831:         }
 2832:     }
 2833:     if (newwin == 1) {
 2834:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2835:         url = url+'&inhibitmenu=yes';
 2836:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2837:             previousWin = window.open(url,'',options,1);
 2838:         } else {
 2839:             previousWin.location.href = url;
 2840:         }
 2841:         previousWin.focus();
 2842:         return false;
 2843:     } else {
 2844:         document.location.href = url;
 2845:         return false;
 2846:     }
 2847: JSTHREE
 2848:     }
 2849:     $js .= <<"ENDJS";
 2850:     return false;
 2851: }
 2852: // ]]>
 2853: </script>
 2854: ENDJS
 2855: 
 2856: }
 2857: 
 2858: #--- Called from submission routine
 2859: sub processHandGrade {
 2860:     my ($request) = shift;
 2861:     my ($symb)   = &get_symb($request);
 2862:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2863:     my $button = $env{'form.gradeOpt'};
 2864:     my $ngrade = $env{'form.NCT'};
 2865:     my $ntstu  = $env{'form.NTSTU'};
 2866:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2867:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2868: 
 2869:     if ($button eq 'Save & Next') {
 2870: 	my $ctr = 0;
 2871: 	while ($ctr < $ngrade) {
 2872: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2873: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2874:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2875: 	    if ($errorflag eq 'no_score') {
 2876: 		$ctr++;
 2877: 		next;
 2878: 	    }
 2879: 	    if ($errorflag eq 'not_allowed') {
 2880:                 $request->print(
 2881:                     '<span class="LC_error">'
 2882:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2883:                    .'</span>');
 2884: 		$ctr++;
 2885: 		next;
 2886: 	    }
 2887:             if ($numhidden) {
 2888:                 $request->print(
 2889:                     '<span class="LC_info">'
 2890:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2891:                    .'</span><br />');
 2892:             }
 2893: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2894: 	    my ($subject,$message,$msgstatus) = ('','','');
 2895: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2896:             my ($feedurl,$showsymb) =
 2897: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2898: 	    my $messagetail;
 2899: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2900: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2901: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2902: 		$subject.=' ['.$restitle.']';
 2903: 		my (@msgnum) = split(/,/,$includemsg);
 2904: 		foreach (@msgnum) {
 2905: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2906: 		}
 2907: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2908: 		if ($env{'form.withgrades'.$ctr}) {
 2909: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2910: 		    $messagetail = " for <a href=\"".
 2911: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2912: 		}
 2913: 		$msgstatus = 
 2914:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2915: 						     $message.$messagetail,
 2916:                                                      undef,$feedurl,undef,
 2917:                                                      undef,undef,$showsymb,
 2918:                                                      $restitle);
 2919: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2920: 				$msgstatus.'<br />');
 2921: 	    }
 2922: 	    if ($env{'form.collaborator'.$ctr}) {
 2923: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2924: 		foreach my $collabstr (@collabstrs) {
 2925: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2926: 		    foreach my $collaborator (@collaborators) {
 2927: 			my ($errorflag,$pts,$wgt) = 
 2928: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2929: 					   $env{'form.unamedom'.$ctr},$part);
 2930: 			if ($errorflag eq 'not_allowed') {
 2931: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2932: 			    next;
 2933: 			} elsif ($message ne '') {
 2934: 			    my ($baseurl,$showsymb) = 
 2935: 				&get_feedurl_and_symb($symb,$collaborator,
 2936: 						      $udom);
 2937: 			    if ($env{'form.withgrades'.$ctr}) {
 2938: 				$messagetail = " for <a href=\"".
 2939:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2940: 			    }
 2941: 			    $msgstatus = 
 2942: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2943: 			}
 2944: 		    }
 2945: 		}
 2946: 	    }
 2947: 	    $ctr++;
 2948: 	}
 2949:     }
 2950: 
 2951:     if ($env{'form.handgrade'} eq 'yes') {
 2952: 	# Keywords sorted in alphabatical order
 2953: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2954: 	my %keyhash = ();
 2955: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2956: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2957: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2958: 	$env{'form.keywords'} = join(' ',@keywords);
 2959: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2960: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2961: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2962: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2963: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2964: 
 2965: 	# message center - Order of message gets changed. Blank line is eliminated.
 2966: 	# New messages are saved in env for the next student.
 2967: 	# All messages are saved in nohist_handgrade.db
 2968: 	my ($ctr,$idx) = (1,1);
 2969: 	while ($ctr <= $env{'form.savemsgN'}) {
 2970: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2971: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2972: 		$idx++;
 2973: 	    }
 2974: 	    $ctr++;
 2975: 	}
 2976: 	$ctr = 0;
 2977: 	while ($ctr < $ngrade) {
 2978: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2979: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2980: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2981: 		$idx++;
 2982: 	    }
 2983: 	    $ctr++;
 2984: 	}
 2985: 	$env{'form.savemsgN'} = --$idx;
 2986: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2987: 	my $putresult = &Apache::lonnet::put
 2988: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2989:     }
 2990:     # Called by Save & Refresh from Highlight Attribute Window
 2991:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2992:     if ($env{'form.refresh'} eq 'on') {
 2993: 	my ($ctr,$total) = (0,0);
 2994: 	while ($ctr < $ngrade) {
 2995: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2996: 	    $ctr++;
 2997: 	}
 2998: 	$env{'form.NTSTU'}=$ngrade;
 2999: 	$ctr = 0;
 3000: 	while ($ctr < $total) {
 3001: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3002: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3003: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3004: 	    &submission($request,$ctr,$total-1);
 3005: 	    $ctr++;
 3006: 	}
 3007: 	return '';
 3008:     }
 3009: 
 3010: # Go directly to grade student - from submission or link from chart page
 3011:     if ($button eq 'Grade Student') {
 3012: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 3013: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 3014: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3015: 	$env{'form.fullname'} = $$fullname{$processUser};
 3016: 	&submission($request,0,0);
 3017: 	return '';
 3018:     }
 3019: 
 3020:     # Get the next/previous one or group of students
 3021:     my $firststu = $env{'form.unamedom0'};
 3022:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3023:     my $ctr = 2;
 3024:     while ($laststu eq '') {
 3025: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3026: 	$ctr++;
 3027: 	$laststu = $firststu if ($ctr > $ngrade);
 3028:     }
 3029: 
 3030:     my (@parsedlist,@nextlist);
 3031:     my ($nextflg) = 0;
 3032:     foreach my $item (sort 
 3033: 	     {
 3034: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3035: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3036: 		 }
 3037: 		 return $a cmp $b;
 3038: 	     } (keys(%$fullname))) {
 3039: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3040: 	    push(@parsedlist,$item);
 3041: 	}
 3042: 	$nextflg = 1 if ($item eq $laststu);
 3043: 	if ($button eq 'Previous') {
 3044: 	    last if ($item eq $firststu);
 3045: 	    push(@parsedlist,$item);
 3046: 	}
 3047:     }
 3048:     $ctr = 0;
 3049:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3050:     my $res_error;
 3051:     my ($partlist) = &response_type($symb,\$res_error);
 3052:     if ($res_error) {
 3053:         $request->print(&navmap_errormsg());
 3054:         return;
 3055:     }
 3056:     foreach my $student (@parsedlist) {
 3057: 	my $submitonly=$env{'form.submitonly'};
 3058: 	my ($uname,$udom) = split(/:/,$student);
 3059: 	
 3060: 	if ($submitonly eq 'queued') {
 3061: 	    my %queue_status = 
 3062: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3063: 							$udom,$uname);
 3064: 	    next if (!defined($queue_status{'gradingqueue'}));
 3065: 	}
 3066: 
 3067: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3068: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3069: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3070: 	    my $submitted = 0;
 3071: 	    my $ungraded = 0;
 3072: 	    my $incorrect = 0;
 3073: 	    foreach my $item (keys(%status)) {
 3074: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3075: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3076: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3077: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3078: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3079: 		    $submitted = 0;
 3080: 		}
 3081: 	    }
 3082: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3083: 				     $submitonly eq 'incorrect' ||
 3084: 				     $submitonly eq 'graded'));
 3085: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3086: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3087: 	}
 3088: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3089: 	last if ($ctr == $ntstu);
 3090: 	$ctr++;
 3091:     }
 3092: 
 3093:     $ctr = 0;
 3094:     my $total = scalar(@nextlist)-1;
 3095: 
 3096:     foreach (sort(@nextlist)) {
 3097: 	my ($uname,$udom,$submitter) = split(/:/);
 3098: 	$env{'form.student'}  = $uname;
 3099: 	$env{'form.userdom'}  = $udom;
 3100: 	$env{'form.fullname'} = $$fullname{$_};
 3101: 	&submission($request,$ctr,$total);
 3102: 	$ctr++;
 3103:     }
 3104:     if ($total < 0) {
 3105: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3106: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3107: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3108: 	$the_end.=&show_grading_menu_form($symb);
 3109: 	$request->print($the_end);
 3110:     }
 3111:     return '';
 3112: }
 3113: 
 3114: #---- Save the score and award for each student, if changed
 3115: sub saveHandGrade {
 3116:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3117:     my @version_parts;
 3118:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3119: 					   $env{'request.course.id'});
 3120:     if (!&canmodify($usec)) { return('not_allowed'); }
 3121:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3122:     my @parts_graded;
 3123:     my %newrecord  = ();
 3124:     my ($pts,$wgt,$totchg) = ('','',0);
 3125:     my %aggregate = ();
 3126:     my $aggregateflag = 0;
 3127:     if ($env{'form.HIDE'.$newflg}) {
 3128:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3129:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3130:         $totchg += $numchgs;
 3131:     }
 3132:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3133:     foreach my $new_part (@parts) {
 3134: 	#collaborator ($submi may vary for different parts
 3135: 	if ($submitter && $new_part ne $part) { next; }
 3136: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3137: 	if ($dropMenu eq 'excused') {
 3138: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3139: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3140: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3141: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3142: 		}
 3143: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3144: 	    }
 3145: 	} elsif ($dropMenu eq 'reset status'
 3146: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3147: 	    foreach my $key (keys(%record)) {
 3148: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3149: 	    }
 3150: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3151: 		"$env{'user.name'}:$env{'user.domain'}";
 3152:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3153: 
 3154:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3155: 					       [$new_part]);
 3156:             my $aggtries =$totaltries;
 3157:             if ($last_resets{$new_part}) {
 3158:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3159: 					   $new_part);
 3160:             }
 3161: 
 3162:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3163:             if ($aggtries > 0) {
 3164:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3165:                 $aggregateflag = 1;
 3166:             }
 3167: 	} elsif ($dropMenu eq '') {
 3168: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3169: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3170: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3171: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3172: 		next;
 3173: 	    }
 3174: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3175: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3176: 	    my $partial= $pts/$wgt;
 3177: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3178: 		#do not update score for part if not changed.
 3179:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3180: 		next;
 3181: 	    } else {
 3182: 	        push(@parts_graded,$new_part);
 3183: 	    }
 3184: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3185: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3186: 	    }
 3187: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3188: 	    if ($partial == 0) {
 3189: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3190: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3191: 		}
 3192: 	    } else {
 3193: 		if ($record{$reckey} ne 'correct_by_override') {
 3194: 		    $newrecord{$reckey} = 'correct_by_override';
 3195: 		}
 3196: 	    }	    
 3197: 	    if ($submitter && 
 3198: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3199: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3200: 	    }
 3201: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3202: 		"$env{'user.name'}:$env{'user.domain'}";
 3203: 	}
 3204: 	# unless problem has been graded, set flag to version the submitted files
 3205: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3206: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3207: 	        $dropMenu eq 'reset status')
 3208: 	   {
 3209: 	    push(@version_parts,$new_part);
 3210: 	}
 3211:     }
 3212:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3213:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3214: 
 3215:     if (%newrecord) {
 3216:         if (@version_parts) {
 3217:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3218:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3219: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3220: 	    foreach my $new_part (@version_parts) {
 3221: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3222: 				$new_part,\%newrecord);
 3223: 	    }
 3224:         }
 3225: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3226: 				$env{'request.course.id'},$domain,$stuname);
 3227: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3228: 				     $cdom,$cnum,$domain,$stuname);
 3229:     }
 3230:     if ($aggregateflag) {
 3231:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3232: 			      $cdom,$cnum);
 3233:     }
 3234:     return ('',$pts,$wgt,$totchg);
 3235: }
 3236: 
 3237: sub makehidden {
 3238:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3239:     return unless (ref($record) eq 'HASH');
 3240:     my %modified;
 3241:     my $numchanged = 0;
 3242:     if (exists($record->{$version.':keys'})) {
 3243:         my $partsregexp = $parts;
 3244:         $partsregexp =~ s/,/|/g;
 3245:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3246:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3247:                  my $item = $1;
 3248:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3249:                      $modified{$key} = $record->{$version.':'.$key};
 3250:                  }
 3251:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3252:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3253:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3254:                 $modified{$key} = $record->{$version.':'.$key};
 3255:             }
 3256:         }
 3257:         if (keys(%modified)) {
 3258:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3259:                                           $domain,$stuname,$tolog) eq 'ok') {
 3260:                 $numchanged ++;
 3261:             }
 3262:         }
 3263:     }
 3264:     return $numchanged;
 3265: }
 3266: 
 3267: sub check_and_remove_from_queue {
 3268:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3269:     my @ungraded_parts;
 3270:     foreach my $part (@{$parts}) {
 3271: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3272: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3273: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3274: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3275: 		) {
 3276: 	    push(@ungraded_parts, $part);
 3277: 	}
 3278:     }
 3279:     if ( !@ungraded_parts ) {
 3280: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3281: 					       $cnum,$domain,$stuname);
 3282:     }
 3283: }
 3284: 
 3285: sub handback_files {
 3286:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3287:     my $portfolio_root = '/userfiles/portfolio';
 3288:     my $res_error;
 3289:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3290:     if ($res_error) {
 3291:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3292:         return;
 3293:     }
 3294:     my @handedback;
 3295:     my $file_msg;
 3296:     my @part_response_id = &flatten_responseType($responseType);
 3297:     foreach my $part_response_id (@part_response_id) {
 3298:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3299: 	my $part_resp = join('_',@{ $part_response_id });
 3300:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3301:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3302:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3303: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3304:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3305:                     my ($directory,$answer_file) = 
 3306:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3307:                     my ($answer_name,$answer_ver,$answer_ext) =
 3308: 		        &file_name_version_ext($answer_file);
 3309: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3310:                     my $getpropath = 1;
 3311:                     my ($dir_list,$listerror) =
 3312:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3313:                                                  $domain,$stuname,$getpropath);
 3314: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3315:                     # fix filename
 3316:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3317:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3318:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3319:             	                                $save_file_name);
 3320:                     if ($result !~ m|^/uploaded/|) {
 3321:                         $request->print('<br /><span class="LC_error">'.
 3322:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3323:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3324:                                         '</span>');
 3325:                     } else {
 3326:                         # mark the file as read only
 3327:                         push(@handedback,$save_file_name);
 3328: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3329: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3330: 			}
 3331:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3332: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3333: 
 3334:                     }
 3335:                     $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>'));
 3336:                 }
 3337:             }
 3338:         }
 3339:     }
 3340:     if (@handedback > 0) {
 3341:         $request->print('<br />');
 3342:         my @what = ($symb,$env{'request.course.id'},'handback');
 3343:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3344:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3345:         my ($subject,$message);
 3346:         if (scalar(@handedback) == 1) {
 3347:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3348:         } else {
 3349:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3350:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3351:         }
 3352:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3353:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3354:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3355:         my ($feedurl,$showsymb) =
 3356:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3357:         my $restitle = &Apache::lonnet::gettitle($symb);
 3358:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3359:         my $msgstatus =
 3360:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3361:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3362:                  $restitle);
 3363:         if ($msgstatus) {
 3364:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3365:         }
 3366:     }
 3367:     return;
 3368: }
 3369: 
 3370: sub get_feedurl_and_symb {
 3371:     my ($symb,$uname,$udom) = @_;
 3372:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3373:     $url = &Apache::lonnet::clutter($url);
 3374:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3375: 					$symb,$udom,$uname);
 3376:     if ($encrypturl =~ /^yes$/i) {
 3377: 	&Apache::lonenc::encrypted(\$url,1);
 3378: 	&Apache::lonenc::encrypted(\$symb,1);
 3379:     }
 3380:     return ($url,$symb);
 3381: }
 3382: 
 3383: sub get_submitted_files {
 3384:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3385:     my @files;
 3386:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3387:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3388:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3389:     	    push(@files,$file_url.$file);
 3390:         }
 3391:     }
 3392:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3393:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3394:     }
 3395:     return (\@files);
 3396: }
 3397: 
 3398: # ----------- Provides number of tries since last reset.
 3399: sub get_num_tries {
 3400:     my ($record,$last_reset,$part) = @_;
 3401:     my $timestamp = '';
 3402:     my $num_tries = 0;
 3403:     if ($$record{'version'}) {
 3404:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3405:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3406:                 $timestamp = $$record{$version.':timestamp'};
 3407:                 if ($timestamp > $last_reset) {
 3408:                     $num_tries ++;
 3409:                 } else {
 3410:                     last;
 3411:                 }
 3412:             }
 3413:         }
 3414:     }
 3415:     return $num_tries;
 3416: }
 3417: 
 3418: # ----------- Determine decrements required in aggregate totals 
 3419: sub decrement_aggs {
 3420:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3421:     my %decrement = (
 3422:                         attempts => 0,
 3423:                         users => 0,
 3424:                         correct => 0
 3425:                     );
 3426:     $decrement{'attempts'} = $aggtries;
 3427:     if ($solvedstatus =~ /^correct/) {
 3428:         $decrement{'correct'} = 1;
 3429:     }
 3430:     if ($aggtries == $totaltries) {
 3431:         $decrement{'users'} = 1;
 3432:     }
 3433:     foreach my $type (keys(%decrement)) {
 3434:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3435:     }
 3436:     return;
 3437: }
 3438: 
 3439: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3440: sub get_last_resets {
 3441:     my ($symb,$courseid,$partids) =@_;
 3442:     my %last_resets;
 3443:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3444:     my $cname = $env{'course.'.$courseid.'.num'};
 3445:     my @keys;
 3446:     foreach my $part (@{$partids}) {
 3447: 	push(@keys,"$symb\0$part\0resettime");
 3448:     }
 3449:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3450: 				     $cdom,$cname);
 3451:     foreach my $part (@{$partids}) {
 3452: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3453:     }
 3454:     return %last_resets;
 3455: }
 3456: 
 3457: # ----------- Handles creating versions for portfolio files as answers
 3458: sub version_portfiles {
 3459:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3460:     my $version_parts = join('|',@$v_flag);
 3461:     my @returned_keys;
 3462:     my $parts = join('|', @$parts_graded);
 3463:     my $portfolio_root = '/userfiles/portfolio';
 3464:     foreach my $key (keys(%$record)) {
 3465:         my $new_portfiles;
 3466:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3467:             my @versioned_portfiles;
 3468:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3469:             foreach my $file (@portfiles) {
 3470:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3471:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3472: 		my ($answer_name,$answer_ver,$answer_ext) =
 3473: 		    &file_name_version_ext($answer_file);
 3474:                 my $getpropath = 1;
 3475:                 my ($dir_list,$listerror) =
 3476:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3477:                                              $stu_name,$getpropath);
 3478:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3479:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3480:                 if ($new_answer ne 'problem getting file') {
 3481:                     push(@versioned_portfiles, $directory.$new_answer);
 3482:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3483:                         [$directory.$new_answer],
 3484:                         [$symb,$env{'request.course.id'},'graded']);
 3485:                 }
 3486:             }
 3487:             $$record{$key} = join(',',@versioned_portfiles);
 3488:             push(@returned_keys,$key);
 3489:         }
 3490:     } 
 3491:     return (@returned_keys);   
 3492: }
 3493: 
 3494: sub get_next_version {
 3495:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3496:     my $version;
 3497:     if (ref($dir_list) eq 'ARRAY') {
 3498:         foreach my $row (@{$dir_list}) {
 3499:             my ($file) = split(/\&/,$row,2);
 3500:             my ($file_name,$file_version,$file_ext) =
 3501: 	        &file_name_version_ext($file);
 3502:             if (($file_name eq $answer_name) && 
 3503: 	        ($file_ext eq $answer_ext)) {
 3504:                 # gets here if filename and extension match, 
 3505:                 # regardless of version
 3506:                 if ($file_version ne '') {
 3507:                     # a versioned file is found  so save it for later
 3508:                     if ($file_version > $version) {
 3509: 		        $version = $file_version;
 3510:                     }
 3511: 	        }
 3512:             }
 3513:         }
 3514:     }
 3515:     $version ++;
 3516:     return($version);
 3517: }
 3518: 
 3519: sub version_selected_portfile {
 3520:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3521:     my ($answer_name,$answer_ver,$answer_ext) =
 3522:         &file_name_version_ext($file_name);
 3523:     my $new_answer;
 3524:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3525:     if($env{'form.copy'} eq '-1') {
 3526:         $new_answer = 'problem getting file';
 3527:     } else {
 3528:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3529:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3530:                             $stu_name,$domain,'copy',
 3531: 		        '/portfolio'.$directory.$new_answer);
 3532:     }    
 3533:     return ($new_answer);
 3534: }
 3535: 
 3536: sub file_name_version_ext {
 3537:     my ($file)=@_;
 3538:     my @file_parts = split(/\./, $file);
 3539:     my ($name,$version,$ext);
 3540:     if (@file_parts > 1) {
 3541: 	$ext=pop(@file_parts);
 3542: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3543: 	    $version=pop(@file_parts);
 3544: 	}
 3545: 	$name=join('.',@file_parts);
 3546:     } else {
 3547: 	$name=join('.',@file_parts);
 3548:     }
 3549:     return($name,$version,$ext);
 3550: }
 3551: 
 3552: #--------------------------------------------------------------------------------------
 3553: #
 3554: #-------------------------- Next few routines handles grading by section or whole class
 3555: #
 3556: #--- Javascript to handle grading by section or whole class
 3557: sub viewgrades_js {
 3558:     my ($request) = shift;
 3559: 
 3560:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3561:     &js_escape(\$alertmsg);
 3562:     $request->print(<<VIEWJAVASCRIPT);
 3563: <script type="text/javascript" language="javascript">
 3564:    function writePoint(partid,weight,point) {
 3565: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3566: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3567: 	if (point == "textval") {
 3568: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3569: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3570: 		alert("$alertmsg"+parseFloat(point));
 3571: 		var resetbox = false;
 3572: 		for (var i=0; i<radioButton.length; i++) {
 3573: 		    if (radioButton[i].checked) {
 3574: 			textbox.value = i;
 3575: 			resetbox = true;
 3576: 		    }
 3577: 		}
 3578: 		if (!resetbox) {
 3579: 		    textbox.value = "";
 3580: 		}
 3581: 		return;
 3582: 	    }
 3583: 	    if (parseFloat(point) > parseFloat(weight)) {
 3584: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3585: 				   ") greater than the weight for the part. Accept?");
 3586: 		if (resp == false) {
 3587: 		    textbox.value = "";
 3588: 		    return;
 3589: 		}
 3590: 	    }
 3591: 	    for (var i=0; i<radioButton.length; i++) {
 3592: 		radioButton[i].checked=false;
 3593: 		if (parseFloat(point) == i) {
 3594: 		    radioButton[i].checked=true;
 3595: 		}
 3596: 	    }
 3597: 
 3598: 	} else {
 3599: 	    textbox.value = parseFloat(point);
 3600: 	}
 3601: 	for (i=0;i<document.classgrade.total.value;i++) {
 3602: 	    var user = document.classgrade["ctr"+i].value;
 3603: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3604: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3605: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3606: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3607: 	    if (saveval != "correct") {
 3608: 		scorename.value = point;
 3609: 		if (selname[0].selected != true) {
 3610: 		    selname[0].selected = true;
 3611: 		}
 3612: 	    }
 3613: 	}
 3614: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3615:     }
 3616: 
 3617:     function writeRadText(partid,weight) {
 3618: 	var selval   = document.classgrade["SELVAL_"+partid];
 3619: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3620:         var override = document.classgrade["FORCE_"+partid].checked;
 3621: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3622: 	if (selval[1].selected || selval[2].selected) {
 3623: 	    for (var i=0; i<radioButton.length; i++) {
 3624: 		radioButton[i].checked=false;
 3625: 
 3626: 	    }
 3627: 	    textbox.value = "";
 3628: 
 3629: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3630: 		var user = document.classgrade["ctr"+i].value;
 3631: 		user = user.replace(new RegExp(':', 'g'),"_");
 3632: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3633: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3634: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3635: 		if ((saveval != "correct") || override) {
 3636: 		    scorename.value = "";
 3637: 		    if (selval[1].selected) {
 3638: 			selname[1].selected = true;
 3639: 		    } else {
 3640: 			selname[2].selected = true;
 3641: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3642: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3643: 		    }
 3644: 		}
 3645: 	    }
 3646: 	} else {
 3647: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3648: 		var user = document.classgrade["ctr"+i].value;
 3649: 		user = user.replace(new RegExp(':', 'g'),"_");
 3650: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3651: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3652: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3653: 		if ((saveval != "correct") || override) {
 3654: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3655: 		    selname[0].selected = true;
 3656: 		}
 3657: 	    }
 3658: 	}	    
 3659:     }
 3660: 
 3661:     function changeSelect(partid,user) {
 3662: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3663: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3664: 	var point  = textbox.value;
 3665: 	var weight = document.classgrade["weight_"+partid].value;
 3666: 
 3667: 	if (isNaN(point) || parseFloat(point) < 0) {
 3668: 	    alert("$alertmsg"+parseFloat(point));
 3669: 	    textbox.value = "";
 3670: 	    return;
 3671: 	}
 3672: 	if (parseFloat(point) > parseFloat(weight)) {
 3673: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3674: 			       ") greater than the weight of the part. Accept?");
 3675: 	    if (resp == false) {
 3676: 		textbox.value = "";
 3677: 		return;
 3678: 	    }
 3679: 	}
 3680: 	selval[0].selected = true;
 3681:     }
 3682: 
 3683:     function changeOneScore(partid,user) {
 3684: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3685: 	if (selval[1].selected || selval[2].selected) {
 3686: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3687: 	    if (selval[2].selected) {
 3688: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3689: 	    }
 3690:         }
 3691:     }
 3692: 
 3693:     function resetEntry(numpart) {
 3694: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3695: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3696: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3697: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3698: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3699: 	    for (var i=0; i<radioButton.length; i++) {
 3700: 		radioButton[i].checked=false;
 3701: 
 3702: 	    }
 3703: 	    textbox.value = "";
 3704: 	    selval[0].selected = true;
 3705: 
 3706: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3707: 		var user = document.classgrade["ctr"+i].value;
 3708: 		user = user.replace(new RegExp(':', 'g'),"_");
 3709: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3710: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3711: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3712: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3713: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3714: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3715: 		if (saveselval == "excused") {
 3716: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3717: 		} else {
 3718: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3719: 		}
 3720: 	    }
 3721: 	}
 3722:     }
 3723: 
 3724: </script>
 3725: VIEWJAVASCRIPT
 3726: }
 3727: 
 3728: #--- show scores for a section or whole class w/ option to change/update a score
 3729: sub viewgrades {
 3730:     my ($request) = shift;
 3731:     &viewgrades_js($request);
 3732: 
 3733:     my ($symb) = &get_symb($request);
 3734:     #need to make sure we have the correct data for later EXT calls, 
 3735:     #thus invalidate the cache
 3736:     &Apache::lonnet::devalidatecourseresdata(
 3737:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3738:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3739:     &Apache::lonnet::clear_EXT_cache_status();
 3740: 
 3741:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3742:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3743: 
 3744:     #view individual student submission form - called using Javascript viewOneStudent
 3745:     $result.=&jscriptNform($symb);
 3746: 
 3747:     #beginning of class grading form
 3748:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3749:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3750: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3751: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3752: 	&build_section_inputs().
 3753: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3754: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3755: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3756: 
 3757:     my ($common_header,$specific_header);
 3758:     if ($env{'form.section'} eq 'all') {
 3759: 	$common_header = &mt('Assign Common Grade to Class');
 3760:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3761:     } elsif ($env{'form.section'} eq 'none') {
 3762:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3763: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3764:     } else {
 3765:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3766:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3767: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3768:     }
 3769:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3770:     #radio buttons/text box for assigning points for a section or class.
 3771:     #handles different parts of a problem
 3772:     my $res_error;
 3773:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3774:     if ($res_error) {
 3775:         return &navmap_errormsg();
 3776:     }
 3777:     my %weight = ();
 3778:     my $ctsparts = 0;
 3779:     my %seen = ();
 3780:     my @part_response_id = &flatten_responseType($responseType);
 3781:     foreach my $part_response_id (@part_response_id) {
 3782:     	my ($partid,$respid) = @{ $part_response_id };
 3783: 	my $part_resp = join('_',@{ $part_response_id });
 3784: 	next if $seen{$partid};
 3785: 	$seen{$partid}++;
 3786: 	my $handgrade=$$handgrade{$part_resp};
 3787: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3788: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3789: 
 3790: 	my $display_part=&get_display_part($partid,$symb);
 3791: 	my $radio.='<table border="0"><tr>';  
 3792: 	my $ctr = 0;
 3793: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3794: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3795: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3796: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3797: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3798: 	    $ctr++;
 3799: 	}
 3800: 	$radio.='</tr></table>';
 3801: 	my $line = '<input type="text" name="TEXTVAL_'.
 3802: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3803: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3804: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3805: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3806:                 '<select name="SELVAL_'.$partid.'" '.
 3807: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3808: 		$weight{$partid}.')"> '.
 3809: 	    '<option selected="selected"> </option>'.
 3810: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3811: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3812: 	    '</select></td>'.
 3813:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3814: 	$line.='<input type="hidden" name="partid_'.
 3815: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3816: 	$line.='<input type="hidden" name="weight_'.
 3817: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3818: 
 3819: 	$result.=
 3820: 	    &Apache::loncommon::start_data_table_row()."\n".
 3821: 	    '<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>'.
 3822: 	    &Apache::loncommon::end_data_table_row()."\n";
 3823: 	$ctsparts++;
 3824:     }
 3825:     $result.=&Apache::loncommon::end_data_table()."\n".
 3826: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3827:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3828: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3829: 
 3830:     #table listing all the students in a section/class
 3831:     #header of table
 3832:     $result.= '<h3>'.$specific_header.'</h3>'.
 3833:               &Apache::loncommon::start_data_table().
 3834: 	      &Apache::loncommon::start_data_table_header_row().
 3835: 	      '<th>'.&mt('No.').'</th>'.
 3836: 	      '<th>'.&nameUserString('header')."</th>\n";
 3837:     my $partserror;
 3838:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3839:     if ($partserror) {
 3840:         return &navmap_errormsg();
 3841:     }
 3842:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3843:     my @partids = ();
 3844:     foreach my $part (@parts) {
 3845: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3846:         my $narrowtext = &mt('Tries');
 3847: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3848: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3849: 	my ($partid) = &split_part_type($part);
 3850:         push(@partids,$partid);
 3851: 	my $display_part=&get_display_part($partid,$symb);
 3852: 	if ($display =~ /^Partial Credit Factor/) {
 3853: 	    $result.='<th>'.
 3854:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3855:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3856: 	    next;
 3857: 	    
 3858: 	} else {
 3859: 	    if ($display =~ /Problem Status/) {
 3860: 		my $grade_status_mt = &mt('Grade Status');
 3861: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3862: 	    }
 3863: 	    my $part_mt = &mt('Part:');
 3864: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3865: 	}
 3866: 
 3867: 	$result.='<th>'.$display.'</th>'."\n";
 3868:     }
 3869:     $result.=&Apache::loncommon::end_data_table_header_row();
 3870: 
 3871:     my %last_resets = 
 3872: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3873: 
 3874:     #get info for each student
 3875:     #list all the students - with points and grade status
 3876:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3877:     my $ctr = 0;
 3878:     foreach (sort 
 3879: 	     {
 3880: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3881: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3882: 		 }
 3883: 		 return $a cmp $b;
 3884: 	     } (keys(%$fullname))) {
 3885: 	$ctr++;
 3886: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3887: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3888:     }
 3889:     $result.=&Apache::loncommon::end_data_table();
 3890:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3891:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3892: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3893:     if (scalar(%$fullname) eq 0) {
 3894: 	my $colspan=3+scalar(@parts);
 3895: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3896:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3897: 	$result='<span class="LC_warning">'.
 3898: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3899: 	        $section_display, $stu_status).
 3900: 	    '</span>';
 3901:     }
 3902:     $result.=&show_grading_menu_form($symb);
 3903:     return $result;
 3904: }
 3905: 
 3906: #--- call by previous routine to display each student
 3907: sub viewstudentgrade {
 3908:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3909:     my ($uname,$udom) = split(/:/,$student);
 3910:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3911:     my %aggregates = (); 
 3912:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3913: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3914: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3915: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3916: 	'\');" target="_self">'.$fullname.'</a> '.
 3917: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3918:     $student=~s/:/_/; # colon doen't work in javascript for names
 3919:     foreach my $apart (@$parts) {
 3920: 	my ($part,$type) = &split_part_type($apart);
 3921: 	my $score=$record{"resource.$part.$type"};
 3922:         $result.='<td align="center">';
 3923:         my ($aggtries,$totaltries);
 3924:         unless (exists($aggregates{$part})) {
 3925: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3926: 
 3927: 	    $aggtries = $totaltries;
 3928:             if ($$last_resets{$part}) {  
 3929:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3930: 					   $part);
 3931:             }
 3932:             $result.='<input type="hidden" name="'.
 3933:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3934:             $result.='<input type="hidden" name="'.
 3935:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3936:             $aggregates{$part} = 1;
 3937:         }
 3938: 	if ($type eq 'awarded') {
 3939: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3940: 	    $result.='<input type="hidden" name="'.
 3941: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3942: 	    $result.='<input type="text" name="'.
 3943: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3944:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3945: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3946: 	} elsif ($type eq 'solved') {
 3947: 	    my ($status,$foo)=split(/_/,$score,2);
 3948: 	    $status = 'nothing' if ($status eq '');
 3949: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3950: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3951: 	    $result.='&nbsp;<select name="'.
 3952: 		'GD_'.$student.'_'.$part.'_solved" '.
 3953:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3954: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3955: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3956: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3957: 	    $result.="</select>&nbsp;</td>\n";
 3958: 	} else {
 3959: 	    $result.='<input type="hidden" name="'.
 3960: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3961: 		    "\n";
 3962: 	    $result.='<input type="text" name="'.
 3963: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3964: 		'value="'.$score.'" size="4" /></td>'."\n";
 3965: 	}
 3966:     }
 3967:     $result.=&Apache::loncommon::end_data_table_row();
 3968:     return $result;
 3969: }
 3970: 
 3971: #--- change scores for all the students in a section/class
 3972: #    record does not get update if unchanged
 3973: sub editgrades {
 3974:     my ($request) = @_;
 3975: 
 3976:     my ($symb)=&get_symb($request);
 3977:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3978:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3979:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3980:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 3981: 
 3982:     my $result= &Apache::loncommon::start_data_table().
 3983: 	&Apache::loncommon::start_data_table_header_row().
 3984: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3985: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3986:     my %scoreptr = (
 3987: 		    'correct'  =>'correct_by_override',
 3988: 		    'incorrect'=>'incorrect_by_override',
 3989: 		    'excused'  =>'excused',
 3990: 		    'ungraded' =>'ungraded_attempted',
 3991:                     'credited' =>'credit_attempted',
 3992: 		    'nothing'  => '',
 3993: 		    );
 3994:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3995: 
 3996:     my (@partid);
 3997:     my %weight = ();
 3998:     my %columns = ();
 3999:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4000: 
 4001:     my $partserror;
 4002:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4003:     if ($partserror) {
 4004:         return &navmap_errormsg();
 4005:     }
 4006:     my $header;
 4007:     while ($ctr < $env{'form.totalparts'}) {
 4008: 	my $partid = $env{'form.partid_'.$ctr};
 4009: 	push(@partid,$partid);
 4010: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4011: 	$ctr++;
 4012:     }
 4013:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4014:     foreach my $partid (@partid) {
 4015: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4016: 	    '<th align="center">'.&mt('New Score').'</th>';
 4017: 	$columns{$partid}=2;
 4018: 	foreach my $stores (@parts) {
 4019: 	    my ($part,$type) = &split_part_type($stores);
 4020: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4021: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4022: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4023: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4024:             my $narrowtext = &mt('Tries');
 4025: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4026: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4027: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4028: 	    $columns{$partid}+=2;
 4029: 	}
 4030:     }
 4031:     foreach my $partid (@partid) {
 4032: 	my $display_part=&get_display_part($partid,$symb);
 4033: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4034: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4035: 	    '</th>';
 4036: 
 4037:     }
 4038:     $result .= &Apache::loncommon::end_data_table_header_row().
 4039: 	&Apache::loncommon::start_data_table_header_row().
 4040: 	$header.
 4041: 	&Apache::loncommon::end_data_table_header_row();
 4042:     my @noupdate;
 4043:     my ($updateCtr,$noupdateCtr) = (1,1);
 4044:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4045: 	my $line;
 4046: 	my $user = $env{'form.ctr'.$i};
 4047: 	my ($uname,$udom)=split(/:/,$user);
 4048: 	my %newrecord;
 4049: 	my $updateflag = 0;
 4050: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4051: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4052: 	if (!&canmodify($usec)) {
 4053: 	    my $numcols=scalar(@partid)*4+2;
 4054: 	    push(@noupdate,
 4055: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 4056: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 4057: 	    next;
 4058: 	}
 4059:         my %aggregate = ();
 4060:         my $aggregateflag = 0;
 4061: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4062: 	foreach (@partid) {
 4063: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4064: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4065: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4066: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4067: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4068: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4069: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4070: 	    my $score;
 4071: 	    if ($partial eq '') {
 4072: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4073: 	    } elsif ($partial > 0) {
 4074: 		$score = 'correct_by_override';
 4075: 	    } elsif ($partial == 0) {
 4076: 		$score = 'incorrect_by_override';
 4077: 	    }
 4078: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4079: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4080: 
 4081: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4082: 		"$env{'user.name'}:$env{'user.domain'}";
 4083: 	    if ($dropMenu eq 'reset status' &&
 4084: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4085: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4086: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4087: 		$newrecord{'resource.'.$_.'.award'} = '';
 4088: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4089: 		$updateflag = 1;
 4090:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4091:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4092:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4093:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4094:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4095:                     $aggregateflag = 1;
 4096:                 }
 4097: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4098: 		$updateflag = 1;
 4099: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4100: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4101: 		$rec_update++;
 4102: 	    }
 4103: 
 4104: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4105: 		'<td align="center">'.$awarded.
 4106: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4107: 
 4108: 
 4109: 	    my $partid=$_;
 4110: 	    foreach my $stores (@parts) {
 4111: 		my ($part,$type) = &split_part_type($stores);
 4112: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4113: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4114: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4115: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4116: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4117: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4118: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4119: 		    $updateflag=1;
 4120: 		}
 4121: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4122: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4123: 	    }
 4124: 	}
 4125: 	$line.="\n";
 4126: 
 4127: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4128: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4129: 
 4130: 	if ($updateflag) {
 4131: 	    $count++;
 4132: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4133: 				    $udom,$uname);
 4134: 
 4135: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4136: 					      $cnum,$udom,$uname)) {
 4137: 		# need to figure out if should be in queue.
 4138: 		my %record =  
 4139: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4140: 					     $udom,$uname);
 4141: 		my $all_graded = 1;
 4142: 		my $none_graded = 1;
 4143: 		foreach my $part (@parts) {
 4144: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4145: 			$all_graded = 0;
 4146: 		    } else {
 4147: 			$none_graded = 0;
 4148: 		    }
 4149: 		}
 4150: 
 4151: 		if ($all_graded || $none_graded) {
 4152: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4153: 							   $symb,$cdom,$cnum,
 4154: 							   $udom,$uname);
 4155: 		}
 4156: 	    }
 4157: 
 4158: 	    $result.=&Apache::loncommon::start_data_table_row().
 4159: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4160: 		&Apache::loncommon::end_data_table_row();
 4161: 	    $updateCtr++;
 4162: 	} else {
 4163: 	    push(@noupdate,
 4164: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4165: 	    $noupdateCtr++;
 4166: 	}
 4167:         if ($aggregateflag) {
 4168:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4169: 				  $cdom,$cnum);
 4170:         }
 4171:     }
 4172:     if (@noupdate) {
 4173: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4174: 	my $numcols=scalar(@partid)*4+2;
 4175: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4176: 	    '<td align="center" colspan="'.$numcols.'">'.
 4177: 	    &mt('No Changes Occurred For the Students Below').
 4178: 	    '</td>'.
 4179: 	    &Apache::loncommon::end_data_table_row();
 4180: 	foreach my $line (@noupdate) {
 4181: 	    $result.=
 4182: 		&Apache::loncommon::start_data_table_row().
 4183: 		$line.
 4184: 		&Apache::loncommon::end_data_table_row();
 4185: 	}
 4186:     }
 4187:     $result .= &Apache::loncommon::end_data_table().
 4188: 	&show_grading_menu_form($symb);
 4189:     my $msg = '<p><b>'.
 4190: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4191: 	    $rec_update,$count).'</b><br />'.
 4192: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4193: 	'</b></p>';
 4194:     return $title.$msg.$result;
 4195: }
 4196: 
 4197: sub split_part_type {
 4198:     my ($partstr) = @_;
 4199:     my ($temp,@allparts)=split(/_/,$partstr);
 4200:     my $type=pop(@allparts);
 4201:     my $part=join('_',@allparts);
 4202:     return ($part,$type);
 4203: }
 4204: 
 4205: #------------- end of section for handling grading by section/class ---------
 4206: #
 4207: #----------------------------------------------------------------------------
 4208: 
 4209: 
 4210: #----------------------------------------------------------------------------
 4211: #
 4212: #-------------------------- Next few routines handles grading by csv upload
 4213: #
 4214: #--- Javascript to handle csv upload
 4215: sub csvupload_javascript_reverse_associate {
 4216:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4217:     my $error2=&mt('You need to specify at least one grading field');
 4218:   &js_escape(\$error1);
 4219:   &js_escape(\$error2);
 4220:   return(<<ENDPICK);
 4221:   function verify(vf) {
 4222:     var foundsomething=0;
 4223:     var founduname=0;
 4224:     var foundID=0;
 4225:     for (i=0;i<=vf.nfields.value;i++) {
 4226:       tw=eval('vf.f'+i+'.selectedIndex');
 4227:       if (i==0 && tw!=0) { foundID=1; }
 4228:       if (i==1 && tw!=0) { founduname=1; }
 4229:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4230:     }
 4231:     if (founduname==0 && foundID==0) {
 4232: 	alert('$error1');
 4233: 	return;
 4234:     }
 4235:     if (foundsomething==0) {
 4236: 	alert('$error2');
 4237: 	return;
 4238:     }
 4239:     vf.submit();
 4240:   }
 4241:   function flip(vf,tf) {
 4242:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4243:     var i;
 4244:     for (i=0;i<=vf.nfields.value;i++) {
 4245:       //can not pick the same destination field for both name and domain
 4246:       if (((i ==0)||(i ==1)) && 
 4247:           ((tf==0)||(tf==1)) && 
 4248:           (i!=tf) &&
 4249:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4250:         eval('vf.f'+i+'.selectedIndex=0;')
 4251:       }
 4252:     }
 4253:   }
 4254: ENDPICK
 4255: }
 4256: 
 4257: sub csvupload_javascript_forward_associate {
 4258:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4259:     my $error2=&mt('You need to specify at least one grading field');
 4260:   &js_escape(\$error1);
 4261:   &js_escape(\$error2);
 4262:   return(<<ENDPICK);
 4263:   function verify(vf) {
 4264:     var foundsomething=0;
 4265:     var founduname=0;
 4266:     var foundID=0;
 4267:     for (i=0;i<=vf.nfields.value;i++) {
 4268:       tw=eval('vf.f'+i+'.selectedIndex');
 4269:       if (tw==1) { foundID=1; }
 4270:       if (tw==2) { founduname=1; }
 4271:       if (tw>3) { foundsomething=1; }
 4272:     }
 4273:     if (founduname==0 && foundID==0) {
 4274: 	alert('$error1');
 4275: 	return;
 4276:     }
 4277:     if (foundsomething==0) {
 4278: 	alert('$error2');
 4279: 	return;
 4280:     }
 4281:     vf.submit();
 4282:   }
 4283:   function flip(vf,tf) {
 4284:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4285:     var i;
 4286:     //can not pick the same destination field twice
 4287:     for (i=0;i<=vf.nfields.value;i++) {
 4288:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4289:         eval('vf.f'+i+'.selectedIndex=0;')
 4290:       }
 4291:     }
 4292:   }
 4293: ENDPICK
 4294: }
 4295: 
 4296: sub csvuploadmap_header {
 4297:     my ($request,$symb,$datatoken,$distotal)= @_;
 4298:     my $javascript;
 4299:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4300: 	$javascript=&csvupload_javascript_reverse_associate();
 4301:     } else {
 4302: 	$javascript=&csvupload_javascript_forward_associate();
 4303:     }
 4304: 
 4305:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4306:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4307:     my $ignore=&mt('Ignore First Line');
 4308:     $symb = &Apache::lonenc::check_encrypt($symb);
 4309:     $request->print(<<ENDPICK);
 4310: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4311: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4312: $result
 4313: <hr />
 4314: <h3>Identify fields</h3>
 4315: Total number of records found in file: $distotal <hr />
 4316: Enter as many fields as you can. The system will inform you and bring you back
 4317: to this page if the data selected is insufficient to run your class.<hr />
 4318: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4319: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4320: <input type="hidden" name="associate"  value="" />
 4321: <input type="hidden" name="phase"      value="three" />
 4322: <input type="hidden" name="datatoken"  value="$datatoken" />
 4323: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4324: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4325: <input type="hidden" name="upfile_associate" 
 4326:                                        value="$env{'form.upfile_associate'}" />
 4327: <input type="hidden" name="symb"       value="$symb" />
 4328: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4329: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4330: <input type="hidden" name="command"    value="csvuploadoptions" />
 4331: <hr />
 4332: <script type="text/javascript" language="Javascript">
 4333: $javascript
 4334: </script>
 4335: ENDPICK
 4336:     return '';
 4337: 
 4338: }
 4339: 
 4340: sub csvupload_fields {
 4341:     my ($symb,$errorref) = @_;
 4342:     my (@parts) = &getpartlist($symb,$errorref);
 4343:     if (ref($errorref)) {
 4344:         if ($$errorref) {
 4345:             return;
 4346:         }
 4347:     }
 4348: 
 4349:     my @fields=(['ID','Student/Employee ID'],
 4350: 		['username','Student Username'],
 4351: 		['domain','Student Domain']);
 4352:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4353:     foreach my $part (sort(@parts)) {
 4354: 	my @datum;
 4355: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4356: 	my $name=$part;
 4357: 	if  (!$display) { $display = $name; }
 4358: 	@datum=($name,$display);
 4359: 	if ($name=~/^stores_(.*)_awarded/) {
 4360: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4361: 	}
 4362: 	push(@fields,\@datum);
 4363:     }
 4364:     return (@fields);
 4365: }
 4366: 
 4367: sub csvuploadmap_footer {
 4368:     my ($request,$i,$keyfields) =@_;
 4369:     my $buttontext = &mt('Assign Grades');
 4370:     $request->print(<<ENDPICK);
 4371: </table>
 4372: <input type="hidden" name="nfields" value="$i" />
 4373: <input type="hidden" name="keyfields" value="$keyfields" />
 4374: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4375: </form>
 4376: ENDPICK
 4377: }
 4378: 
 4379: sub checkforfile_js {
 4380:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4381:     &js_escape(\$alertmsg);
 4382:     my $result =<<CSVFORMJS;
 4383: <script type="text/javascript" language="javascript">
 4384:     function checkUpload(formname) {
 4385: 	if (formname.upfile.value == "") {
 4386: 	    alert("$alertmsg");
 4387: 	    return false;
 4388: 	}
 4389: 	formname.submit();
 4390:     }
 4391:     </script>
 4392: CSVFORMJS
 4393:     return $result;
 4394: }
 4395: 
 4396: sub upcsvScores_form {
 4397:     my ($request) = shift;
 4398:     my ($symb)=&get_symb($request);
 4399:     if (!$symb) {return '';}
 4400:     my $result=&checkforfile_js();
 4401:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4402:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4403:     $result.=$table;
 4404:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4405:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4406:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4407: 	'</b></td></tr>'."\n";
 4408:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4409:     my $upload=&mt("Upload Scores");
 4410:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4411:     my $ignore=&mt('Ignore First Line');
 4412:     $symb = &Apache::lonenc::check_encrypt($symb);
 4413:     $result.=<<ENDUPFORM;
 4414: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4415: <input type="hidden" name="symb" value="$symb" />
 4416: <input type="hidden" name="command" value="csvuploadmap" />
 4417: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4418: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4419: $upfile_select
 4420: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4421: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4422: </form>
 4423: ENDUPFORM
 4424:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4425:                            &mt("How do I create a CSV file from a spreadsheet"))
 4426:     .'</td></tr></table>'."\n";
 4427:     $result.='</td></tr></table><br /><br />'."\n";
 4428:     $result.=&show_grading_menu_form($symb);
 4429:     return $result;
 4430: }
 4431: 
 4432: 
 4433: sub csvuploadmap {
 4434:     my ($request)= @_;
 4435:     my ($symb)=&get_symb($request);
 4436:     if (!$symb) {return '';}
 4437: 
 4438:     my $datatoken;
 4439:     if (!$env{'form.datatoken'}) {
 4440: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4441:     } else {
 4442: 	$datatoken=$env{'form.datatoken'};
 4443: 	&Apache::loncommon::load_tmp_file($request);
 4444:     }
 4445:     my @records=&Apache::loncommon::upfile_record_sep();
 4446:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4447:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4448:     my ($i,$keyfields);
 4449:     if (@records) {
 4450:         my $fieldserror;
 4451: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4452:         if ($fieldserror) {
 4453:             $request->print(&navmap_errormsg());
 4454:             return;
 4455:         }
 4456: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4457: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4458: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4459: 							  \@fields);
 4460: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4461: 	    chop($keyfields);
 4462: 	} else {
 4463: 	    unshift(@fields,['none','']);
 4464: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4465: 							    \@fields);
 4466:             foreach my $rec (@records) {
 4467:                 my %temp = &Apache::loncommon::record_sep($rec);
 4468:                 if (%temp) {
 4469:                     $keyfields=join(',',sort(keys(%temp)));
 4470:                     last;
 4471:                 }
 4472:             }
 4473: 	}
 4474:     }
 4475:     &csvuploadmap_footer($request,$i,$keyfields);
 4476:     $request->print(&show_grading_menu_form($symb));
 4477: 
 4478:     return '';
 4479: }
 4480: 
 4481: sub csvuploadoptions {
 4482:     my ($request)= @_;
 4483:     my ($symb)=&get_symb($request);
 4484:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4485:     my $ignore=&mt('Ignore First Line');
 4486:     $request->print(<<ENDPICK);
 4487: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4488: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4489: <input type="hidden" name="command"    value="csvuploadassign" />
 4490: <!--
 4491: <p>
 4492: <label>
 4493:    <input type="checkbox" name="show_full_results" />
 4494:    Show a table of all changes
 4495: </label>
 4496: </p>
 4497: -->
 4498: <p>
 4499: <label>
 4500:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4501:    Overwrite any existing score
 4502: </label>
 4503: </p>
 4504: ENDPICK
 4505:     my %fields=&get_fields();
 4506:     if (!defined($fields{'domain'})) {
 4507: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4508: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4509:     }
 4510:     foreach my $key (sort(keys(%env))) {
 4511: 	if ($key !~ /^form\.(.*)$/) { next; }
 4512: 	my $cleankey=$1;
 4513: 	if ($cleankey eq 'command') { next; }
 4514: 	$request->print('<input type="hidden" name="'.$cleankey.
 4515: 			'"  value="'.$env{$key}.'" />'."\n");
 4516:     }
 4517:     # FIXME do a check for any duplicated user ids...
 4518:     # FIXME do a check for any invalid user ids?...
 4519:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4520: <hr /></form>'."\n");
 4521:     $request->print(&show_grading_menu_form($symb));
 4522:     return '';
 4523: }
 4524: 
 4525: sub get_fields {
 4526:     my %fields;
 4527:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4528:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4529: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4530: 	    if ($env{'form.f'.$i} ne 'none') {
 4531: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4532: 	    }
 4533: 	} else {
 4534: 	    if ($env{'form.f'.$i} ne 'none') {
 4535: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4536: 	    }
 4537: 	}
 4538:     }
 4539:     return %fields;
 4540: }
 4541: 
 4542: sub csvuploadassign {
 4543:     my ($request)= @_;
 4544:     my ($symb)=&get_symb($request);
 4545:     if (!$symb) {return '';}
 4546:     my $error_msg = '';
 4547:     &Apache::loncommon::load_tmp_file($request);
 4548:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4549:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4550:     my %fields=&get_fields();
 4551:     $request->print('<h3>Assigning Grades</h3>');
 4552:     my $courseid=$env{'request.course.id'};
 4553:     my ($classlist) = &getclasslist('all',0);
 4554:     my @notallowed;
 4555:     my @skipped;
 4556:     my @warnings;
 4557:     my $countdone=0;
 4558:     foreach my $grade (@gradedata) {
 4559: 	my %entries=&Apache::loncommon::record_sep($grade);
 4560: 	my $domain;
 4561: 	if ($entries{$fields{'domain'}}) {
 4562: 	    $domain=$entries{$fields{'domain'}};
 4563: 	} else {
 4564: 	    $domain=$env{'form.default_domain'};
 4565: 	}
 4566: 	$domain=~s/\s//g;
 4567: 	my $username=$entries{$fields{'username'}};
 4568: 	$username=~s/\s//g;
 4569: 	if (!$username) {
 4570: 	    my $id=$entries{$fields{'ID'}};
 4571: 	    $id=~s/\s//g;
 4572: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4573: 	    $username=$ids{$id};
 4574: 	}
 4575: 	if (!exists($$classlist{"$username:$domain"})) {
 4576: 	    my $id=$entries{$fields{'ID'}};
 4577: 	    $id=~s/\s//g;
 4578: 	    if ($id) {
 4579: 		push(@skipped,"$id:$domain");
 4580: 	    } else {
 4581: 		push(@skipped,"$username:$domain");
 4582: 	    }
 4583: 	    next;
 4584: 	}
 4585: 	my $usec=$classlist->{"$username:$domain"}[5];
 4586: 	if (!&canmodify($usec)) {
 4587: 	    push(@notallowed,"$username:$domain");
 4588: 	    next;
 4589: 	}
 4590: 	my %points;
 4591: 	my %grades;
 4592: 	foreach my $dest (keys(%fields)) {
 4593: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4594: 		$dest eq 'domain') { next; }
 4595: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4596: 	    if ($dest=~/stores_(.*)_points/) {
 4597: 		my $part=$1;
 4598: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4599: 					      $symb,$domain,$username);
 4600:                 if ($wgt) {
 4601:                     $entries{$fields{$dest}}=~s/\s//g;
 4602:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4603:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4604:                                           : 'correct_by_override';
 4605:                     if ($pcr>1) {
 4606:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4607:                     }
 4608:                     $grades{"resource.$part.awarded"}=$pcr;
 4609:                     $grades{"resource.$part.solved"}=$award;
 4610:                     $points{$part}=1;
 4611:                 } else {
 4612:                     $error_msg = "<br />" .
 4613:                         &mt("Some point values were assigned"
 4614:                             ." for problems with a weight "
 4615:                             ."of zero. These values were "
 4616:                             ."ignored.");
 4617:                 }
 4618: 	    } else {
 4619: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4620: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4621: 		my $store_key=$dest;
 4622: 		$store_key=~s/^stores/resource/;
 4623: 		$store_key=~s/_/\./g;
 4624: 		$grades{$store_key}=$entries{$fields{$dest}};
 4625: 	    }
 4626: 	}
 4627: 	if (! %grades) { 
 4628:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4629:         } else {
 4630: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4631: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4632: 					   $env{'request.course.id'},
 4633: 					   $domain,$username);
 4634: 	   if ($result eq 'ok') {
 4635: 	      $request->print('.');
 4636: # Remove from grading queue
 4637:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4638:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4639:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4640:                                              $domain,$username);
 4641: 	   } else {
 4642: 	      $request->print("<p><span class=\"LC_error\">".
 4643:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4644:                                   "$username:$domain",$result)."</span></p>");
 4645: 	   }
 4646: 	   $request->rflush();
 4647: 	   $countdone++;
 4648:         }
 4649:     }
 4650:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4651:     if (@warnings) {
 4652:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4653:         $request->print(join(', ',@warnings));
 4654:     }
 4655:     if (@skipped) {
 4656: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4657:         $request->print(join(', ',@skipped));
 4658:     }
 4659:     if (@notallowed) {
 4660: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4661: 	$request->print(join(', ',@notallowed));
 4662:     }
 4663:     $request->print("<br />\n");
 4664:     $request->print(&show_grading_menu_form($symb));
 4665:     return $error_msg;
 4666: }
 4667: #------------- end of section for handling csv file upload ---------
 4668: #
 4669: #-------------------------------------------------------------------
 4670: #
 4671: #-------------- Next few routines handle grading by page/sequence
 4672: #
 4673: #--- Select a page/sequence and a student to grade
 4674: sub pickStudentPage {
 4675:     my ($request) = shift;
 4676: 
 4677:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4678:     &js_escape(\$alertmsg);
 4679:     $request->print(<<LISTJAVASCRIPT);
 4680: <script type="text/javascript" language="javascript">
 4681: 
 4682: function checkPickOne(formname) {
 4683:     if (radioSelection(formname.student) == null) {
 4684: 	alert("$alertmsg");
 4685: 	return;
 4686:     }
 4687:     ptr = pullDownSelection(formname.selectpage);
 4688:     formname.page.value = formname["page"+ptr].value;
 4689:     formname.title.value = formname["title"+ptr].value;
 4690:     formname.submit();
 4691: }
 4692: 
 4693: </script>
 4694: LISTJAVASCRIPT
 4695:     &commonJSfunctions($request);
 4696:     my ($symb) = &get_symb($request);
 4697:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4698:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4699:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4700: 
 4701:     my $result='<h3><span class="LC_info">&nbsp;'.
 4702: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4703: 
 4704:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4705:     my $map_error;
 4706:     my ($titles,$symbx) = &getSymbMap($map_error);
 4707:     if ($map_error) {
 4708:         $request->print(&navmap_errormsg());
 4709:         return; 
 4710:     }
 4711:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4712: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4713: #    my $type=($curpage =~ /\.(page|sequence)/);
 4714:     my $select = '<select name="selectpage">'."\n";
 4715:     my $ctr=0;
 4716:     foreach (@$titles) {
 4717: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4718: 	$select.='<option value="'.$ctr.'" '.
 4719: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4720: 	    '>'.$showtitle.'</option>'."\n";
 4721: 	$ctr++;
 4722:     }
 4723:     $select.= '</select>';
 4724:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4725: 
 4726:     $ctr=0;
 4727:     foreach (@$titles) {
 4728: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4729: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4730: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4731: 	$ctr++;
 4732:     }
 4733:     $result.='<input type="hidden" name="page" />'."\n".
 4734: 	'<input type="hidden" name="title" />'."\n";
 4735: 
 4736:     my $options =
 4737: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4738: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4739:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4740: 
 4741:     $options =
 4742: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4743: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4744: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4745:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4746:     
 4747:     $result.=&build_section_inputs();
 4748:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4749:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4750: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4751: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4752: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4753: 
 4754:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4755: 
 4756:     $result.='&nbsp;<input type="button" '.
 4757:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4758: 
 4759:     $request->print($result);
 4760: 
 4761:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4762: 	&Apache::loncommon::start_data_table().
 4763: 	&Apache::loncommon::start_data_table_header_row().
 4764: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4765: 	'<th>'.&nameUserString('header').'</th>'.
 4766: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4767: 	'<th>'.&nameUserString('header').'</th>'.
 4768: 	&Apache::loncommon::end_data_table_header_row();
 4769:  
 4770:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4771:     my $ptr = 1;
 4772:     foreach my $student (sort 
 4773: 			 {
 4774: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4775: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4776: 			     }
 4777: 			     return $a cmp $b;
 4778: 			 } (keys(%$fullname))) {
 4779: 	my ($uname,$udom) = split(/:/,$student);
 4780: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4781:                                   : '</td>');
 4782: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4783: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4784: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4785: 	$studentTable.=
 4786: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4787:                          : '');
 4788: 	$ptr++;
 4789:     }
 4790:     if ($ptr%2 == 0) {
 4791: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4792: 	    &Apache::loncommon::end_data_table_row();
 4793:     }
 4794:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4795:     $studentTable.='<input type="button" '.
 4796:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4797: 
 4798:     $studentTable.=&show_grading_menu_form($symb);
 4799:     $request->print($studentTable);
 4800: 
 4801:     return '';
 4802: }
 4803: 
 4804: sub getSymbMap {
 4805:     my ($map_error) = @_;
 4806:     my $navmap = Apache::lonnavmaps::navmap->new();
 4807:     unless (ref($navmap)) {
 4808:         if (ref($map_error)) {
 4809:             $$map_error = 'navmap';
 4810:         }
 4811:         return;
 4812:     }
 4813:     my %symbx = ();
 4814:     my @titles = ();
 4815:     my $minder = 0;
 4816: 
 4817:     # Gather every sequence that has problems.
 4818:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4819: 					       1,0,1);
 4820:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4821: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4822: 	    my $title = $minder.'.'.
 4823: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4824: 	    push(@titles, $title); # minder in case two titles are identical
 4825: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4826: 	    $minder++;
 4827: 	}
 4828:     }
 4829:     return \@titles,\%symbx;
 4830: }
 4831: 
 4832: #
 4833: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4834: sub displayPage {
 4835:     my ($request) = shift;
 4836: 
 4837:     my ($symb) = &get_symb($request);
 4838:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4839:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4840:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4841:     my $pageTitle = $env{'form.page'};
 4842:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4843:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4844:     my $usec=$classlist->{$env{'form.student'}}[5];
 4845: 
 4846:     #need to make sure we have the correct data for later EXT calls, 
 4847:     #thus invalidate the cache
 4848:     &Apache::lonnet::devalidatecourseresdata(
 4849:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4850:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4851:     &Apache::lonnet::clear_EXT_cache_status();
 4852: 
 4853:     if (!&canview($usec)) {
 4854: 	$request->print('<span class="LC_warning">'.
 4855:                         &mt('Unable to view requested student. ([_1])',
 4856:                             $env{'form.student'}).
 4857:                         '</span>');
 4858:         $request->print(&show_grading_menu_form($symb));
 4859:         return;
 4860:     }
 4861:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4862:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4863: 	'</h3>'."\n";
 4864:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4865:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4866: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4867:     } else {
 4868: 	delete($env{'form.CODE'});
 4869:     }
 4870:     &sub_page_js($request);
 4871:     $request->print($result);
 4872: 
 4873:     my $navmap = Apache::lonnavmaps::navmap->new();
 4874:     unless (ref($navmap)) {
 4875:         $request->print(&navmap_errormsg());
 4876:         $request->print(&show_grading_menu_form($symb));
 4877:         return;
 4878:     }
 4879:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4880:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4881:     if (!$map) {
 4882: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4883: 	$request->print(&show_grading_menu_form($symb));
 4884: 	return; 
 4885:     }
 4886:     my $iterator = $navmap->getIterator($map->map_start(),
 4887: 					$map->map_finish());
 4888: 
 4889:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4890: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4891: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4892: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4893: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4894: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4895: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4896: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4897: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4898: 
 4899:     if (defined($env{'form.CODE'})) {
 4900: 	$studentTable.=
 4901: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4902:     }
 4903:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4904: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4905: 
 4906:     $studentTable.='&nbsp;<span class="LC_info">'.
 4907:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4908:         '</span>'."\n".
 4909: 	&Apache::loncommon::start_data_table().
 4910: 	&Apache::loncommon::start_data_table_header_row().
 4911: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4912: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4913: 	&Apache::loncommon::end_data_table_header_row();
 4914: 
 4915:     &Apache::lonxml::clear_problem_counter();
 4916:     my ($depth,$question,$prob) = (1,1,1);
 4917:     $iterator->next(); # skip the first BEGIN_MAP
 4918:     my $curRes = $iterator->next(); # for "current resource"
 4919:     while ($depth > 0) {
 4920:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4921:         if($curRes == $iterator->END_MAP) { $depth--; }
 4922: 
 4923:         if (ref($curRes) && $curRes->is_problem()) {
 4924: 	    my $parts = $curRes->parts();
 4925:             my $title = $curRes->compTitle();
 4926: 	    my $symbx = $curRes->symb();
 4927: 	    $studentTable.=
 4928: 		&Apache::loncommon::start_data_table_row().
 4929: 		'<td align="center" valign="top" >'.$prob.
 4930: 		(scalar(@{$parts}) == 1 ? '' 
 4931: 		                        : '<br />('.&mt('[_1]parts',
 4932: 							scalar(@{$parts}).'&nbsp;').')'
 4933: 		 ).
 4934: 		 '</td>';
 4935: 	    $studentTable.='<td valign="top">';
 4936: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4937: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4938: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4939: 					     undef,'both',\%form);
 4940: 	    } else {
 4941: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4942: 		$companswer =~ s|<form(.*?)>||g;
 4943: 		$companswer =~ s|</form>||g;
 4944: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4945: #		    $companswer =~ s/$1/ /ms;
 4946: #		    $request->print('match='.$1."<br />\n");
 4947: #		}
 4948: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4949: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4950: 	    }
 4951: 
 4952: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4953: 
 4954: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4955: 		if ($record{'version'} eq '') {
 4956: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4957: 		} else {
 4958: 		    my %responseType = ();
 4959: 		    foreach my $partid (@{$parts}) {
 4960: 			my @responseIds =$curRes->responseIds($partid);
 4961: 			my @responseType =$curRes->responseType($partid);
 4962: 			my %responseIds;
 4963: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4964: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4965: 			}
 4966: 			$responseType{$partid} = \%responseIds;
 4967: 		    }
 4968: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4969: 
 4970: 		}
 4971: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4972: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4973:                 my $identifier = (&canmodify($usec)? $prob : '');
 4974: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4975: 									$env{'request.course.id'},
 4976: 									'','.submission',undef,
 4977:                                                                         $usec,$identifier);
 4978:  
 4979: 	    }
 4980: 	    if (&canmodify($usec)) {
 4981:             $studentTable.=&gradeBox_start();
 4982: 		foreach my $partid (@{$parts}) {
 4983: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4984: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4985: 		    $question++;
 4986: 		}
 4987:             $studentTable.=&gradeBox_end();
 4988: 		$prob++;
 4989: 	    }
 4990: 	    $studentTable.='</td></tr>';
 4991: 
 4992: 	}
 4993:         $curRes = $iterator->next();
 4994:     }
 4995: 
 4996:     $studentTable.=
 4997:         '</table>'."\n".
 4998:         '<input type="button" value="'.&mt('Save').'" '.
 4999:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5000:         '</form>'."\n";
 5001:     $studentTable.=&show_grading_menu_form($symb);
 5002:     $request->print($studentTable);
 5003: 
 5004:     return '';
 5005: }
 5006: 
 5007: sub displaySubByDates {
 5008:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5009:     my $isCODE=0;
 5010:     my $isTask = ($symb =~/\.task$/);
 5011:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5012:     my $studentTable=&Apache::loncommon::start_data_table().
 5013: 	&Apache::loncommon::start_data_table_header_row().
 5014: 	'<th>'.&mt('Date/Time').'</th>'.
 5015: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5016:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5017: 	'<th>'.&mt('Submission').'</th>'.
 5018: 	'<th>'.&mt('Status').'</th>'.
 5019: 	&Apache::loncommon::end_data_table_header_row();
 5020:     my ($version);
 5021:     my %mark;
 5022:     my %orders;
 5023:     $mark{'correct_by_student'} = $checkIcon;
 5024:     if (!exists($$record{'1:timestamp'})) {
 5025: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5026:     }
 5027: 
 5028:     my $interaction;
 5029:     my $no_increment = 1;
 5030:     my (%lastrndseed,%lasttype);
 5031:     for ($version=1;$version<=$$record{'version'};$version++) {
 5032: 	my $timestamp = 
 5033: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5034: 	if (exists($$record{$version.':resource.0.version'})) {
 5035: 	    $interaction = $$record{$version.':resource.0.version'};
 5036: 	}
 5037:         if ($isTask && $env{'form.previousversion'}) {
 5038:             next unless ($interaction == $env{'form.previousversion'});
 5039:         }
 5040: 	my $where = ($isTask ? "$version:resource.$interaction"
 5041: 		             : "$version:resource");
 5042: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5043: 	    '<td>'.$timestamp.'</td>';
 5044: 	if ($isCODE) {
 5045: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5046: 	}
 5047:         if ($isTask) {
 5048:             $studentTable.='<td>'.$interaction.'</td>';
 5049:         }
 5050: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5051: 	my @displaySub = ();
 5052: 	foreach my $partid (@{$parts}) {
 5053:             my ($hidden,$type);
 5054:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5055:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5056:                 $hidden = 1;
 5057:             }
 5058: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5059: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5060: 	    
 5061: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5062: 	    my $display_part=&get_display_part($partid,$symb);
 5063: 	    foreach my $matchKey (@matchKey) {
 5064: 		if (exists($$record{$version.':'.$matchKey}) &&
 5065: 		    $$record{$version.':'.$matchKey} ne '') {
 5066:                     
 5067: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5068: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5069:                     $displaySub[0].='<span class="LC_nobreak">';
 5070:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5071:                                    .' <span class="LC_internal_info">'
 5072:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5073:                                    .'</span>'
 5074:                                    .' <b>';
 5075:                     if ($hidden) {
 5076:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5077:                     } else {
 5078:                         my ($trial,$rndseed,$newvariation);
 5079:                         if ($type eq 'randomizetry') {
 5080:                             $trial = $$record{"$where.$partid.tries"};
 5081:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5082:                         }
 5083: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5084: 			    $displaySub[0].=&mt('Trial not counted');
 5085: 		        } else {
 5086: 			    $displaySub[0].=&mt('Trial: [_1]',
 5087: 					    $$record{"$where.$partid.tries"});
 5088:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5089:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5090:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5091:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5092:                                 }
 5093:                             }
 5094:                             $lastrndseed{$partid} = $rndseed;
 5095:                             $lasttype{$partid} = $type;
 5096: 		        }
 5097: 		        my $responseType=($isTask ? 'Task'
 5098:                                               : $responseType->{$partid}->{$responseId});
 5099: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5100: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5101: 			    $orders{$partid}->{$responseId}=
 5102: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5103:                                            $no_increment,$type,$trial,$rndseed);
 5104: 		        }
 5105: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5106: 		        $displaySub[0].='&nbsp; '.
 5107: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5108:                     }
 5109: 		}
 5110: 	    }
 5111: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5112: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5113: 				    $$record{"$where.$partid.checkedin"},
 5114: 				    $$record{"$where.$partid.checkedin.slot"}).
 5115: 					'<br />';
 5116: 	    }
 5117: 	    if (exists $$record{"$where.$partid.award"}) {
 5118: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5119: 		    lc($$record{"$where.$partid.award"}).' '.
 5120: 		    $mark{$$record{"$where.$partid.solved"}}.
 5121: 		    '<br />';
 5122: 	    }
 5123: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5124: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5125: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5126: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5127: 		$displaySub[2].=
 5128: 		    $$record{"$version:resource.$partid.regrader"}.
 5129: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5130: 	    }
 5131: 	}
 5132: 	# needed because old essay regrader has not parts info
 5133: 	if (exists $$record{"$version:resource.regrader"}) {
 5134: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5135: 	}
 5136: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5137: 	if ($displaySub[2]) {
 5138: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5139: 	}
 5140: 	$studentTable.='&nbsp;</td>'.
 5141: 	    &Apache::loncommon::end_data_table_row();
 5142:     }
 5143:     $studentTable.=&Apache::loncommon::end_data_table();
 5144:     return $studentTable;
 5145: }
 5146: 
 5147: sub updateGradeByPage {
 5148:     my ($request) = shift;
 5149: 
 5150:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5151:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5152:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5153:     my $pageTitle = $env{'form.page'};
 5154:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5155:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5156:     my $usec=$classlist->{$env{'form.student'}}[5];
 5157:     if (!&canmodify($usec)) {
 5158: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5159: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5160: 	return;
 5161:     }
 5162:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5163:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5164: 	'</h3>'."\n";
 5165: 
 5166:     $request->print($result);
 5167: 
 5168: 
 5169:     my $navmap = Apache::lonnavmaps::navmap->new();
 5170:     unless (ref($navmap)) {
 5171:         $request->print(&navmap_errormsg());
 5172:         return;
 5173:     }
 5174:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5175:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5176:     if (!$map) {
 5177: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5178: 	my ($symb)=&get_symb($request);
 5179: 	$request->print(&show_grading_menu_form($symb));
 5180: 	return; 
 5181:     }
 5182:     my $iterator = $navmap->getIterator($map->map_start(),
 5183: 					$map->map_finish());
 5184: 
 5185:     my $studentTable=
 5186: 	&Apache::loncommon::start_data_table().
 5187: 	&Apache::loncommon::start_data_table_header_row().
 5188: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5189: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5190: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5191: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5192: 	&Apache::loncommon::end_data_table_header_row();
 5193: 
 5194:     $iterator->next(); # skip the first BEGIN_MAP
 5195:     my $curRes = $iterator->next(); # for "current resource"
 5196:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5197:     while ($depth > 0) {
 5198:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5199:         if($curRes == $iterator->END_MAP) { $depth--; }
 5200: 
 5201:         if (ref($curRes) && $curRes->is_problem()) {
 5202: 	    my $parts = $curRes->parts();
 5203:             my $title = $curRes->compTitle();
 5204: 	    my $symbx = $curRes->symb();
 5205: 	    $studentTable.=
 5206: 		&Apache::loncommon::start_data_table_row().
 5207: 		'<td align="center" valign="top" >'.$prob.
 5208: 		(scalar(@{$parts}) == 1 ? '' 
 5209:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5210: 		.')').'</td>';
 5211: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5212: 
 5213: 	    my %newrecord=();
 5214: 	    my @displayPts=();
 5215:             my %aggregate = ();
 5216:             my $aggregateflag = 0;
 5217:             if ($env{'form.HIDE'.$prob}) {
 5218:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5219:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5220:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5221:                 $hideflag += $numchgs;
 5222:             }
 5223: 	    foreach my $partid (@{$parts}) {
 5224: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5225: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5226: 
 5227: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5228: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5229: 		my $partial = $newpts/$wgt;
 5230: 		my $score;
 5231: 		if ($partial > 0) {
 5232: 		    $score = 'correct_by_override';
 5233: 		} elsif ($newpts ne '') { #empty is taken as 0
 5234: 		    $score = 'incorrect_by_override';
 5235: 		}
 5236: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5237: 		if ($dropMenu eq 'excused') {
 5238: 		    $partial = '';
 5239: 		    $score = 'excused';
 5240: 		} elsif ($dropMenu eq 'reset status'
 5241: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5242: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5243: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5244: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5245: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5246: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5247: 		    $changeflag++;
 5248: 		    $newpts = '';
 5249:                     
 5250:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5251:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5252:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5253:                     if ($aggtries > 0) {
 5254:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5255:                         $aggregateflag = 1;
 5256:                     }
 5257: 		}
 5258: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5259: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5260: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5261: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5262: 		    '&nbsp;<br />';
 5263: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5264: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5265: 		    '&nbsp;<br />';
 5266: 		$question++;
 5267: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5268: 
 5269: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5270: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5271: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5272: 		    if (scalar(keys(%newrecord)) > 0);
 5273: 
 5274: 		$changeflag++;
 5275: 	    }
 5276: 	    if (scalar(keys(%newrecord)) > 0) {
 5277: 		my %record = 
 5278: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5279: 					     $udom,$uname);
 5280: 
 5281: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5282: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5283: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5284: 		    $newrecord{'resource.CODE'} = '';
 5285: 		}
 5286: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5287: 					$udom,$uname);
 5288: 		%record = &Apache::lonnet::restore($symbx,
 5289: 						   $env{'request.course.id'},
 5290: 						   $udom,$uname);
 5291: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5292: 					     $cdom,$cnum,$udom,$uname);
 5293: 	    }
 5294: 	    
 5295:             if ($aggregateflag) {
 5296:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5297:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5298:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5299:             }
 5300: 
 5301: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5302: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5303: 		&Apache::loncommon::end_data_table_row();
 5304: 
 5305: 	    $prob++;
 5306: 	}
 5307:         $curRes = $iterator->next();
 5308:     }
 5309: 
 5310:     $studentTable.=&Apache::loncommon::end_data_table();
 5311:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5312:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5313: 		  &mt('The scores were changed for [quant,_1,problem].',
 5314: 		  $changeflag).'<br />');
 5315:     my $hidemsg=($hideflag == 0 ? '' :
 5316:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5317:                      $hideflag).'<br />');
 5318:     $request->print($hidemsg.$grademsg.$studentTable);
 5319: 
 5320:     return '';
 5321: }
 5322: 
 5323: #-------- end of section for handling grading by page/sequence ---------
 5324: #
 5325: #-------------------------------------------------------------------
 5326: 
 5327: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5328: #
 5329: #------ start of section for handling grading by page/sequence ---------
 5330: 
 5331: =pod
 5332: 
 5333: =head1 Bubble sheet grading routines
 5334: 
 5335:   For this documentation:
 5336: 
 5337:    'scanline' refers to the full line of characters
 5338:    from the file that we are parsing that represents one entire sheet
 5339: 
 5340:    'bubble line' refers to the data
 5341:    representing the line of bubbles that are on the physical bubblesheet
 5342: 
 5343: 
 5344: The overall process is that a scanned in bubblesheet data is uploaded
 5345: into a course. When a user wants to grade, they select a
 5346: sequence/folder of resources, a file of bubblesheet info, and pick
 5347: one of the predefined configurations for what each scanline looks
 5348: like.
 5349: 
 5350: Next each scanline is checked for any errors of either 'missing
 5351: bubbles' (it's an error because it may have been mis-scanned
 5352: because too light bubbling), 'double bubble' (each bubble line should
 5353: have no more than one letter picked), invalid or duplicated CODE,
 5354: invalid student/employee ID
 5355: 
 5356: If the CODE option is used that determines the randomization of the
 5357: homework problems, either way the student/employee ID is looked up into a
 5358: username:domain.
 5359: 
 5360: During the validation phase the instructor can choose to skip scanlines. 
 5361: 
 5362: After the validation phase, there are now 3 bubblesheet files
 5363: 
 5364:   scantron_original_filename (unmodified original file)
 5365:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5366:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5367: 
 5368: Also there is a separate hash nohist_scantrondata that contains extra
 5369: correction information that isn't representable in the bubblesheet
 5370: file (see &scantron_getfile() for more information)
 5371: 
 5372: After all scanlines are either valid, marked as valid or skipped, then
 5373: foreach line foreach problem in the picked sequence, an ssi request is
 5374: made that simulates a user submitting their selected letter(s) against
 5375: the homework problem.
 5376: 
 5377: =over 4
 5378: 
 5379: 
 5380: 
 5381: =item defaultFormData
 5382: 
 5383:   Returns html hidden inputs used to hold context/default values.
 5384: 
 5385:  Arguments:
 5386:   $symb - $symb of the current resource 
 5387: 
 5388: =cut
 5389: 
 5390: sub defaultFormData {
 5391:     my ($symb)=@_;
 5392:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5393:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5394:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5395: }
 5396: 
 5397: 
 5398: =pod 
 5399: 
 5400: =item getSequenceDropDown
 5401: 
 5402:    Return html dropdown of possible sequences to grade
 5403:  
 5404:  Arguments:
 5405:    $symb - $symb of the current resource
 5406:    $map_error - ref to scalar which will container error if
 5407:                 $navmap object is unavailable in &getSymbMap().
 5408: 
 5409: =cut
 5410: 
 5411: sub getSequenceDropDown {
 5412:     my ($symb,$map_error)=@_;
 5413:     my $result='<select name="selectpage">'."\n";
 5414:     my ($titles,$symbx) = &getSymbMap($map_error);
 5415:     if (ref($map_error)) {
 5416:         return if ($$map_error);
 5417:     }
 5418:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5419:     my $ctr=0;
 5420:     foreach (@$titles) {
 5421: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5422: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5423: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5424: 	    '>'.$showtitle.'</option>'."\n";
 5425: 	$ctr++;
 5426:     }
 5427:     $result.= '</select>';
 5428:     return $result;
 5429: }
 5430: 
 5431: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5432:                                    # key is zero-based index - 0, 1, 2 ...
 5433: 
 5434: my %first_bubble_line;             # First bubble line no. for each bubble.
 5435: 
 5436: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5437:                                    # matchresponse or rankresponse, where 
 5438:                                    # an individual response can have multiple 
 5439:                                    # lines
 5440: 
 5441: my %responsetype_per_response;     # responsetype for each response
 5442: 
 5443: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5444:                                    # numbered response. Needed when randomorder
 5445:                                    # or randompick are in use. Key is ID, value 
 5446:                                    # is response number.
 5447: 
 5448: # Save and restore the bubble lines array to the form env.
 5449: 
 5450: 
 5451: sub save_bubble_lines {
 5452:     foreach my $line (keys(%bubble_lines_per_response)) {
 5453: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5454: 	$env{"form.scantron.first_bubble_line.$line"} =
 5455: 	    $first_bubble_line{$line};
 5456:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5457:             $subdivided_bubble_lines{$line};
 5458:         $env{"form.scantron.responsetype.$line"} =
 5459:             $responsetype_per_response{$line};
 5460:     }
 5461:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5462:         my $line = $masterseq_id_responsenum{$resid};
 5463:         $env{"form.scantron.residpart.$line"} = $resid;
 5464:     }
 5465: }
 5466: 
 5467: 
 5468: sub restore_bubble_lines {
 5469:     my $line = 0;
 5470:     %bubble_lines_per_response = ();
 5471:     %masterseq_id_responsenum = ();
 5472:     while ($env{"form.scantron.bubblelines.$line"}) {
 5473: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5474: 	$bubble_lines_per_response{$line} = $value;
 5475: 	$first_bubble_line{$line}  =
 5476: 	    $env{"form.scantron.first_bubble_line.$line"};
 5477:         $subdivided_bubble_lines{$line} =
 5478:             $env{"form.scantron.sub_bubblelines.$line"};
 5479:         $responsetype_per_response{$line} =
 5480:             $env{"form.scantron.responsetype.$line"};
 5481:         my $id = $env{"form.scantron.residpart.$line"};
 5482:         $masterseq_id_responsenum{$id} = $line;
 5483: 	$line++;
 5484:     }
 5485: }
 5486: 
 5487: =pod 
 5488: 
 5489: =item scantron_filenames
 5490: 
 5491:    Returns a list of the scantron files in the current course 
 5492: 
 5493: =cut
 5494: 
 5495: sub scantron_filenames {
 5496:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5497:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5498:     my $getpropath = 1;
 5499:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5500:                                                         $cname,$getpropath);
 5501:     my @possiblenames;
 5502:     if (ref($dirlist) eq 'ARRAY') {
 5503:         foreach my $filename (sort(@{$dirlist})) {
 5504: 	    ($filename)=split(/&/,$filename);
 5505: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5506: 	    $filename=~s/^scantron_orig_//;
 5507: 	    push(@possiblenames,$filename);
 5508:         }
 5509:     }
 5510:     return @possiblenames;
 5511: }
 5512: 
 5513: =pod 
 5514: 
 5515: =item scantron_uploads
 5516: 
 5517:    Returns  html drop-down list of scantron files in current course.
 5518: 
 5519:  Arguments:
 5520:    $file2grade - filename to set as selected in the dropdown
 5521: 
 5522: =cut
 5523: 
 5524: sub scantron_uploads {
 5525:     my ($file2grade) = @_;
 5526:     my $result=	'<select name="scantron_selectfile">';
 5527:     $result.="<option></option>";
 5528:     foreach my $filename (sort(&scantron_filenames())) {
 5529: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5530:     }
 5531:     $result.="</select>";
 5532:     return $result;
 5533: }
 5534: 
 5535: =pod 
 5536: 
 5537: =item scantron_scantab
 5538: 
 5539:   Returns html drop down of the scantron formats in the scantronformat.tab
 5540:   file.
 5541: 
 5542: =cut
 5543: 
 5544: sub scantron_scantab {
 5545:     my $result='<select name="scantron_format">'."\n";
 5546:     $result.='<option></option>'."\n";
 5547:     my @lines = &get_scantronformat_file();
 5548:     if (@lines > 0) {
 5549:         foreach my $line (@lines) {
 5550:             next if (($line =~ /^\#/) || ($line eq ''));
 5551: 	    my ($name,$descrip)=split(/:/,$line);
 5552: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5553:         }
 5554:     }
 5555:     $result.='</select>'."\n";
 5556:     return $result;
 5557: }
 5558: 
 5559: =pod
 5560: 
 5561: =item get_scantronformat_file
 5562: 
 5563:   Returns an array containing lines from the scantron format file for
 5564:   the domain of the course.
 5565: 
 5566:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5567:   lines are from this file.
 5568: 
 5569:   Otherwise, if a default.tab has been published in RES space by the 
 5570:   domainconfig user, lines are from this file.
 5571: 
 5572:   Otherwise, fall back to getting lines from the legacy file on the
 5573:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5574: 
 5575: =cut
 5576: 
 5577: sub get_scantronformat_file {
 5578:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5579:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5580:     my $gottab = 0;
 5581:     my @lines;
 5582:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5583:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5584:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5585:             if ($formatfile ne '-1') {
 5586:                 @lines = split("\n",$formatfile,-1);
 5587:                 $gottab = 1;
 5588:             }
 5589:         }
 5590:     }
 5591:     if (!$gottab) {
 5592:         my $confname = $cdom.'-domainconfig';
 5593:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5594:         my $formatfile =  &Apache::lonnet::getfile($default);
 5595:         if ($formatfile ne '-1') {
 5596:             @lines = split("\n",$formatfile,-1);
 5597:             $gottab = 1;
 5598:         }
 5599:     }
 5600:     if (!$gottab) {
 5601:         my @domains = &Apache::lonnet::current_machine_domains();
 5602:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5603:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5604:             @lines = <$fh>;
 5605:             close($fh);
 5606:         } else {
 5607:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5608:             @lines = <$fh>;
 5609:             close($fh);
 5610:         }
 5611:     }
 5612:     return @lines;
 5613: }
 5614: 
 5615: =pod 
 5616: 
 5617: =item scantron_CODElist
 5618: 
 5619:   Returns html drop down of the saved CODE lists from current course,
 5620:   generated from earlier printings.
 5621: 
 5622: =cut
 5623: 
 5624: sub scantron_CODElist {
 5625:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5626:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5627:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5628:     my $namechoice='<option></option>';
 5629:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5630: 	if ($name =~ /^error: 2 /) { next; }
 5631: 	if ($name =~ /^type\0/) { next; }
 5632: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5633:     }
 5634:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5635:     return $namechoice;
 5636: }
 5637: 
 5638: =pod 
 5639: 
 5640: =item scantron_CODEunique
 5641: 
 5642:   Returns the html for "Each CODE to be used once" radio.
 5643: 
 5644: =cut
 5645: 
 5646: sub scantron_CODEunique {
 5647:     my $result='<span class="LC_nobreak">
 5648:                  <label><input type="radio" name="scantron_CODEunique"
 5649:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5650:                 </span>
 5651:                 <span class="LC_nobreak">
 5652:                  <label><input type="radio" name="scantron_CODEunique"
 5653:                         value="no" />'.&mt('No').' </label>
 5654:                 </span>';
 5655:     return $result;
 5656: }
 5657: 
 5658: =pod 
 5659: 
 5660: =item scantron_selectphase
 5661: 
 5662:   Generates the initial screen to start the bubblesheet process.
 5663:   Allows for - starting a grading run.
 5664:              - downloading existing scan data (original, corrected
 5665:                                                 or skipped info)
 5666: 
 5667:              - uploading new scan data
 5668: 
 5669:  Arguments:
 5670:   $r          - The Apache request object
 5671:   $file2grade - name of the file that contain the scanned data to score
 5672: 
 5673: =cut
 5674: 
 5675: sub scantron_selectphase {
 5676:     my ($r,$file2grade) = @_;
 5677:     my ($symb)=&get_symb($r);
 5678:     if (!$symb) {return '';}
 5679:     my $map_error;
 5680:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5681:     if ($map_error) {
 5682:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5683:         return;
 5684:     }
 5685:     my $default_form_data=&defaultFormData($symb);
 5686:     my $grading_menu_button=&show_grading_menu_form($symb);
 5687:     my $file_selector=&scantron_uploads($file2grade);
 5688:     my $format_selector=&scantron_scantab();
 5689:     my $CODE_selector=&scantron_CODElist();
 5690:     my $CODE_unique=&scantron_CODEunique();
 5691:     my $result;
 5692: 
 5693:     $ssi_error = 0;
 5694: 
 5695:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5696:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5697: 
 5698:         # Chunk of form to prompt for a scantron file upload.
 5699: 
 5700:         $r->print('
 5701:     <br />
 5702:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5703:        '.&Apache::loncommon::start_data_table_header_row().'
 5704:             <th>
 5705:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5706:             </th>
 5707:        '.&Apache::loncommon::end_data_table_header_row().'
 5708:        '.&Apache::loncommon::start_data_table_row().'
 5709:             <td>
 5710: ');
 5711:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5712:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5713:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5714:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5715:     &js_escape(\$alertmsg);
 5716:     $r->print('
 5717:               <script type="text/javascript" language="javascript">
 5718:     function checkUpload(formname) {
 5719:         if (formname.upfile.value == "") {
 5720:             alert("'.$alertmsg.'");
 5721:             return false;
 5722:         }
 5723:         formname.submit();
 5724:     }
 5725:               </script>
 5726: 
 5727:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5728:                 '.$default_form_data.'
 5729:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5730:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5731:                 <input name="command" value="scantronupload_save" type="hidden" />
 5732:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5733:                 <br />
 5734:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5735:               </form>
 5736: ');
 5737: 
 5738:         $r->print('
 5739:             </td>
 5740:        '.&Apache::loncommon::end_data_table_row().'
 5741:        '.&Apache::loncommon::end_data_table().'
 5742: ');
 5743:     }
 5744: 
 5745:     # Chunk of form to prompt for a file to grade and how:
 5746: 
 5747:     $result.= '
 5748:     <br />
 5749:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5750:     <input type="hidden" name="command" value="scantron_warning" />
 5751:     '.$default_form_data.'
 5752:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5753:        '.&Apache::loncommon::start_data_table_header_row().'
 5754:             <th colspan="2">
 5755:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5756:             </th>
 5757:        '.&Apache::loncommon::end_data_table_header_row().'
 5758:        '.&Apache::loncommon::start_data_table_row().'
 5759:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5760:        '.&Apache::loncommon::end_data_table_row().'
 5761:        '.&Apache::loncommon::start_data_table_row().'
 5762:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5763:        '.&Apache::loncommon::end_data_table_row().'
 5764:        '.&Apache::loncommon::start_data_table_row().'
 5765:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5766:        '.&Apache::loncommon::end_data_table_row().'
 5767:        '.&Apache::loncommon::start_data_table_row().'
 5768:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5769:        '.&Apache::loncommon::end_data_table_row().'
 5770:        '.&Apache::loncommon::start_data_table_row().'
 5771:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5772:        '.&Apache::loncommon::end_data_table_row().'
 5773:        '.&Apache::loncommon::start_data_table_row().'
 5774: 	    <td> '.&mt('Options:').' </td>
 5775:             <td>
 5776: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5777:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5778:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5779: 	    </td>
 5780:        '.&Apache::loncommon::end_data_table_row().'
 5781:        '.&Apache::loncommon::start_data_table_row().'
 5782:             <td colspan="2">
 5783:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5784:             </td>
 5785:        '.&Apache::loncommon::end_data_table_row().'
 5786:     '.&Apache::loncommon::end_data_table().'
 5787:     </form>
 5788: ';
 5789:    
 5790:     $r->print($result);
 5791: 
 5792:     # Chunk of the form that prompts to view a scoring office file,
 5793:     # corrected file, skipped records in a file.
 5794: 
 5795:     $r->print('
 5796:    <br />
 5797:    <form action="/adm/grades" name="scantron_download">
 5798:      '.$default_form_data.'
 5799:      <input type="hidden" name="command" value="scantron_download" />
 5800:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5801:        '.&Apache::loncommon::start_data_table_header_row().'
 5802:               <th>
 5803:                 &nbsp;'.&mt('Download a scoring office file').'
 5804:               </th>
 5805:        '.&Apache::loncommon::end_data_table_header_row().'
 5806:        '.&Apache::loncommon::start_data_table_row().'
 5807:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5808:                 <br />
 5809:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5810:        '.&Apache::loncommon::end_data_table_row().'
 5811:      '.&Apache::loncommon::end_data_table().'
 5812:    </form>
 5813:    <br />
 5814: ');
 5815: 
 5816:     &Apache::lonpickcode::code_list($r,2);
 5817: 
 5818:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5819:              $default_form_data."\n".
 5820:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5821:              &Apache::loncommon::start_data_table_header_row()."\n".
 5822:              '<th colspan="2">
 5823:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5824:              '</th>'."\n".
 5825:               &Apache::loncommon::end_data_table_header_row()."\n".
 5826:               &Apache::loncommon::start_data_table_row()."\n".
 5827:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5828:               '<td> '.$sequence_selector.' </td>'.
 5829:               &Apache::loncommon::end_data_table_row()."\n".
 5830:               &Apache::loncommon::start_data_table_row()."\n".
 5831:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5832:               '<td> '.$file_selector.' </td>'."\n".
 5833:               &Apache::loncommon::end_data_table_row()."\n".
 5834:               &Apache::loncommon::start_data_table_row()."\n".
 5835:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5836:               '<td> '.$format_selector.' </td>'."\n".
 5837:               &Apache::loncommon::end_data_table_row()."\n".
 5838:               &Apache::loncommon::start_data_table_row()."\n".
 5839:               '<td> '.&mt('Options').' </td>'."\n".
 5840:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5841:               &Apache::loncommon::end_data_table_row()."\n".
 5842:               &Apache::loncommon::start_data_table_row()."\n".
 5843:               '<td colspan="2">'."\n".
 5844:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5845:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5846:               '</td>'."\n".
 5847:               &Apache::loncommon::end_data_table_row()."\n".
 5848:               &Apache::loncommon::end_data_table()."\n".
 5849:               '</form><br />');
 5850:     $r->print($grading_menu_button);
 5851:     return;
 5852: }
 5853: 
 5854: =pod
 5855: 
 5856: =item get_scantron_config
 5857: 
 5858:    Parse and return the scantron configuration line selected as a
 5859:    hash of configuration file fields.
 5860: 
 5861:  Arguments:
 5862:     which - the name of the configuration to parse from the file.
 5863: 
 5864: 
 5865:  Returns:
 5866:             If the named configuration is not in the file, an empty
 5867:             hash is returned.
 5868:     a hash with the fields
 5869:       name         - internal name for the this configuration setup
 5870:       description  - text to display to operator that describes this config
 5871:       CODElocation - if 0 or the string 'none'
 5872:                           - no CODE exists for this config
 5873:                      if -1 || the string 'letter'
 5874:                           - a CODE exists for this config and is
 5875:                             a string of letters
 5876:                      Unsupported value (but planned for future support)
 5877:                           if a positive integer
 5878:                                - The CODE exists as the first n items from
 5879:                                  the question section of the form
 5880:                           if the string 'number'
 5881:                                - The CODE exists for this config and is
 5882:                                  a string of numbers
 5883:       CODEstart   - (only matter if a CODE exists) column in the line where
 5884:                      the CODE starts
 5885:       CODElength  - length of the CODE
 5886:       IDstart     - column where the student/employee ID starts
 5887:       IDlength    - length of the student/employee ID info
 5888:       Qstart      - column where the information from the bubbled
 5889:                     'questions' start
 5890:       Qlength     - number of columns comprising a single bubble line from
 5891:                     the sheet. (usually either 1 or 10)
 5892:       Qon         - either a single character representing the character used
 5893:                     to signal a bubble was chosen in the positional setup, or
 5894:                     the string 'letter' if the letter of the chosen bubble is
 5895:                     in the final, or 'number' if a number representing the
 5896:                     chosen bubble is in the file (1->A 0->J)
 5897:       Qoff        - the character used to represent that a bubble was
 5898:                     left blank
 5899:       PaperID     - if the scanning process generates a unique number for each
 5900:                     sheet scanned the column that this ID number starts in
 5901:       PaperIDlength - number of columns that comprise the unique ID number
 5902:                       for the sheet of paper
 5903:       FirstName   - column that the first name starts in
 5904:       FirstNameLength - number of columns that the first name spans
 5905:  
 5906:       LastName    - column that the last name starts in
 5907:       LastNameLength - number of columns that the last name spans
 5908:       BubblesPerRow - number of bubbles available in each row used to
 5909:                       bubble an answer. (If not specified, 10 assumed).
 5910: 
 5911: =cut
 5912: 
 5913: sub get_scantron_config {
 5914:     my ($which) = @_;
 5915:     my @lines = &get_scantronformat_file();
 5916:     my %config;
 5917:     #FIXME probably should move to XML it has already gotten a bit much now
 5918:     foreach my $line (@lines) {
 5919: 	my ($name,$descrip)=split(/:/,$line);
 5920: 	if ($name ne $which ) { next; }
 5921: 	chomp($line);
 5922: 	my @config=split(/:/,$line);
 5923: 	$config{'name'}=$config[0];
 5924: 	$config{'description'}=$config[1];
 5925: 	$config{'CODElocation'}=$config[2];
 5926: 	$config{'CODEstart'}=$config[3];
 5927: 	$config{'CODElength'}=$config[4];
 5928: 	$config{'IDstart'}=$config[5];
 5929: 	$config{'IDlength'}=$config[6];
 5930: 	$config{'Qstart'}=$config[7];
 5931:  	$config{'Qlength'}=$config[8];
 5932: 	$config{'Qoff'}=$config[9];
 5933: 	$config{'Qon'}=$config[10];
 5934: 	$config{'PaperID'}=$config[11];
 5935: 	$config{'PaperIDlength'}=$config[12];
 5936: 	$config{'FirstName'}=$config[13];
 5937: 	$config{'FirstNamelength'}=$config[14];
 5938: 	$config{'LastName'}=$config[15];
 5939: 	$config{'LastNamelength'}=$config[16];
 5940:         $config{'BubblesPerRow'}=$config[17];
 5941: 	last;
 5942:     }
 5943:     return %config;
 5944: }
 5945: 
 5946: =pod 
 5947: 
 5948: =item username_to_idmap
 5949: 
 5950:     creates a hash keyed by student/employee ID with values of the corresponding
 5951:     student username:domain.
 5952: 
 5953:   Arguments:
 5954: 
 5955:     $classlist - reference to the class list hash. This is a hash
 5956:                  keyed by student name:domain  whose elements are references
 5957:                  to arrays containing various chunks of information
 5958:                  about the student. (See loncoursedata for more info).
 5959: 
 5960:   Returns
 5961:     %idmap - the constructed hash
 5962: 
 5963: =cut
 5964: 
 5965: sub username_to_idmap {
 5966:     my ($classlist)= @_;
 5967:     my %idmap;
 5968:     foreach my $student (keys(%$classlist)) {
 5969:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 5970:         unless ($id eq '') {
 5971:             if (!exists($idmap{$id})) {
 5972:                 $idmap{$id} = $student;
 5973:             } else {
 5974:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 5975:                 if ($status eq 'Active') {
 5976:                     $idmap{$id} = $student;
 5977:                 }
 5978:             }
 5979:         }
 5980:     }
 5981:     return %idmap;
 5982: }
 5983: 
 5984: =pod
 5985: 
 5986: =item scantron_fixup_scanline
 5987: 
 5988:    Process a requested correction to a scanline.
 5989: 
 5990:   Arguments:
 5991:     $scantron_config   - hash from &get_scantron_config()
 5992:     $scan_data         - hash of correction information 
 5993:                           (see &scantron_getfile())
 5994:     $line              - existing scanline
 5995:     $whichline         - line number of the passed in scanline
 5996:     $field             - type of change to process 
 5997:                          (either 
 5998:                           'ID'     -> correct the student/employee ID
 5999:                           'CODE'   -> correct the CODE
 6000:                           'answer' -> fixup the submitted answers)
 6001:     
 6002:    $args               - hash of additional info,
 6003:                           - 'ID' 
 6004:                                'newid' -> studentID to use in replacement
 6005:                                           of existing one
 6006:                           - 'CODE' 
 6007:                                'CODE_ignore_dup' - set to true if duplicates
 6008:                                                    should be ignored.
 6009: 	                       'CODE' - is new code or 'use_unfound'
 6010:                                         if the existing unfound code should
 6011:                                         be used as is
 6012:                           - 'answer'
 6013:                                'response' - new answer or 'none' if blank
 6014:                                'question' - the bubble line to change
 6015:                                'questionnum' - the question identifier,
 6016:                                                may include subquestion. 
 6017: 
 6018:   Returns:
 6019:     $line - the modified scanline
 6020: 
 6021:   Side effects: 
 6022:     $scan_data - may be updated
 6023: 
 6024: =cut
 6025: 
 6026: 
 6027: sub scantron_fixup_scanline {
 6028:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6029:     if ($field eq 'ID') {
 6030: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6031: 	    return ($line,1,'New value too large');
 6032: 	}
 6033: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6034: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6035: 				     $args->{'newid'});
 6036: 	}
 6037: 	substr($line,$$scantron_config{'IDstart'}-1,
 6038: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6039: 	if ($args->{'newid'}=~/^\s*$/) {
 6040: 	    &scan_data($scan_data,"$whichline.user",
 6041: 		       $args->{'username'}.':'.$args->{'domain'});
 6042: 	}
 6043:     } elsif ($field eq 'CODE') {
 6044: 	if ($args->{'CODE_ignore_dup'}) {
 6045: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6046: 	}
 6047: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6048: 	if ($args->{'CODE'} ne 'use_unfound') {
 6049: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6050: 		return ($line,1,'New CODE value too large');
 6051: 	    }
 6052: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6053: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6054: 	    }
 6055: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6056: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6057: 	}
 6058:     } elsif ($field eq 'answer') {
 6059: 	my $length=$scantron_config->{'Qlength'};
 6060: 	my $off=$scantron_config->{'Qoff'};
 6061: 	my $on=$scantron_config->{'Qon'};
 6062: 	my $answer=${off}x$length;
 6063: 	if ($args->{'response'} eq 'none') {
 6064: 	    &scan_data($scan_data,
 6065: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6066: 	} else {
 6067: 	    if ($on eq 'letter') {
 6068: 		my @alphabet=('A'..'Z');
 6069: 		$answer=$alphabet[$args->{'response'}];
 6070: 	    } elsif ($on eq 'number') {
 6071: 		$answer=$args->{'response'}+1;
 6072: 		if ($answer == 10) { $answer = '0'; }
 6073: 	    } else {
 6074: 		substr($answer,$args->{'response'},1)=$on;
 6075: 	    }
 6076: 	    &scan_data($scan_data,
 6077: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6078: 	}
 6079: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6080: 	substr($line,$where-1,$length)=$answer;
 6081:     }
 6082:     return $line;
 6083: }
 6084: 
 6085: =pod
 6086: 
 6087: =item scan_data
 6088: 
 6089:     Edit or look up  an item in the scan_data hash.
 6090: 
 6091:   Arguments:
 6092:     $scan_data  - The hash (see scantron_getfile)
 6093:     $key        - shorthand of the key to edit (actual key is
 6094:                   scantronfilename_key).
 6095:     $data        - New value of the hash entry.
 6096:     $delete      - If true, the entry is removed from the hash.
 6097: 
 6098:   Returns:
 6099:     The new value of the hash table field (undefined if deleted).
 6100: 
 6101: =cut
 6102: 
 6103: 
 6104: sub scan_data {
 6105:     my ($scan_data,$key,$value,$delete)=@_;
 6106:     my $filename=$env{'form.scantron_selectfile'};
 6107:     if (defined($value)) {
 6108: 	$scan_data->{$filename.'_'.$key} = $value;
 6109:     }
 6110:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6111:     return $scan_data->{$filename.'_'.$key};
 6112: }
 6113: 
 6114: # ----- These first few routines are general use routines.----
 6115: 
 6116: # Return the number of occurences of a pattern in a string.
 6117: 
 6118: sub occurence_count {
 6119:     my ($string, $pattern) = @_;
 6120: 
 6121:     my @matches = ($string =~ /$pattern/g);
 6122: 
 6123:     return scalar(@matches);
 6124: }
 6125: 
 6126: 
 6127: # Take a string known to have digits and convert all the
 6128: # digits into letters in the range J,A..I.
 6129: 
 6130: sub digits_to_letters {
 6131:     my ($input) = @_;
 6132: 
 6133:     my @alphabet = ('J', 'A'..'I');
 6134: 
 6135:     my @input    = split(//, $input);
 6136:     my $output ='';
 6137:     for (my $i = 0; $i < scalar(@input); $i++) {
 6138: 	if ($input[$i] =~ /\d/) {
 6139: 	    $output .= $alphabet[$input[$i]];
 6140: 	} else {
 6141: 	    $output .= $input[$i];
 6142: 	}
 6143:     }
 6144:     return $output;
 6145: }
 6146: 
 6147: =pod 
 6148: 
 6149: =item scantron_parse_scanline
 6150: 
 6151:   Decodes a scanline from the selected scantron file
 6152: 
 6153:  Arguments:
 6154:     line             - The text of the scantron file line to process
 6155:     whichline        - Line number
 6156:     scantron_config  - Hash describing the format of the scantron lines.
 6157:     scan_data        - Hash of extra information about the scanline
 6158:                        (see scantron_getfile for more information)
 6159:     just_header      - True if should not process question answers but only
 6160:                        the stuff to the left of the answers.
 6161:     randomorder      - True if randomorder in use
 6162:     randompick       - True if randompick in use
 6163:     sequence         - Exam folder URL
 6164:     master_seq       - Ref to array containing symbs in exam folder
 6165:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6166:                        (corresponding values are resource objects)
 6167:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6168:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6169:                        are refs to an array of resource objects, ordered
 6170:                        according to order used for CODE, when randomorder
 6171:                        and or randompick are in use.
 6172:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6173:                        for current line to question number used for same question
 6174:                         in "Master Sequence" (as seen by Course Coordinator).
 6175:     startline        - Ref to hash where key is question number (0 is first)
 6176:                        and value is number of first bubble line for current 
 6177:                        student or code-based randompick and/or randomorder.
 6178:     totalref         - Ref of scalar used to score total number of bubble
 6179:                        lines needed for responses in a scan line (used when
 6180:                        randompick in use. 
 6181: 
 6182:  Returns:
 6183:    Hash containing the result of parsing the scanline
 6184: 
 6185:    Keys are all proceeded by the string 'scantron.'
 6186: 
 6187:        CODE    - the CODE in use for this scanline
 6188:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6189:                  by the operator
 6190:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6191:                             CODEs were selected, but the usage has been
 6192:                             forced by the operator
 6193:        ID  - student/employee ID
 6194:        PaperID - if used, the ID number printed on the sheet when the 
 6195:                  paper was scanned
 6196:        FirstName - first name from the sheet
 6197:        LastName  - last name from the sheet
 6198: 
 6199:      if just_header was not true these key may also exist
 6200: 
 6201:        missingerror - a list of bubble ranges that are considered to be answers
 6202:                       to a single question that don't have any bubbles filled in.
 6203:                       Of the form questionnumber:firstbubblenumber:count.
 6204:        doubleerror  - a list of bubble ranges that are considered to be answers
 6205:                       to a single question that have more than one bubble filled in.
 6206:                       Of the form questionnumber::firstbubblenumber:count
 6207:    
 6208:                 In the above, count is the number of bubble responses in the
 6209:                 input line needed to represent the possible answers to the question.
 6210:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6211:                 per line would have count = 2.
 6212: 
 6213:        maxquest     - the number of the last bubble line that was parsed
 6214: 
 6215:        (<number> starts at 1)
 6216:        <number>.answer - zero or more letters representing the selected
 6217:                          letters from the scanline for the bubble line 
 6218:                          <number>.
 6219:                          if blank there was either no bubble or there where
 6220:                          multiple bubbles, (consult the keys missingerror and
 6221:                          doubleerror if this is an error condition)
 6222: 
 6223: =cut
 6224: 
 6225: sub scantron_parse_scanline {
 6226:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6227:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6228:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6229: 
 6230:     my %record;
 6231:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6232:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6233: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6234: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6235: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6236: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6237: 	    $record{'scantron.CODE'}=substr($data,
 6238: 					    $$scantron_config{'CODEstart'}-1,
 6239: 					    $$scantron_config{'CODElength'});
 6240: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6241: 		$record{'scantron.useCODE'}=1;
 6242: 	    }
 6243: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6244: 		$record{'scantron.CODE_ignore_dup'}=1;
 6245: 	    }
 6246: 	} else {
 6247: 	    #FIXME interpret first N questions
 6248: 	}
 6249:     }
 6250:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6251: 				  $$scantron_config{'IDlength'});
 6252:     $record{'scantron.PaperID'}=
 6253: 	substr($data,$$scantron_config{'PaperID'}-1,
 6254: 	       $$scantron_config{'PaperIDlength'});
 6255:     $record{'scantron.FirstName'}=
 6256: 	substr($data,$$scantron_config{'FirstName'}-1,
 6257: 	       $$scantron_config{'FirstNamelength'});
 6258:     $record{'scantron.LastName'}=
 6259: 	substr($data,$$scantron_config{'LastName'}-1,
 6260: 	       $$scantron_config{'LastNamelength'});
 6261:     if ($just_header) { return \%record; }
 6262: 
 6263:     my @alphabet=('A'..'Z');
 6264:     my $questnum=0;
 6265:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6266: 
 6267:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6268:     if ($randompick || $randomorder) {
 6269:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6270:                                          $master_seq,$symb_to_resource,
 6271:                                          $partids_by_symb,$orderedforcode,
 6272:                                          $respnumlookup,$startline);
 6273:         if ($total) {
 6274:             $lastpos = $total*$$scantron_config{'Qlength'};
 6275:         }
 6276:         if (ref($totalref)) {
 6277:             $$totalref = $total;
 6278:         }
 6279:     }
 6280:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6281:     chomp($questions);		# Get rid of any trailing \n.
 6282:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6283:     while (length($questions)) {
 6284:         my $answers_needed;
 6285:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6286:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6287:         } else {
 6288:             $answers_needed = $bubble_lines_per_response{$questnum};
 6289:         }
 6290:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6291:                              || 1;
 6292:         $questnum++;
 6293:         my $quest_id = $questnum;
 6294:         my $currentquest = substr($questions,0,$answer_length);
 6295:         $questions       = substr($questions,$answer_length);
 6296:         if (length($currentquest) < $answer_length) { next; }
 6297: 
 6298:         my $subdivided;
 6299:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6300:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6301:         } else {
 6302:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6303:         }
 6304:         if ($subdivided =~ /,/) {
 6305:             my $subquestnum = 1;
 6306:             my $subquestions = $currentquest;
 6307:             my @subanswers_needed = split(/,/,$subdivided);
 6308:             foreach my $subans (@subanswers_needed) {
 6309:                 my $subans_length =
 6310:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6311:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6312:                 $subquestions   = substr($subquestions,$subans_length);
 6313:                 $quest_id = "$questnum.$subquestnum";
 6314:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6315:                     ($$scantron_config{'Qon'} eq 'number')) {
 6316:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6317:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6318:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6319:                         $randomorder,$randompick,$respnumlookup);
 6320:                 } else {
 6321:                     $ansnum = &scantron_validator_positional($ansnum,
 6322:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6323:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6324:                         $randomorder,$randompick,$respnumlookup);
 6325:                 }
 6326:                 $subquestnum ++;
 6327:             }
 6328:         } else {
 6329:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6330:                 ($$scantron_config{'Qon'} eq 'number')) {
 6331:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6332:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6333:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6334:                     $randomorder,$randompick,$respnumlookup);
 6335:             } else {
 6336:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6337:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6338:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6339:                     $randomorder,$randompick,$respnumlookup);
 6340:             }
 6341:         }
 6342:     }
 6343:     $record{'scantron.maxquest'}=$questnum;
 6344:     return \%record;
 6345: }
 6346: 
 6347: sub get_master_seq {
 6348:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6349:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6350:                    (ref($symb_to_resource) eq 'HASH'));
 6351:     my $resource_error;
 6352:     foreach my $resource (@{$resources}) {
 6353:         my $ressymb;
 6354:         if (ref($resource)) {
 6355:             $ressymb = $resource->symb();
 6356:             push(@{$master_seq},$ressymb);
 6357:             $symb_to_resource->{$ressymb} = $resource;
 6358:         } else {
 6359:             $resource_error = 1;
 6360:             last;
 6361:         }
 6362:     }
 6363:     return $resource_error;
 6364: }
 6365: 
 6366: sub get_respnum_lookups {
 6367:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6368:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6369:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6370:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6371:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6372:                    (ref($startline) eq 'HASH'));
 6373:     my ($user,$scancode);
 6374:     if ((exists($record->{'scantron.CODE'})) &&
 6375:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6376:         $scancode = $record->{'scantron.CODE'};
 6377:     } else {
 6378:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6379:     }
 6380:     my @mapresources =
 6381:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6382:                      $orderedforcode);
 6383:     my $total = 0;
 6384:     my $count = 0;
 6385:     foreach my $resource (@mapresources) {
 6386:         my $id = $resource->id();
 6387:         my $symb = $resource->symb();
 6388:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6389:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6390:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6391:                 if ($respnum ne '') {
 6392:                     $respnumlookup->{$count} = $respnum;
 6393:                     $startline->{$count} = $total;
 6394:                     $total += $bubble_lines_per_response{$respnum};
 6395:                     $count ++;
 6396:                 }
 6397:             }
 6398:         }
 6399:     }
 6400:     return $total;
 6401: }
 6402: 
 6403: sub scantron_validator_lettnum {
 6404:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6405:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6406:         $randompick,$respnumlookup) = @_;
 6407: 
 6408:     # Qon 'letter' implies for each slot in currquest we have:
 6409:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6410:     #    about anything else (esp. a value of Qoff) for missing
 6411:     #    bubbles.
 6412:     #
 6413:     # Qon 'number' implies each slot gives a digit that indexes the
 6414:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6415:     #    and * or ? for double bubbles on a single line.
 6416:     #
 6417: 
 6418:     my $matchon;
 6419:     if ($$scantron_config{'Qon'} eq 'letter') {
 6420:         $matchon = '[A-Z]';
 6421:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6422:         $matchon = '\d';
 6423:     }
 6424:     my $occurrences = 0;
 6425:     my $responsenum = $questnum-1;
 6426:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6427:        $responsenum = $respnumlookup->{$questnum-1}
 6428:     }
 6429:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6430:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6431:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6432:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6433:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6434:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6435:         my @singlelines = split('',$currquest);
 6436:         foreach my $entry (@singlelines) {
 6437:             $occurrences = &occurence_count($entry,$matchon);
 6438:             if ($occurrences > 1) {
 6439:                 last;
 6440:             }
 6441:         }
 6442:     } else {
 6443:         $occurrences = &occurence_count($currquest,$matchon); 
 6444:     }
 6445:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6446:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6447:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6448:             my $bubble = substr($currquest,$ans,1);
 6449:             if ($bubble =~ /$matchon/ ) {
 6450:                 if ($$scantron_config{'Qon'} eq 'number') {
 6451:                     if ($bubble == 0) {
 6452:                         $bubble = 10; 
 6453:                     }
 6454:                     $record->{"scantron.$ansnum.answer"} = 
 6455:                         $alphabet->[$bubble-1];
 6456:                 } else {
 6457:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6458:                 }
 6459:             } else {
 6460:                 $record->{"scantron.$ansnum.answer"}='';
 6461:             }
 6462:             $ansnum++;
 6463:         }
 6464:     } elsif (!defined($currquest)
 6465:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6466:             || (&occurence_count($currquest,$matchon) == 0)) {
 6467:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6468:             $record->{"scantron.$ansnum.answer"}='';
 6469:             $ansnum++;
 6470:         }
 6471:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6472:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6473:         }
 6474:     } else {
 6475:         if ($$scantron_config{'Qon'} eq 'number') {
 6476:             $currquest = &digits_to_letters($currquest);            
 6477:         }
 6478:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6479:             my $bubble = substr($currquest,$ans,1);
 6480:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6481:             $ansnum++;
 6482:         }
 6483:     }
 6484:     return $ansnum;
 6485: }
 6486: 
 6487: sub scantron_validator_positional {
 6488:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6489:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6490:         $randomorder,$randompick,$respnumlookup) = @_;
 6491: 
 6492:     # Otherwise there's a positional notation;
 6493:     # each bubble line requires Qlength items, and there are filled in
 6494:     # bubbles for each case where there 'Qon' characters.
 6495:     #
 6496: 
 6497:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6498: 
 6499:     # If the split only gives us one element.. the full length of the
 6500:     # answer string, no bubbles are filled in:
 6501: 
 6502:     if ($answers_needed eq '') {
 6503:         return;
 6504:     }
 6505: 
 6506:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6507:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6508:             $record->{"scantron.$ansnum.answer"}='';
 6509:             $ansnum++;
 6510:         }
 6511:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6512:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6513:         }
 6514:     } elsif (scalar(@array) == 2) {
 6515:         my $location = length($array[0]);
 6516:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6517:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6518:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6519:             if ($ans eq $line_num) {
 6520:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6521:             } else {
 6522:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6523:             }
 6524:             $ansnum++;
 6525:          }
 6526:     } else {
 6527:         #  If there's more than one instance of a bubble character
 6528:         #  That's a double bubble; with positional notation we can
 6529:         #  record all the bubbles filled in as well as the
 6530:         #  fact this response consists of multiple bubbles.
 6531:         #
 6532:         my $responsenum = $questnum-1;
 6533:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6534:             $responsenum = $respnumlookup->{$questnum-1}
 6535:         }
 6536:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6537:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6538:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6539:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6540:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6541:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6542:             my $doubleerror = 0;
 6543:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6544:                    (!$doubleerror)) {
 6545:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6546:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6547:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6548:                if (length(@currarray) > 2) {
 6549:                    $doubleerror = 1;
 6550:                } 
 6551:             }
 6552:             if ($doubleerror) {
 6553:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6554:             }
 6555:         } else {
 6556:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6557:         }
 6558:         my $item = $ansnum;
 6559:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6560:             $record->{"scantron.$item.answer"} = '';
 6561:             $item ++;
 6562:         }
 6563: 
 6564:         my @ans=@array;
 6565:         my $i=0;
 6566:         my $increment = 0;
 6567:         while ($#ans) {
 6568:             $i+=length($ans[0]) + $increment;
 6569:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6570:             my $bubble = $i%$$scantron_config{'Qlength'};
 6571:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6572:             shift(@ans);
 6573:             $increment = 1;
 6574:         }
 6575:         $ansnum += $answers_needed;
 6576:     }
 6577:     return $ansnum;
 6578: }
 6579: 
 6580: =pod
 6581: 
 6582: =item scantron_add_delay
 6583: 
 6584:    Adds an error message that occurred during the grading phase to a
 6585:    queue of messages to be shown after grading pass is complete
 6586: 
 6587:  Arguments:
 6588:    $delayqueue  - arrary ref of hash ref of error messages
 6589:    $scanline    - the scanline that caused the error
 6590:    $errormesage - the error message
 6591:    $errorcode   - a numeric code for the error
 6592: 
 6593:  Side Effects:
 6594:    updates the $delayqueue to have a new hash ref of the error
 6595: 
 6596: =cut
 6597: 
 6598: sub scantron_add_delay {
 6599:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6600:     push(@$delayqueue,
 6601: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6602: 	  'ecode' => $errorcode }
 6603: 	 );
 6604: }
 6605: 
 6606: =pod
 6607: 
 6608: =item scantron_find_student
 6609: 
 6610:    Finds the username for the current scanline
 6611: 
 6612:   Arguments:
 6613:    $scantron_record - hash result from scantron_parse_scanline
 6614:    $scan_data       - hash of correction information 
 6615:                       (see &scantron_getfile() form more information)
 6616:    $idmap           - hash from &username_to_idmap()
 6617:    $line            - number of current scanline
 6618:  
 6619:   Returns:
 6620:    Either 'username:domain' or undef if unknown
 6621: 
 6622: =cut
 6623: 
 6624: sub scantron_find_student {
 6625:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6626:     my $scanID=$$scantron_record{'scantron.ID'};
 6627:     if ($scanID =~ /^\s*$/) {
 6628:  	return &scan_data($scan_data,"$line.user");
 6629:     }
 6630:     foreach my $id (keys(%$idmap)) {
 6631:  	if (lc($id) eq lc($scanID)) {
 6632:  	    return $$idmap{$id};
 6633:  	}
 6634:     }
 6635:     return undef;
 6636: }
 6637: 
 6638: =pod
 6639: 
 6640: =item scantron_filter
 6641: 
 6642:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6643:    hidden resources was selected
 6644: 
 6645: =cut
 6646: 
 6647: sub scantron_filter {
 6648:     my ($curres)=@_;
 6649: 
 6650:     if (ref($curres) && $curres->is_problem()) {
 6651: 	# if the user has asked to not have either hidden
 6652: 	# or 'randomout' controlled resources to be graded
 6653: 	# don't include them
 6654: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6655: 	    && $curres->randomout) {
 6656: 	    return 0;
 6657: 	}
 6658: 	return 1;
 6659:     }
 6660:     return 0;
 6661: }
 6662: 
 6663: =pod
 6664: 
 6665: =item scantron_process_corrections
 6666: 
 6667:    Gets correction information out of submitted form data and corrects
 6668:    the scanline
 6669: 
 6670: =cut
 6671: 
 6672: sub scantron_process_corrections {
 6673:     my ($r) = @_;
 6674:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6675:     my ($scanlines,$scan_data)=&scantron_getfile();
 6676:     my $classlist=&Apache::loncoursedata::get_classlist();
 6677:     my $which=$env{'form.scantron_line'};
 6678:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6679:     my ($skip,$err,$errmsg);
 6680:     if ($env{'form.scantron_skip_record'}) {
 6681: 	$skip=1;
 6682:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6683: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6684: 	    $env{'form.scantron_domain'};
 6685: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6686: 	($line,$err,$errmsg)=
 6687: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6688: 				     'ID',{'newid'=>$newid,
 6689: 				    'username'=>$env{'form.scantron_username'},
 6690: 				    'domain'=>$env{'form.scantron_domain'}});
 6691:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6692: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6693: 	my $newCODE;
 6694: 	my %args;
 6695: 	if      ($resolution eq 'use_unfound') {
 6696: 	    $newCODE='use_unfound';
 6697: 	} elsif ($resolution eq 'use_found') {
 6698: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6699: 	} elsif ($resolution eq 'use_typed') {
 6700: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6701: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6702: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6703: 	}
 6704: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6705: 	    $args{'CODE_ignore_dup'}=1;
 6706: 	}
 6707: 	$args{'CODE'}=$newCODE;
 6708: 	($line,$err,$errmsg)=
 6709: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6710: 				     'CODE',\%args);
 6711:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6712: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6713: 	    ($line,$err,$errmsg)=
 6714: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6715: 					 $which,'answer',
 6716: 					 { 'question'=>$question,
 6717: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6718:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6719: 	    if ($err) { last; }
 6720: 	}
 6721:     }
 6722:     if ($err) {
 6723: 	$r->print(
 6724:             '<p class="LC_error">'
 6725:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6726:                 $errmsg)
 6727:            .'</p>');
 6728:     } else {
 6729: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6730: 	&scantron_putfile($scanlines,$scan_data);
 6731:     }
 6732: }
 6733: 
 6734: =pod
 6735: 
 6736: =item reset_skipping_status
 6737: 
 6738:    Forgets the current set of remember skipped scanlines (and thus
 6739:    reverts back to considering all lines in the
 6740:    scantron_skipped_<filename> file)
 6741: 
 6742: =cut
 6743: 
 6744: sub reset_skipping_status {
 6745:     my ($scanlines,$scan_data)=&scantron_getfile();
 6746:     &scan_data($scan_data,'remember_skipping',undef,1);
 6747:     &scantron_putfile(undef,$scan_data);
 6748: }
 6749: 
 6750: =pod
 6751: 
 6752: =item start_skipping
 6753: 
 6754:    Marks a scanline to be skipped. 
 6755: 
 6756: =cut
 6757: 
 6758: sub start_skipping {
 6759:     my ($scan_data,$i)=@_;
 6760:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6761:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6762: 	$remembered{$i}=2;
 6763:     } else {
 6764: 	$remembered{$i}=1;
 6765:     }
 6766:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6767: }
 6768: 
 6769: =pod
 6770: 
 6771: =item should_be_skipped
 6772: 
 6773:    Checks whether a scanline should be skipped.
 6774: 
 6775: =cut
 6776: 
 6777: sub should_be_skipped {
 6778:     my ($scanlines,$scan_data,$i)=@_;
 6779:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6780: 	# not redoing old skips
 6781: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6782: 	return 0;
 6783:     }
 6784:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6785: 
 6786:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6787: 	return 0;
 6788:     }
 6789:     return 1;
 6790: }
 6791: 
 6792: =pod
 6793: 
 6794: =item remember_current_skipped
 6795: 
 6796:    Discovers what scanlines are in the scantron_skipped_<filename>
 6797:    file and remembers them into scan_data for later use.
 6798: 
 6799: =cut
 6800: 
 6801: sub remember_current_skipped {
 6802:     my ($scanlines,$scan_data)=&scantron_getfile();
 6803:     my %to_remember;
 6804:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6805: 	if ($scanlines->{'skipped'}[$i]) {
 6806: 	    $to_remember{$i}=1;
 6807: 	}
 6808:     }
 6809: 
 6810:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6811:     &scantron_putfile(undef,$scan_data);
 6812: }
 6813: 
 6814: =pod
 6815: 
 6816: =item check_for_error
 6817: 
 6818:     Checks if there was an error when attempting to remove a specific
 6819:     scantron_.. bubblesheet data file. Prints out an error if
 6820:     something went wrong.
 6821: 
 6822: =cut
 6823: 
 6824: sub check_for_error {
 6825:     my ($r,$result)=@_;
 6826:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6827: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6828:     }
 6829: }
 6830: 
 6831: =pod
 6832: 
 6833: =item scantron_warning_screen
 6834: 
 6835:    Interstitial screen to make sure the operator has selected the
 6836:    correct options before we start the validation phase.
 6837: 
 6838: =cut
 6839: 
 6840: sub scantron_warning_screen {
 6841:     my ($button_text)=@_;
 6842:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6843:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6844:     my $CODElist;
 6845:     if ($scantron_config{'CODElocation'} &&
 6846: 	$scantron_config{'CODEstart'} &&
 6847: 	$scantron_config{'CODElength'}) {
 6848: 	$CODElist=$env{'form.scantron_CODElist'};
 6849: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6850: 	$CODElist=
 6851: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6852: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6853:     }
 6854:     my $lastbubblepoints;
 6855:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6856:         $lastbubblepoints =
 6857:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6858:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6859:     }
 6860:     return ('
 6861: <p>
 6862: <span class="LC_warning">
 6863: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6864: </p>
 6865: <table>
 6866: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6867: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6868: '.$CODElist.$lastbubblepoints.'
 6869: </table>
 6870: <br />
 6871: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 6872: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 6873: 
 6874: <br />
 6875: ');
 6876: }
 6877: 
 6878: =pod
 6879: 
 6880: =item scantron_do_warning
 6881: 
 6882:    Check if the operator has picked something for all required
 6883:    fields. Error out if something is missing.
 6884: 
 6885: =cut
 6886: 
 6887: sub scantron_do_warning {
 6888:     my ($r)=@_;
 6889:     my ($symb)=&get_symb($r);
 6890:     if (!$symb) {return '';}
 6891:     my $default_form_data=&defaultFormData($symb);
 6892:     $r->print(&scantron_form_start().$default_form_data);
 6893:     if ( $env{'form.selectpage'} eq '' ||
 6894: 	 $env{'form.scantron_selectfile'} eq '' ||
 6895: 	 $env{'form.scantron_format'} eq '' ) {
 6896: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6897: 	if ( $env{'form.selectpage'} eq '') {
 6898: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6899: 	} 
 6900: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6901: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6902: 	} 
 6903: 	if ( $env{'form.scantron_format'} eq '') {
 6904: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6905: 	} 
 6906:     } else {
 6907: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6908:         my $bubbledbyhand=&hand_bubble_option();
 6909: 	$r->print('
 6910: '.$warning.$bubbledbyhand.'
 6911: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6912: <input type="hidden" name="command" value="scantron_validate" />
 6913: ');
 6914:     }
 6915:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6916:     return '';
 6917: }
 6918: 
 6919: =pod
 6920: 
 6921: =item scantron_form_start
 6922: 
 6923:     html hidden input for remembering all selected grading options
 6924: 
 6925: =cut
 6926: 
 6927: sub scantron_form_start {
 6928:     my ($max_bubble)=@_;
 6929:     my $result= <<SCANTRONFORM;
 6930: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6931:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6932:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6933:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6934:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6935:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6936:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6937:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6938:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6939:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6940: SCANTRONFORM
 6941: 
 6942:   my $line = 0;
 6943:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6944:        my $chunk =
 6945: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6946:        $chunk .=
 6947: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6948:        $chunk .= 
 6949:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6950:        $chunk .=
 6951:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6952:        $chunk .=
 6953:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6954:        $result .= $chunk;
 6955:        $line++;
 6956:     }
 6957:     return $result;
 6958: }
 6959: 
 6960: =pod
 6961: 
 6962: =item scantron_validate_file
 6963: 
 6964:     Dispatch routine for doing validation of a bubblesheet data file.
 6965: 
 6966:     Also processes any necessary information resets that need to
 6967:     occur before validation begins (ignore previous corrections,
 6968:     restarting the skipped records processing)
 6969: 
 6970: =cut
 6971: 
 6972: sub scantron_validate_file {
 6973:     my ($r) = @_;
 6974:     my ($symb)=&get_symb($r);
 6975:     if (!$symb) {return '';}
 6976:     my $default_form_data=&defaultFormData($symb);
 6977:     
 6978:     # do the detection of only doing skipped records first before we delete
 6979:     # them when doing the corrections reset
 6980:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6981: 	&reset_skipping_status();
 6982:     }
 6983:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6984: 	&remember_current_skipped();
 6985: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6986:     }
 6987: 
 6988:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6989: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6990: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6991: 	&check_for_error($r,&scantron_remove_scan_data());
 6992: 	$env{'form.scantron_options_ignore'}='done';
 6993:     }
 6994: 
 6995:     if ($env{'form.scantron_corrections'}) {
 6996: 	&scantron_process_corrections($r);
 6997:     }
 6998:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6999:     #get the student pick code ready
 7000:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7001:     my $nav_error;
 7002:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7003:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7004:     if ($nav_error) {
 7005:         $r->print(&navmap_errormsg());
 7006:         return '';
 7007:     }
 7008:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7009:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7010:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7011:     }
 7012:     $r->print($result);
 7013:     
 7014:     my @validate_phases=( 'sequence',
 7015: 			  'ID',
 7016: 			  'CODE',
 7017: 			  'doublebubble',
 7018: 			  'missingbubbles');
 7019:     if (!$env{'form.validatepass'}) {
 7020: 	$env{'form.validatepass'} = 0;
 7021:     }
 7022:     my $currentphase=$env{'form.validatepass'};
 7023: 
 7024: 
 7025:     my $stop=0;
 7026:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7027: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7028: 	$r->rflush();
 7029: 
 7030: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7031: 	{
 7032: 	    no strict 'refs';
 7033: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7034: 	}
 7035:     }
 7036:     if (!$stop) {
 7037: 	my $warning=&scantron_warning_screen('Start Grading');
 7038: 	$r->print(&mt('Validation process complete.').'<br />'.
 7039:                   $warning.
 7040:                   &mt('Perform verification for each student after storage of submissions?').
 7041:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7042:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7043:                   ('&nbsp;'x3).'<label>'.
 7044:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7045:                   '</label></span><br />'.
 7046:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7047:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 7048:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7049:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7050:     } else {
 7051: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7052: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7053:     }
 7054:     if ($stop) {
 7055: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7056: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7057: 	    $r->print(' '.&mt('this error').' <br />');
 7058: 
 7059: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 7060: 	} else {
 7061:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7062: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7063:             } else {
 7064:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7065:             }
 7066: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7067: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7068: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7069: 	}
 7070:     }
 7071:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 7072:     return '';
 7073: }
 7074: 
 7075: 
 7076: =pod
 7077: 
 7078: =item scantron_remove_file
 7079: 
 7080:    Removes the requested bubblesheet data file, makes sure that
 7081:    scantron_original_<filename> is never removed
 7082: 
 7083: 
 7084: =cut
 7085: 
 7086: sub scantron_remove_file {
 7087:     my ($which)=@_;
 7088:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7089:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7090:     my $file='scantron_';
 7091:     if ($which eq 'corrected' || $which eq 'skipped') {
 7092: 	$file.=$which.'_';
 7093:     } else {
 7094: 	return 'refused';
 7095:     }
 7096:     $file.=$env{'form.scantron_selectfile'};
 7097:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7098: }
 7099: 
 7100: 
 7101: =pod
 7102: 
 7103: =item scantron_remove_scan_data
 7104: 
 7105:    Removes all scan_data correction for the requested bubblesheet
 7106:    data file.  (In the case that both the are doing skipped records we need
 7107:    to remember the old skipped lines for the time being so that element
 7108:    persists for a while.)
 7109: 
 7110: =cut
 7111: 
 7112: sub scantron_remove_scan_data {
 7113:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7114:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7115:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7116:     my @todelete;
 7117:     my $filename=$env{'form.scantron_selectfile'};
 7118:     foreach my $key (@keys) {
 7119: 	if ($key=~/^\Q$filename\E_/) {
 7120: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7121: 		$key=~/remember_skipping/) {
 7122: 		next;
 7123: 	    }
 7124: 	    push(@todelete,$key);
 7125: 	}
 7126:     }
 7127:     my $result;
 7128:     if (@todelete) {
 7129: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7130: 				       \@todelete,$cdom,$cname);
 7131:     } else {
 7132: 	$result = 'ok';
 7133:     }
 7134:     return $result;
 7135: }
 7136: 
 7137: 
 7138: =pod
 7139: 
 7140: =item scantron_getfile
 7141: 
 7142:     Fetches the requested bubblesheet data file (all 3 versions), and
 7143:     the scan_data hash
 7144:   
 7145:   Arguments:
 7146:     None
 7147: 
 7148:   Returns:
 7149:     2 hash references
 7150: 
 7151:      - first one has 
 7152:          orig      -
 7153:          corrected -
 7154:          skipped   -  each of which points to an array ref of the specified
 7155:                       file broken up into individual lines
 7156:          count     - number of scanlines
 7157:  
 7158:      - second is the scan_data hash possible keys are
 7159:        ($number refers to scanline numbered $number and thus the key affects
 7160:         only that scanline
 7161:         $bubline refers to the specific bubble line element and the aspects
 7162:         refers to that specific bubble line element)
 7163: 
 7164:        $number.user - username:domain to use
 7165:        $number.CODE_ignore_dup 
 7166:                     - ignore the duplicate CODE error 
 7167:        $number.useCODE
 7168:                     - use the CODE in the scanline as is
 7169:        $number.no_bubble.$bubline
 7170:                     - it is valid that there is no bubbled in bubble
 7171:                       at $number $bubline
 7172:        remember_skipping
 7173:                     - a frozen hash containing keys of $number and values
 7174:                       of either 
 7175:                         1 - we are on a 'do skipped records pass' and plan
 7176:                             on processing this line
 7177:                         2 - we are on a 'do skipped records pass' and this
 7178:                             scanline has been marked to skip yet again
 7179: 
 7180: =cut
 7181: 
 7182: sub scantron_getfile {
 7183:     #FIXME really would prefer a scantron directory
 7184:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7185:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7186:     my $lines;
 7187:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7188: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7189:     my %scanlines;
 7190:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7191:     my $temp=$scanlines{'orig'};
 7192:     $scanlines{'count'}=$#$temp;
 7193: 
 7194:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7195: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7196:     if ($lines eq '-1') {
 7197: 	$scanlines{'corrected'}=[];
 7198:     } else {
 7199: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7200:     }
 7201:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7202: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7203:     if ($lines eq '-1') {
 7204: 	$scanlines{'skipped'}=[];
 7205:     } else {
 7206: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7207:     }
 7208:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7209:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7210:     my %scan_data = @tmp;
 7211:     return (\%scanlines,\%scan_data);
 7212: }
 7213: 
 7214: =pod
 7215: 
 7216: =item lonnet_putfile
 7217: 
 7218:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7219: 
 7220:  Arguments:
 7221:    $contents - data to store
 7222:    $filename - filename to store $contents into
 7223: 
 7224:  Returns:
 7225:    result value from &Apache::lonnet::finishuserfileupload
 7226: 
 7227: =cut
 7228: 
 7229: sub lonnet_putfile {
 7230:     my ($contents,$filename)=@_;
 7231:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7232:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7233:     $env{'form.sillywaytopassafilearound'}=$contents;
 7234:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7235: 
 7236: }
 7237: 
 7238: =pod
 7239: 
 7240: =item scantron_putfile
 7241: 
 7242:     Stores the current version of the bubblesheet data files, and the
 7243:     scan_data hash. (Does not modify the original version only the
 7244:     corrected and skipped versions.
 7245: 
 7246:  Arguments:
 7247:     $scanlines - hash ref that looks like the first return value from
 7248:                  &scantron_getfile()
 7249:     $scan_data - hash ref that looks like the second return value from
 7250:                  &scantron_getfile()
 7251: 
 7252: =cut
 7253: 
 7254: sub scantron_putfile {
 7255:     my ($scanlines,$scan_data) = @_;
 7256:     #FIXME really would prefer a scantron directory
 7257:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7258:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7259:     if ($scanlines) {
 7260: 	my $prefix='scantron_';
 7261: # no need to update orig, shouldn't change
 7262: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7263: #		    $env{'form.scantron_selectfile'});
 7264: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7265: 			$prefix.'corrected_'.
 7266: 			$env{'form.scantron_selectfile'});
 7267: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7268: 			$prefix.'skipped_'.
 7269: 			$env{'form.scantron_selectfile'});
 7270:     }
 7271:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7272: }
 7273: 
 7274: =pod
 7275: 
 7276: =item scantron_get_line
 7277: 
 7278:    Returns the correct version of the scanline
 7279: 
 7280:  Arguments:
 7281:     $scanlines - hash ref that looks like the first return value from
 7282:                  &scantron_getfile()
 7283:     $scan_data - hash ref that looks like the second return value from
 7284:                  &scantron_getfile()
 7285:     $i         - number of the requested line (starts at 0)
 7286: 
 7287:  Returns:
 7288:    A scanline, (either the original or the corrected one if it
 7289:    exists), or undef if the requested scanline should be
 7290:    skipped. (Either because it's an skipped scanline, or it's an
 7291:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7292:    pass.
 7293: 
 7294: =cut
 7295: 
 7296: sub scantron_get_line {
 7297:     my ($scanlines,$scan_data,$i)=@_;
 7298:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7299:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7300:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7301:     return $scanlines->{'orig'}[$i]; 
 7302: }
 7303: 
 7304: =pod
 7305: 
 7306: =item scantron_todo_count
 7307: 
 7308:     Counts the number of scanlines that need processing.
 7309: 
 7310:  Arguments:
 7311:     $scanlines - hash ref that looks like the first return value from
 7312:                  &scantron_getfile()
 7313:     $scan_data - hash ref that looks like the second return value from
 7314:                  &scantron_getfile()
 7315: 
 7316:  Returns:
 7317:     $count - number of scanlines to process
 7318: 
 7319: =cut
 7320: 
 7321: sub get_todo_count {
 7322:     my ($scanlines,$scan_data)=@_;
 7323:     my $count=0;
 7324:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7325: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7326: 	if ($line=~/^[\s\cz]*$/) { next; }
 7327: 	$count++;
 7328:     }
 7329:     return $count;
 7330: }
 7331: 
 7332: =pod
 7333: 
 7334: =item scantron_put_line
 7335: 
 7336:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7337:     data file.
 7338: 
 7339:  Arguments:
 7340:     $scanlines - hash ref that looks like the first return value from
 7341:                  &scantron_getfile()
 7342:     $scan_data - hash ref that looks like the second return value from
 7343:                  &scantron_getfile()
 7344:     $i         - line number to update
 7345:     $newline   - contents of the updated scanline
 7346:     $skip      - if true make the line for skipping and update the
 7347:                  'skipped' file
 7348: 
 7349: =cut
 7350: 
 7351: sub scantron_put_line {
 7352:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7353:     if ($skip) {
 7354: 	$scanlines->{'skipped'}[$i]=$newline;
 7355: 	&start_skipping($scan_data,$i);
 7356: 	return;
 7357:     }
 7358:     $scanlines->{'corrected'}[$i]=$newline;
 7359: }
 7360: 
 7361: =pod
 7362: 
 7363: =item scantron_clear_skip
 7364: 
 7365:    Remove a line from the 'skipped' file
 7366: 
 7367:  Arguments:
 7368:     $scanlines - hash ref that looks like the first return value from
 7369:                  &scantron_getfile()
 7370:     $scan_data - hash ref that looks like the second return value from
 7371:                  &scantron_getfile()
 7372:     $i         - line number to update
 7373: 
 7374: =cut
 7375: 
 7376: sub scantron_clear_skip {
 7377:     my ($scanlines,$scan_data,$i)=@_;
 7378:     if (exists($scanlines->{'skipped'}[$i])) {
 7379: 	undef($scanlines->{'skipped'}[$i]);
 7380: 	return 1;
 7381:     }
 7382:     return 0;
 7383: }
 7384: 
 7385: =pod
 7386: 
 7387: =item scantron_filter_not_exam
 7388: 
 7389:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7390:    filter out resources that are not marked as 'exam' mode
 7391: 
 7392: =cut
 7393: 
 7394: sub scantron_filter_not_exam {
 7395:     my ($curres)=@_;
 7396:     
 7397:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7398: 	# if the user has asked to not have either hidden
 7399: 	# or 'randomout' controlled resources to be graded
 7400: 	# don't include them
 7401: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7402: 	    && $curres->randomout) {
 7403: 	    return 0;
 7404: 	}
 7405: 	return 1;
 7406:     }
 7407:     return 0;
 7408: }
 7409: 
 7410: =pod
 7411: 
 7412: =item scantron_validate_sequence
 7413: 
 7414:     Validates the selected sequence, checking for resource that are
 7415:     not set to exam mode.
 7416: 
 7417: =cut
 7418: 
 7419: sub scantron_validate_sequence {
 7420:     my ($r,$currentphase) = @_;
 7421: 
 7422:     my $navmap=Apache::lonnavmaps::navmap->new();
 7423:     unless (ref($navmap)) {
 7424:         $r->print(&navmap_errormsg());
 7425:         return (1,$currentphase);
 7426:     }
 7427:     my (undef,undef,$sequence)=
 7428: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7429: 
 7430:     my $map=$navmap->getResourceByUrl($sequence);
 7431: 
 7432:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7433:                                     value="ignore" />');
 7434:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7435: 	my @resources=
 7436: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7437: 	if (@resources) {
 7438: 	    $r->print('<p class="LC_warning">'
 7439:                .&mt('Some resources in the sequence currently are not set to'
 7440:                    .' exam mode. Grading these resources currently may not'
 7441:                    .' work correctly.')
 7442:                .'</p>'
 7443:             );
 7444: 	    return (1,$currentphase);
 7445: 	}
 7446:     }
 7447: 
 7448:     return (0,$currentphase+1);
 7449: }
 7450: 
 7451: 
 7452: 
 7453: sub scantron_validate_ID {
 7454:     my ($r,$currentphase) = @_;
 7455:     
 7456:     #get student info
 7457:     my $classlist=&Apache::loncoursedata::get_classlist();
 7458:     my %idmap=&username_to_idmap($classlist);
 7459: 
 7460:     #get scantron line setup
 7461:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7462:     my ($scanlines,$scan_data)=&scantron_getfile();
 7463: 
 7464:     my $nav_error;
 7465:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7466:     if ($nav_error) {
 7467:         $r->print(&navmap_errormsg());
 7468:         return(1,$currentphase);
 7469:     }
 7470: 
 7471:     my %found=('ids'=>{},'usernames'=>{});
 7472:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7473: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7474: 	if ($line=~/^[\s\cz]*$/) { next; }
 7475: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7476: 						 $scan_data);
 7477: 	my $id=$$scan_record{'scantron.ID'};
 7478: 	my $found;
 7479: 	foreach my $checkid (keys(%idmap)) {
 7480: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7481: 	}
 7482: 	if ($found) {
 7483: 	    my $username=$idmap{$found};
 7484: 	    if ($found{'ids'}{$found}) {
 7485: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7486: 					 $line,'duplicateID',$found);
 7487: 		return(1,$currentphase);
 7488: 	    } elsif ($found{'usernames'}{$username}) {
 7489: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7490: 					 $line,'duplicateID',$username);
 7491: 		return(1,$currentphase);
 7492: 	    }
 7493: 	    #FIXME store away line we previously saw the ID on to use above
 7494: 	    $found{'ids'}{$found}++;
 7495: 	    $found{'usernames'}{$username}++;
 7496: 	} else {
 7497: 	    if ($id =~ /^\s*$/) {
 7498: 		my $username=&scan_data($scan_data,"$i.user");
 7499: 		if (defined($username) && $found{'usernames'}{$username}) {
 7500: 		    &scantron_get_correction($r,$i,$scan_record,
 7501: 					     \%scantron_config,
 7502: 					     $line,'duplicateID',$username);
 7503: 		    return(1,$currentphase);
 7504: 		} elsif (!defined($username)) {
 7505: 		    &scantron_get_correction($r,$i,$scan_record,
 7506: 					     \%scantron_config,
 7507: 					     $line,'incorrectID');
 7508: 		    return(1,$currentphase);
 7509: 		}
 7510: 		$found{'usernames'}{$username}++;
 7511: 	    } else {
 7512: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7513: 					 $line,'incorrectID');
 7514: 		return(1,$currentphase);
 7515: 	    }
 7516: 	}
 7517:     }
 7518: 
 7519:     return (0,$currentphase+1);
 7520: }
 7521: 
 7522: 
 7523: sub scantron_get_correction {
 7524:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7525:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7526: #FIXME in the case of a duplicated ID the previous line, probably need
 7527: #to show both the current line and the previous one and allow skipping
 7528: #the previous one or the current one
 7529: 
 7530:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7531:         $r->print(
 7532:             '<p class="LC_warning">'
 7533:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7534:                 "<b>$error</b>",
 7535:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7536:            ."</p> \n");
 7537:     } else {
 7538:         $r->print(
 7539:             '<p class="LC_warning">'
 7540:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7541:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7542:            ."</p> \n");
 7543:     }
 7544:     my $message =
 7545:         '<p>'
 7546:        .&mt('The ID on the form is [_1]',
 7547:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7548:        .'<br />'
 7549:        .&mt('The name on the paper is [_1], [_2]',
 7550:             $$scan_record{'scantron.LastName'},
 7551:             $$scan_record{'scantron.FirstName'})
 7552:        .'</p>';
 7553: 
 7554:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7555:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7556:                            # Array populated for doublebubble or
 7557:     my @lines_to_correct;  # missingbubble errors to build javascript
 7558:                            # to validate radio button checking   
 7559: 
 7560:     if ($error =~ /ID$/) {
 7561: 	if ($error eq 'incorrectID') {
 7562: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7563: 		      "</p>\n");
 7564: 	} elsif ($error eq 'duplicateID') {
 7565: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7566: 	}
 7567: 	$r->print($message);
 7568: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7569: 	$r->print("\n<ul><li> ");
 7570: 	#FIXME it would be nice if this sent back the user ID and
 7571: 	#could do partial userID matches
 7572: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7573: 				       'scantron_username','scantron_domain'));
 7574: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7575: 	$r->print("\n:\n".
 7576: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7577: 
 7578: 	$r->print('</li>');
 7579:     } elsif ($error =~ /CODE$/) {
 7580: 	if ($error eq 'incorrectCODE') {
 7581: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7582: 	} elsif ($error eq 'duplicateCODE') {
 7583: 	    $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");
 7584: 	}
 7585:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7586:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7587:                  ."</p>\n");
 7588: 	$r->print($message);
 7589: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7590: 	$r->print("\n<br /> ");
 7591: 	my $i=0;
 7592: 	if ($error eq 'incorrectCODE' 
 7593: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7594: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7595: 	    if ($closest > 0) {
 7596: 		foreach my $testcode (@{$closest}) {
 7597: 		    my $checked='';
 7598: 		    if (!$i) { $checked=' checked="checked"'; }
 7599: 		    $r->print("
 7600:    <label>
 7601:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7602:        ".&mt("Use the similar CODE [_1] instead.",
 7603: 	    "<b><tt>".$testcode."</tt></b>")."
 7604:     </label>
 7605:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7606: 		    $r->print("\n<br />");
 7607: 		    $i++;
 7608: 		}
 7609: 	    }
 7610: 	}
 7611: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7612: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7613: 	    $r->print("
 7614:     <label>
 7615:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7616:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7617: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7618:     </label>");
 7619: 	    $r->print("\n<br />");
 7620: 	}
 7621: 
 7622: 	$r->print(<<ENDSCRIPT);
 7623: <script type="text/javascript">
 7624: function change_radio(field) {
 7625:     var slct=document.scantronupload.scantron_CODE_resolution;
 7626:     var i;
 7627:     for (i=0;i<slct.length;i++) {
 7628:         if (slct[i].value==field) { slct[i].checked=true; }
 7629:     }
 7630: }
 7631: </script>
 7632: ENDSCRIPT
 7633: 	my $href="/adm/pickcode?".
 7634: 	   "form=".&escape("scantronupload").
 7635: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7636: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7637: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7638: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7639: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7640: 	    $r->print("
 7641:     <label>
 7642:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7643:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7644: 	     "<a target='_blank' href='$href'>","</a>")."
 7645:     </label> 
 7646:     ".&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\')" />'));
 7647: 	    $r->print("\n<br />");
 7648: 	}
 7649: 	$r->print("
 7650:     <label>
 7651:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7652:        ".&mt("Use [_1] as the CODE.",
 7653: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7654: 	$r->print("\n<br /><br />");
 7655:     } elsif ($error eq 'doublebubble') {
 7656: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7657: 
 7658: 	# The form field scantron_questions is acutally a list of line numbers.
 7659: 	# represented by this form so:
 7660: 
 7661: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7662:                                                 $respnumlookup,$startline);
 7663: 
 7664: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7665: 		  $line_list.'" />');
 7666: 	$r->print($message);
 7667: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7668: 	foreach my $question (@{$arg}) {
 7669: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7670:                                                    $scan_record, $error,
 7671:                                                    $randomorder,$randompick,
 7672:                                                    $respnumlookup,$startline);
 7673:             push(@lines_to_correct,@linenums);
 7674: 	}
 7675:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7676:     } elsif ($error eq 'missingbubble') {
 7677: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7678: 	$r->print($message);
 7679: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7680: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7681: 
 7682: 	# The form field scantron_questions is actually a list of line numbers not
 7683: 	# a list of question numbers. Therefore:
 7684: 	#
 7685: 	
 7686: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7687:                                                 $respnumlookup,$startline);
 7688: 
 7689: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7690: 		  $line_list.'" />');
 7691: 	foreach my $question (@{$arg}) {
 7692: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7693:                                                    $scan_record, $error,
 7694:                                                    $randomorder,$randompick,
 7695:                                                    $respnumlookup,$startline);
 7696:             push(@lines_to_correct,@linenums);
 7697: 	}
 7698:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7699:     } else {
 7700: 	$r->print("\n<ul>");
 7701:     }
 7702:     $r->print("\n</li></ul>");
 7703: }
 7704: 
 7705: sub verify_bubbles_checked {
 7706:     my (@ansnums) = @_;
 7707:     my $ansnumstr = join('","',@ansnums);
 7708:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7709:     &js_escape(\$warning);
 7710:     my $output = (<<ENDSCRIPT);
 7711: <script type="text/javascript">
 7712: function verify_bubble_radio(form) {
 7713:     var ansnumArray = new Array ("$ansnumstr");
 7714:     var need_bubble_count = 0;
 7715:     for (var i=0; i<ansnumArray.length; i++) {
 7716:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7717:             var bubble_picked = 0; 
 7718:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7719:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7720:                     bubble_picked = 1;
 7721:                 }
 7722:             }
 7723:             if (bubble_picked == 0) {
 7724:                 need_bubble_count ++;
 7725:             }
 7726:         }
 7727:     }
 7728:     if (need_bubble_count) {
 7729:         alert("$warning");
 7730:         return;
 7731:     }
 7732:     form.submit(); 
 7733: }
 7734: </script>
 7735: ENDSCRIPT
 7736:     return $output;
 7737: }
 7738: 
 7739: =pod
 7740: 
 7741: =item  questions_to_line_list
 7742: 
 7743: Converts a list of questions into a string of comma separated
 7744: line numbers in the answer sheet used by the questions.  This is
 7745: used to fill in the scantron_questions form field.
 7746: 
 7747:   Arguments:
 7748:      questions    - Reference to an array of questions.
 7749:      randomorder  - True if randomorder in use.
 7750:      randompick   - True if randompick in use.
 7751:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7752:                      for current line to question number used for same question
 7753:                      in "Master Seqence" (as seen by Course Coordinator).
 7754:      startline    - Reference to hash where key is question number (0 is first)
 7755:                     and key is number of first bubble line for current student
 7756:                     or code-based randompick and/or randomorder.
 7757: 
 7758: =cut
 7759: 
 7760: 
 7761: sub questions_to_line_list {
 7762:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7763:     my @lines;
 7764: 
 7765:     foreach my $item (@{$questions}) {
 7766:         my $question = $item;
 7767:         my ($first,$count,$last);
 7768:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7769:             $question = $1;
 7770:             my $subquestion = $2;
 7771:             my $responsenum = $question-1;
 7772:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7773:                 $responsenum = $respnumlookup->{$question-1};
 7774:                 if (ref($startline) eq 'HASH') {
 7775:                     $first = $startline->{$question-1} + 1;
 7776:                 }
 7777:             } else {
 7778:                 $first = $first_bubble_line{$responsenum} + 1;
 7779:             }
 7780:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7781:             my $subcount = 1;
 7782:             while ($subcount<$subquestion) {
 7783:                 $first += $subans[$subcount-1];
 7784:                 $subcount ++;
 7785:             }
 7786:             $count = $subans[$subquestion-1];
 7787:         } else {
 7788:             my $responsenum = $question-1;
 7789:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7790:                 $responsenum = $respnumlookup->{$question-1};
 7791:                 if (ref($startline) eq 'HASH') {
 7792:                     $first = $startline->{$question-1} + 1;
 7793:                 }
 7794:             } else {
 7795:                 $first = $first_bubble_line{$responsenum} + 1;
 7796:             }
 7797:             $count   = $bubble_lines_per_response{$responsenum};
 7798:         }
 7799:         $last = $first+$count-1;
 7800:         push(@lines, ($first..$last));
 7801:     }
 7802:     return join(',', @lines);
 7803: }
 7804: 
 7805: =pod 
 7806: 
 7807: =item prompt_for_corrections
 7808: 
 7809: Prompts for a potentially multiline correction to the
 7810: user's bubbling (factors out common code from scantron_get_correction
 7811: for multi and missing bubble cases).
 7812: 
 7813:  Arguments:
 7814:    $r           - Apache request object.
 7815:    $question    - The question number to prompt for.
 7816:    $scan_config - The scantron file configuration hash.
 7817:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7818:    $error       - Type of error
 7819:    $randomorder - True if randomorder in use.
 7820:    $randompick  - True if randompick in use.
 7821:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7822:                     for current line to question number used for same question
 7823:                     in "Master Seqence" (as seen by Course Coordinator).
 7824:    $startline   - Reference to hash where key is question number (0 is first)
 7825:                   and value is number of first bubble line for current student
 7826:                   or code-based randompick and/or randomorder.
 7827: 
 7828:  Implicit inputs:
 7829:    %bubble_lines_per_response   - Starting line numbers for each question.
 7830:                                   Numbered from 0 (but question numbers are from
 7831:                                   1.
 7832:    %first_bubble_line           - Starting bubble line for each question.
 7833:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7834:                                   type problems render as separate sub-questions, 
 7835:                                   in exam mode. This hash contains a 
 7836:                                   comma-separated list of the lines per 
 7837:                                   sub-question.
 7838:    %responsetype_per_response   - essayresponse, formularesponse,
 7839:                                   stringresponse, imageresponse, reactionresponse,
 7840:                                   and organicresponse type problem parts can have
 7841:                                   multiple lines per response if the weight
 7842:                                   assigned exceeds 10.  In this case, only
 7843:                                   one bubble per line is permitted, but more 
 7844:                                   than one line might contain bubbles, e.g.
 7845:                                   bubbling of: line 1 - J, line 2 - J, 
 7846:                                   line 3 - B would assign 22 points.  
 7847: 
 7848: =cut
 7849: 
 7850: sub prompt_for_corrections {
 7851:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7852:         $randompick, $respnumlookup, $startline) = @_;
 7853:     my ($current_line,$lines);
 7854:     my @linenums;
 7855:     my $questionnum = $question;
 7856:     my ($first,$responsenum);
 7857:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7858:         $question = $1;
 7859:         my $subquestion = $2;
 7860:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7861:             $responsenum = $respnumlookup->{$question-1};
 7862:             if (ref($startline) eq 'HASH') {
 7863:                 $first = $startline->{$question-1};
 7864:             }
 7865:         } else {
 7866:             $responsenum = $question-1;
 7867:             $first = $first_bubble_line{$responsenum};
 7868:         }
 7869:         $current_line = $first + 1 ;
 7870:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7871:         my $subcount = 1;
 7872:         while ($subcount<$subquestion) {
 7873:             $current_line += $subans[$subcount-1];
 7874:             $subcount ++;
 7875:         }
 7876:         $lines = $subans[$subquestion-1];
 7877:     } else {
 7878:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7879:             $responsenum = $respnumlookup->{$question-1};
 7880:             if (ref($startline) eq 'HASH') {
 7881:                 $first = $startline->{$question-1};
 7882:             }
 7883:         } else {
 7884:             $responsenum = $question-1;
 7885:             $first = $first_bubble_line{$responsenum};
 7886:         }
 7887:         $current_line = $first + 1;
 7888:         $lines        = $bubble_lines_per_response{$responsenum};
 7889:     }
 7890:     if ($lines > 1) {
 7891:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7892:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7893:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7894:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7895:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7896:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7897:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7898:             $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 />');
 7899:         } else {
 7900:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7901:         }
 7902:     }
 7903:     for (my $i =0; $i < $lines; $i++) {
 7904:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7905: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7906: 	        		  $questionnum,$error,split('', $selected));
 7907:         push(@linenums,$current_line);
 7908: 	$current_line++;
 7909:     }
 7910:     if ($lines > 1) {
 7911: 	$r->print("<hr /><br />");
 7912:     }
 7913:     return @linenums;
 7914: }
 7915: 
 7916: =pod
 7917: 
 7918: =item scantron_bubble_selector
 7919:   
 7920:    Generates the html radiobuttons to correct a single bubble line
 7921:    possibly showing the existing the selected bubbles if known
 7922: 
 7923:  Arguments:
 7924:     $r           - Apache request object
 7925:     $scan_config - hash from &get_scantron_config()
 7926:     $line        - Number of the line being displayed.
 7927:     $questionnum - Question number (may include subquestion)
 7928:     $error       - Type of error.
 7929:     @selected    - Array of bubbles picked on this line.
 7930: 
 7931: =cut
 7932: 
 7933: sub scantron_bubble_selector {
 7934:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7935:     my $max=$$scan_config{'Qlength'};
 7936: 
 7937:     my $scmode=$$scan_config{'Qon'};
 7938:     if ($scmode eq 'number' || $scmode eq 'letter') {
 7939:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7940:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7941:             $max=$$scan_config{'BubblesPerRow'};
 7942:             if (($scmode eq 'number') && ($max > 10)) {
 7943:                 $max = 10;
 7944:             } elsif (($scmode eq 'letter') && $max > 26) {
 7945:                 $max = 26;
 7946:             }
 7947:         } else {
 7948:             $max = 10;
 7949:         }
 7950:     }
 7951: 
 7952:     my @alphabet=('A'..'Z');
 7953:     $r->print(&Apache::loncommon::start_data_table().
 7954:               &Apache::loncommon::start_data_table_row());
 7955:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7956:     for (my $i=0;$i<$max+1;$i++) {
 7957: 	$r->print("\n".'<td align="center">');
 7958: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7959: 	else { $r->print('&nbsp;'); }
 7960: 	$r->print('</td>');
 7961:     }
 7962:     $r->print(&Apache::loncommon::end_data_table_row().
 7963:               &Apache::loncommon::start_data_table_row());
 7964:     for (my $i=0;$i<$max;$i++) {
 7965: 	$r->print("\n".
 7966: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7967: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7968:     }
 7969:     my $nobub_checked = ' ';
 7970:     if ($error eq 'missingbubble') {
 7971:         $nobub_checked = ' checked = "checked" ';
 7972:     }
 7973:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7974: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7975:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7976:               $line.'" value="'.$questionnum.'" /></td>');
 7977:     $r->print(&Apache::loncommon::end_data_table_row().
 7978:               &Apache::loncommon::end_data_table());
 7979: }
 7980: 
 7981: =pod
 7982: 
 7983: =item num_matches
 7984: 
 7985:    Counts the number of characters that are the same between the two arguments.
 7986: 
 7987:  Arguments:
 7988:    $orig - CODE from the scanline
 7989:    $code - CODE to match against
 7990: 
 7991:  Returns:
 7992:    $count - integer count of the number of same characters between the
 7993:             two arguments
 7994: 
 7995: =cut
 7996: 
 7997: sub num_matches {
 7998:     my ($orig,$code) = @_;
 7999:     my @code=split(//,$code);
 8000:     my @orig=split(//,$orig);
 8001:     my $same=0;
 8002:     for (my $i=0;$i<scalar(@code);$i++) {
 8003: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8004:     }
 8005:     return $same;
 8006: }
 8007: 
 8008: =pod
 8009: 
 8010: =item scantron_get_closely_matching_CODEs
 8011: 
 8012:    Cycles through all CODEs and finds the set that has the greatest
 8013:    number of same characters as the provided CODE
 8014: 
 8015:  Arguments:
 8016:    $allcodes - hash ref returned by &get_codes()
 8017:    $CODE     - CODE from the current scanline
 8018: 
 8019:  Returns:
 8020:    2 element list
 8021:     - first elements is number of how closely matching the best fit is 
 8022:       (5 means best set has 5 matching characters)
 8023:     - second element is an arrary ref containing the set of valid CODEs
 8024:       that best fit the passed in CODE
 8025: 
 8026: =cut
 8027: 
 8028: sub scantron_get_closely_matching_CODEs {
 8029:     my ($allcodes,$CODE)=@_;
 8030:     my @CODEs;
 8031:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8032: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8033:     }
 8034: 
 8035:     return ($#CODEs,$CODEs[-1]);
 8036: }
 8037: 
 8038: =pod
 8039: 
 8040: =item get_codes
 8041: 
 8042:    Builds a hash which has keys of all of the valid CODEs from the selected
 8043:    set of remembered CODEs.
 8044: 
 8045:  Arguments:
 8046:   $old_name - name of the set of remembered CODEs
 8047:   $cdom     - domain of the course
 8048:   $cnum     - internal course name
 8049: 
 8050:  Returns:
 8051:   %allcodes - keys are the valid CODEs, values are all 1
 8052: 
 8053: =cut
 8054: 
 8055: sub get_codes {
 8056:     my ($old_name, $cdom, $cnum) = @_;
 8057:     if (!$old_name) {
 8058: 	$old_name=$env{'form.scantron_CODElist'};
 8059:     }
 8060:     if (!$cdom) {
 8061: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8062:     }
 8063:     if (!$cnum) {
 8064: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8065:     }
 8066:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8067: 				    $cdom,$cnum);
 8068:     my %allcodes;
 8069:     if ($result{"type\0$old_name"} eq 'number') {
 8070: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8071:     } else {
 8072: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8073:     }
 8074:     return %allcodes;
 8075: }
 8076: 
 8077: =pod
 8078: 
 8079: =item scantron_validate_CODE
 8080: 
 8081:    Validates all scanlines in the selected file to not have any
 8082:    invalid or underspecified CODEs and that none of the codes are
 8083:    duplicated if this was requested.
 8084: 
 8085: =cut
 8086: 
 8087: sub scantron_validate_CODE {
 8088:     my ($r,$currentphase) = @_;
 8089:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8090:     if ($scantron_config{'CODElocation'} &&
 8091: 	$scantron_config{'CODEstart'} &&
 8092: 	$scantron_config{'CODElength'}) {
 8093: 	if (!defined($env{'form.scantron_CODElist'})) {
 8094: 	    &FIXME_blow_up()
 8095: 	}
 8096:     } else {
 8097: 	return (0,$currentphase+1);
 8098:     }
 8099:     
 8100:     my %usedCODEs;
 8101: 
 8102:     my %allcodes=&get_codes();
 8103: 
 8104:     my $nav_error;
 8105:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8106:     if ($nav_error) {
 8107:         $r->print(&navmap_errormsg());
 8108:         return(1,$currentphase);
 8109:     }
 8110: 
 8111:     my ($scanlines,$scan_data)=&scantron_getfile();
 8112:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8113: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8114: 	if ($line=~/^[\s\cz]*$/) { next; }
 8115: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8116: 						 $scan_data);
 8117: 	my $CODE=$$scan_record{'scantron.CODE'};
 8118: 	my $error=0;
 8119: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8120: 	    &scantron_get_correction($r,$i,$scan_record,
 8121: 				     \%scantron_config,
 8122: 				     $line,'incorrectCODE',\%allcodes);
 8123: 	    return(1,$currentphase);
 8124: 	}
 8125: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8126: 	    && !$$scan_record{'scantron.useCODE'}) {
 8127: 	    &scantron_get_correction($r,$i,$scan_record,
 8128: 				     \%scantron_config,
 8129: 				     $line,'incorrectCODE',\%allcodes);
 8130: 	    return(1,$currentphase);
 8131: 	}
 8132: 	if (exists($usedCODEs{$CODE}) 
 8133: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8134: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8135: 	    &scantron_get_correction($r,$i,$scan_record,
 8136: 				     \%scantron_config,
 8137: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8138: 	    return(1,$currentphase);
 8139: 	}
 8140: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8141:     }
 8142:     return (0,$currentphase+1);
 8143: }
 8144: 
 8145: =pod
 8146: 
 8147: =item scantron_validate_doublebubble
 8148: 
 8149:    Validates all scanlines in the selected file to not have any
 8150:    bubble lines with multiple bubbles marked.
 8151: 
 8152: =cut
 8153: 
 8154: sub scantron_validate_doublebubble {
 8155:     my ($r,$currentphase) = @_;
 8156:     #get student info
 8157:     my $classlist=&Apache::loncoursedata::get_classlist();
 8158:     my %idmap=&username_to_idmap($classlist);
 8159:     my (undef,undef,$sequence)=
 8160:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8161: 
 8162:     #get scantron line setup
 8163:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8164:     my ($scanlines,$scan_data)=&scantron_getfile();
 8165: 
 8166:     my $navmap = Apache::lonnavmaps::navmap->new();
 8167:     unless (ref($navmap)) {
 8168:         $r->print(&navmap_errormsg());
 8169:         return(1,$currentphase);
 8170:     }
 8171:     my $map=$navmap->getResourceByUrl($sequence);
 8172:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8173:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8174:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8175:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8176: 
 8177:     my $nav_error;
 8178:     if (ref($map)) {
 8179:         $randomorder = $map->randomorder();
 8180:         $randompick = $map->randompick();
 8181:         if ($randomorder || $randompick) {
 8182:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8183:             if ($nav_error) {
 8184:                 $r->print(&navmap_errormsg());
 8185:                 return(1,$currentphase);
 8186:             }
 8187:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8188:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8189:         }
 8190:     } else {
 8191:         $r->print(&navmap_errormsg());
 8192:         return(1,$currentphase);
 8193:     }
 8194: 
 8195:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8196:     if ($nav_error) {
 8197:         $r->print(&navmap_errormsg());
 8198:         return(1,$currentphase);
 8199:     }
 8200: 
 8201:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8202: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8203: 	if ($line=~/^[\s\cz]*$/) { next; }
 8204: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8205: 						 $scan_data,undef,\%idmap,$randomorder,
 8206:                                                  $randompick,$sequence,\@master_seq,
 8207:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8208:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8209: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8210: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8211: 				 'doublebubble',
 8212: 				 $$scan_record{'scantron.doubleerror'},
 8213:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8214:     	return (1,$currentphase);
 8215:     }
 8216:     return (0,$currentphase+1);
 8217: }
 8218: 
 8219: 
 8220: sub scantron_get_maxbubble {
 8221:     my ($nav_error,$scantron_config) = @_;
 8222:     if (defined($env{'form.scantron_maxbubble'}) &&
 8223: 	$env{'form.scantron_maxbubble'}) {
 8224: 	&restore_bubble_lines();
 8225: 	return $env{'form.scantron_maxbubble'};
 8226:     }
 8227: 
 8228:     my (undef, undef, $sequence) =
 8229: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8230: 
 8231:     my $navmap=Apache::lonnavmaps::navmap->new();
 8232:     unless (ref($navmap)) {
 8233:         if (ref($nav_error)) {
 8234:             $$nav_error = 1;
 8235:         }
 8236:         return;
 8237:     }
 8238:     my $map=$navmap->getResourceByUrl($sequence);
 8239:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8240:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8241: 
 8242:     &Apache::lonxml::clear_problem_counter();
 8243: 
 8244:     my $uname       = $env{'user.name'};
 8245:     my $udom        = $env{'user.domain'};
 8246:     my $cid         = $env{'request.course.id'};
 8247:     my $total_lines = 0;
 8248:     %bubble_lines_per_response = ();
 8249:     %first_bubble_line         = ();
 8250:     %subdivided_bubble_lines   = ();
 8251:     %responsetype_per_response = ();
 8252:     %masterseq_id_responsenum  = ();
 8253: 
 8254:     my $response_number = 0;
 8255:     my $bubble_line     = 0;
 8256:     foreach my $resource (@resources) {
 8257:         my $resid = $resource->id();
 8258:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8259:                                                           $udom,undef,$bubbles_per_row);
 8260:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8261: 	    foreach my $part_id (@{$parts}) {
 8262:                 my $lines;
 8263: 
 8264: 	        # TODO - make this a persistent hash not an array.
 8265: 
 8266:                 # optionresponse, matchresponse and rankresponse type items 
 8267:                 # render as separate sub-questions in exam mode.
 8268:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8269:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8270:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8271:                     my ($numbub,$numshown);
 8272:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8273:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8274:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8275:                         }
 8276:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8277:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8278:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8279:                         }
 8280:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8281:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8282:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8283:                         }
 8284:                     }
 8285:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8286:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8287:                     }
 8288:                     my $bubbles_per_row =
 8289:                         &bubblesheet_bubbles_per_row($scantron_config);
 8290:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8291:                     if (($numbub % $bubbles_per_row) != 0) {
 8292:                         $inner_bubble_lines++;
 8293:                     }
 8294:                     for (my $i=0; $i<$numshown; $i++) {
 8295:                         $subdivided_bubble_lines{$response_number} .= 
 8296:                             $inner_bubble_lines.',';
 8297:                     }
 8298:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8299:                     $lines = $numshown * $inner_bubble_lines;
 8300:                 } else {
 8301:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8302:                 }
 8303: 
 8304:                 $first_bubble_line{$response_number} = $bubble_line;
 8305: 	        $bubble_lines_per_response{$response_number} = $lines;
 8306:                 $responsetype_per_response{$response_number} = 
 8307:                     $analysis->{$part_id.'.type'};
 8308:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8309: 	        $response_number++;
 8310: 
 8311: 	        $bubble_line +=  $lines;
 8312: 	        $total_lines +=  $lines;
 8313: 	    }
 8314:         }
 8315:     }
 8316:     &Apache::lonnet::delenv('scantron.');
 8317: 
 8318:     &save_bubble_lines();
 8319:     $env{'form.scantron_maxbubble'} =
 8320: 	$total_lines;
 8321:     return $env{'form.scantron_maxbubble'};
 8322: }
 8323: 
 8324: sub bubblesheet_bubbles_per_row {
 8325:     my ($scantron_config) = @_;
 8326:     my $bubbles_per_row;
 8327:     if (ref($scantron_config) eq 'HASH') {
 8328:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8329:     }
 8330:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8331:         $bubbles_per_row = 10;
 8332:     }
 8333:     return $bubbles_per_row;
 8334: }
 8335: 
 8336: sub scantron_validate_missingbubbles {
 8337:     my ($r,$currentphase) = @_;
 8338:     #get student info
 8339:     my $classlist=&Apache::loncoursedata::get_classlist();
 8340:     my %idmap=&username_to_idmap($classlist);
 8341:     my (undef,undef,$sequence)=
 8342:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8343: 
 8344:     #get scantron line setup
 8345:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8346:     my ($scanlines,$scan_data)=&scantron_getfile();
 8347: 
 8348:     my $navmap = Apache::lonnavmaps::navmap->new();
 8349:     unless (ref($navmap)) {
 8350:         $r->print(&navmap_errormsg());
 8351:         return(1,$currentphase);
 8352:     }
 8353: 
 8354:     my $map=$navmap->getResourceByUrl($sequence);
 8355:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8356:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8357:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8358:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8359: 
 8360:     my $nav_error;
 8361:     if (ref($map)) {
 8362:         $randomorder = $map->randomorder();
 8363:         $randompick = $map->randompick();
 8364:         if ($randomorder || $randompick) {
 8365:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8366:             if ($nav_error) {
 8367:                 $r->print(&navmap_errormsg());
 8368:                 return(1,$currentphase);
 8369:             }
 8370:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8371:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8372:         }
 8373:     } else {
 8374:         $r->print(&navmap_errormsg());
 8375:         return(1,$currentphase);
 8376:     }
 8377: 
 8378: 
 8379:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8380:     if ($nav_error) {
 8381:         $r->print(&navmap_errormsg());
 8382:         return(1,$currentphase);
 8383:     }
 8384: 
 8385:     if (!$max_bubble) { $max_bubble=2**31; }
 8386:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8387: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8388: 	if ($line=~/^[\s\cz]*$/) { next; }
 8389:         my $scan_record =
 8390:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8391:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8392:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8393:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8394: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8395: 	my @to_correct;
 8396: 	
 8397: 	# Probably here's where the error is...
 8398: 
 8399: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8400:             my $lastbubble;
 8401:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8402:                 my $question = $1;
 8403:                 my $subquestion = $2;
 8404:                 my ($first,$responsenum);
 8405:                 if ($randomorder || $randompick) {
 8406:                     $responsenum = $respnumlookup{$question-1};
 8407:                     $first = $startline{$question-1};
 8408:                 } else {
 8409:                     $responsenum = $question-1;
 8410:                     $first = $first_bubble_line{$responsenum};
 8411:                 }
 8412:                 if (!defined($first)) { next; }
 8413:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8414:                 my $subcount = 1;
 8415:                 while ($subcount<$subquestion) {
 8416:                     $first += $subans[$subcount-1];
 8417:                     $subcount ++;
 8418:                 }
 8419:                 my $count = $subans[$subquestion-1];
 8420:                 $lastbubble = $first + $count;
 8421:             } else {
 8422:                 my ($first,$responsenum);
 8423:                 if ($randomorder || $randompick) {
 8424:                     $responsenum = $respnumlookup{$missing-1};
 8425:                     $first = $startline{$missing-1};
 8426:                 } else {
 8427:                     $responsenum = $missing-1;
 8428:                     $first = $first_bubble_line{$responsenum};
 8429:                 }
 8430:                 if (!defined($first)) { next; }
 8431:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8432:             }
 8433:             if ($lastbubble > $max_bubble) { next; }
 8434: 	    push(@to_correct,$missing);
 8435: 	}
 8436: 	if (@to_correct) {
 8437: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8438: 				     $line,'missingbubble',\@to_correct,
 8439:                                      $randomorder,$randompick,\%respnumlookup,
 8440:                                      \%startline);
 8441: 	    return (1,$currentphase);
 8442: 	}
 8443: 
 8444:     }
 8445:     return (0,$currentphase+1);
 8446: }
 8447: 
 8448: sub hand_bubble_option {
 8449:     my (undef, undef, $sequence) =
 8450:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8451:     return if ($sequence eq '');
 8452:     my $navmap = Apache::lonnavmaps::navmap->new();
 8453:     unless (ref($navmap)) {
 8454:         return;
 8455:     }
 8456:     my $needs_hand_bubbles;
 8457:     my $map=$navmap->getResourceByUrl($sequence);
 8458:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8459:     foreach my $res (@resources) {
 8460:         if (ref($res)) {
 8461:             if ($res->is_problem()) {
 8462:                 my $partlist = $res->parts();
 8463:                 foreach my $part (@{ $partlist }) {
 8464:                     my @types = $res->responseType($part);
 8465:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8466:                         $needs_hand_bubbles = 1;
 8467:                         last;
 8468:                     }
 8469:                 }
 8470:             }
 8471:         }
 8472:     }
 8473:     if ($needs_hand_bubbles) {
 8474:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8475:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8476:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8477:                &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 />').
 8478:                '<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;'.
 8479:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8480:     }
 8481:     return;
 8482: }
 8483: 
 8484: sub scantron_process_students {
 8485:     my ($r) = @_;
 8486: 
 8487:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8488:     my ($symb)=&get_symb($r);
 8489:     if (!$symb) {
 8490: 	return '';
 8491:     }
 8492:     my $default_form_data=&defaultFormData($symb);
 8493: 
 8494:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8495:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8496:     my ($scanlines,$scan_data)=&scantron_getfile();
 8497:     my $classlist=&Apache::loncoursedata::get_classlist();
 8498:     my %idmap=&username_to_idmap($classlist);
 8499:     my $navmap=Apache::lonnavmaps::navmap->new();
 8500:     unless (ref($navmap)) {
 8501:         $r->print(&navmap_errormsg());
 8502:         return '';
 8503:     }
 8504:     my $map=$navmap->getResourceByUrl($sequence);
 8505:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8506:         %grader_randomlists_by_symb);
 8507:     if (ref($map)) {
 8508:         $randomorder = $map->randomorder();
 8509:         $randompick = $map->randompick();
 8510:     } else {
 8511:         $r->print(&navmap_errormsg());
 8512:         return '';
 8513:     }
 8514:     my $nav_error;
 8515:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8516:     if ($randomorder || $randompick) {
 8517:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8518:         if ($nav_error) {
 8519:             $r->print(&navmap_errormsg());
 8520:             return '';
 8521:         }
 8522:     }
 8523:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8524:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8525: 
 8526:     my ($uname,$udom);
 8527:     my $result= <<SCANTRONFORM;
 8528: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8529:   <input type="hidden" name="command" value="scantron_configphase" />
 8530:   $default_form_data
 8531: SCANTRONFORM
 8532:     $r->print($result);
 8533: 
 8534:     my @delayqueue;
 8535:     my (%completedstudents,%scandata);
 8536:     
 8537:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8538:     my $count=&get_todo_count($scanlines,$scan_data);
 8539:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8540:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8541: 					  'Processing first student');
 8542:     $r->print('<br />');
 8543:     my $start=&Time::HiRes::time();
 8544:     my $i=-1;
 8545:     my $started;
 8546: 
 8547:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8548:     if ($nav_error) {
 8549:         $r->print(&navmap_errormsg());
 8550:         return '';
 8551:     }
 8552: 
 8553:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8554:     # the user and return.
 8555: 
 8556:     if ($ssi_error) {
 8557: 	$r->print("</form>");
 8558: 	&ssi_print_error($r);
 8559: 	$r->print(&show_grading_menu_form($symb));
 8560:         &Apache::lonnet::remove_lock($lock);
 8561: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8562:     }
 8563: 
 8564:     my %lettdig = &letter_to_digits();
 8565:     my $numletts = scalar(keys(%lettdig));
 8566:     my %orderedforcode;
 8567: 
 8568:     while ($i<$scanlines->{'count'}) {
 8569:  	($uname,$udom)=('','');
 8570:  	$i++;
 8571:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8572:  	if ($line=~/^[\s\cz]*$/) { next; }
 8573: 	if ($started) {
 8574: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8575: 						     'last student');
 8576: 	}
 8577: 	$started=1;
 8578:         my %respnumlookup = ();
 8579:         my %startline = ();
 8580:         my $total;
 8581:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8582:  						 $scan_data,undef,\%idmap,$randomorder,
 8583:                                                  $randompick,$sequence,\@master_seq,
 8584:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8585:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8586:                                                  \$total);
 8587:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8588:  					      \%idmap,$i)) {
 8589:   	    &scantron_add_delay(\@delayqueue,$line,
 8590:  				'Unable to find a student that matches',1);
 8591:  	    next;
 8592:   	}
 8593:  	if (exists $completedstudents{$uname}) {
 8594:  	    &scantron_add_delay(\@delayqueue,$line,
 8595:  				'Student '.$uname.' has multiple sheets',2);
 8596:  	    next;
 8597:  	}
 8598:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8599:         my $user = $uname.':'.$usec;
 8600:   	($uname,$udom)=split(/:/,$uname);
 8601: 
 8602:         my $scancode;
 8603:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8604:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8605:             $scancode = $scan_record->{'scantron.CODE'};
 8606:         } else {
 8607:             $scancode = '';
 8608:         }
 8609: 
 8610:         my @mapresources = @resources;
 8611:         if ($randomorder || $randompick) {
 8612:             @mapresources =
 8613:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8614:                              \%orderedforcode);
 8615:         }
 8616:         my (%partids_by_symb,$res_error);
 8617:         foreach my $resource (@mapresources) {
 8618:             my $ressymb;
 8619:             if (ref($resource)) {
 8620:                 $ressymb = $resource->symb();
 8621:             } else {
 8622:                 $res_error = 1;
 8623:                 last;
 8624:             }
 8625:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8626:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8627:                 my ($analysis,$parts) =
 8628:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8629:                                               $uname,$udom,undef,$bubbles_per_row);
 8630:                 $partids_by_symb{$ressymb} = $parts;
 8631:             } else {
 8632:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8633:             }
 8634:         }
 8635: 
 8636:         if ($res_error) {
 8637:             &scantron_add_delay(\@delayqueue,$line,
 8638:                                 'An error occurred while grading student '.$uname,2);
 8639:             next;
 8640:         }
 8641: 
 8642: 	&Apache::lonxml::clear_problem_counter();
 8643:   	&Apache::lonnet::appenv($scan_record);
 8644: 
 8645: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8646: 	    &scantron_putfile($scanlines,$scan_data);
 8647: 	}
 8648: 	
 8649:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8650:                                    \@mapresources,\%partids_by_symb,
 8651:                                    $bubbles_per_row,$randomorder,$randompick,
 8652:                                    \%respnumlookup,\%startline) 
 8653:             eq 'ssi_error') {
 8654:             $ssi_error = 0; # So end of handler error message does not trigger.
 8655:             $r->print("</form>");
 8656:             &ssi_print_error($r);
 8657:             $r->print(&show_grading_menu_form($symb));
 8658:             &Apache::lonnet::remove_lock($lock);
 8659:             return '';      # Why return ''?  Beats me.
 8660:         }
 8661: 
 8662:         if (($scancode) && ($randomorder || $randompick)) {
 8663:             my $parmresult =
 8664:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8665:                                                        '0_examcode',2,$scancode,
 8666:                                                        'string_examcode',$uname,
 8667:                                                        $udom);
 8668:         }
 8669: 	$completedstudents{$uname}={'line'=>$line};
 8670:         if ($env{'form.verifyrecord'}) {
 8671:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8672:             if ($randompick) {
 8673:                 if ($total) {
 8674:                     $lastpos = $total*$scantron_config{'Qlength'};
 8675:                 }
 8676:             }
 8677: 
 8678:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8679:             chomp($studentdata);
 8680:             $studentdata =~ s/\r$//;
 8681:             my $studentrecord = '';
 8682:             my $counter = -1;
 8683:             foreach my $resource (@mapresources) {
 8684:                 my $ressymb = $resource->symb();
 8685:                 ($counter,my $recording) =
 8686:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8687:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8688:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8689:                                              $randompick,\%respnumlookup,\%startline);
 8690:                 $studentrecord .= $recording;
 8691:             }
 8692:             if ($studentrecord ne $studentdata) {
 8693:                 &Apache::lonxml::clear_problem_counter();
 8694:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8695:                                            \@mapresources,\%partids_by_symb,
 8696:                                            $bubbles_per_row,$randomorder,$randompick,
 8697:                                            \%respnumlookup,\%startline)
 8698:                     eq 'ssi_error') {
 8699:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8700:                     $r->print("</form>");
 8701:                     &ssi_print_error($r);
 8702:                     $r->print(&show_grading_menu_form($symb));
 8703:                     &Apache::lonnet::remove_lock($lock);
 8704:                     delete($completedstudents{$uname});
 8705:                     return '';
 8706:                 }
 8707:                 $counter = -1;
 8708:                 $studentrecord = '';
 8709:                 foreach my $resource (@mapresources) {
 8710:                     my $ressymb = $resource->symb();
 8711:                     ($counter,my $recording) =
 8712:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8713:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8714:                                                  \%scantron_config,\%lettdig,$numletts,
 8715:                                                  $randomorder,$randompick,\%respnumlookup,
 8716:                                                  \%startline);
 8717:                     $studentrecord .= $recording;
 8718:                 }
 8719:                 if ($studentrecord ne $studentdata) {
 8720:                     $r->print('<p><span class="LC_warning">');
 8721:                     if ($scancode eq '') {
 8722:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8723:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8724:                     } else {
 8725:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8726:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8727:                     }
 8728:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8729:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8730:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8731:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8732:                               &Apache::loncommon::start_data_table_row().
 8733:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8734:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8735:                               &Apache::loncommon::end_data_table_row().
 8736:                               &Apache::loncommon::start_data_table_row().
 8737:                               '<td>'.&mt('Stored submissions').'</td>'.
 8738:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8739:                               &Apache::loncommon::end_data_table_row().
 8740:                               &Apache::loncommon::end_data_table().'</p>');
 8741:                 } else {
 8742:                     $r->print('<br /><span class="LC_warning">'.
 8743:                              &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 />'.
 8744:                              &mt("As a consequence, this user's submission history records two tries.").
 8745:                                  '</span><br />');
 8746:                 }
 8747:             }
 8748:         }
 8749:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8750:     } continue {
 8751: 	&Apache::lonxml::clear_problem_counter();
 8752: 	&Apache::lonnet::delenv('scantron.');
 8753:     }
 8754:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8755:     &Apache::lonnet::remove_lock($lock);
 8756: #    my $lasttime = &Time::HiRes::time()-$start;
 8757: #    $r->print("<p>took $lasttime</p>");
 8758: 
 8759:     $r->print("</form>");
 8760:     $r->print(&show_grading_menu_form($symb));
 8761:     return '';
 8762: }
 8763: 
 8764: sub graders_resources_pass {
 8765:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8766:         $bubbles_per_row) = @_;
 8767:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8768:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8769:         foreach my $resource (@{$resources}) {
 8770:             my $ressymb = $resource->symb();
 8771:             my ($analysis,$parts) =
 8772:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8773:                                           $env{'user.name'},$env{'user.domain'},
 8774:                                           1,$bubbles_per_row);
 8775:             $grader_partids_by_symb->{$ressymb} = $parts;
 8776:             if (ref($analysis) eq 'HASH') {
 8777:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8778:                     $grader_randomlists_by_symb->{$ressymb} =
 8779:                         $analysis->{'parts_withrandomlist'};
 8780:                 }
 8781:             }
 8782:         }
 8783:     }
 8784:     return;
 8785: }
 8786: 
 8787: =pod
 8788: 
 8789: =item users_order
 8790: 
 8791:   Returns array of resources in current map, ordered based on either CODE,
 8792:   if this is a CODEd exam, or based on student's identity if this is a
 8793:   "NAMEd" exam.
 8794: 
 8795:   Should be used when randomorder and/or randompick applied when the 
 8796:   corresponding exam was printed, prior to students completing bubblesheets 
 8797:   for the version of the exam the student received.
 8798: 
 8799: =cut
 8800: 
 8801: sub users_order  {
 8802:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8803:     my @mapresources;
 8804:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8805:         return @mapresources;
 8806:     }
 8807:     if ($scancode) {
 8808:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8809:             @mapresources = @{$orderedforcode->{$scancode}};
 8810:         } else {
 8811:             $env{'form.CODE'} = $scancode;
 8812:             my $actual_seq =
 8813:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8814:                                                                $master_seq,
 8815:                                                                $user,$scancode,1);
 8816:             if (ref($actual_seq) eq 'ARRAY') {
 8817:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8818:                 if (ref($orderedforcode) eq 'HASH') {
 8819:                     if (@mapresources > 0) {
 8820:                         $orderedforcode->{$scancode} = \@mapresources;
 8821:                     }
 8822:                 }
 8823:             }
 8824:             delete($env{'form.CODE'});
 8825:         }
 8826:     } else {
 8827:         my $actual_seq =
 8828:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8829:                                                            $master_seq,
 8830:                                                            $user,undef,1);
 8831:         if (ref($actual_seq) eq 'ARRAY') {
 8832:             @mapresources =
 8833:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8834:         }
 8835:     }
 8836:     return @mapresources;
 8837: }
 8838: 
 8839: sub grade_student_bubbles {
 8840:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8841:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8842:     my $uselookup = 0;
 8843:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8844:         (ref($startline) eq 'HASH')) {
 8845:         $uselookup = 1;
 8846:     }
 8847: 
 8848:     if (ref($resources) eq 'ARRAY') {
 8849:         my $count = 0;
 8850:         foreach my $resource (@{$resources}) {
 8851:             my $ressymb = $resource->symb();
 8852:             my %form = ('submitted'      => 'scantron',
 8853:                         'grade_target'   => 'grade',
 8854:                         'grade_username' => $uname,
 8855:                         'grade_domain'   => $udom,
 8856:                         'grade_courseid' => $env{'request.course.id'},
 8857:                         'grade_symb'     => $ressymb,
 8858:                         'CODE'           => $scancode
 8859:                        );
 8860:             if ($bubbles_per_row ne '') {
 8861:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8862:             }
 8863:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8864:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8865:             }
 8866:             if (ref($parts) eq 'HASH') {
 8867:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8868:                     foreach my $part (@{$parts->{$ressymb}}) {
 8869:                         if ($uselookup) {
 8870:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8871:                         } else {
 8872:                             $form{'scantron_questnum_start.'.$part} =
 8873:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8874:                         }
 8875:                         $count++;
 8876:                     }
 8877:                 }
 8878:             }
 8879:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8880:             return 'ssi_error' if ($ssi_error);
 8881:             last if (&Apache::loncommon::connection_aborted($r));
 8882:         }
 8883:     }
 8884:     return;
 8885: }
 8886: 
 8887: sub scantron_upload_scantron_data {
 8888:     my ($r)=@_;
 8889:     my $dom = $env{'request.role.domain'};
 8890:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8891:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8892:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8893: 							  'domainid',
 8894: 							  'coursename',$dom);
 8895:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8896:                        ('&nbsp'x2).&mt('(shows course personnel)');
 8897:     my ($symb) = &get_symb($r,1);
 8898:     my $default_form_data=&defaultFormData($symb);
 8899:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8900:     &js_escape(\$nofile_alert); 
 8901:     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.");
 8902:     &js_escape(\$nocourseid_alert);
 8903:     $r->print('
 8904: <script type="text/javascript" language="javascript">
 8905:     function checkUpload(formname) {
 8906: 	if (formname.upfile.value == "") {
 8907: 	    alert("'.$nofile_alert.'");
 8908: 	    return false;
 8909: 	}
 8910:         if (formname.courseid.value == "") {
 8911:             alert("'.$nocourseid_alert.'");
 8912:             return false;
 8913:         }
 8914: 	formname.submit();
 8915:     }
 8916: 
 8917:     function ToSyllabus() {
 8918:         var cdom = '."'$dom'".';
 8919:         var cnum = document.rules.courseid.value;
 8920:         if (cdom == "" || cdom == null) {
 8921:             return;
 8922:         }
 8923:         if (cnum == "" || cnum == null) {
 8924:            return;
 8925:         }
 8926:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8927:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8928:         return;
 8929:     }
 8930: 
 8931: </script>
 8932: 
 8933: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8934: 
 8935: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8936: '.$default_form_data.
 8937:   &Apache::lonhtmlcommon::start_pick_box().
 8938:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8939:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8940:   &Apache::lonhtmlcommon::row_closure().
 8941:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8942:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8943:   &Apache::lonhtmlcommon::row_closure().
 8944:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8945:   '<input name="domainid" type="hidden" />'.$domdesc.
 8946:   &Apache::lonhtmlcommon::row_closure().
 8947:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8948:   '<input type="file" name="upfile" size="50" />'.
 8949:   &Apache::lonhtmlcommon::row_closure(1).
 8950:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8951: 
 8952: <input name="command" value="scantronupload_save" type="hidden" />
 8953: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8954: </form>
 8955: ');
 8956:     return '';
 8957: }
 8958: 
 8959: 
 8960: sub scantron_upload_scantron_data_save {
 8961:     my($r)=@_;
 8962:     my ($symb)=&get_symb($r,1);
 8963:     my $doanotherupload=
 8964: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8965: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8966: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8967: 	'</form>'."\n";
 8968:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8969: 	!&Apache::lonnet::allowed('usc',
 8970: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8971: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8972: 	if ($symb) {
 8973: 	    $r->print(&show_grading_menu_form($symb));
 8974: 	} else {
 8975: 	    $r->print($doanotherupload);
 8976: 	}
 8977: 	return '';
 8978:     }
 8979:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8980:     my $uploadedfile;
 8981:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 8982:     if (length($env{'form.upfile'}) < 2) {
 8983:         $r->print(
 8984:             &Apache::lonhtmlcommon::confirm_success(
 8985:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8986:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8987:     } else {
 8988:         my $result = 
 8989:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8990:                                             $env{'form.courseid'},$env{'form.domainid'});
 8991: 	if ($result =~ m{^/uploaded/}) {
 8992:             $r->print(
 8993:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8994:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8995:                         (length($env{'form.upfile'})-1),
 8996:                         '<span class="LC_filename">'.$result.'</span>'));
 8997:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8998:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8999:                                                        $env{'form.courseid'},$uploadedfile));
 9000: 	} else {
 9001:             $r->print(
 9002:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9003:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9004:                           $result,
 9005: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9006: 	}
 9007:     }
 9008:     if ($symb) {
 9009: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 9010:     } else {
 9011: 	$r->print($doanotherupload);
 9012:     }
 9013:     return '';
 9014: }
 9015: 
 9016: sub validate_uploaded_scantron_file {
 9017:     my ($cdom,$cname,$fname) = @_;
 9018:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9019:     my @lines;
 9020:     if ($scanlines ne '-1') {
 9021:         @lines=split("\n",$scanlines,-1);
 9022:     }
 9023:     my $output;
 9024:     if (@lines) {
 9025:         my (%counts,$max_match_format);
 9026:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9027:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9028:         my %idmap = &username_to_idmap($classlist);
 9029:         foreach my $key (keys(%idmap)) {
 9030:             my $lckey = lc($key);
 9031:             $idmap{$lckey} = $idmap{$key};
 9032:         }
 9033:         my %unique_formats;
 9034:         my @formatlines = &get_scantronformat_file();
 9035:         foreach my $line (@formatlines) {
 9036:             chomp($line);
 9037:             my @config = split(/:/,$line);
 9038:             my $idstart = $config[5];
 9039:             my $idlength = $config[6];
 9040:             if (($idstart ne '') && ($idlength > 0)) {
 9041:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9042:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9043:                 } else {
 9044:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9045:                 }
 9046:             }
 9047:         }
 9048:         foreach my $key (keys(%unique_formats)) {
 9049:             my ($idstart,$idlength) = split(':',$key);
 9050:             %{$counts{$key}} = (
 9051:                                'found'   => 0,
 9052:                                'total'   => 0,
 9053:                               );
 9054:             foreach my $line (@lines) {
 9055:                 next if ($line =~ /^#/);
 9056:                 next if ($line =~ /^[\s\cz]*$/);
 9057:                 my $id = substr($line,$idstart-1,$idlength);
 9058:                 $id = lc($id);
 9059:                 if (exists($idmap{$id})) {
 9060:                     $counts{$key}{'found'} ++;
 9061:                 }
 9062:                 $counts{$key}{'total'} ++;
 9063:             }
 9064:             if ($counts{$key}{'total'}) {
 9065:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9066:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9067:                     $max_match_pct = $percent_match;
 9068:                     $max_match_format = $key;
 9069:                     $found_match_count = $counts{$key}{'found'};
 9070:                     $max_match_count = $counts{$key}{'total'};
 9071:                 }
 9072:             }
 9073:         }
 9074:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9075:             my $format_descs;
 9076:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9077:             for (my $i=0; $i<$numwithformat; $i++) {
 9078:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9079:                 if ($i<$numwithformat-2) {
 9080:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9081:                 } elsif ($i==$numwithformat-2) {
 9082:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9083:                 } elsif ($i==$numwithformat-1) {
 9084:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9085:                 }
 9086:             }
 9087:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9088:             $output .= '<br />';
 9089:             if ($found_match_count == $max_match_count) {
 9090:                 # 100% matching entries
 9091:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9092:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9093:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9094:                 &mt('Comparison of student IDs in the uploaded file with'.
 9095:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9096:                     ' in the file (for the format defined for [_3]).',
 9097:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9098:             } else {
 9099:                 # Not all entries matching? -> Show warning and additional info
 9100:                 $output .=
 9101:                     &Apache::lonhtmlcommon::confirm_success(
 9102:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9103:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9104:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9105:                     &mt('Comparison of student IDs in the uploaded file with'.
 9106:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9107:                         ' in the file (for the format defined for [_3]).',
 9108:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9109:                     '<p class="LC_info">'.
 9110:                     &mt('A low percentage of matches results from one of the following:').
 9111:                     '</p><ul>'.
 9112:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9113:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9114:                                '<i>'.$cdom.'</i>').'</li>'.
 9115:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9116:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9117:                     '</ul>';
 9118:             }
 9119:         }
 9120:     } else {
 9121:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9122:     }
 9123:     return $output;
 9124: }
 9125: 
 9126: sub valid_file {
 9127:     my ($requested_file)=@_;
 9128:     foreach my $filename (sort(&scantron_filenames())) {
 9129: 	if ($requested_file eq $filename) { return 1; }
 9130:     }
 9131:     return 0;
 9132: }
 9133: 
 9134: sub scantron_download_scantron_data {
 9135:     my ($r)=@_;
 9136:     my ($symb) = &get_symb($r,1);
 9137:     my $default_form_data=&defaultFormData($symb);
 9138:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9139:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9140:     my $file=$env{'form.scantron_selectfile'};
 9141:     if (! &valid_file($file)) {
 9142: 	$r->print('
 9143: 	<p>
 9144: 	    '.&mt('The requested filename was invalid.').'
 9145:         </p>
 9146: ');
 9147: 	$r->print(&show_grading_menu_form($symb));
 9148: 	return;
 9149:     }
 9150:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9151:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9152:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9153:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9154:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9155:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9156:     $r->print('
 9157:     <p>
 9158: 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
 9159: 	      '<a href="'.$orig.'">','</a>').'
 9160:     </p>
 9161:     <p>
 9162: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9163: 	      '<a href="'.$corrected.'">','</a>').'
 9164:     </p>
 9165:     <p>
 9166: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9167: 	      '<a href="'.$skipped.'">','</a>').'
 9168:     </p>
 9169: ');
 9170:     $r->print(&show_grading_menu_form($symb));
 9171:     return '';
 9172: }
 9173: 
 9174: sub checkscantron_results {
 9175:     my ($r) = @_;
 9176:     my ($symb)=&get_symb($r);
 9177:     if (!$symb) {return '';}
 9178:     my $grading_menu_button=&show_grading_menu_form($symb);
 9179:     my $cid = $env{'request.course.id'};
 9180:     my %lettdig = &letter_to_digits();
 9181:     my $numletts = scalar(keys(%lettdig));
 9182:     my $cnum = $env{'course.'.$cid.'.num'};
 9183:     my $cdom = $env{'course.'.$cid.'.domain'};
 9184:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9185:     my %record;
 9186:     my %scantron_config =
 9187:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9188:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9189:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9190:     my $classlist=&Apache::loncoursedata::get_classlist();
 9191:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9192:     my $navmap=Apache::lonnavmaps::navmap->new();
 9193:     unless (ref($navmap)) {
 9194:         $r->print(&navmap_errormsg());
 9195:         return '';
 9196:     }
 9197:     my $map=$navmap->getResourceByUrl($sequence);
 9198:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9199:         %grader_randomlists_by_symb,%orderedforcode);
 9200:     if (ref($map)) {
 9201:         $randomorder=$map->randomorder();
 9202:         $randompick=$map->randompick();
 9203:     }
 9204:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9205:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9206:     if ($nav_error) {
 9207:         $r->print(&navmap_errormsg());
 9208:         return '';
 9209:     }
 9210:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9211:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9212:     my ($uname,$udom);
 9213:     my (%scandata,%lastname,%bylast);
 9214:     $r->print('
 9215: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9216: 
 9217:     my @delayqueue;
 9218:     my %completedstudents;
 9219: 
 9220:     my $count=&get_todo_count($scanlines,$scan_data);
 9221:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9222:     my ($username,$domain,$started);
 9223:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9224:     if ($nav_error) {
 9225:         $r->print(&navmap_errormsg());
 9226:         return '';
 9227:     }
 9228: 
 9229:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9230:                                           'Processing first student');
 9231:     my $start=&Time::HiRes::time();
 9232:     my $i=-1;
 9233: 
 9234:     while ($i<$scanlines->{'count'}) {
 9235:         ($username,$domain,$uname)=('','','');
 9236:         $i++;
 9237:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9238:         if ($line=~/^[\s\cz]*$/) { next; }
 9239:         if ($started) {
 9240:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9241:                                                      'last student');
 9242:         }
 9243:         $started=1;
 9244:         my $scan_record=
 9245:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9246:                                                      $scan_data);
 9247:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9248:                                               \%idmap,$i)) {
 9249:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9250:                                 'Unable to find a student that matches',1);
 9251:             next;
 9252:         }
 9253:         if (exists $completedstudents{$uname}) {
 9254:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9255:                                 'Student '.$uname.' has multiple sheets',2);
 9256:             next;
 9257:         }
 9258:         my $pid = $scan_record->{'scantron.ID'};
 9259:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9260:         push(@{$bylast{$lastname{$pid}}},$pid);
 9261:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9262:         my $user = $uname.':'.$usec;
 9263:         ($username,$domain)=split(/:/,$uname);
 9264: 
 9265:         my $scancode;
 9266:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9267:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9268:             $scancode = $scan_record->{'scantron.CODE'};
 9269:         } else {
 9270:             $scancode = '';
 9271:         }
 9272: 
 9273:         my @mapresources = @resources;
 9274:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9275:         my %respnumlookup=();
 9276:         my %startline=();
 9277:         if ($randomorder || $randompick) {
 9278:             @mapresources =
 9279:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9280:                              \%orderedforcode);
 9281:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9282:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9283:                                              \%grader_partids_by_symb,\%orderedforcode,
 9284:                                              \%respnumlookup,\%startline);
 9285:             if ($randompick && $total) {
 9286:                 $lastpos = $total*$scantron_config{'Qlength'};
 9287:             }
 9288:         }
 9289:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9290:         chomp($scandata{$pid});
 9291:         $scandata{$pid} =~ s/\r$//;
 9292: 
 9293:         my $counter = -1;
 9294:         foreach my $resource (@mapresources) {
 9295:             my $parts;
 9296:             my $ressymb = $resource->symb();
 9297:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9298:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9299:                 (my $analysis,$parts) =
 9300:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9301:                                               $username,$domain,undef,
 9302:                                               $bubbles_per_row);
 9303:             } else {
 9304:                 $parts = $grader_partids_by_symb{$ressymb};
 9305:             }
 9306:             ($counter,my $recording) =
 9307:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9308:                                          $scandata{$pid},$parts,
 9309:                                          \%scantron_config,\%lettdig,$numletts,
 9310:                                          $randomorder,$randompick,
 9311:                                          \%respnumlookup,\%startline);
 9312:             $record{$pid} .= $recording;
 9313:         }
 9314:     }
 9315:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9316:     $r->print('<br />');
 9317:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9318:     $passed = 0;
 9319:     $failed = 0;
 9320:     $numstudents = 0;
 9321:     foreach my $last (sort(keys(%bylast))) {
 9322:         if (ref($bylast{$last}) eq 'ARRAY') {
 9323:             foreach my $pid (sort(@{$bylast{$last}})) {
 9324:                 my $showscandata = $scandata{$pid};
 9325:                 my $showrecord = $record{$pid};
 9326:                 $showscandata =~ s/\s/&nbsp;/g;
 9327:                 $showrecord =~ s/\s/&nbsp;/g;
 9328:                 if ($scandata{$pid} eq $record{$pid}) {
 9329:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9330:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9331: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9332: '</tr>'."\n".
 9333: '<tr class="'.$css_class.'">'."\n".
 9334: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9335:                     $passed ++;
 9336:                 } else {
 9337:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9338:                     $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".
 9339: '</tr>'."\n".
 9340: '<tr class="'.$css_class.'">'."\n".
 9341: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9342: '</tr>'."\n";
 9343:                     $failed ++;
 9344:                 }
 9345:                 $numstudents ++;
 9346:             }
 9347:         }
 9348:     }
 9349:     $r->print('<p>'.
 9350:               &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).',
 9351:                   '<b>',
 9352:                   $numstudents,
 9353:                   '</b>',
 9354:                   $env{'form.scantron_maxbubble'}).
 9355:               '</p>'
 9356:     );
 9357:     $r->print('<p>'
 9358:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9359:              .'<br />'
 9360:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9361:              .'</p>');
 9362:     if ($passed) {
 9363:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9364:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9365:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9366:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9367:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9368:                  $okstudents."\n".
 9369:                  &Apache::loncommon::end_data_table().'<br />');
 9370:     }
 9371:     if ($failed) {
 9372:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9373:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9374:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9375:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9376:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9377:                  $badstudents."\n".
 9378:                  &Apache::loncommon::end_data_table()).'<br />'.
 9379:                  &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.');  
 9380:     }
 9381:     $r->print('</form><br />'.$grading_menu_button);
 9382:     return;
 9383: }
 9384: 
 9385: sub verify_scantron_grading {
 9386:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9387:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9388:         $respnumlookup,$startline) = @_;
 9389:     my ($record,%expected,%startpos);
 9390:     return ($counter,$record) if (!ref($resource));
 9391:     return ($counter,$record) if (!$resource->is_problem());
 9392:     my $symb = $resource->symb();
 9393:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9394:     foreach my $part_id (@{$partids}) {
 9395:         $counter ++;
 9396:         $expected{$part_id} = 0;
 9397:         my $respnum = $counter;
 9398:         if ($randomorder || $randompick) {
 9399:             $respnum = $respnumlookup->{$counter};
 9400:             $startpos{$part_id} = $startline->{$counter} + 1;
 9401:         } else {
 9402:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9403:         }
 9404:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9405:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9406:             foreach my $item (@sub_lines) {
 9407:                 $expected{$part_id} += $item;
 9408:             }
 9409:         } else {
 9410:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9411:         }
 9412:     }
 9413:     if ($symb) {
 9414:         my %recorded;
 9415:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9416:         if ($returnhash{'version'}) {
 9417:             my %lasthash=();
 9418:             my $version;
 9419:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9420:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9421:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9422:                 }
 9423:             }
 9424:             foreach my $key (keys(%lasthash)) {
 9425:                 if ($key =~ /\.scantron$/) {
 9426:                     my $value = &unescape($lasthash{$key});
 9427:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9428:                     if ($value eq '') {
 9429:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9430:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9431:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9432:                             }
 9433:                         }
 9434:                     } else {
 9435:                         my @tocheck;
 9436:                         my @items = split(//,$value);
 9437:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9438:                             ($scantron_config->{'Qon'} eq 'number')) {
 9439:                             if (@items < $expected{$part_id}) {
 9440:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9441:                                 my @singles = split(//,$fragment);
 9442:                                 foreach my $pos (@singles) {
 9443:                                     if ($pos eq ' ') {
 9444:                                         push(@tocheck,$pos);
 9445:                                     } else {
 9446:                                         my $next = shift(@items);
 9447:                                         push(@tocheck,$next);
 9448:                                     }
 9449:                                 }
 9450:                             } else {
 9451:                                 @tocheck = @items;
 9452:                             }
 9453:                             foreach my $letter (@tocheck) {
 9454:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9455:                                     if ($letter !~ /^[A-J]$/) {
 9456:                                         $letter = $scantron_config->{'Qoff'};
 9457:                                     }
 9458:                                     $recorded{$part_id} .= $letter;
 9459:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9460:                                     my $digit;
 9461:                                     if ($letter !~ /^[A-J]$/) {
 9462:                                         $digit = $scantron_config->{'Qoff'};
 9463:                                     } else {
 9464:                                         $digit = $lettdig->{$letter};
 9465:                                     }
 9466:                                     $recorded{$part_id} .= $digit;
 9467:                                 }
 9468:                             }
 9469:                         } else {
 9470:                             @tocheck = @items;
 9471:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9472:                                 my $curr_sub = shift(@tocheck);
 9473:                                 my $digit;
 9474:                                 if ($curr_sub =~ /^[A-J]$/) {
 9475:                                     $digit = $lettdig->{$curr_sub}-1;
 9476:                                 }
 9477:                                 if ($curr_sub eq 'J') {
 9478:                                     $digit += scalar($numletts);
 9479:                                 }
 9480:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9481:                                     if ($j == $digit) {
 9482:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9483:                                     } else {
 9484:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9485:                                     }
 9486:                                 }
 9487:                             }
 9488:                         }
 9489:                     }
 9490:                 }
 9491:             }
 9492:         }
 9493:         foreach my $part_id (@{$partids}) {
 9494:             if ($recorded{$part_id} eq '') {
 9495:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9496:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9497:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9498:                     }
 9499:                 }
 9500:             }
 9501:             $record .= $recorded{$part_id};
 9502:         }
 9503:     }
 9504:     return ($counter,$record);
 9505: }
 9506: 
 9507: sub letter_to_digits {
 9508:     my %lettdig = (
 9509:                     A => 1,
 9510:                     B => 2,
 9511:                     C => 3,
 9512:                     D => 4,
 9513:                     E => 5,
 9514:                     F => 6,
 9515:                     G => 7,
 9516:                     H => 8,
 9517:                     I => 9,
 9518:                     J => 0,
 9519:                   );
 9520:     return %lettdig;
 9521: }
 9522: 
 9523: 
 9524: #-------- end of section for handling grading scantron forms -------
 9525: #
 9526: #-------------------------------------------------------------------
 9527: 
 9528: #-------------------------- Menu interface -------------------------
 9529: #
 9530: #--- Show a Grading Menu button - Calls the next routine ---
 9531: sub show_grading_menu_form {
 9532:     my ($symb)=@_;
 9533:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9534: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9535: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9536: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9537: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9538: 	'</form>'."\n";
 9539:     return $result;
 9540: }
 9541: 
 9542: # -- Retrieve choices for grading form
 9543: sub savedState {
 9544:     my %savedState = ();
 9545:     if ($env{'form.saveState'}) {
 9546: 	foreach (split(/:/,$env{'form.saveState'})) {
 9547: 	    my ($key,$value) = split(/=/,$_,2);
 9548: 	    $savedState{$key} = $value;
 9549: 	}
 9550:     }
 9551:     return \%savedState;
 9552: }
 9553: 
 9554: #--- Href with symb and command ---
 9555: 
 9556: sub href_symb_cmd {
 9557:     my ($symb,$cmd)=@_;
 9558:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9559: }
 9560: 
 9561: sub grading_menu {
 9562:     my ($request) = @_;
 9563:     my ($symb)=&get_symb($request);
 9564:     if (!$symb) {return '';}
 9565:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9566:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9567: 
 9568:     $request->print($table);
 9569:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9570:                   'handgrade'=>$hdgrade,
 9571:                   'probTitle'=>$probTitle,
 9572:                   'command'=>'submit_options',
 9573:                   'saveState'=>"",
 9574:                   'gradingMenu'=>1,
 9575:                   'showgrading'=>"yes");
 9576:     
 9577:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9578:     
 9579:     $fields{'command'} = 'csvform';
 9580:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9581:     
 9582:     $fields{'command'} = 'processclicker';
 9583:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9584:     
 9585:     $fields{'command'} = 'scantron_selectphase';
 9586:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9587:     
 9588:     my @menu = ({	categorytitle=>'Course Grading',
 9589:             items =>[
 9590:                         {	linktext => 'Manual Grading/View Submissions',
 9591:                     		url => $url1,
 9592:                     		permission => 'F',
 9593:                     		icon => 'edit-find-replace.png',
 9594:                     		linktitle => 'Start the process of hand grading submissions.'
 9595:                         },
 9596:                 	    {	linktext => 'Upload Scores',
 9597:                     		url => $url2,
 9598:                     		permission => 'F',
 9599:                     		icon => 'uploadscores.png',
 9600:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9601:                 	    },
 9602:                 	    {	linktext => 'Process Clicker',
 9603:                     		url => $url3,
 9604:                     		permission => 'F',
 9605:                     		icon => 'addClickerInfoFile.png',
 9606:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9607:                 	    },
 9608:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9609:                     		url => $url4,
 9610:                     		permission => 'F',
 9611:                     		icon => 'stat.png',
 9612:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9613:                 	    }
 9614:                     ]
 9615:             });
 9616: 
 9617:     #$fields{'command'} = 'verify';
 9618:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9619:     #
 9620:     # Create the menu
 9621:     my $Str;
 9622:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9623:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9624:     $Str .= '<input type="hidden" name="command" value="" />'.
 9625:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9626: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9627: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9628: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9629: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9630: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9631: 
 9632:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9633:     #$menudata->{'jscript'}
 9634:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9635:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9636:         ' /> '.
 9637:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9638:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9639: 
 9640:     $Str .="</form>\n";
 9641:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9642:     $request->print(<<GRADINGMENUJS);
 9643: <script type="text/javascript" language="javascript">
 9644:     function checkChoice(formname,val,cmdx) {
 9645: 	if (val <= 2) {
 9646: 	    var cmd = radioSelection(formname.radioChoice);
 9647: 	    var cmdsave = cmd;
 9648: 	} else {
 9649: 	    cmd = cmdx;
 9650: 	    cmdsave = 'submission';
 9651: 	}
 9652: 	formname.command.value = cmd;
 9653: 	if (val < 5) formname.submit();
 9654: 	if (val == 5) {
 9655: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9656: 	        return false;
 9657: 	    } else {
 9658: 	        formname.submit();
 9659: 	    }
 9660: 	}
 9661:     }
 9662: 
 9663:     function checkReceiptNo(formname,nospace) {
 9664: 	var receiptNo = formname.receipt.value;
 9665: 	var checkOpt = false;
 9666: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9667: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9668: 	if (checkOpt) {
 9669: 	    alert("$receiptalert");
 9670: 	    formname.receipt.value = "";
 9671: 	    formname.receipt.focus();
 9672: 	    return false;
 9673: 	}
 9674: 	return true;
 9675:     }
 9676: </script>
 9677: GRADINGMENUJS
 9678:     &commonJSfunctions($request);
 9679:     return $Str;    
 9680: }
 9681: 
 9682: 
 9683: #--- Displays the submissions first page -------
 9684: sub submit_options {
 9685:     my ($request) = @_;
 9686:     my ($symb)=&get_symb($request);
 9687:     if (!$symb) {return '';}
 9688:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9689: 
 9690:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9691:     $request->print(<<GRADINGMENUJS);
 9692: <script type="text/javascript" language="javascript">
 9693:     function checkChoice(formname,val,cmdx) {
 9694: 	if (val <= 2) {
 9695: 	    var cmd = radioSelection(formname.radioChoice);
 9696: 	    var cmdsave = cmd;
 9697: 	} else {
 9698: 	    cmd = cmdx;
 9699: 	    cmdsave = 'submission';
 9700: 	}
 9701: 	formname.command.value = cmd;
 9702: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9703: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9704: 	if (val < 5) formname.submit();
 9705: 	if (val == 5) {
 9706: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9707: 	    formname.submit();
 9708: 	}
 9709: 	if (val < 7) formname.submit();
 9710:     }
 9711: 
 9712:     function checkReceiptNo(formname,nospace) {
 9713: 	var receiptNo = formname.receipt.value;
 9714: 	var checkOpt = false;
 9715: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9716: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9717: 	if (checkOpt) {
 9718: 	    alert("$receiptalert");
 9719: 	    formname.receipt.value = "";
 9720: 	    formname.receipt.focus();
 9721: 	    return false;
 9722: 	}
 9723: 	return true;
 9724:     }
 9725: </script>
 9726: GRADINGMENUJS
 9727:     &commonJSfunctions($request);
 9728:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9729:     my $result;
 9730:     my (undef,$sections) = &getclasslist('all','0');
 9731:     my $savedState = &savedState();
 9732:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9733:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9734:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9735:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9736: 
 9737:     # Preselect sections
 9738:     my $selsec="";
 9739:     if (ref($sections)) {
 9740:         foreach my $section (sort(@$sections)) {
 9741:             $selsec.='<option value="'.$section.'" '.
 9742:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9743:         }
 9744:     }
 9745: 
 9746:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9747: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9748: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9749: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9750: 	'<input type="hidden" name="command"     value="" />'."\n".
 9751: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9752: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9753: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9754: 
 9755:     $result.='
 9756: <h2>
 9757:   '.&mt('Grade Current Resource').'
 9758: </h2>
 9759: <div>
 9760:   '.$table.'
 9761: </div>
 9762: 
 9763: <div class="LC_columnSection">
 9764:   
 9765:     <fieldset>
 9766:       <legend>
 9767:        '.&mt('Sections').'
 9768:       </legend>
 9769:       <select name="section" multiple="multiple" size="5">'."\n";
 9770:     $result.= $selsec;
 9771:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9772:     $result.='
 9773:     </fieldset>
 9774:   
 9775:     <fieldset>
 9776:       <legend>
 9777:         '.&mt('Groups').'
 9778:       </legend>
 9779:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9780:     </fieldset>
 9781:   
 9782:     <fieldset>
 9783:       <legend>
 9784:         '.&mt('Access Status').'
 9785:       </legend>
 9786:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9787:     </fieldset>
 9788:   
 9789:     <fieldset>
 9790:       <legend>
 9791:         '.&mt('Submission Status').'
 9792:       </legend>
 9793:       <select name="submitonly" size="5">
 9794: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9795: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9796: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9797: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9798:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9799:       </select>
 9800:     </fieldset>
 9801:   
 9802: </div>
 9803: 
 9804: <br />
 9805:           <div>
 9806:             <div>
 9807:               <label>
 9808:                 <input type="radio" name="radioChoice" value="submission" '.
 9809:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9810:              &mt('Select individual students to grade and view submissions.').'
 9811: 	      </label> 
 9812:             </div>
 9813:             <div>
 9814: 	      <label>
 9815:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9816:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9817:                     &mt('Grade all selected students in a grading table.').'
 9818:               </label>
 9819:             </div>
 9820:             <div>
 9821: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9822:             </div>
 9823:           </div>
 9824: 
 9825: 
 9826:         <h2>
 9827:          '.&mt('Grade Complete Folder for One Student').'
 9828:         </h2>
 9829:         <div>
 9830:             <div>
 9831:               <label>
 9832:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9833: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9834:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9835:               </label>
 9836:             </div>
 9837:             <div>
 9838: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9839:             </div>
 9840:         </div>
 9841:   </form>';
 9842:     $result .= &show_grading_menu_form($symb);
 9843:     return $result;
 9844: }
 9845: 
 9846: sub reset_perm {
 9847:     undef(%perm);
 9848: }
 9849: 
 9850: sub init_perm {
 9851:     &reset_perm();
 9852:     foreach my $test_perm ('vgr','mgr','opa') {
 9853: 
 9854: 	my $scope = $env{'request.course.id'};
 9855: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9856: 
 9857: 	    $scope .= '/'.$env{'request.course.sec'};
 9858: 	    if ( $perm{$test_perm}=
 9859: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9860: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9861: 	    } else {
 9862: 		delete($perm{$test_perm});
 9863: 	    }
 9864: 	}
 9865:     }
 9866: }
 9867: 
 9868: sub init_old_essays {
 9869:     my ($symb,$apath,$adom,$aname) = @_;
 9870:     if ($symb ne '') {
 9871:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9872:         if (keys(%essays) > 0) {
 9873:             $old_essays{$symb} = \%essays;
 9874:         }
 9875:     }
 9876:     return;
 9877: }
 9878: 
 9879: sub reset_old_essays {
 9880:     undef(%old_essays);
 9881: }
 9882: 
 9883: sub gather_clicker_ids {
 9884:     my %clicker_ids;
 9885: 
 9886:     my $classlist = &Apache::loncoursedata::get_classlist();
 9887: 
 9888:     # Set up a couple variables.
 9889:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9890:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9891:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9892: 
 9893:     foreach my $student (keys(%$classlist)) {
 9894:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9895:         my $username = $classlist->{$student}->[$username_idx];
 9896:         my $domain   = $classlist->{$student}->[$domain_idx];
 9897:         my $clickers =
 9898: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9899:         foreach my $id (split(/\,/,$clickers)) {
 9900:             $id=~s/^[\#0]+//;
 9901:             $id=~s/[\-\:]//g;
 9902:             if (exists($clicker_ids{$id})) {
 9903: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9904:             } else {
 9905: 		$clicker_ids{$id}=$username.':'.$domain;
 9906:             }
 9907:         }
 9908:     }
 9909:     return %clicker_ids;
 9910: }
 9911: 
 9912: sub gather_adv_clicker_ids {
 9913:     my %clicker_ids;
 9914:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9915:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9916:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9917:     foreach my $element (sort(keys(%coursepersonnel))) {
 9918:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9919:             my ($puname,$pudom)=split(/\:/,$person);
 9920:             my $clickers =
 9921: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9922:             foreach my $id (split(/\,/,$clickers)) {
 9923: 		$id=~s/^[\#0]+//;
 9924:                 $id=~s/[\-\:]//g;
 9925: 		if (exists($clicker_ids{$id})) {
 9926: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9927: 		} else {
 9928: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9929: 		}
 9930:             }
 9931:         }
 9932:     }
 9933:     return %clicker_ids;
 9934: }
 9935: 
 9936: sub clicker_grading_parameters {
 9937:     return ('gradingmechanism' => 'scalar',
 9938:             'upfiletype' => 'scalar',
 9939:             'specificid' => 'scalar',
 9940:             'pcorrect' => 'scalar',
 9941:             'pincorrect' => 'scalar');
 9942: }
 9943: 
 9944: sub process_clicker {
 9945:     my ($r)=@_;
 9946:     my ($symb)=&get_symb($r);
 9947:     if (!$symb) {return '';}
 9948:     my $result=&checkforfile_js();
 9949:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9950:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9951:     $result.=$table;
 9952:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9953:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9954:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9955:         '</b></td></tr>'."\n";
 9956:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9957: # Attempt to restore parameters from last session, set defaults if not present
 9958:     my %Saveable_Parameters=&clicker_grading_parameters();
 9959:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9960:                                                  \%Saveable_Parameters);
 9961:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9962:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9963:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9964:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9965: 
 9966:     my %checked;
 9967:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9968:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9969:           $checked{$gradingmechanism}=' checked="checked"';
 9970:        }
 9971:     }
 9972: 
 9973:     my $upload=&mt("Upload File");
 9974:     my $type=&mt("Type");
 9975:     my $attendance=&mt("Award points just for participation");
 9976:     my $personnel=&mt("Correctness determined from response by course personnel");
 9977:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9978:     my $given=&mt("Correctness determined from given list of answers").' '.
 9979:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9980:     my $pcorrect=&mt("Percentage points for correct solution");
 9981:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9982:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9983:                                                    {'iclicker' => 'i>clicker',
 9984:                                                     'interwrite' => 'interwrite PRS',
 9985:                                                     'turning' => 'Turning Technologies'});
 9986:     $symb = &Apache::lonenc::check_encrypt($symb);
 9987:     $result.=<<ENDUPFORM;
 9988: <script type="text/javascript">
 9989: function sanitycheck() {
 9990: // Accept only integer percentages
 9991:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9992:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9993: // Find out grading choice
 9994:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9995:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9996:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9997:       }
 9998:    }
 9999: // By default, new choice equals user selection
10000:    newgradingchoice=gradingchoice;
10001: // Not good to give more points for false answers than correct ones
10002:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10003:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10004:    }
10005: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10006:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10007:       document.forms.gradesupload.pcorrect.value=100;
10008:       document.forms.gradesupload.pincorrect.value=100;
10009:    }
10010: // If the values are different, cannot be attendance only
10011:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10012:        (gradingchoice=='attendance')) {
10013:        newgradingchoice='personnel';
10014:    }
10015: // Change grading choice to new one
10016:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10017:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10018:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10019:       } else {
10020:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10021:       }
10022:    }
10023: // Remember the old state
10024:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10025: }
10026: </script>
10027: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10028: <input type="hidden" name="symb" value="$symb" />
10029: <input type="hidden" name="command" value="processclickerfile" />
10030: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10031: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10032: <input type="file" name="upfile" size="50" />
10033: <br /><label>$type: $selectform</label>
10034: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10035: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10036: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10037: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10038: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10039: <br />&nbsp;&nbsp;&nbsp;
10040: <input type="text" name="givenanswer" size="50" />
10041: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10042: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10043: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10044: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10045: </form>
10046: ENDUPFORM
10047:     $result.='</td></tr></table>'."\n".
10048:              '</td></tr></table><br /><br />'."\n";
10049:     $result.=&show_grading_menu_form($symb);
10050:     return $result;
10051: }
10052: 
10053: sub process_clicker_file {
10054:     my ($r)=@_;
10055:     my ($symb)=&get_symb($r);
10056:     if (!$symb) {return '';}
10057: 
10058:     my %Saveable_Parameters=&clicker_grading_parameters();
10059:     &Apache::loncommon::store_course_settings('grades_clicker',
10060:                                               \%Saveable_Parameters);
10061: 
10062:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10063:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10064: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10065: 	return $result.&show_grading_menu_form($symb);
10066:     }
10067:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10068:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10069:         return $result.&show_grading_menu_form($symb);
10070:     }
10071:     my $foundgiven=0;
10072:     if ($env{'form.gradingmechanism'} eq 'given') {
10073:         $env{'form.givenanswer'}=~s/^\s*//gs;
10074:         $env{'form.givenanswer'}=~s/\s*$//gs;
10075:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10076:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10077:         my @answers=split(/\,/,$env{'form.givenanswer'});
10078:         $foundgiven=$#answers+1;
10079:     }
10080:     my %clicker_ids=&gather_clicker_ids();
10081:     my %correct_ids;
10082:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10083: 	%correct_ids=&gather_adv_clicker_ids();
10084:     }
10085:     if ($env{'form.gradingmechanism'} eq 'specific') {
10086: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10087: 	   $correct_id=~tr/a-z/A-Z/;
10088: 	   $correct_id=~s/\s//gs;
10089: 	   $correct_id=~s/^[\#0]+//;
10090:            $correct_id=~s/[\-\:]//g;
10091:            if ($correct_id) {
10092: 	      $correct_ids{$correct_id}='specified';
10093:            }
10094:         }
10095:     }
10096:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10097: 	$result.=&mt('Score based on attendance only');
10098:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10099:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10100:     } else {
10101: 	my $number=0;
10102: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10103: 	foreach my $id (sort(keys(%correct_ids))) {
10104: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10105: 	    if ($correct_ids{$id} eq 'specified') {
10106: 		$result.=&mt('specified');
10107: 	    } else {
10108: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10109: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10110: 	    }
10111: 	    $number++;
10112: 	}
10113:         $result.="</p>\n";
10114:         if ($number==0) {
10115:             $result .=
10116:                  &Apache::lonhtmlcommon::confirm_success(
10117:                      &mt('No IDs found to determine correct answer'),1);
10118:             return $result,.&show_grading_menu_form($symb);
10119:         }
10120:     }
10121:     if (length($env{'form.upfile'}) < 2) {
10122:         $result .=
10123:             &Apache::lonhtmlcommon::confirm_success(
10124:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10125:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10126:         return $result.&show_grading_menu_form($symb);
10127:     }
10128: 
10129: # Were able to get all the info needed, now analyze the file
10130: 
10131:     $result.=&Apache::loncommon::studentbrowser_javascript();
10132:     $symb = &Apache::lonenc::check_encrypt($symb);
10133:     my $heading=&mt('Scanning clicker file');
10134:     $result.=(<<ENDHEADER);
10135: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10136: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10137: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10138: <form method="post" action="/adm/grades" name="clickeranalysis">
10139: <input type="hidden" name="symb" value="$symb" />
10140: <input type="hidden" name="command" value="assignclickergrades" />
10141: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10142: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10143: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10144: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10145: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10146: ENDHEADER
10147:     if ($env{'form.gradingmechanism'} eq 'given') {
10148:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10149:     } 
10150:     my %responses;
10151:     my @questiontitles;
10152:     my $errormsg='';
10153:     my $number=0;
10154:     if ($env{'form.upfiletype'} eq 'iclicker') {
10155: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10156:     }
10157:     if ($env{'form.upfiletype'} eq 'interwrite') {
10158:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10159:     }
10160:     if ($env{'form.upfiletype'} eq 'turning') {
10161:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10162:     }
10163:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10164:              '<input type="hidden" name="number" value="'.$number.'" />'.
10165:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10166:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10167:              '<br />';
10168:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10169:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10170:        return $result.&show_grading_menu_form($symb);
10171:     } 
10172: # Remember Question Titles
10173: # FIXME: Possibly need delimiter other than ":"
10174:     for (my $i=0;$i<$number;$i++) {
10175:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10176:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10177:     }
10178:     my $correct_count=0;
10179:     my $student_count=0;
10180:     my $unknown_count=0;
10181: # Match answers with usernames
10182: # FIXME: Possibly need delimiter other than ":"
10183:     foreach my $id (keys(%responses)) {
10184:        if ($correct_ids{$id}) {
10185:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10186:           $correct_count++;
10187:        } elsif ($clicker_ids{$id}) {
10188:           if ($clicker_ids{$id}=~/\,/) {
10189: # More than one user with the same clicker!
10190:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10191:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10192:                            "<select name='multi".$id."'>";
10193:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10194:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10195:              }
10196:              $result.='</select>';
10197:              $unknown_count++;
10198:           } else {
10199: # Good: found one and only one user with the right clicker
10200:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10201:              $student_count++;
10202:           }
10203:        } else {
10204:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10205:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10206:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10207:                    "\n".&mt("Domain").": ".
10208:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10209:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10210:           $unknown_count++;
10211:        }
10212:     }
10213:     $result.='<hr />'.
10214:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10215:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10216:        if ($correct_count==0) {
10217:           $errormsg.="Found no correct answers for grading!";
10218:        } elsif ($correct_count>1) {
10219:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10220:        }
10221:     }
10222:     if ($number<1) {
10223:        $errormsg.="Found no questions.";
10224:     }
10225:     if ($errormsg) {
10226:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10227:     } else {
10228:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10229:     }
10230:     $result.='</form></td></tr></table>'."\n".
10231:              '</td></tr></table><br /><br />'."\n";
10232:     return $result.&show_grading_menu_form($symb);
10233: }
10234: 
10235: sub iclicker_eval {
10236:     my ($questiontitles,$responses)=@_;
10237:     my $number=0;
10238:     my $errormsg='';
10239:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10240:         my %components=&Apache::loncommon::record_sep($line);
10241:         my @entries=map {$components{$_}} (sort(keys(%components)));
10242: 	if ($entries[0] eq 'Question') {
10243: 	    for (my $i=3;$i<$#entries;$i+=6) {
10244: 		$$questiontitles[$number]=$entries[$i];
10245: 		$number++;
10246: 	    }
10247: 	}
10248: 	if ($entries[0]=~/^\#/) {
10249: 	    my $id=$entries[0];
10250: 	    my @idresponses;
10251: 	    $id=~s/^[\#0]+//;
10252: 	    for (my $i=0;$i<$number;$i++) {
10253: 		my $idx=3+$i*6;
10254:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10255: 		push(@idresponses,$entries[$idx]);
10256: 	    }
10257: 	    $$responses{$id}=join(',',@idresponses);
10258: 	}
10259:     }
10260:     return ($errormsg,$number);
10261: }
10262: 
10263: sub interwrite_eval {
10264:     my ($questiontitles,$responses)=@_;
10265:     my $number=0;
10266:     my $errormsg='';
10267:     my $skipline=1;
10268:     my $questionnumber=0;
10269:     my %idresponses=();
10270:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10271:         my %components=&Apache::loncommon::record_sep($line);
10272:         my @entries=map {$components{$_}} (sort(keys(%components)));
10273:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10274:         if ($entries[1] eq 'Response') { $skipline=1; }
10275:         next if $skipline;
10276:         if ($entries[0]!=$questionnumber) {
10277:            $questionnumber=$entries[0];
10278:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10279:            $number++;
10280:         }
10281:         my $id=$entries[4];
10282:         $id=~s/^[\#0]+//;
10283:         $id=~s/^v\d*\://i;
10284:         $id=~s/[\-\:]//g;
10285:         $idresponses{$id}[$number]=$entries[6];
10286:     }
10287:     foreach my $id (keys(%idresponses)) {
10288:        $$responses{$id}=join(',',@{$idresponses{$id}});
10289:        $$responses{$id}=~s/^\s*\,//;
10290:     }
10291:     return ($errormsg,$number);
10292: }
10293: 
10294: sub turning_eval {
10295:     my ($questiontitles,$responses)=@_;
10296:     my $number=0;
10297:     my $errormsg='';
10298:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10299:         my %components=&Apache::loncommon::record_sep($line);
10300:         my @entries=map {$components{$_}} (sort(keys(%components)));
10301:         if ($#entries>$number) { $number=$#entries; }
10302:         my $id=$entries[0];
10303:         my @idresponses;
10304:         $id=~s/^[\#0]+//;
10305:         unless ($id) { next; }
10306:         for (my $idx=1;$idx<=$#entries;$idx++) {
10307:             $entries[$idx]=~s/\,/\;/g;
10308:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10309:             push(@idresponses,$entries[$idx]);
10310:         }
10311:         $$responses{$id}=join(',',@idresponses);
10312:     }
10313:     for (my $i=1; $i<=$number; $i++) {
10314:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10315:     }
10316:     return ($errormsg,$number);
10317: }
10318: 
10319: sub assign_clicker_grades {
10320:     my ($r)=@_;
10321:     my ($symb)=&get_symb($r);
10322:     if (!$symb) {return '';}
10323: # See which part we are saving to
10324:     my $res_error;
10325:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10326:     if ($res_error) {
10327:         return &navmap_errormsg();
10328:     }
10329: # FIXME: This should probably look for the first handgradeable part
10330:     my $part=$$partlist[0];
10331: # Start screen output
10332:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10333: 
10334:     $result .= '<br />'.
10335:                &Apache::loncommon::start_data_table().
10336:                &Apache::loncommon::start_data_table_header_row().
10337:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10338:                &Apache::loncommon::end_data_table_header_row().
10339:                &Apache::loncommon::start_data_table_row().'<td>';
10340: 
10341: # Get correct result
10342: # FIXME: Possibly need delimiter other than ":"
10343:     my @correct=();
10344:     my $gradingmechanism=$env{'form.gradingmechanism'};
10345:     my $number=$env{'form.number'};
10346:     if ($gradingmechanism ne 'attendance') {
10347:        foreach my $key (keys(%env)) {
10348:           if ($key=~/^form\.correct\:/) {
10349:              my @input=split(/\,/,$env{$key});
10350:              for (my $i=0;$i<=$#input;$i++) {
10351:                  if (($correct[$i]) && ($input[$i]) &&
10352:                      ($correct[$i] ne $input[$i])) {
10353:                     $result.='<br /><span class="LC_warning">'.
10354:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10355:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10356:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10357:                     $correct[$i]=$input[$i];
10358:                  }
10359:              }
10360:           }
10361:        }
10362:        for (my $i=0;$i<$number;$i++) {
10363:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10364:              $result.='<br /><span class="LC_error">'.
10365:                       &mt('No correct result given for question "[_1]"!',
10366:                           $env{'form.question:'.$i}).'</span>';
10367:           }
10368:        }
10369:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10370:     }
10371: # Start grading
10372:     my $pcorrect=$env{'form.pcorrect'};
10373:     my $pincorrect=$env{'form.pincorrect'};
10374:     my $storecount=0;
10375:     my %users=();
10376:     foreach my $key (keys(%env)) {
10377:        my $user='';
10378:        if ($key=~/^form\.student\:(.*)$/) {
10379:           $user=$1;
10380:        }
10381:        if ($key=~/^form\.unknown\:(.*)$/) {
10382:           my $id=$1;
10383:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10384:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10385:           } elsif ($env{'form.multi'.$id}) {
10386:              $user=$env{'form.multi'.$id};
10387:           }
10388:        }
10389:        if ($user) {
10390:           if ($users{$user}) {
10391:              $result.='<br /><span class="LC_warning">'.
10392:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10393:                       '</span><br />';
10394:           }
10395:           $users{$user}=1;
10396:           my @answer=split(/\,/,$env{$key});
10397:           my $sum=0;
10398:           my $realnumber=$number;
10399:           for (my $i=0;$i<$number;$i++) {
10400:              if  ($correct[$i] eq '-') {
10401:                 $realnumber--;
10402:              } elsif ($answer[$i]) {
10403:                 if ($gradingmechanism eq 'attendance') {
10404:                    $sum+=$pcorrect;
10405:                 } elsif ($correct[$i] eq '*') {
10406:                    $sum+=$pcorrect;
10407:                 } else {
10408: # We actually grade if correct or not
10409:                    my $increment=$pincorrect;
10410: # Special case: numerical answer "0"
10411:                    if ($correct[$i] eq '0') {
10412:                       if ($answer[$i]=~/^[0\.]+$/) {
10413:                          $increment=$pcorrect;
10414:                       }
10415: # General numerical answer, both evaluate to something non-zero
10416:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10417:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10418:                          $increment=$pcorrect;
10419:                       }
10420: # Must be just alphanumeric
10421:                    } elsif ($answer[$i] eq $correct[$i]) {
10422:                       $increment=$pcorrect;
10423:                    }
10424:                    $sum+=$increment;
10425:                 }
10426:              }
10427:           }
10428:           my $ave=$sum/(100*$realnumber);
10429: # Store
10430:           my ($username,$domain)=split(/\:/,$user);
10431:           my %grades=();
10432:           $grades{"resource.$part.solved"}='correct_by_override';
10433:           $grades{"resource.$part.awarded"}=$ave;
10434:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10435:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10436:                                                  $env{'request.course.id'},
10437:                                                  $domain,$username);
10438:           if ($returncode ne 'ok') {
10439:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10440:           } else {
10441:              $storecount++;
10442:           }
10443:        }
10444:     }
10445: # We are done
10446:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10447:              '</td>'.
10448:              &Apache::loncommon::end_data_table_row().
10449:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10450:     return $result.&show_grading_menu_form($symb);
10451: }
10452: 
10453: sub navmap_errormsg {
10454:     return '<div class="LC_error">'.
10455:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10456:            &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>').
10457:            '</div>';
10458: }
10459: 
10460: sub startpage {
10461:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10462:     if ($nomenu) {
10463:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10464:     } else {
10465:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10466:                                                  {'bread_crumbs' => $crumbs}));
10467:     }
10468:     unless ($nodisplayflag) {
10469:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10470:     }
10471: }
10472: 
10473: sub handler {
10474:     my $request=$_[0];
10475:     &reset_caches();
10476:     if ($request->header_only) {
10477:         &Apache::loncommon::content_type($request,'text/html');
10478:         $request->send_http_header;
10479:         return OK;
10480:     }
10481:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10482: 
10483:     my $symb=&get_symb($request,1);
10484:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10485:     my $command=$commands[0];
10486: 
10487:     if ($#commands > 0) {
10488: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10489:     }
10490: 
10491:     $ssi_error = 0;
10492:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10493:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10494:                                                     {'bread_crumbs' => $brcrum});
10495:     if ($symb eq '' && $command eq '') {
10496: 	if ($env{'user.adv'}) {
10497:             &Apache::loncommon::content_type($request,'text/html');
10498:             $request->send_http_header;
10499:             $request->print($start_page);
10500: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10501: 		($env{'form.codethree'})) {
10502: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10503: 		    $env{'form.codethree'};
10504: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10505: 		    &Apache::lonnet::checkin($token);
10506: 		if ($tsymb) {
10507: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10508: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10509: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10510: 					  ('grade_username' => $tuname,
10511: 					   'grade_domain' => $tudom,
10512: 					   'grade_courseid' => $tcrsid,
10513: 					   'grade_symb' => $tsymb)));
10514: 		    } else {
10515: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10516: 		    }
10517: 		} else {
10518: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10519: 		}
10520: 	    } else {
10521: 		$request->print(&Apache::lonxml::tokeninputfield());
10522: 	    }
10523:         } elsif ($env{'request.course.id'}) {
10524:             &init_perm(); 
10525:             if (!%perm) {
10526:                 $request->internal_redirect('/adm/quickgrades');
10527:                 return OK;
10528:             } else {
10529:                 &Apache::loncommon::content_type($request,'text/html');
10530:                 $request->send_http_header;
10531:                 $request->print($start_page);
10532:             }
10533:         }
10534:     } else {
10535:         &init_perm();
10536:         if (!$env{'request.course.id'}) {
10537:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10538:                     ($command =~ /^scantronupload/)) {
10539:                 # Not in a course.
10540:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10541:                 return HTTP_NOT_ACCEPTABLE;
10542:             }
10543:         } elsif (!%perm) {
10544:             $request->internal_redirect('/adm/quickgrades');
10545:         }
10546:         &Apache::loncommon::content_type($request,'text/html');
10547:         $request->send_http_header;
10548:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10549:             $request->print($start_page); 
10550:         }
10551: 	if ($command eq 'submission' && $perm{'vgr'}) {
10552:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10553:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10554:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10555:                     &choose_task_version_form($symb,$env{'form.student'},
10556:                                               $env{'form.userdom'});
10557:             }
10558:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10559:             if ($versionform) {
10560:                 $request->print($versionform);
10561:             }
10562:             $request->print('<br clear="all" />');
10563: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10564:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10565:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10566:                 &choose_task_version_form($symb,$env{'form.student'},
10567:                                           $env{'form.userdom'},
10568:                                           $env{'form.inhibitmenu'});
10569:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10570:             if ($versionform) {
10571:                 $request->print($versionform);
10572:             }
10573:             $request->print('<br clear="all" />');
10574:             $request->print(&show_previous_task_version($request,$symb));
10575: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10576: 	    &pickStudentPage($request);
10577: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10578: 	    &displayPage($request);
10579: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10580: 	    &updateGradeByPage($request);
10581: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10582: 	    &processGroup($request);
10583: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10584: 	    $request->print(&grading_menu($request));
10585: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10586: 	    $request->print(&submit_options($request));
10587: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10588: 	    $request->print(&viewgrades($request));
10589: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10590: 	    $request->print(&processHandGrade($request));
10591: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10592: 	    $request->print(&editgrades($request));
10593: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10594: 	    $request->print(&verifyreceipt($request));
10595:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10596:             $request->print(&process_clicker($request));
10597:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10598:             $request->print(&process_clicker_file($request));
10599:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10600:             $request->print(&assign_clicker_grades($request));
10601: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10602: 	    $request->print(&upcsvScores_form($request));
10603: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10604: 	    $request->print(&csvupload($request));
10605: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10606: 	    $request->print(&csvuploadmap($request));
10607: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10608: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10609: 		$request->print(&csvuploadoptions($request));
10610: 	    } else {
10611: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10612: 		    $env{'form.upfile_associate'} = 'reverse';
10613: 		} else {
10614: 		    $env{'form.upfile_associate'} = 'forward';
10615: 		}
10616: 		$request->print(&csvuploadmap($request));
10617: 	    }
10618: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10619: 	    $request->print(&csvuploadassign($request));
10620: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10621: 	    $request->print(&scantron_selectphase($request));
10622:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10623:  	    $request->print(&scantron_do_warning($request));
10624: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10625: 	    $request->print(&scantron_validate_file($request));
10626: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10627: 	    $request->print(&scantron_process_students($request));
10628:  	} elsif ($command eq 'scantronupload' && 
10629:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10630: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10631:  	    $request->print(&scantron_upload_scantron_data($request)); 
10632:  	} elsif ($command eq 'scantronupload_save' &&
10633:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10634: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10635:  	    $request->print(&scantron_upload_scantron_data_save($request));
10636:  	} elsif ($command eq 'scantron_download' &&
10637: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10638:  	    $request->print(&scantron_download_scantron_data($request));
10639:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10640:             $request->print(&checkscantron_results($request));     
10641: 	} elsif ($command) {
10642: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10643: 	}
10644:     }
10645:     if ($ssi_error) {
10646: 	&ssi_print_error($request);
10647:     }
10648:     $request->print(&Apache::loncommon::end_page());
10649:     &reset_caches();
10650:     return OK;
10651: }
10652: 
10653: 1;
10654: 
10655: __END__;
10656: 
10657: 
10658: =head1 NAME
10659: 
10660: Apache::grades
10661: 
10662: =head1 SYNOPSIS
10663: 
10664: Handles the viewing of grades.
10665: 
10666: This is part of the LearningOnline Network with CAPA project
10667: described at http://www.lon-capa.org.
10668: 
10669: =head1 OVERVIEW
10670: 
10671: Do an ssi with retries:
10672: While I'd love to factor out this with the vesrion in lonprintout,
10673: 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
10674: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10675: 
10676: At least the logic that drives this has been pulled out into loncommon.
10677: 
10678: 
10679: 
10680: ssi_with_retries - Does the server side include of a resource.
10681:                      if the ssi call returns an error we'll retry it up to
10682:                      the number of times requested by the caller.
10683:                      If we still have a problem, no text is appended to the
10684:                      output and we set some global variables.
10685:                      to indicate to the caller an SSI error occurred.  
10686:                      All of this is supposed to deal with the issues described
10687:                      in LON-CAPA BZ 5631 see:
10688:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10689:                      by informing the user that this happened.
10690: 
10691: Parameters:
10692:   resource   - The resource to include.  This is passed directly, without
10693:                interpretation to lonnet::ssi.
10694:   form       - The form hash parameters that guide the interpretation of the resource
10695:                
10696:   retries    - Number of retries allowed before giving up completely.
10697: Returns:
10698:   On success, returns the rendered resource identified by the resource parameter.
10699: Side Effects:
10700:   The following global variables can be set:
10701:    ssi_error                - If an unrecoverable error occurred this becomes true.
10702:                               It is up to the caller to initialize this to false
10703:                               if desired.
10704:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10705:                               of the resource that could not be rendered by the ssi
10706:                               call.
10707:    ssi_error_message   - The error string fetched from the ssi response
10708:                               in the event of an error.
10709: 
10710: 
10711: =head1 HANDLER SUBROUTINE
10712: 
10713: ssi_with_retries()
10714: 
10715: =head1 SUBROUTINES
10716: 
10717: =over
10718: 
10719: =item scantron_get_correction() : 
10720: 
10721:    Builds the interface screen to interact with the operator to fix a
10722:    specific error condition in a specific scanline
10723: 
10724:  Arguments:
10725:     $r           - Apache request object
10726:     $i           - number of the current scanline
10727:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10728:     $scan_config - hash ref as returned from &get_scantron_config()
10729:     $line        - full contents of the current scanline
10730:     $error       - error condition, valid values are
10731:                    'incorrectCODE', 'duplicateCODE',
10732:                    'doublebubble', 'missingbubble',
10733:                    'duplicateID', 'incorrectID'
10734:     $arg         - extra information needed
10735:        For errors:
10736:          - duplicateID   - paper number that this studentID was seen before on
10737:          - duplicateCODE - array ref of the paper numbers this CODE was
10738:                            seen on before
10739:          - incorrectCODE - current incorrect CODE 
10740:          - doublebubble  - array ref of the bubble lines that have double
10741:                            bubble errors
10742:          - missingbubble - array ref of the bubble lines that have missing
10743:                            bubble errors
10744: 
10745:    $randomorder - True if exam folder has randomorder set
10746:    $randompick  - True if exam folder has randompick set
10747:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10748:                      for current line to question number used for same question
10749:                      in "Master Seqence" (as seen by Course Coordinator).
10750:    $startline   - Reference to hash where key is question number (0 is first)
10751:                   and value is number of first bubble line for current student
10752:                   or code-based randompick and/or randomorder.
10753: 
10754: 
10755: =item  scantron_get_maxbubble() : 
10756: 
10757:    Arguments:
10758:        $nav_error  - Reference to scalar which is a flag to indicate a
10759:                       failure to retrieve a navmap object.
10760:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10761:        calling routine should trap the error condition and display the warning
10762:        found in &navmap_errormsg().
10763: 
10764:        $scantron_config - Reference to bubblesheet format configuration hash.
10765: 
10766:    Returns the maximum number of bubble lines that are expected to
10767:    occur. Does this by walking the selected sequence rendering the
10768:    resource and then checking &Apache::lonxml::get_problem_counter()
10769:    for what the current value of the problem counter is.
10770: 
10771:    Caches the results to $env{'form.scantron_maxbubble'},
10772:    $env{'form.scantron.bubble_lines.n'}, 
10773:    $env{'form.scantron.first_bubble_line.n'} and
10774:    $env{"form.scantron.sub_bubblelines.n"}
10775:    which are the total number of bubble lines, the number of bubble
10776:    lines for response n and number of the first bubble line for response n,
10777:    and a comma separated list of numbers of bubble lines for sub-questions
10778:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10779: 
10780: 
10781: =item  scantron_validate_missingbubbles() : 
10782: 
10783:    Validates all scanlines in the selected file to not have any
10784:     answers that don't have bubbles that have not been verified
10785:     to be bubble free.
10786: 
10787: =item  scantron_process_students() : 
10788: 
10789:    Routine that does the actual grading of the bubblesheet information.
10790: 
10791:    The parsed scanline hash is added to %env 
10792: 
10793:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10794:    foreach resource , with the form data of
10795: 
10796: 	'submitted'     =>'scantron' 
10797: 	'grade_target'  =>'grade',
10798: 	'grade_username'=> username of student
10799: 	'grade_domain'  => domain of student
10800: 	'grade_courseid'=> of course
10801: 	'grade_symb'    => symb of resource to grade
10802: 
10803:     This triggers a grading pass. The problem grading code takes care
10804:     of converting the bubbled letter information (now in %env) into a
10805:     valid submission.
10806: 
10807: =item  scantron_upload_scantron_data() :
10808: 
10809:     Creates the screen for adding a new bubblesheet data file to a course.
10810: 
10811: =item  scantron_upload_scantron_data_save() : 
10812: 
10813:    Adds a provided bubble information data file to the course if user
10814:    has the correct privileges to do so. 
10815: 
10816: =item  valid_file() :
10817: 
10818:    Validates that the requested bubble data file exists in the course.
10819: 
10820: =item  scantron_download_scantron_data() : 
10821: 
10822:    Shows a list of the three internal files (original, corrected,
10823:    skipped) for a specific bubblesheet data file that exists in the
10824:    course.
10825: 
10826: =item  scantron_validate_ID() : 
10827: 
10828:    Validates all scanlines in the selected file to not have any
10829:    invalid or underspecified student/employee IDs
10830: 
10831: =item navmap_errormsg() :
10832: 
10833:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10834:    Should be called whenever the request to instantiate a navmap object fails.  
10835: 
10836: =back
10837: 
10838: =cut

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