File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.8: download - view: text, annotated - select for diffs
Sun May 13 01:43:54 2012 UTC (11 years, 11 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11.
  - Backport part of changes in 1.649, ommitted in 1.596.2.12.2.1.
  - Bacport 1.673.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.8 2012/05/13 01:43:54 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: 
   56: #  These variables are used to recover from ssi errors
   57: 
   58: my $ssi_retries = 5;
   59: my $ssi_error;
   60: my $ssi_error_resource;
   61: my $ssi_error_message;
   62: 
   63: 
   64: sub ssi_with_retries {
   65:     my ($resource, $retries, %form) = @_;
   66:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   67:     if ($response->is_error) {
   68: 	$ssi_error          = 1;
   69: 	$ssi_error_resource = $resource;
   70: 	$ssi_error_message  = $response->code . " " . $response->message;
   71:     }
   72: 
   73:     return $content;
   74: 
   75: }
   76: #
   77: #  Prodcuces an ssi retry failure error message to the user:
   78: #
   79: 
   80: sub ssi_print_error {
   81:     my ($r) = @_;
   82:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   83:     $r->print('
   84: <br />
   85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   86: <p>
   87: '.&mt('Unable to retrieve a resource from a server:').'<br />
   88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   89: '.&mt('Error:').' '.$ssi_error_message.'
   90: </p>
   91: <p>'.
   92: &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 />'.
   93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   94: '</p>');
   95:     return;
   96: }
   97: 
   98: #
   99: # --- Retrieve the parts from the metadata file.---
  100: sub getpartlist {
  101:     my ($symb,$errorref) = @_;
  102: 
  103:     my $navmap   = Apache::lonnavmaps::navmap->new();
  104:     unless (ref($navmap)) {
  105:         if (ref($errorref)) { 
  106:             $$errorref = 'navmap';
  107:             return;
  108:         }
  109:     }
  110:     my $res      = $navmap->getBySymb($symb);
  111:     my $partlist = $res->parts();
  112:     my $url      = $res->src();
  113:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  114: 
  115:     my @stores;
  116:     foreach my $part (@{ $partlist }) {
  117: 	foreach my $key (@metakeys) {
  118: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  119: 	}
  120:     }
  121:     return @stores;
  122: }
  123: 
  124: # --- Get the symbolic name of a problem and the url
  125: sub get_symb {
  126:     my ($request,$silent) = @_;
  127:     my $symb=$env{'form.symb'};
  128:     unless ($symb) {
  129:         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  130:         $symb = &Apache::lonnet::symbread($url);
  131:         if ($symb eq '') { 
  132: 	    if (!$silent) {
  133:                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  134: 	        return ();
  135: 	    }
  136:         }
  137:     }
  138:     &Apache::lonenc::check_decrypt(\$symb);
  139:     return ($symb);
  140: }
  141: 
  142: #--- Format fullname, username:domain if different for display
  143: #--- Use anywhere where the student names are listed
  144: sub nameUserString {
  145:     my ($type,$fullname,$uname,$udom) = @_;
  146:     if ($type eq 'header') {
  147: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  148:     } else {
  149: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  150: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  151:     }
  152: }
  153: 
  154: #--- Get the partlist and the response type for a given problem. ---
  155: #--- Indicate if a response type is coded handgraded or not. ---
  156: sub response_type {
  157:     my ($symb,$response_error) = @_;
  158: 
  159:     my $navmap = Apache::lonnavmaps::navmap->new();
  160:     unless (ref($navmap)) {
  161:         if (ref($response_error)) {
  162:             $$response_error = 1;
  163:         }
  164:         return;
  165:     }
  166:     my $res = $navmap->getBySymb($symb);
  167:     unless (ref($res)) {
  168:         $$response_error = 1;
  169:         return;
  170:     }
  171:     my $partlist = $res->parts();
  172:     my %vPart = 
  173: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  174:     my (%response_types,%handgrade);
  175:     foreach my $part (@{ $partlist }) {
  176: 	next if (%vPart && !exists($vPart{$part}));
  177: 
  178: 	my @types = $res->responseType($part);
  179: 	my @ids = $res->responseIds($part);
  180: 	for (my $i=0; $i < scalar(@ids); $i++) {
  181: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  182: 	    $handgrade{$part.'_'.$ids[$i]} = 
  183: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  184: 				     '.handgrade',$symb);
  185: 	}
  186:     }
  187:     return ($partlist,\%handgrade,\%response_types);
  188: }
  189: 
  190: sub flatten_responseType {
  191:     my ($responseType) = @_;
  192:     my @part_response_id =
  193: 	map { 
  194: 	    my $part = $_;
  195: 	    map {
  196: 		[$part,$_]
  197: 		} sort(keys(%{ $responseType->{$part} }));
  198: 	} sort(keys(%$responseType));
  199:     return @part_response_id;
  200: }
  201: 
  202: sub get_display_part {
  203:     my ($partID,$symb)=@_;
  204:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  205:     if (defined($display) and $display ne '') {
  206:         $display.= ' (<span class="LC_internal_info">'
  207:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  208:     } else {
  209: 	$display=$partID;
  210:     }
  211:     return $display;
  212: }
  213: 
  214: #--- Show resource title
  215: #--- and parts and response type
  216: sub showResourceInfo {
  217:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  218:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  219:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  220:     if (ref($res_error)) {
  221:         if ($$res_error) {
  222:             return;
  223:         }
  224:     }
  225:     $result.=&Apache::loncommon::start_data_table()
  226:             .&Apache::loncommon::start_data_table_header_row();
  227:     if ($checkboxes) {
  228:         $result.='<th>&nbsp;</th>';
  229:     }
  230:     $result.='<th>'.&mt('Problem Part').'</th>'
  231:             .'<th>'.&mt('Res. ID').'</th>'
  232:             .'<th>'.&mt('Type').'</th>'
  233:             .&Apache::loncommon::end_data_table_header_row();
  234:     my %resptype = ();
  235:     my $hdgrade='no';
  236:     my %partsseen;
  237:     foreach my $partID (sort(keys(%$responseType))) {
  238:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  239:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  240:             my $responsetype = $responseType->{$partID}->{$resID};
  241:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  242:             $result.=&Apache::loncommon::start_data_table_row();
  243:             if ($checkboxes) {
  244:                 if (exists($partsseen{$partID})) {
  245:                     $result.="<td>&nbsp;</td>";
  246:                 } else {
  247:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  248:                 }
  249:                 $partsseen{$partID}=1;
  250:             }
  251:             my $display_part=&get_display_part($partID,$symb);
  252:             $result.='<td>'.$display_part.'</td>'
  253:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  254:                     .'<td>'.&mt($responsetype).'</td>'
  255: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
  256:                     .&Apache::loncommon::end_data_table_row();
  257:         }
  258:     }
  259:     $result.=&Apache::loncommon::end_data_table();
  260:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  261: }
  262: 
  263: sub reset_caches {
  264:     &reset_analyze_cache();
  265:     &reset_perm();
  266: }
  267: 
  268: {
  269:     my %analyze_cache;
  270:     my %analyze_cache_formkeys;
  271: 
  272:     sub reset_analyze_cache {
  273: 	undef(%analyze_cache);
  274:         undef(%analyze_cache_formkeys);
  275:     }
  276: 
  277:     sub get_analyze {
  278: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  279: 	my $key = "$symb\0$uname\0$udom";
  280:         if ($type eq 'randomizetry') {
  281:             if ($trial ne '') {
  282:                 $key .= "\0".$trial;
  283:             }
  284:         }
  285: 	if (exists($analyze_cache{$key})) {
  286:             my $getupdate = 0;
  287:             if (ref($add_to_hash) eq 'HASH') {
  288:                 foreach my $item (keys(%{$add_to_hash})) {
  289:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  290:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  291:                             $getupdate = 1;
  292:                             last;
  293:                         }
  294:                     } else {
  295:                         $getupdate = 1;
  296:                     }
  297:                 }
  298:             }
  299:             if (!$getupdate) {
  300:                 return $analyze_cache{$key};
  301:             }
  302:         }
  303: 
  304: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  305: 	$url=&Apache::lonnet::clutter($url);
  306:         my %form = ('grade_target'      => 'analyze',
  307:                     'grade_domain'      => $udom,
  308:                     'grade_symb'        => $symb,
  309:                     'grade_courseid'    =>  $env{'request.course.id'},
  310:                     'grade_username'    => $uname,
  311:                     'grade_noincrement' => $no_increment);
  312:         if ($bubbles_per_row ne '') {
  313:             $form{'bubbles_per_row'} = $bubbles_per_row;
  314:         }
  315:         if ($type eq 'randomizetry') {
  316:             $form{'grade_questiontype'} = $type;
  317:             if ($rndseed ne '') {
  318:                 $form{'grade_rndseed'} = $rndseed;
  319:             }
  320:         }
  321:         if (ref($add_to_hash)) {
  322:             %form = (%form,%{$add_to_hash});
  323:         }
  324: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  325: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  326: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  327:         if (ref($add_to_hash) eq 'HASH') {
  328:             $analyze_cache_formkeys{$key} = $add_to_hash;
  329:         } else {
  330:             $analyze_cache_formkeys{$key} = {};
  331:         }
  332: 	return $analyze_cache{$key} = \%analyze;
  333:     }
  334: 
  335:     sub get_order {
  336: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  337: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  338: 	return $analyze->{"$partid.$respid.shown"};
  339:     }
  340: 
  341:     sub get_radiobutton_correct_foil {
  342: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  343: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  344:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  345:         if (ref($foils) eq 'ARRAY') {
  346: 	    foreach my $foil (@{$foils}) {
  347: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  348: 		    return $foil;
  349: 	        }
  350: 	    }
  351: 	}
  352:     }
  353: 
  354:     sub scantron_partids_tograde {
  355:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  356:         my (%analysis,@parts);
  357:         if (ref($resource)) {
  358:             my $symb = $resource->symb();
  359:             my $add_to_form;
  360:             if ($check_for_randomlist) {
  361:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  362:             }
  363:             my $analyze =
  364:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  365:                              undef,undef,undef,$bubbles_per_row);
  366:             if (ref($analyze) eq 'HASH') {
  367:                 %analysis = %{$analyze};
  368:             }
  369:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  370:                 foreach my $part (@{$analysis{'parts'}}) {
  371:                     my ($id,$respid) = split(/\./,$part);
  372:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  373:                         push(@parts,$part);
  374:                     }
  375:                 }
  376:             }
  377:         }
  378:         return (\%analysis,\@parts);
  379:     }
  380: 
  381: }
  382: 
  383: #--- Clean response type for display
  384: #--- Currently filters option/rank/radiobutton/match/essay/Task
  385: #        response types only.
  386: sub cleanRecord {
  387:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  388: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  389:     my $grayFont = '<span class="LC_internal_info">';
  390:     if ($response =~ /^(option|rank)$/) {
  391: 	my %answer=&Apache::lonnet::str2hash($answer);
  392: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  393: 	my ($toprow,$bottomrow);
  394: 	foreach my $foil (@$order) {
  395: 	    if ($grading{$foil} == 1) {
  396: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  397: 	    } else {
  398: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  399: 	    }
  400: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  401: 	}
  402: 	return '<blockquote><table border="1">'.
  403: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  404: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  405: 	    $bottomrow.'</tr></table></blockquote>';
  406:     } elsif ($response eq 'match') {
  407: 	my %answer=&Apache::lonnet::str2hash($answer);
  408: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  409: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  410: 	my ($toprow,$middlerow,$bottomrow);
  411: 	foreach my $foil (@$order) {
  412: 	    my $item=shift(@items);
  413: 	    if ($grading{$foil} == 1) {
  414: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  415: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  416: 	    } else {
  417: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  418: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  419: 	    }
  420: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  421: 	}
  422: 	return '<blockquote><table border="1">'.
  423: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  424: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  425: 	    $middlerow.'</tr>'.
  426: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  427: 	    $bottomrow.'</tr></table></blockquote>';
  428:     } elsif ($response eq 'radiobutton') {
  429: 	my %answer=&Apache::lonnet::str2hash($answer);
  430: 	my ($toprow,$bottomrow);
  431: 	my $correct = 
  432: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  433: 	foreach my $foil (@$order) {
  434: 	    if (exists($answer{$foil})) {
  435: 		if ($foil eq $correct) {
  436: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  437: 		} else {
  438: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  439: 		}
  440: 	    } else {
  441: 		$toprow.='<td>'.&mt('false').'</td>';
  442: 	    }
  443: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  444: 	}
  445: 	return '<blockquote><table border="1">'.
  446: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  447: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  448: 	    $bottomrow.'</tr></table></blockquote>';
  449:     } elsif ($response eq 'essay') {
  450: 	if (! exists ($env{'form.'.$symb})) {
  451: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  452: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  453: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  454: 
  455: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  456: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  457: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  458: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  459: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  460: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  461: 	}
  462: 	$answer =~ s-\n-<br />-g;
  463: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  464:     } elsif ( $response eq 'organic') {
  465: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  466: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  467: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  468: 	return $result;
  469:     } elsif ( $response eq 'Task') {
  470: 	if ( $answer eq 'SUBMITTED') {
  471: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  472: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  473: 	    return $result;
  474: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  475: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  476: 			       keys(%{$record}));
  477: 	    return join('<br />',($version,@matches));
  478: 			       
  479: 			       
  480: 	} else {
  481: 	    my $result =
  482: 		'<p>'
  483: 		.&mt('Overall result: [_1]',
  484: 		     $record->{$version."resource.$respid.$partid.status"})
  485: 		.'</p>';
  486: 	    
  487: 	    $result .= '<ul>';
  488: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  489: 			     keys(%{$record}));
  490: 	    foreach my $grade (sort(@grade)) {
  491: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  492: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  493: 				     $dim, $record->{$grade}).
  494: 			  '</li>';
  495: 	    }
  496: 	    $result.='</ul>';
  497: 	    return $result;
  498: 	}
  499:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  500: 	$answer = 
  501: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  502: 							      $answer);
  503:     }
  504:     return $answer;
  505: }
  506: 
  507: #-- A couple of common js functions
  508: sub commonJSfunctions {
  509:     my $request = shift;
  510:     $request->print(<<COMMONJSFUNCTIONS);
  511: <script type="text/javascript" language="javascript">
  512:     function radioSelection(radioButton) {
  513: 	var selection=null;
  514: 	if (radioButton.length > 1) {
  515: 	    for (var i=0; i<radioButton.length; i++) {
  516: 		if (radioButton[i].checked) {
  517: 		    return radioButton[i].value;
  518: 		}
  519: 	    }
  520: 	} else {
  521: 	    if (radioButton.checked) return radioButton.value;
  522: 	}
  523: 	return selection;
  524:     }
  525: 
  526:     function pullDownSelection(selectOne) {
  527: 	var selection="";
  528: 	if (selectOne.length > 1) {
  529: 	    for (var i=0; i<selectOne.length; i++) {
  530: 		if (selectOne[i].selected) {
  531: 		    return selectOne[i].value;
  532: 		}
  533: 	    }
  534: 	} else {
  535:             // only one value it must be the selected one
  536: 	    return selectOne.value;
  537: 	}
  538:     }
  539: </script>
  540: COMMONJSFUNCTIONS
  541: }
  542: 
  543: #--- Dumps the class list with usernames,list of sections,
  544: #--- section, ids and fullnames for each user.
  545: sub getclasslist {
  546:     my ($getsec,$filterlist,$getgroup) = @_;
  547:     my @getsec;
  548:     my @getgroup;
  549:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  550:     if (!ref($getsec)) {
  551: 	if ($getsec ne '' && $getsec ne 'all') {
  552: 	    @getsec=($getsec);
  553: 	}
  554:     } else {
  555: 	@getsec=@{$getsec};
  556:     }
  557:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  558:     if (!ref($getgroup)) {
  559: 	if ($getgroup ne '' && $getgroup ne 'all') {
  560: 	    @getgroup=($getgroup);
  561: 	}
  562:     } else {
  563: 	@getgroup=@{$getgroup};
  564:     }
  565:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  566: 
  567:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  568:     # Bail out if we were unable to get the classlist
  569:     return if (! defined($classlist));
  570:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  571:     #
  572:     my %sections;
  573:     my %fullnames;
  574:     foreach my $student (keys(%$classlist)) {
  575:         my $end      = 
  576:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  577:         my $start    = 
  578:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  579:         my $id       = 
  580:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  581:         my $section  = 
  582:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  583:         my $fullname = 
  584:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  585:         my $status   = 
  586:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  587:         my $group   = 
  588:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  589: 	# filter students according to status selected
  590: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  591: 	    if (!($stu_status =~ $status)) {
  592: 		delete($classlist->{$student});
  593: 		next;
  594: 	    }
  595: 	}
  596: 	# filter students according to groups selected
  597: 	my @stu_groups = split(/,/,$group);
  598: 	if (@getgroup) {
  599: 	    my $exclude = 1;
  600: 	    foreach my $grp (@getgroup) {
  601: 	        foreach my $stu_group (@stu_groups) {
  602: 	            if ($stu_group eq $grp) {
  603: 	                $exclude = 0;
  604:     	            } 
  605: 	        }
  606:     	        if (($grp eq 'none') && !$group) {
  607:         	        $exclude = 0;
  608:         	}
  609: 	    }
  610: 	    if ($exclude) {
  611: 	        delete($classlist->{$student});
  612: 	    }
  613: 	}
  614: 	$section = ($section ne '' ? $section : 'none');
  615: 	if (&canview($section)) {
  616: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  617: 		$sections{$section}++;
  618: 		if ($classlist->{$student}) {
  619: 		    $fullnames{$student}=$fullname;
  620: 		}
  621: 	    } else {
  622: 		delete($classlist->{$student});
  623: 	    }
  624: 	} else {
  625: 	    delete($classlist->{$student});
  626: 	}
  627:     }
  628:     my %seen = ();
  629:     my @sections = sort(keys(%sections));
  630:     return ($classlist,\@sections,\%fullnames);
  631: }
  632: 
  633: sub canmodify {
  634:     my ($sec)=@_;
  635:     if ($perm{'mgr'}) {
  636: 	if (!defined($perm{'mgr_section'})) {
  637: 	    # can modify whole class
  638: 	    return 1;
  639: 	} else {
  640: 	    if ($sec eq $perm{'mgr_section'}) {
  641: 		#can modify the requested section
  642: 		return 1;
  643: 	    } else {
  644: 		# can't modify the request section
  645: 		return 0;
  646: 	    }
  647: 	}
  648:     }
  649:     #can't modify
  650:     return 0;
  651: }
  652: 
  653: sub canview {
  654:     my ($sec)=@_;
  655:     if ($perm{'vgr'}) {
  656: 	if (!defined($perm{'vgr_section'})) {
  657: 	    # can modify whole class
  658: 	    return 1;
  659: 	} else {
  660: 	    if ($sec eq $perm{'vgr_section'}) {
  661: 		#can modify the requested section
  662: 		return 1;
  663: 	    } else {
  664: 		# can't modify the request section
  665: 		return 0;
  666: 	    }
  667: 	}
  668:     }
  669:     #can't modify
  670:     return 0;
  671: }
  672: 
  673: #--- Retrieve the grade status of a student for all the parts
  674: sub student_gradeStatus {
  675:     my ($symb,$udom,$uname,$partlist) = @_;
  676:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  677:     my %partstatus = ();
  678:     foreach (@$partlist) {
  679: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  680: 	$status              = 'nothing' if ($status eq '');
  681: 	$partstatus{$_}      = $status;
  682: 	my $subkey           = "resource.$_.submitted_by";
  683: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  684:     }
  685:     return %partstatus;
  686: }
  687: 
  688: # hidden form and javascript that calls the form
  689: # Use by verifyscript and viewgrades
  690: # Shows a student's view of problem and submission
  691: sub jscriptNform {
  692:     my ($symb) = @_;
  693:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  694:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  695: 	'    function viewOneStudent(user,domain) {'."\n".
  696: 	'	document.onestudent.student.value = user;'."\n".
  697: 	'	document.onestudent.userdom.value = domain;'."\n".
  698: 	'	document.onestudent.submit();'."\n".
  699: 	'    }'."\n".
  700: 	'</script>'."\n";
  701:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  702: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  703: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  704: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  705: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  706: 	'<input type="hidden" name="command" value="submission" />'."\n".
  707: 	'<input type="hidden" name="student" value="" />'."\n".
  708: 	'<input type="hidden" name="userdom" value="" />'."\n".
  709: 	'</form>'."\n";
  710:     return $jscript;
  711: }
  712: 
  713: 
  714: 
  715: # Given the score (as a number [0-1] and the weight) what is the final
  716: # point value? This function will round to the nearest tenth, third,
  717: # or quarter if one of those is within the tolerance of .00001.
  718: sub compute_points {
  719:     my ($score, $weight) = @_;
  720:     
  721:     my $tolerance = .00001;
  722:     my $points = $score * $weight;
  723: 
  724:     # Check for nearness to 1/x.
  725:     my $check_for_nearness = sub {
  726:         my ($factor) = @_;
  727:         my $num = ($points * $factor) + $tolerance;
  728:         my $floored_num = floor($num);
  729:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  730:             return $floored_num / $factor;
  731:         }
  732:         return $points;
  733:     };
  734: 
  735:     $points = $check_for_nearness->(10);
  736:     $points = $check_for_nearness->(3);
  737:     $points = $check_for_nearness->(4);
  738:     
  739:     return $points;
  740: }
  741: 
  742: #------------------ End of general use routines --------------------
  743: 
  744: #
  745: # Find most similar essay
  746: #
  747: 
  748: sub most_similar {
  749:     my ($uname,$udom,$uessay,$old_essays)=@_;
  750: 
  751: # ignore spaces and punctuation
  752: 
  753:     $uessay=~s/\W+/ /gs;
  754: 
  755: # ignore empty submissions (occuring when only files are sent)
  756: 
  757:     unless ($uessay=~/\w+/s) { return ''; }
  758: 
  759: # these will be returned. Do not care if not at least 50 percent similar
  760:     my $limit=0.6;
  761:     my $sname='';
  762:     my $sdom='';
  763:     my $scrsid='';
  764:     my $sessay='';
  765: # go through all essays ...
  766:     foreach my $tkey (keys(%$old_essays)) {
  767: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  768: # ... except the same student
  769:         next if (($tname eq $uname) && ($tdom eq $udom));
  770: 	my $tessay=$old_essays->{$tkey};
  771: 	$tessay=~s/\W+/ /gs;
  772: # String similarity gives up if not even limit
  773: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  774: # Found one
  775: 	if ($tsimilar>$limit) {
  776: 	    $limit=$tsimilar;
  777: 	    $sname=$tname;
  778: 	    $sdom=$tdom;
  779: 	    $scrsid=$tcrsid;
  780: 	    $sessay=$old_essays->{$tkey};
  781: 	}
  782:     }
  783:     if ($limit>0.6) {
  784:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  785:     } else {
  786:        return ('','','','',0);
  787:     }
  788: }
  789: 
  790: #-------------------------------------------------------------------
  791: 
  792: #------------------------------------ Receipt Verification Routines
  793: #
  794: #--- Check whether a receipt number is valid.---
  795: sub verifyreceipt {
  796:     my $request  = shift;
  797: 
  798:     my $courseid = $env{'request.course.id'};
  799:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  800: 	$env{'form.receipt'};
  801:     $receipt     =~ s/[^\-\d]//g;
  802:     my ($symb)   = &get_symb($request);
  803: 
  804:     my $title.=
  805: 	'<h3><span class="LC_info">'.
  806: 	&mt('Verifying Receipt No. [_1]',$receipt).
  807: 	'</span></h3>'."\n".
  808: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  809: 	'</h4>'."\n";
  810: 
  811:     my ($string,$contents,$matches) = ('','',0);
  812:     my (undef,undef,$fullname) = &getclasslist('all','0');
  813:     
  814:     my $receiptparts=0;
  815:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  816: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  817:     my $parts=['0'];
  818:     if ($receiptparts) {
  819:         my $res_error; 
  820:         ($parts)=&response_type($symb,\$res_error);
  821:         if ($res_error) {
  822:             return &navmap_errormsg();
  823:         } 
  824:     }
  825:     
  826:     my $header = 
  827: 	&Apache::loncommon::start_data_table().
  828: 	&Apache::loncommon::start_data_table_header_row().
  829: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  830: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  831: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  832:     if ($receiptparts) {
  833: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  834:     }
  835:     $header.=
  836: 	&Apache::loncommon::end_data_table_header_row();
  837: 
  838:     foreach (sort 
  839: 	     {
  840: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  841: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  842: 		 }
  843: 		 return $a cmp $b;
  844: 	     } (keys(%$fullname))) {
  845: 	my ($uname,$udom)=split(/\:/);
  846: 	foreach my $part (@$parts) {
  847: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  848: 		$contents.=
  849: 		    &Apache::loncommon::start_data_table_row().
  850: 		    '<td>&nbsp;'."\n".
  851: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  852: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  853: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  854: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  855: 		if ($receiptparts) {
  856: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  857: 		}
  858: 		$contents.= 
  859: 		    &Apache::loncommon::end_data_table_row()."\n";
  860: 		
  861: 		$matches++;
  862: 	    }
  863: 	}
  864:     }
  865:     if ($matches == 0) {
  866:         $string = $title
  867:                  .'<p class="LC_warning">'
  868:                  .&mt('No match found for the above receipt number.')
  869:                  .'</p>';
  870:     } else {
  871: 	$string = &jscriptNform($symb).$title.
  872: 	    '<p>'.
  873: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  874: 	    '</p>'.
  875: 	    $header.
  876: 	    $contents.
  877: 	    &Apache::loncommon::end_data_table()."\n";
  878:     }
  879:     return $string.&show_grading_menu_form($symb);
  880: }
  881: 
  882: #--- This is called by a number of programs.
  883: #--- Called from the Grading Menu - View/Grade an individual student
  884: #--- Also called directly when one clicks on the subm button 
  885: #    on the problem page.
  886: sub listStudents {
  887:     my ($request) = shift;
  888: 
  889:     my ($symb) = &get_symb($request);
  890:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  891:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  892:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  893:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  894:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  895:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  896:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  897: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  898: 
  899:     my $result='<h3><span class="LC_info">&nbsp;'
  900: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  901: 	.'</span></h3>';
  902: 
  903:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  904: 
  905:     my %lt = &Apache::lonlocal::texthash (
  906: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  907: 		'single'   => 'Please select the student before clicking on the Next button.',
  908: 	     );
  909:     $request->print(<<LISTJAVASCRIPT);
  910: <script type="text/javascript" language="javascript">
  911:     function checkSelect(checkBox) {
  912: 	var ctr=0;
  913: 	var sense="";
  914: 	if (checkBox.length > 1) {
  915: 	    for (var i=0; i<checkBox.length; i++) {
  916: 		if (checkBox[i].checked) {
  917: 		    ctr++;
  918: 		}
  919: 	    }
  920: 	    sense = '$lt{'multiple'}';
  921: 	} else {
  922: 	    if (checkBox.checked) {
  923: 		ctr = 1;
  924: 	    }
  925: 	    sense = '$lt{'single'}';
  926: 	}
  927: 	if (ctr == 0) {
  928: 	    alert(sense);
  929: 	    return false;
  930: 	}
  931: 	document.gradesub.submit();
  932:     }
  933: 
  934:     function reLoadList(formname) {
  935: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  936: 	formname.command.value = 'submission';
  937: 	formname.submit();
  938:     }
  939: </script>
  940: LISTJAVASCRIPT
  941: 
  942:     &commonJSfunctions($request);
  943:     $request->print($result);
  944: 
  945:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  946:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  947:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  948: 	"\n".$table;
  949: 	
  950:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  951:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  952:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  953:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  954:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  955:                   .&Apache::lonhtmlcommon::row_closure();
  956:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  957:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  958:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  959:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  960:                   .&Apache::lonhtmlcommon::row_closure();
  961: 
  962:     my $submission_options;
  963:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  964: 	$submission_options.=
  965: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  966:     }
  967:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  968:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  969:     $env{'form.Status'} = $saveStatus;
  970:     $submission_options.=
  971:         '<span class="LC_nobreak">'.
  972:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  973:         &mt('last submission only').' </label></span>'."\n".
  974:         '<span class="LC_nobreak">'.
  975:         '<label><input type="radio" name="lastSub" value="last" /> '.
  976:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  977:         '<span class="LC_nobreak">'.
  978:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  979:         &mt('by dates and submissions').'</label></span>'."\n".
  980:         '<span class="LC_nobreak">'.
  981:         '<label><input type="radio" name="lastSub" value="all" /> '.
  982:         &mt('all details').'</label></span>';
  983:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  984:                   .$submission_options
  985:                   .&Apache::lonhtmlcommon::row_closure();
  986: 
  987:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  988:                   .'<select name="increment">'
  989:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  990:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  991:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  992:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  993:                   .'</select>'
  994:                   .&Apache::lonhtmlcommon::row_closure();
  995: 
  996:     $gradeTable .= 
  997:         &build_section_inputs().
  998: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  999: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1000: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1001: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1002: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1003: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1004: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1005: 
 1006:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1007: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1008:     } else {
 1009:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1010:                       .&Apache::lonhtmlcommon::StatusOptions(
 1011:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1012:                       .&Apache::lonhtmlcommon::row_closure();
 1013:     }
 1014: 
 1015:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1016:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1017:                   .&Apache::lonhtmlcommon::row_closure(1)
 1018:                   .&Apache::lonhtmlcommon::end_pick_box();
 1019: 
 1020:     $gradeTable .= '<p>'
 1021:                   .&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"
 1022:                   .'<input type="hidden" name="command" value="processGroup" />'
 1023:                   .'</p>';
 1024: 
 1025: # checkall buttons
 1026:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1027:     $gradeTable.='<input type="button" '."\n".
 1028:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1029:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1030:     $gradeTable.=&check_buttons();
 1031:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1032:     $gradeTable.= &Apache::loncommon::start_data_table().
 1033: 	&Apache::loncommon::start_data_table_header_row();
 1034:     my $loop = 0;
 1035:     while ($loop < 2) {
 1036: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1037: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1038: 	if ($env{'form.showgrading'} eq 'yes' 
 1039: 	    && $submitonly ne 'queued'
 1040: 	    && $submitonly ne 'all') {
 1041: 	    foreach my $part (sort(@$partlist)) {
 1042: 		my $display_part=
 1043: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1044: 		$gradeTable.=
 1045: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1046: 	    }
 1047: 	} elsif ($submitonly eq 'queued') {
 1048: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1049: 	}
 1050: 	$loop++;
 1051: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1052:     }
 1053:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1054: 
 1055:     my $ctr = 0;
 1056:     foreach my $student (sort 
 1057: 			 {
 1058: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1059: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1060: 			     }
 1061: 			     return $a cmp $b;
 1062: 			 }
 1063: 			 (keys(%$fullname))) {
 1064: 	my ($uname,$udom) = split(/:/,$student);
 1065: 
 1066: 	my %status = ();
 1067: 
 1068: 	if ($submitonly eq 'queued') {
 1069: 	    my %queue_status = 
 1070: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1071: 							$udom,$uname);
 1072: 	    next if (!defined($queue_status{'gradingqueue'}));
 1073: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1074: 	}
 1075: 
 1076: 	if ($env{'form.showgrading'} eq 'yes' 
 1077: 	    && $submitonly ne 'queued'
 1078: 	    && $submitonly ne 'all') {
 1079: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1080: 	    my $submitted = 0;
 1081: 	    my $graded = 0;
 1082: 	    my $incorrect = 0;
 1083: 	    foreach (keys(%status)) {
 1084: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1085: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1086: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1087: 		
 1088: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1089: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1090: 		    $submitted = 0;
 1091: 		    my ($part)=split(/\./,$partid);
 1092: 		    $gradeTable.='<input type="hidden" name="'.
 1093: 			$student.':'.$part.':submitted_by" value="'.
 1094: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1095: 		}
 1096: 	    }
 1097: 	    
 1098: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1099: 				     $submitonly eq 'incorrect' ||
 1100: 				     $submitonly eq 'graded'));
 1101: 	    next if (!$graded && ($submitonly eq 'graded'));
 1102: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1103: 	}
 1104: 
 1105: 	$ctr++;
 1106: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1107:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1108: 	if ( $perm{'vgr'} eq 'F' ) {
 1109: 	    if ($ctr%2 ==1) {
 1110: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1111: 	    }
 1112: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1113:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1114:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1115: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1116: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1117: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1118: 
 1119: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1120: 		foreach (sort(keys(%status))) {
 1121: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1122: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1123: 		}
 1124: 	    }
 1125: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1126: 	    if ($ctr%2 ==0) {
 1127: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1128: 	    }
 1129: 	}
 1130:     }
 1131:     if ($ctr%2 ==1) {
 1132: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1133: 	    if ($env{'form.showgrading'} eq 'yes' 
 1134: 		&& $submitonly ne 'queued'
 1135: 		&& $submitonly ne 'all') {
 1136: 		foreach (@$partlist) {
 1137: 		    $gradeTable.='<td>&nbsp;</td>';
 1138: 		}
 1139: 	    } elsif ($submitonly eq 'queued') {
 1140: 		$gradeTable.='<td>&nbsp;</td>';
 1141: 	    }
 1142: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1143:     }
 1144: 
 1145:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1146:         '<input type="button" '.
 1147:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1148:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1149:     if ($ctr == 0) {
 1150: 	my $num_students=(scalar(keys(%$fullname)));
 1151: 	if ($num_students eq 0) {
 1152: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1153: 	} else {
 1154: 	    my $submissions='submissions';
 1155: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1156: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1157: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1158: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1159: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1160: 		    $num_students).
 1161: 		'</span><br />';
 1162: 	}
 1163:     } elsif ($ctr == 1) {
 1164: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1165:     }
 1166:     $gradeTable.=&show_grading_menu_form($symb);
 1167:     $request->print($gradeTable);
 1168:     return '';
 1169: }
 1170: 
 1171: #---- Called from the listStudents routine
 1172: 
 1173: sub check_script {
 1174:     my ($form, $type)=@_;
 1175:     my $chkallscript='<script type="text/javascript">
 1176:     function checkall() {
 1177:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1178:             ele = document.forms.'.$form.'.elements[i];
 1179:             if (ele.name == "'.$type.'") {
 1180:             document.forms.'.$form.'.elements[i].checked=true;
 1181:                                        }
 1182:         }
 1183:     }
 1184: 
 1185:     function checksec() {
 1186:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1187:             ele = document.forms.'.$form.'.elements[i];
 1188:            string = document.forms.'.$form.'.chksec.value;
 1189:            if
 1190:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1191:               document.forms.'.$form.'.elements[i].checked=true;
 1192:             }
 1193:         }
 1194:     }
 1195: 
 1196: 
 1197:     function uncheckall() {
 1198:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1199:             ele = document.forms.'.$form.'.elements[i];
 1200:             if (ele.name == "'.$type.'") {
 1201:             document.forms.'.$form.'.elements[i].checked=false;
 1202:                                        }
 1203:         }
 1204:     }
 1205: 
 1206: </script>'."\n";
 1207:     return $chkallscript;
 1208: }
 1209: 
 1210: sub check_buttons {
 1211:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1212:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1213:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1214:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1215:     return $buttons;
 1216: }
 1217: 
 1218: #     Displays the submissions for one student or a group of students
 1219: sub processGroup {
 1220:     my ($request)  = shift;
 1221:     my $ctr        = 0;
 1222:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1223:     my $total      = scalar(@stuchecked)-1;
 1224: 
 1225:     foreach my $student (@stuchecked) {
 1226: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1227: 	$env{'form.student'}        = $uname;
 1228: 	$env{'form.userdom'}        = $udom;
 1229: 	$env{'form.fullname'}       = $fullname;
 1230: 	&submission($request,$ctr,$total);
 1231: 	$ctr++;
 1232:     }
 1233:     return '';
 1234: }
 1235: 
 1236: #------------------------------------------------------------------------------------
 1237: #
 1238: #-------------------------- Next few routines handles grading by student, essentially
 1239: #                           handles essay response type problem/part
 1240: #
 1241: #--- Javascript to handle the submission page functionality ---
 1242: sub sub_page_js {
 1243:     my $request = shift;
 1244: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1245:     $request->print(<<SUBJAVASCRIPT);
 1246: <script type="text/javascript" language="javascript">
 1247:     function updateRadio(formname,id,weight) {
 1248: 	var gradeBox = formname["GD_BOX"+id];
 1249: 	var radioButton = formname["RADVAL"+id];
 1250: 	var oldpts = formname["oldpts"+id].value;
 1251: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1252: 	gradeBox.value = pts;
 1253: 	var resetbox = false;
 1254: 	if (isNaN(pts) || pts < 0) {
 1255: 	    alert("$alertmsg"+pts);
 1256: 	    for (var i=0; i<radioButton.length; i++) {
 1257: 		if (radioButton[i].checked) {
 1258: 		    gradeBox.value = i;
 1259: 		    resetbox = true;
 1260: 		}
 1261: 	    }
 1262: 	    if (!resetbox) {
 1263: 		formtextbox.value = "";
 1264: 	    }
 1265: 	    return;
 1266: 	}
 1267: 
 1268: 	if (pts > weight) {
 1269: 	    var resp = confirm("You entered a value ("+pts+
 1270: 			       ") greater than the weight for the part. Accept?");
 1271: 	    if (resp == false) {
 1272: 		gradeBox.value = oldpts;
 1273: 		return;
 1274: 	    }
 1275: 	}
 1276: 
 1277: 	for (var i=0; i<radioButton.length; i++) {
 1278: 	    radioButton[i].checked=false;
 1279: 	    if (pts == i && pts != "") {
 1280: 		radioButton[i].checked=true;
 1281: 	    }
 1282: 	}
 1283: 	updateSelect(formname,id);
 1284: 	formname["stores"+id].value = "0";
 1285:     }
 1286: 
 1287:     function writeBox(formname,id,pts) {
 1288: 	var gradeBox = formname["GD_BOX"+id];
 1289: 	if (checkSolved(formname,id) == 'update') {
 1290: 	    gradeBox.value = pts;
 1291: 	} else {
 1292: 	    var oldpts = formname["oldpts"+id].value;
 1293: 	    gradeBox.value = oldpts;
 1294: 	    var radioButton = formname["RADVAL"+id];
 1295: 	    for (var i=0; i<radioButton.length; i++) {
 1296: 		radioButton[i].checked=false;
 1297: 		if (i == oldpts) {
 1298: 		    radioButton[i].checked=true;
 1299: 		}
 1300: 	    }
 1301: 	}
 1302: 	formname["stores"+id].value = "0";
 1303: 	updateSelect(formname,id);
 1304: 	return;
 1305:     }
 1306: 
 1307:     function clearRadBox(formname,id) {
 1308: 	if (checkSolved(formname,id) == 'noupdate') {
 1309: 	    updateSelect(formname,id);
 1310: 	    return;
 1311: 	}
 1312: 	gradeSelect = formname["GD_SEL"+id];
 1313: 	for (var i=0; i<gradeSelect.length; i++) {
 1314: 	    if (gradeSelect[i].selected) {
 1315: 		var selectx=i;
 1316: 	    }
 1317: 	}
 1318: 	var stores = formname["stores"+id];
 1319: 	if (selectx == stores.value) { return };
 1320: 	var gradeBox = formname["GD_BOX"+id];
 1321: 	gradeBox.value = "";
 1322: 	var radioButton = formname["RADVAL"+id];
 1323: 	for (var i=0; i<radioButton.length; i++) {
 1324: 	    radioButton[i].checked=false;
 1325: 	}
 1326: 	stores.value = selectx;
 1327:     }
 1328: 
 1329:     function checkSolved(formname,id) {
 1330: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1331: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1332: 	    if (!reply) {return "noupdate";}
 1333: 	    formname.overRideScore.value = 'yes';
 1334: 	}
 1335: 	return "update";
 1336:     }
 1337: 
 1338:     function updateSelect(formname,id) {
 1339: 	formname["GD_SEL"+id][0].selected = true;
 1340: 	return;
 1341:     }
 1342: 
 1343: //=========== Check that a point is assigned for all the parts  ============
 1344:     function checksubmit(formname,val,total,parttot) {
 1345: 	formname.gradeOpt.value = val;
 1346: 	if (val == "Save & Next") {
 1347: 	    for (i=0;i<=total;i++) {
 1348: 		for (j=0;j<parttot;j++) {
 1349: 		    var partid = formname["partid"+i+"_"+j].value;
 1350: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1351: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1352: 			if (points == "") {
 1353: 			    var name = formname["name"+i].value;
 1354: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1355: 			    var resp = confirm("You did not assign a score for "+studentID+
 1356: 					       ", part "+partid+". Continue?");
 1357: 			    if (resp == false) {
 1358: 				formname["GD_BOX"+i+"_"+partid].focus();
 1359: 				return false;
 1360: 			    }
 1361: 			}
 1362: 		    }
 1363: 		    
 1364: 		}
 1365: 	    }
 1366: 	    
 1367: 	}
 1368: 	if (val == "Grade Student") {
 1369: 	    formname.showgrading.value = "yes";
 1370: 	    if (formname.Status.value == "") {
 1371: 		formname.Status.value = "Active";
 1372: 	    }
 1373: 	    formname.studentNo.value = total;
 1374: 	}
 1375: 	formname.submit();
 1376:     }
 1377: 
 1378: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1379:     function checkSubmitPage(formname,total) {
 1380: 	noscore = new Array(100);
 1381: 	var ptr = 0;
 1382: 	for (i=1;i<total;i++) {
 1383: 	    var partid = formname["q_"+i].value;
 1384: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1385: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1386: 		var status = formname["solved"+i+"_"+partid].value;
 1387: 		if (points == "" && status != "correct_by_student") {
 1388: 		    noscore[ptr] = i;
 1389: 		    ptr++;
 1390: 		}
 1391: 	    }
 1392: 	}
 1393: 	if (ptr != 0) {
 1394: 	    var sense = ptr == 1 ? ": " : "s: ";
 1395: 	    var prolist = "";
 1396: 	    if (ptr == 1) {
 1397: 		prolist = noscore[0];
 1398: 	    } else {
 1399: 		var i = 0;
 1400: 		while (i < ptr-1) {
 1401: 		    prolist += noscore[i]+", ";
 1402: 		    i++;
 1403: 		}
 1404: 		prolist += "and "+noscore[i];
 1405: 	    }
 1406: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1407: 	    if (resp == false) {
 1408: 		return false;
 1409: 	    }
 1410: 	}
 1411: 
 1412: 	formname.submit();
 1413:     }
 1414: </script>
 1415: SUBJAVASCRIPT
 1416: }
 1417: 
 1418: #--- javascript for essay type problem --
 1419: sub sub_page_kw_js {
 1420:     my $request = shift;
 1421:     my $iconpath = $request->dir_config('lonIconsURL');
 1422:     &commonJSfunctions($request);
 1423: 
 1424:     my $inner_js_msg_central=<<INNERJS;
 1425:     <script text="text/javascript">
 1426:     function checkInput() {
 1427:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1428:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1429:       var usrctr = document.msgcenter.usrctr.value;
 1430:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1431:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1432: 
 1433:       var msgchk = "";
 1434:       if (document.msgcenter.subchk.checked) {
 1435:          msgchk = "msgsub,";
 1436:       }
 1437:       var includemsg = 0;
 1438:       for (var i=1; i<=nmsg; i++) {
 1439:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1440:           var frmmsg = document.msgcenter["msg"+i];
 1441:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1442:           var showflg = opener.document.SCORE["shownOnce"+i];
 1443:           showflg.value = "1";
 1444:           var chkbox = document.msgcenter["msgn"+i];
 1445:           if (chkbox.checked) {
 1446:              msgchk += "savemsg"+i+",";
 1447:              includemsg = 1;
 1448:           }
 1449:       }
 1450:       if (document.msgcenter.newmsgchk.checked) {
 1451:          msgchk += "newmsg"+usrctr;
 1452:          includemsg = 1;
 1453:       }
 1454:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1455:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1456:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1457:       includemsg.value = msgchk;
 1458: 
 1459:       self.close()
 1460: 
 1461:     }
 1462:     </script>
 1463: INNERJS
 1464: 
 1465:     my $inner_js_highlight_central=<<INNERJS;
 1466:  <script type="text/javascript">
 1467:     function updateChoice(flag) {
 1468:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1469:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1470:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1471:       opener.document.SCORE.refresh.value = "on";
 1472:       if (opener.document.SCORE.keywords.value!=""){
 1473:          opener.document.SCORE.submit();
 1474:       }
 1475:       self.close()
 1476:     }
 1477: </script>
 1478: INNERJS
 1479: 
 1480:     my $start_page_msg_central = 
 1481:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1482: 				       {'js_ready'  => 1,
 1483: 					'only_body' => 1,
 1484: 					'bgcolor'   =>'#FFFFFF',});
 1485:     my $end_page_msg_central = 
 1486: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1487: 
 1488: 
 1489:     my $start_page_highlight_central = 
 1490:         &Apache::loncommon::start_page('Highlight Central',
 1491: 				       $inner_js_highlight_central,
 1492: 				       {'js_ready'  => 1,
 1493: 					'only_body' => 1,
 1494: 					'bgcolor'   =>'#FFFFFF',});
 1495:     my $end_page_highlight_central = 
 1496: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1497: 
 1498:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1499:     $docopen=~s/^document\.//;
 1500:     my %lt = &Apache::lonlocal::texthash(
 1501:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1502:                 plse => 'Please select a word or group of words from document and then click this link.',
 1503:                 adds => 'Add selection to keyword list? Edit if desired.',
 1504:                 comp => 'Compose Message for: ',
 1505:                 incl => 'Include',
 1506:                 type => 'Type',
 1507:                 subj => 'Subject',
 1508:                 mesa => 'Message',
 1509:                 new  => 'New',
 1510:                 save => 'Save',
 1511:                 canc => 'Cancel',
 1512:                 kehi => 'Keyword Highlight Options',
 1513:                 txtc => 'Text Color',
 1514:                 font => 'Font Size',
 1515:                 fnst => 'Font Style',
 1516:              );
 1517:     $request->print(<<SUBJAVASCRIPT);
 1518: <script type="text/javascript" language="javascript">
 1519: 
 1520: //===================== Show list of keywords ====================
 1521:   function keywords(formname) {
 1522:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1523:     if (nret==null) return;
 1524:     formname.keywords.value = nret;
 1525: 
 1526:     if (formname.keywords.value != "") {
 1527: 	formname.refresh.value = "on";
 1528: 	formname.submit();
 1529:     }
 1530:     return;
 1531:   }
 1532: 
 1533: //===================== Script to view submitted by ==================
 1534:   function viewSubmitter(submitter) {
 1535:     document.SCORE.refresh.value = "on";
 1536:     document.SCORE.NCT.value = "1";
 1537:     document.SCORE.unamedom0.value = submitter;
 1538:     document.SCORE.submit();
 1539:     return;
 1540:   }
 1541: 
 1542: //===================== Script to add keyword(s) ==================
 1543:   function getSel() {
 1544:     if (document.getSelection) txt = document.getSelection();
 1545:     else if (document.selection) txt = document.selection.createRange().text;
 1546:     else return;
 1547:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1548:     if (cleantxt=="") {
 1549: 	alert("$lt{'plse'}");
 1550: 	return;
 1551:     }
 1552:     var nret = prompt("$lt{'adds'}",cleantxt);
 1553:     if (nret==null) return;
 1554:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1555:     if (document.SCORE.keywords.value != "") {
 1556: 	document.SCORE.refresh.value = "on";
 1557: 	document.SCORE.submit();
 1558:     }
 1559:     return;
 1560:   }
 1561: 
 1562: //====================== Script for composing message ==============
 1563:    // preload images
 1564:    img1 = new Image();
 1565:    img1.src = "$iconpath/mailbkgrd.gif";
 1566:    img2 = new Image();
 1567:    img2.src = "$iconpath/mailto.gif";
 1568: 
 1569:   function msgCenter(msgform,usrctr,fullname) {
 1570:     var Nmsg  = msgform.savemsgN.value;
 1571:     savedMsgHeader(Nmsg,usrctr,fullname);
 1572:     var subject = msgform.msgsub.value;
 1573:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1574:     re = /msgsub/;
 1575:     var shwsel = "";
 1576:     if (re.test(msgchk)) { shwsel = "checked" }
 1577:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1578:     displaySubject(checkEntities(subject),shwsel);
 1579:     for (var i=1; i<=Nmsg; i++) {
 1580: 	var testmsg = "savemsg"+i+",";
 1581: 	re = new RegExp(testmsg,"g");
 1582: 	shwsel = "";
 1583: 	if (re.test(msgchk)) { shwsel = "checked" }
 1584: 	var message = document.SCORE["savemsg"+i].value;
 1585: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1586: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1587: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1588:     }
 1589:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1590:     shwsel = "";
 1591:     re = /newmsg/;
 1592:     if (re.test(msgchk)) { shwsel = "checked" }
 1593:     newMsg(newmsg,shwsel);
 1594:     msgTail(); 
 1595:     return;
 1596:   }
 1597: 
 1598:   function checkEntities(strx) {
 1599:     if (strx.length == 0) return strx;
 1600:     var orgStr = ["&", "<", ">", '"']; 
 1601:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1602:     var counter = 0;
 1603:     while (counter < 4) {
 1604: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1605: 	counter++;
 1606:     }
 1607:     return strx;
 1608:   }
 1609: 
 1610:   function strReplace(strx, orgStr, newStr) {
 1611:     return strx.split(orgStr).join(newStr);
 1612:   }
 1613: 
 1614:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1615:     var height = 70*Nmsg+250;
 1616:     if (height > 600) {
 1617: 	height = 600;
 1618:     }
 1619:     var xpos = (screen.width-600)/2;
 1620:     xpos = (xpos < 0) ? '0' : xpos;
 1621:     var ypos = (screen.height-height)/2-30;
 1622:     ypos = (ypos < 0) ? '0' : ypos;
 1623: 
 1624:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1625:     pWin.focus();
 1626:     pDoc = pWin.document;
 1627:     pDoc.$docopen;
 1628:     pDoc.write('$start_page_msg_central');
 1629: 
 1630:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1631:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1632:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1633: 
 1634:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1635:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1636:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1637: }
 1638:     function displaySubject(msg,shwsel) {
 1639:     pDoc = pWin.document;
 1640:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1641:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1642:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1643:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1644: }
 1645: 
 1646:   function displaySavedMsg(ctr,msg,shwsel) {
 1647:     pDoc = pWin.document;
 1648:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1649:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1650:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1651:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1652: }
 1653: 
 1654:   function newMsg(newmsg,shwsel) {
 1655:     pDoc = pWin.document;
 1656:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1657:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1658:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1659:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1660: }
 1661: 
 1662:   function msgTail() {
 1663:     pDoc = pWin.document;
 1664:     pDoc.write("<\\/table>");
 1665:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1666:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1667:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1668:     pDoc.write("<\\/form>");
 1669:     pDoc.write('$end_page_msg_central');
 1670:     pDoc.close();
 1671: }
 1672: 
 1673: //====================== Script for keyword highlight options ==============
 1674:   function kwhighlight() {
 1675:     var kwclr    = document.SCORE.kwclr.value;
 1676:     var kwsize   = document.SCORE.kwsize.value;
 1677:     var kwstyle  = document.SCORE.kwstyle.value;
 1678:     var redsel = "";
 1679:     var grnsel = "";
 1680:     var blusel = "";
 1681:     if (kwclr=="red")   {var redsel="checked"};
 1682:     if (kwclr=="green") {var grnsel="checked"};
 1683:     if (kwclr=="blue")  {var blusel="checked"};
 1684:     var sznsel = "";
 1685:     var sz1sel = "";
 1686:     var sz2sel = "";
 1687:     if (kwsize=="0")  {var sznsel="checked"};
 1688:     if (kwsize=="+1") {var sz1sel="checked"};
 1689:     if (kwsize=="+2") {var sz2sel="checked"};
 1690:     var synsel = "";
 1691:     var syisel = "";
 1692:     var sybsel = "";
 1693:     if (kwstyle=="")    {var synsel="checked"};
 1694:     if (kwstyle=="<i>") {var syisel="checked"};
 1695:     if (kwstyle=="<b>") {var sybsel="checked"};
 1696:     highlightCentral();
 1697:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1698:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1699:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1700:     highlightend();
 1701:     return;
 1702:   }
 1703: 
 1704:   function highlightCentral() {
 1705: //    if (window.hwdWin) window.hwdWin.close();
 1706:     var xpos = (screen.width-400)/2;
 1707:     xpos = (xpos < 0) ? '0' : xpos;
 1708:     var ypos = (screen.height-330)/2-30;
 1709:     ypos = (ypos < 0) ? '0' : ypos;
 1710: 
 1711:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1712:     hwdWin.focus();
 1713:     var hDoc = hwdWin.document;
 1714:     hDoc.$docopen;
 1715:     hDoc.write('$start_page_highlight_central');
 1716:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1717:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1718: 
 1719:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1720:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1721:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1722:   }
 1723: 
 1724:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1725:     var hDoc = hwdWin.document;
 1726:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1727:     hDoc.write("<td align=\\"left\\">");
 1728:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1729:     hDoc.write("<td align=\\"left\\">");
 1730:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1731:     hDoc.write("<td align=\\"left\\">");
 1732:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1733:     hDoc.write("<\\/tr>");
 1734:   }
 1735: 
 1736:   function highlightend() { 
 1737:     var hDoc = hwdWin.document;
 1738:     hDoc.write("<\\/table>");
 1739:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1740:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1741:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1742:     hDoc.write("<\\/form>");
 1743:     hDoc.write('$end_page_highlight_central');
 1744:     hDoc.close();
 1745:   }
 1746: 
 1747: </script>
 1748: SUBJAVASCRIPT
 1749: }
 1750: 
 1751: sub get_increment {
 1752:     my $increment = $env{'form.increment'};
 1753:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1754:         $increment != .1) {
 1755:         $increment = 1;
 1756:     }
 1757:     return $increment;
 1758: }
 1759: 
 1760: sub gradeBox_start {
 1761:     return (
 1762:         &Apache::loncommon::start_data_table()
 1763:        .&Apache::loncommon::start_data_table_header_row()
 1764:        .'<th>'.&mt('Part').'</th>'
 1765:        .'<th>'.&mt('Points').'</th>'
 1766:        .'<th>&nbsp;</th>'
 1767:        .'<th>'.&mt('Assign Grade').'</th>'
 1768:        .'<th>'.&mt('Weight').'</th>'
 1769:        .'<th>'.&mt('Grade Status').'</th>'
 1770:        .&Apache::loncommon::end_data_table_header_row()
 1771:     );
 1772: }
 1773: 
 1774: sub gradeBox_end {
 1775:     return (
 1776:         &Apache::loncommon::end_data_table()
 1777:     );
 1778: }
 1779: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1780: sub gradeBox {
 1781:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1782:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1783: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1784:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1785:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1786:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1787:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1788:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1789: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1790:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1791:     my $display_part= &get_display_part($partid,$symb);
 1792:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1793: 				       [$partid]);
 1794:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1795:     if ($last_resets{$partid}) {
 1796:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1797:     }
 1798:     $result.=&Apache::loncommon::start_data_table_row();
 1799:     my $ctr = 0;
 1800:     my $thisweight = 0;
 1801:     my $increment = &get_increment();
 1802: 
 1803:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1804:     while ($thisweight<=$wgt) {
 1805: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1806:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1807: 	    $thisweight.')" value="'.$thisweight.'" '.
 1808: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1809: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1810:         $thisweight += $increment;
 1811: 	$ctr++;
 1812:     }
 1813:     $radio.='</tr></table>';
 1814: 
 1815:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1816: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1817: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1818: 	$wgt.')" /></td>'."\n";
 1819:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1820: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1821: 	' </td>'."\n";
 1822:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1823: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1824:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1825: 	$line.='<option></option>'.
 1826: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1827:     } else {
 1828: 	$line.='<option selected="selected"></option>'.
 1829: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1830:     }
 1831:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1832: 
 1833: 
 1834:     $result .= 
 1835: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1836:     $result.=&Apache::loncommon::end_data_table_row();
 1837:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1838: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1839: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1840: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1841:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1842:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1843:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1844:         $aggtries.'" />'."\n";
 1845:     my $res_error;
 1846:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1847:     if ($res_error) {
 1848:         return &navmap_errormsg();
 1849:     }
 1850:     return $result;
 1851: }
 1852: 
 1853: sub handback_box {
 1854:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1855:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1856:     my (@respids);
 1857:     my @part_response_id = &flatten_responseType($responseType);
 1858:     foreach my $part_response_id (@part_response_id) {
 1859:     	my ($part,$resp) = @{ $part_response_id };
 1860:         if ($part eq $partid) {
 1861:             push(@respids,$resp);
 1862:         }
 1863:     }
 1864:     my $result;
 1865:     foreach my $respid (@respids) {
 1866: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1867: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1868: 	next if (!@$files);
 1869: 	my $file_counter = 0;
 1870: 	foreach my $file (@$files) {
 1871: 	    if ($file =~ /\/portfolio\//) {
 1872:                 $file_counter++;
 1873:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1874:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1875:     	        $file_disp = "$name.$ext";
 1876:     	        $file = $file_path.$file_disp;
 1877:     	        $result.=&mt('Return commented version of [_1] to student.',
 1878:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1879:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1880:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1881: 	    }
 1882: 	}
 1883:         if ($file_counter) {
 1884:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1885:                        '<span class="LC_info">'.
 1886:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1887:         }
 1888:     }
 1889:     return $result;    
 1890: }
 1891: 
 1892: sub show_problem {
 1893:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1894:     my $rendered;
 1895:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1896:     &Apache::lonxml::remember_problem_counter();
 1897:     if ($mode eq 'both' or $mode eq 'text') {
 1898: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1899: 						       $env{'request.course.id'},
 1900: 						       undef,\%form);
 1901:     }
 1902:     if ($removeform) {
 1903: 	$rendered=~s|<form(.*?)>||g;
 1904: 	$rendered=~s|</form>||g;
 1905: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1906:     }
 1907:     my $companswer;
 1908:     if ($mode eq 'both' or $mode eq 'answer') {
 1909: 	&Apache::lonxml::restore_problem_counter();
 1910: 	$companswer=
 1911: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1912: 						    $env{'request.course.id'},
 1913: 						    %form);
 1914:     }
 1915:     if ($removeform) {
 1916: 	$companswer=~s|<form(.*?)>||g;
 1917: 	$companswer=~s|</form>||g;
 1918: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1919:     }
 1920:     my $renderheading = &mt('View of the problem');
 1921:     my $answerheading = &mt('Correct answer');
 1922:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1923:         my $stu_fullname = $env{'form.fullname'};
 1924:         if ($stu_fullname eq '') {
 1925:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1926:         }
 1927:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1928:         if ($forwhom ne '') {
 1929:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1930:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1931:         }
 1932:     }
 1933:     $rendered=
 1934:         '<div class="LC_Box">'
 1935:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1936:        .$rendered
 1937:        .'</div>';
 1938:     $companswer=
 1939:         '<div class="LC_Box">'
 1940:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1941:        .$companswer
 1942:        .'</div>';
 1943:     my $result;
 1944:     if ($mode eq 'both') {
 1945:         $result=$rendered.$companswer;
 1946:     } elsif ($mode eq 'text') {
 1947:         $result=$rendered;
 1948:     } elsif ($mode eq 'answer') {
 1949:         $result=$companswer;
 1950:     }
 1951:     return $result;
 1952: }
 1953: 
 1954: sub files_exist {
 1955:     my ($r, $symb) = @_;
 1956:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1957: 
 1958:     foreach my $student (@students) {
 1959:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1960:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1961: 					      $udom,$uname);
 1962:         my ($string,$timestamp)= &get_last_submission(\%record);
 1963:         foreach my $submission (@$string) {
 1964:             my ($partid,$respid) =
 1965: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1966:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1967: 					   \%record);
 1968:             return 1 if (@$files);
 1969:         }
 1970:     }
 1971:     return 0;
 1972: }
 1973: 
 1974: sub download_all_link {
 1975:     my ($r,$symb) = @_;
 1976:     my $all_students = 
 1977: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1978: 
 1979:     my $parts =
 1980: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1981: 
 1982:     my $identifier = &Apache::loncommon::get_cgi_id();
 1983:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1984:                              'cgi.'.$identifier.'.symb' => $symb,
 1985:                              'cgi.'.$identifier.'.parts' => $parts,});
 1986:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1987: 	      &mt('Download All Submitted Documents').'</a>');
 1988:     return
 1989: }
 1990: 
 1991: sub build_section_inputs {
 1992:     my $section_inputs;
 1993:     if ($env{'form.section'} eq '') {
 1994:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1995:     } else {
 1996:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1997:         foreach my $section (@sections) {
 1998:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1999:         }
 2000:     }
 2001:     return $section_inputs;
 2002: }
 2003: 
 2004: # --------------------------- show submissions of a student, option to grade 
 2005: sub submission {
 2006:     my ($request,$counter,$total) = @_;
 2007:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2008:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2009:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2010:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2011:     my ($symb) = &get_symb($request); 
 2012:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2013: 
 2014:     if (!&canview($usec)) {
 2015: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 2016: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 2017: 			$env{'request.course.id'}.')</span>');
 2018: 	$request->print(&show_grading_menu_form($symb));
 2019: 	return;
 2020:     }
 2021: 
 2022:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2023:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2024:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2025:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2026:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2027: 	'" src="'.$request->dir_config('lonIconsURL').
 2028: 	'/check.gif" height="16" border="0" />';
 2029: 
 2030:     my %old_essays;
 2031:     # header info
 2032:     if ($counter == 0) {
 2033: 	&sub_page_js($request);
 2034: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2035: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2036: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2037: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2038: 	    &download_all_link($request, $symb);
 2039: 	}
 2040: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2041: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 2042: 
 2043: 	# option to display problem, only once else it cause problems 
 2044:         # with the form later since the problem has a form.
 2045: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2046: 	    my $mode;
 2047: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2048: 		$mode='both';
 2049: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2050: 		$mode='text';
 2051: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2052: 		$mode='answer';
 2053: 	    }
 2054: 	    &Apache::lonxml::clear_problem_counter();
 2055: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2056: 	}
 2057: 
 2058: 	# kwclr is the only variable that is guaranteed to be non blank 
 2059:         # if this subroutine has been called once.
 2060: 	my %keyhash = ();
 2061: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2062: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2063: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2064: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2065: 
 2066: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2067: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2068: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2069: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2070: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2071: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2072: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2073: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2074: 	}
 2075: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2076: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2077: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2078: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2079: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2080: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2081: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2082: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2083: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2084: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2085: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2086: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2087: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2088: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2089: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2090: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2091: 			&build_section_inputs().
 2092: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2093: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2094: 			'<input type="hidden" name="NCT"'.
 2095: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2096: 	if ($env{'form.handgrade'} eq 'yes') {
 2097: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2098: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2099: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2100: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2101: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2102: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2103: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2104: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2105: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2106: 	    }
 2107: 	}
 2108: 	
 2109: 	my ($cts,$prnmsg) = (1,'');
 2110: 	while ($cts <= $env{'form.savemsgN'}) {
 2111: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2112: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2113: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2114: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2115: 		'" />'."\n".
 2116: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2117: 	    $cts++;
 2118: 	}
 2119: 	$request->print($prnmsg);
 2120: 
 2121: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2122: 
 2123:             my %lt = &Apache::lonlocal::texthash(
 2124:                           keyw => 'Keyword Options',
 2125:                           list => 'List',
 2126:                           past => 'Paste Selection to List',
 2127:                           high => 'Highlight Attribute',
 2128:                      );
 2129: #
 2130: # Print out the keyword options line
 2131: #
 2132: 	    $request->print(<<KEYWORDS);
 2133: &nbsp;<b>$lt{'keyw'}:</b>&nbsp;
 2134: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2135: <a href="#" onmousedown="javascript:getSel(); return false"
 2136:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
 2137: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2138: KEYWORDS
 2139: #
 2140: # Load the other essays for similarity check
 2141: #
 2142:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2143: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2144: 	    $apath=&escape($apath);
 2145: 	    $apath=~s/\W/\_/gs;
 2146: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2147:         }
 2148:     }
 2149: 
 2150: # This is where output for one specific student would start
 2151:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2152:     $request->print(
 2153:         "\n\n"
 2154:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2155:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2156:        ."\n"
 2157:     );
 2158: 
 2159:     # Show additional functions if allowed
 2160:     if ($perm{'vgr'}) {
 2161:         $request->print(
 2162:             &Apache::loncommon::track_student_link(
 2163:                 &mt('View recent activity'),
 2164:                 $uname,$udom,'check')
 2165:            .' '
 2166:         );
 2167:     }
 2168:     if ($perm{'opa'}) {
 2169:         $request->print(
 2170:             &Apache::loncommon::pprmlink(
 2171:                 &mt('Set/Change parameters'),
 2172:                 $uname,$udom,$symb,'check'));
 2173:     }
 2174: 
 2175:     # Show Problem
 2176:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2177: 	my $mode;
 2178: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2179: 	    $mode='both';
 2180: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2181: 	    $mode='text';
 2182: 	} elsif ($env{'form.vAns'} eq 'all') {
 2183: 	    $mode='answer';
 2184: 	}
 2185: 	&Apache::lonxml::clear_problem_counter();
 2186: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2187:     }
 2188: 
 2189:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2190:     my $res_error;
 2191:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2192:     if ($res_error) {
 2193:         $request->print(&navmap_errormsg());
 2194:         return;
 2195:     }
 2196: 
 2197:     # Display student info
 2198:     $request->print(($counter == 0 ? '' : '<br />'));
 2199: 
 2200:     my $result='<div class="LC_Box">'
 2201:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2202:     $result.='<input type="hidden" name="name'.$counter.
 2203:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2204:     if ($env{'form.handgrade'} eq 'no') {
 2205:         $result.='<p class="LC_info">'
 2206:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2207:                 ."</p>\n";
 2208:     }
 2209: 
 2210:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2211:     my $fullname;
 2212:     my $col_fullnames = [];
 2213:     if ($env{'form.handgrade'} eq 'yes') {
 2214: 	(my $sub_result,$fullname,$col_fullnames)=
 2215: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2216: 				 $counter);
 2217: 	$result.=$sub_result;
 2218:     }
 2219:     $request->print($result."\n");
 2220: 
 2221:     # print student answer/submission
 2222:     # Options are (1) Handgraded submission only
 2223:     #             (2) Last submission, includes submission that is not handgraded 
 2224:     #                  (for multi-response type part)
 2225:     #             (3) Last submission plus the parts info
 2226:     #             (4) The whole record for this student
 2227:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2228: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2229: 	
 2230: 	my $lastsubonly;
 2231: 
 2232:         if ($$timestamp eq '') {
 2233:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2234:         } else {
 2235:             $lastsubonly =
 2236:                 '<div class="LC_grade_submissions_body">'
 2237:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2238: 
 2239: 	    my %seenparts;
 2240: 	    my @part_response_id = &flatten_responseType($responseType);
 2241: 	    foreach my $part (@part_response_id) {
 2242: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2243: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2244: 
 2245: 		my ($partid,$respid) = @{ $part };
 2246: 		my $display_part=&get_display_part($partid,$symb);
 2247: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2248: 		    if (exists($seenparts{$partid})) { next; }
 2249: 		    $seenparts{$partid}=1;
 2250: 		    my $submitby='<b>Part:</b> '.$display_part.
 2251: 			' <b>Collaborative submission by:</b> '.
 2252: 			'<a href="javascript:viewSubmitter(\''.
 2253: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2254: 			'\');" target="_self">'.
 2255: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2256: 		    $request->print($submitby);
 2257: 		    next;
 2258: 		}
 2259: 		my $responsetype = $responseType->{$partid}->{$respid};
 2260: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2261:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2262:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2263:                         ' <span class="LC_internal_info">'.
 2264:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2265:                         '</span>&nbsp; &nbsp;'.
 2266: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2267: 		    next;
 2268: 		}
 2269: 		foreach my $submission (@$string) {
 2270: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2271: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2272: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2273: 		    # Similarity check
 2274: 		    my $similar='';
 2275:                     my ($type,$trial,$rndseed);
 2276:                     if ($hide eq 'rand') {
 2277:                         $type = 'randomizetry';
 2278:                         $trial = $record{"resource.$partid.tries"};
 2279:                         $rndseed = $record{"resource.$partid.rndseed"};
 2280:                     }
 2281: 		    if($env{'form.checkPlag'}){
 2282: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2283: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2284: 			if ($osim) {
 2285: 			    $osim=int($osim*100.0);
 2286: 			    my %old_course_desc = 
 2287: 				&Apache::lonnet::coursedescription($ocrsid,
 2288: 								   {'one_time' => 1});
 2289: 
 2290:                             if ($hide eq 'anon') {
 2291:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2292:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2293:                             } else {
 2294: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2295: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2296: 				        $osim,
 2297: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2298: 				        $old_course_desc{'description'},
 2299: 				        $old_course_desc{'num'},
 2300: 				        $old_course_desc{'domain'}).
 2301: 				    '</span></h3><blockquote><i>'.
 2302: 				    &keywords_highlight($oessay).
 2303: 				    '</i></blockquote><hr />';
 2304:                             }
 2305: 			}
 2306: 		    }
 2307: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2308:                                          undef,$type,$trial,$rndseed);
 2309: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2310: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2311: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2312: 			my $display_part=&get_display_part($partid,$symb);
 2313:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2314:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2315:                             ' <span class="LC_internal_info">'.
 2316:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2317:                             '</span>&nbsp; &nbsp;';
 2318: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2319: 			if (@$files) {
 2320:                             if ($hide eq 'anon') {
 2321:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2322:                             } else {
 2323:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2324:                                 foreach my $file (@$files) {
 2325:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2326:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2327:                                 }
 2328:                             }
 2329: 			    $lastsubonly.='<br />';
 2330: 			}
 2331:                         if ($hide eq 'anon') {
 2332:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2333:                         } else {
 2334: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2335: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2336: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2337:                         }
 2338: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2339: 			$lastsubonly.='</div>';
 2340: 		    }
 2341: 		}
 2342: 	    }
 2343: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2344: 	}
 2345: 	$request->print($lastsubonly);
 2346:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2347: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2348: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2349:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2350: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2351: 								 $env{'request.course.id'},
 2352: 								 $last,'.submission',
 2353: 								 'Apache::grades::keywords_highlight'));
 2354:     }
 2355: 
 2356:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2357: 	.$udom.'" />'."\n");
 2358:     # return if view submission with no grading option
 2359:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2360: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2361: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2362: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2363: 	$toGrade.='</div>'."\n";
 2364: 	if (($env{'form.command'} eq 'submission') || 
 2365: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2366: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2367: 	}
 2368: 	$request->print($toGrade);
 2369: 	return;
 2370:     } else {
 2371: 	$request->print('</div>'."\n");
 2372:     }
 2373: 
 2374:     # essay grading message center
 2375:     if ($env{'form.handgrade'} eq 'yes') {
 2376: 	my $result='<div class="LC_grade_message_center">';
 2377:     
 2378: 	$result.='<div class="LC_grade_message_center_header">'.
 2379: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2380: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2381: 	my $msgfor = $givenn.' '.$lastname;
 2382: 	if (scalar(@$col_fullnames) > 0) {
 2383: 	    my $lastone = pop(@$col_fullnames);
 2384: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2385: 	}
 2386: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2387: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2388: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2389: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2390: 	    ',\''.$msgfor.'\');" target="_self">'.
 2391: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2392: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2393: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2394: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2395: 	    '<br />&nbsp;('.
 2396: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2397: 	$result.='</div></div>';
 2398: 	$request->print($result);
 2399:     }
 2400: 
 2401:     my %seen = ();
 2402:     my @partlist;
 2403:     my @gradePartRespid;
 2404:     my @part_response_id = &flatten_responseType($responseType);
 2405:     $request->print(
 2406:         '<div class="LC_Box">'
 2407:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2408:     );
 2409:     $request->print(&gradeBox_start());
 2410:     foreach my $part_response_id (@part_response_id) {
 2411:     	my ($partid,$respid) = @{ $part_response_id };
 2412: 	my $part_resp = join('_',@{ $part_response_id });
 2413: 	next if ($seen{$partid} > 0);
 2414: 	$seen{$partid}++;
 2415: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2416: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2417: 	push(@partlist,$partid);
 2418: 	push(@gradePartRespid,$partid.'.'.$respid);
 2419: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2420:     }
 2421:     $request->print(&gradeBox_end()); # </div>
 2422:     $request->print('</div>');
 2423: 
 2424:     $request->print('<div class="LC_grade_info_links">');
 2425:     $request->print('</div>');
 2426: 
 2427:     $result='<input type="hidden" name="partlist'.$counter.
 2428: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2429:     $result.='<input type="hidden" name="gradePartRespid'.
 2430: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2431:     my $ctr = 0;
 2432:     while ($ctr < scalar(@partlist)) {
 2433: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2434: 	    $partlist[$ctr].'" />'."\n";
 2435: 	$ctr++;
 2436:     }
 2437:     $request->print($result.''."\n");
 2438: 
 2439: # Done with printing info for one student
 2440: 
 2441:     $request->print('</div>');#LC_grade_show_user
 2442: 
 2443: 
 2444:     # print end of form
 2445:     if ($counter == $total) {
 2446:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2447: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2448: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2449: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2450: 	my $ntstu ='<select name="NTSTU">'.
 2451: 	    '<option>1</option><option>2</option>'.
 2452: 	    '<option>3</option><option>5</option>'.
 2453: 	    '<option>7</option><option>10</option></select>'."\n";
 2454: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2455: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2456:         $endform.=&mt('[_1]student(s)',$ntstu);
 2457: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2458: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2459: 	    '<input type="button" value="'.&mt('Next').'" '.
 2460: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2461:         $endform.='<span class="LC_warning">'.
 2462:                   &mt('(Next and Previous (student) do not save the scores.)').
 2463:                   '</span>'."\n" ;
 2464:         $endform.="<input type='hidden' value='".&get_increment().
 2465:             "' name='increment' />";
 2466: 	$endform.='</td></tr></table></form>';
 2467: 	$endform.=&show_grading_menu_form($symb);
 2468: 	$request->print($endform);
 2469:     }
 2470:     return '';
 2471: }
 2472: 
 2473: sub check_collaborators {
 2474:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2475:     my ($result,@col_fullnames);
 2476:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2477:     foreach my $part (keys(%$handgrade)) {
 2478: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2479: 					'.maxcollaborators',
 2480: 					$symb,$udom,$uname);
 2481: 	next if ($ncol <= 0);
 2482: 	$part =~ s/\_/\./g;
 2483: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2484: 	my (@good_collaborators, @bad_collaborators);
 2485: 	foreach my $possible_collaborator
 2486: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2487: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2488: 	    next if ($possible_collaborator eq '');
 2489: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2490: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2491: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2492: 	    # Doing this grep allows 'fuzzy' specification
 2493: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2494: 			       keys(%$classlist));
 2495: 	    if (! scalar(@matches)) {
 2496: 		push(@bad_collaborators, $possible_collaborator);
 2497: 	    } else {
 2498: 		push(@good_collaborators, @matches);
 2499: 	    }
 2500: 	}
 2501: 	if (scalar(@good_collaborators) != 0) {
 2502: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2503: 	    foreach my $name (@good_collaborators) {
 2504: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2505: 		push(@col_fullnames, $givenn.' '.$lastname);
 2506: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2507: 	    }
 2508: 	    $result.='</ol><br />'."\n";
 2509: 	    my ($part)=split(/\./,$part);
 2510: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2511: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2512: 		"\n";
 2513: 	}
 2514: 	if (scalar(@bad_collaborators) > 0) {
 2515: 	    $result.='<div class="LC_warning">';
 2516: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2517: 	    $result .= '</div>';
 2518: 	}         
 2519: 	if (scalar(@bad_collaborators > $ncol)) {
 2520: 	    $result .= '<div class="LC_warning">';
 2521: 	    $result .= &mt('This student has submitted too many '.
 2522: 		'collaborators.  Maximum is [_1].',$ncol);
 2523: 	    $result .= '</div>';
 2524: 	}
 2525:     }
 2526:     return ($result,$fullname,\@col_fullnames);
 2527: }
 2528: 
 2529: #--- Retrieve the last submission for all the parts
 2530: sub get_last_submission {
 2531:     my ($returnhash)=@_;
 2532:     my (@string,$timestamp,%lasthidden);
 2533:     if ($$returnhash{'version'}) {
 2534: 	my %lasthash=();
 2535: 	my ($version);
 2536: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2537: 	    foreach my $key (sort(split(/\:/,
 2538: 					$$returnhash{$version.':keys'}))) {
 2539: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2540: 		$timestamp = 
 2541: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2542: 	    }
 2543: 	}
 2544:         my (%typeparts,%randombytry);
 2545:         my $showsurv = 
 2546:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2547:         foreach my $key (sort(keys(%lasthash))) {
 2548:             if ($key =~ /\.type$/) {
 2549:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2550:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2551:                     ($lasthash{$key} eq 'randomizetry')) {
 2552:                     my ($ign,@parts) = split(/\./,$key);
 2553:                     pop(@parts);
 2554:                     my $id = join('.',@parts);
 2555:                     if ($lasthash{$key} eq 'randomizetry') {
 2556:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2557:                     } else {
 2558:                         unless ($showsurv) {
 2559:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2560:                         }
 2561:                     }
 2562:                     delete($lasthash{$key});
 2563:                 }
 2564:             }
 2565:         }
 2566:         my @hidden = keys(%typeparts);
 2567:         my @randomize = keys(%randombytry);
 2568: 	foreach my $key (keys(%lasthash)) {
 2569: 	    next if ($key !~ /\.submission$/);
 2570:             my $hide;
 2571:             if (@hidden) {
 2572:                 foreach my $id (@hidden) {
 2573:                     if ($key =~ /^\Q$id\E/) {
 2574:                         $hide = 'anon';
 2575:                         last;
 2576:                     }
 2577:                 }
 2578:             }
 2579:             unless ($hide) {
 2580:                 if (@randomize) {
 2581:                     foreach my $id (@hidden) {
 2582:                         if ($key =~ /^\Q$id\E/) {
 2583:                             $hide = 'rand';
 2584:                             last;
 2585:                         }
 2586:                     }
 2587:                 }
 2588:             }
 2589: 	    my ($partid,$foo) = split(/submission$/,$key);
 2590: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2591: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2592: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2593: 	}
 2594:     }
 2595:     if (!@string) {
 2596: 	$string[0] =
 2597: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2598:     }
 2599:     return (\@string,\$timestamp);
 2600: }
 2601: 
 2602: #--- High light keywords, with style choosen by user.
 2603: sub keywords_highlight {
 2604:     my $string    = shift;
 2605:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2606:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2607:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2608:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2609:     foreach my $keyword (@keylist) {
 2610: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2611:     }
 2612:     return $string;
 2613: }
 2614: 
 2615: # For Tasks provide a mechanism to display previous version for one specific student
 2616: 
 2617: sub show_previous_task_version {
 2618:     my ($request,$symb) = @_;
 2619:     if ($symb eq '') {
 2620:         $request->print("Unable to handle ambiguous references.");
 2621: 
 2622:         return '';
 2623:     }
 2624:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2625:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2626:     if (!&canview($usec)) {
 2627:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
 2628:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
 2629:                         $env{'request.course.id'}.')</span>');
 2630:         return;
 2631:     }
 2632:     my $mode = 'both';
 2633:     my $isTask = ($symb =~/\.task$/);
 2634:     if ($isTask) {
 2635:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2636:             if ($env{'form.fullname'} eq '') {
 2637:                 $env{'form.fullname'} =
 2638:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2639:             }
 2640:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2641:             $request->print("\n\n".
 2642:                             '<div class="LC_grade_show_user">'.
 2643:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2644:                             '</h2>'."\n");
 2645:             &Apache::lonxml::clear_problem_counter();
 2646:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2647:                             {'previousversion' => $env{'form.previousversion'} }));
 2648:             $request->print("\n</div>");
 2649:         }
 2650:     }
 2651:     return;
 2652: }
 2653: 
 2654: sub choose_task_version_form {
 2655:     my ($symb,$uname,$udom,$nomenu) = @_;
 2656:     my $isTask = ($symb =~/\.task$/);
 2657:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2658:     if ($isTask) {
 2659:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2660:                                               $udom,$uname);
 2661:         if (($record{'resource.0.version'} eq '') ||
 2662:             ($record{'resource.0.version'} < 2)) {
 2663:             return ($record{'resource.0.version'},
 2664:                     $record{'resource.0.version'},$result,$js);
 2665:         } else {
 2666:             $current = $record{'resource.0.version'};
 2667:         }
 2668:         if ($env{'form.previousversion'}) {
 2669:             $displayed = $env{'form.previousversion'};
 2670:             $rowtitle = &mt('Choose another version:')
 2671:         } else {
 2672:             $displayed = $current;
 2673:             $rowtitle = &mt('Show earlier version:');
 2674:         }
 2675:         $result = '<div class="LC_left_float">';
 2676:         my $list;
 2677:         my $numversions = 0;
 2678:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2679:             if ($i == $current) {
 2680:                 if (!$env{'form.previousversion'} || $nomenu) {
 2681:                     next;
 2682:                 } else {
 2683:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2684:                     $numversions ++;
 2685:                 }
 2686:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2687:                 unless ($i == $env{'form.previousversion'}) {
 2688:                     $numversions ++;
 2689:                 }
 2690:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2691:             }
 2692:         }
 2693:         if ($numversions) {
 2694:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2695:             $result .=
 2696:                 '<form name="getprev" method="post" action=""'.
 2697:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2698:                 &Apache::loncommon::start_data_table().
 2699:                 &Apache::loncommon::start_data_table_row().
 2700:                 '<th align="left">'.$rowtitle.'</th>'.
 2701:                 '<td><select name="version">'.
 2702:                 '<option>'.&mt('Select').'</option>'.
 2703:                 $list.
 2704:                 '</select></td>'.
 2705:                 &Apache::loncommon::end_data_table_row();
 2706:             unless ($nomenu) {
 2707:                 $result .= &Apache::loncommon::start_data_table_row().
 2708:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2709:                 '<td><span class="LC_nobreak">'.
 2710:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2711:                 &mt('Yes').'</label>'.
 2712:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2713:                 '</span></td>'.
 2714:                 &Apache::loncommon::end_data_table_row();
 2715:             }
 2716:             $result .=
 2717:                 &Apache::loncommon::start_data_table_row().
 2718:                 '<th align="left">&nbsp;</th>'.
 2719:                 '<td>'.
 2720:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2721:                 '</td>'.
 2722:                 &Apache::loncommon::end_data_table_row().
 2723:                 &Apache::loncommon::end_data_table().
 2724:                 '</form>';
 2725:             $js = &previous_display_javascript($nomenu,$current);
 2726:         } elsif ($displayed && $nomenu) {
 2727:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2728:         } else {
 2729:             $result .= &mt('No previous versions to show for this student');
 2730:         }
 2731:         $result .= '</div>';
 2732:     }
 2733:     return ($current,$displayed,$result,$js);
 2734: }
 2735: 
 2736: sub previous_display_javascript {
 2737:     my ($nomenu,$current) = @_;
 2738:     my $js = <<"JSONE";
 2739: <script type="text/javascript">
 2740: // <![CDATA[
 2741: function previousVersion(uname,udom,symb) {
 2742:     var current = '$current';
 2743:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2744:     var prevstr = new RegExp("^\\\\d+\$");
 2745:     if (!prevstr.test(version)) {
 2746:         return false;
 2747:     }
 2748:     var url = '';
 2749:     if (version == current) {
 2750:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2751:     } else {
 2752:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2753:     }
 2754: JSONE
 2755:     if ($nomenu) {
 2756:         $js .= <<"JSTWO";
 2757:     document.location.href = url;
 2758: JSTWO
 2759:     } else {
 2760:         $js .= <<"JSTHREE";
 2761:     var newwin = 0;
 2762:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2763:         if (document.getprev.prevwin[i].checked == true) {
 2764:             newwin = document.getprev.prevwin[i].value;
 2765:         }
 2766:     }
 2767:     if (newwin == 1) {
 2768:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2769:         url = url+'&inhibitmenu=yes';
 2770:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2771:             previousWin = window.open(url,'',options,1);
 2772:         } else {
 2773:             previousWin.location.href = url;
 2774:         }
 2775:         previousWin.focus();
 2776:         return false;
 2777:     } else {
 2778:         document.location.href = url;
 2779:         return false;
 2780:     }
 2781: JSTHREE
 2782:     }
 2783:     $js .= <<"ENDJS";
 2784:     return false;
 2785: }
 2786: // ]]>
 2787: </script>
 2788: ENDJS
 2789: 
 2790: }
 2791: 
 2792: #--- Called from submission routine
 2793: sub processHandGrade {
 2794:     my ($request) = shift;
 2795:     my ($symb)   = &get_symb($request);
 2796:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2797:     my $button = $env{'form.gradeOpt'};
 2798:     my $ngrade = $env{'form.NCT'};
 2799:     my $ntstu  = $env{'form.NTSTU'};
 2800:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2801:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2802: 
 2803:     if ($button eq 'Save & Next') {
 2804: 	my $ctr = 0;
 2805: 	while ($ctr < $ngrade) {
 2806: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2807: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2808: 	    if ($errorflag eq 'no_score') {
 2809: 		$ctr++;
 2810: 		next;
 2811: 	    }
 2812: 	    if ($errorflag eq 'not_allowed') {
 2813: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2814: 		$ctr++;
 2815: 		next;
 2816: 	    }
 2817: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2818: 	    my ($subject,$message,$msgstatus) = ('','','');
 2819: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2820:             my ($feedurl,$showsymb) =
 2821: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2822: 	    my $messagetail;
 2823: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2824: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2825: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2826: 		$subject.=' ['.$restitle.']';
 2827: 		my (@msgnum) = split(/,/,$includemsg);
 2828: 		foreach (@msgnum) {
 2829: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2830: 		}
 2831: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2832: 		if ($env{'form.withgrades'.$ctr}) {
 2833: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2834: 		    $messagetail = " for <a href=\"".
 2835: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2836: 		}
 2837: 		$msgstatus = 
 2838:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2839: 						     $message.$messagetail,
 2840:                                                      undef,$feedurl,undef,
 2841:                                                      undef,undef,$showsymb,
 2842:                                                      $restitle);
 2843: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2844: 				$msgstatus.'<br />');
 2845: 	    }
 2846: 	    if ($env{'form.collaborator'.$ctr}) {
 2847: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2848: 		foreach my $collabstr (@collabstrs) {
 2849: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2850: 		    foreach my $collaborator (@collaborators) {
 2851: 			my ($errorflag,$pts,$wgt) = 
 2852: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2853: 					   $env{'form.unamedom'.$ctr},$part);
 2854: 			if ($errorflag eq 'not_allowed') {
 2855: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2856: 			    next;
 2857: 			} elsif ($message ne '') {
 2858: 			    my ($baseurl,$showsymb) = 
 2859: 				&get_feedurl_and_symb($symb,$collaborator,
 2860: 						      $udom);
 2861: 			    if ($env{'form.withgrades'.$ctr}) {
 2862: 				$messagetail = " for <a href=\"".
 2863:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2864: 			    }
 2865: 			    $msgstatus = 
 2866: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2867: 			}
 2868: 		    }
 2869: 		}
 2870: 	    }
 2871: 	    $ctr++;
 2872: 	}
 2873:     }
 2874: 
 2875:     if ($env{'form.handgrade'} eq 'yes') {
 2876: 	# Keywords sorted in alphabatical order
 2877: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2878: 	my %keyhash = ();
 2879: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2880: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2881: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2882: 	$env{'form.keywords'} = join(' ',@keywords);
 2883: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2884: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2885: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2886: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2887: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2888: 
 2889: 	# message center - Order of message gets changed. Blank line is eliminated.
 2890: 	# New messages are saved in env for the next student.
 2891: 	# All messages are saved in nohist_handgrade.db
 2892: 	my ($ctr,$idx) = (1,1);
 2893: 	while ($ctr <= $env{'form.savemsgN'}) {
 2894: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2895: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2896: 		$idx++;
 2897: 	    }
 2898: 	    $ctr++;
 2899: 	}
 2900: 	$ctr = 0;
 2901: 	while ($ctr < $ngrade) {
 2902: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2903: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2904: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2905: 		$idx++;
 2906: 	    }
 2907: 	    $ctr++;
 2908: 	}
 2909: 	$env{'form.savemsgN'} = --$idx;
 2910: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2911: 	my $putresult = &Apache::lonnet::put
 2912: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2913:     }
 2914:     # Called by Save & Refresh from Highlight Attribute Window
 2915:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2916:     if ($env{'form.refresh'} eq 'on') {
 2917: 	my ($ctr,$total) = (0,0);
 2918: 	while ($ctr < $ngrade) {
 2919: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2920: 	    $ctr++;
 2921: 	}
 2922: 	$env{'form.NTSTU'}=$ngrade;
 2923: 	$ctr = 0;
 2924: 	while ($ctr < $total) {
 2925: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2926: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2927: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2928: 	    &submission($request,$ctr,$total-1);
 2929: 	    $ctr++;
 2930: 	}
 2931: 	return '';
 2932:     }
 2933: 
 2934: # Go directly to grade student - from submission or link from chart page
 2935:     if ($button eq 'Grade Student') {
 2936: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2937: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2938: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2939: 	$env{'form.fullname'} = $$fullname{$processUser};
 2940: 	&submission($request,0,0);
 2941: 	return '';
 2942:     }
 2943: 
 2944:     # Get the next/previous one or group of students
 2945:     my $firststu = $env{'form.unamedom0'};
 2946:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2947:     my $ctr = 2;
 2948:     while ($laststu eq '') {
 2949: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2950: 	$ctr++;
 2951: 	$laststu = $firststu if ($ctr > $ngrade);
 2952:     }
 2953: 
 2954:     my (@parsedlist,@nextlist);
 2955:     my ($nextflg) = 0;
 2956:     foreach my $item (sort 
 2957: 	     {
 2958: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2959: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2960: 		 }
 2961: 		 return $a cmp $b;
 2962: 	     } (keys(%$fullname))) {
 2963: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2964: 	    push(@parsedlist,$item);
 2965: 	}
 2966: 	$nextflg = 1 if ($item eq $laststu);
 2967: 	if ($button eq 'Previous') {
 2968: 	    last if ($item eq $firststu);
 2969: 	    push(@parsedlist,$item);
 2970: 	}
 2971:     }
 2972:     $ctr = 0;
 2973:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2974:     my $res_error;
 2975:     my ($partlist) = &response_type($symb,\$res_error);
 2976:     if ($res_error) {
 2977:         $request->print(&navmap_errormsg());
 2978:         return;
 2979:     }
 2980:     foreach my $student (@parsedlist) {
 2981: 	my $submitonly=$env{'form.submitonly'};
 2982: 	my ($uname,$udom) = split(/:/,$student);
 2983: 	
 2984: 	if ($submitonly eq 'queued') {
 2985: 	    my %queue_status = 
 2986: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2987: 							$udom,$uname);
 2988: 	    next if (!defined($queue_status{'gradingqueue'}));
 2989: 	}
 2990: 
 2991: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2992: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2993: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2994: 	    my $submitted = 0;
 2995: 	    my $ungraded = 0;
 2996: 	    my $incorrect = 0;
 2997: 	    foreach my $item (keys(%status)) {
 2998: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2999: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3000: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3001: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3002: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3003: 		    $submitted = 0;
 3004: 		}
 3005: 	    }
 3006: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3007: 				     $submitonly eq 'incorrect' ||
 3008: 				     $submitonly eq 'graded'));
 3009: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3010: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3011: 	}
 3012: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3013: 	last if ($ctr == $ntstu);
 3014: 	$ctr++;
 3015:     }
 3016: 
 3017:     $ctr = 0;
 3018:     my $total = scalar(@nextlist)-1;
 3019: 
 3020:     foreach (sort(@nextlist)) {
 3021: 	my ($uname,$udom,$submitter) = split(/:/);
 3022: 	$env{'form.student'}  = $uname;
 3023: 	$env{'form.userdom'}  = $udom;
 3024: 	$env{'form.fullname'} = $$fullname{$_};
 3025: 	&submission($request,$ctr,$total);
 3026: 	$ctr++;
 3027:     }
 3028:     if ($total < 0) {
 3029: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3030: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3031: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3032: 	$the_end.=&show_grading_menu_form($symb);
 3033: 	$request->print($the_end);
 3034:     }
 3035:     return '';
 3036: }
 3037: 
 3038: #---- Save the score and award for each student, if changed
 3039: sub saveHandGrade {
 3040:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3041:     my @version_parts;
 3042:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3043: 					   $env{'request.course.id'});
 3044:     if (!&canmodify($usec)) { return('not_allowed'); }
 3045:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3046:     my @parts_graded;
 3047:     my %newrecord  = ();
 3048:     my ($pts,$wgt) = ('','');
 3049:     my %aggregate = ();
 3050:     my $aggregateflag = 0;
 3051:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3052:     foreach my $new_part (@parts) {
 3053: 	#collaborator ($submi may vary for different parts
 3054: 	if ($submitter && $new_part ne $part) { next; }
 3055: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3056: 	if ($dropMenu eq 'excused') {
 3057: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3058: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3059: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3060: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3061: 		}
 3062: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3063: 	    }
 3064: 	} elsif ($dropMenu eq 'reset status'
 3065: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3066: 	    foreach my $key (keys(%record)) {
 3067: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3068: 	    }
 3069: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3070: 		"$env{'user.name'}:$env{'user.domain'}";
 3071:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3072: 
 3073:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3074: 					       [$new_part]);
 3075:             my $aggtries =$totaltries;
 3076:             if ($last_resets{$new_part}) {
 3077:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3078: 					   $new_part);
 3079:             }
 3080: 
 3081:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3082:             if ($aggtries > 0) {
 3083:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3084:                 $aggregateflag = 1;
 3085:             }
 3086: 	} elsif ($dropMenu eq '') {
 3087: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3088: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3089: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3090: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3091: 		next;
 3092: 	    }
 3093: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3094: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3095: 	    my $partial= $pts/$wgt;
 3096: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3097: 		#do not update score for part if not changed.
 3098:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3099: 		next;
 3100: 	    } else {
 3101: 	        push(@parts_graded,$new_part);
 3102: 	    }
 3103: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3104: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3105: 	    }
 3106: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3107: 	    if ($partial == 0) {
 3108: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3109: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3110: 		}
 3111: 	    } else {
 3112: 		if ($record{$reckey} ne 'correct_by_override') {
 3113: 		    $newrecord{$reckey} = 'correct_by_override';
 3114: 		}
 3115: 	    }	    
 3116: 	    if ($submitter && 
 3117: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3118: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3119: 	    }
 3120: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3121: 		"$env{'user.name'}:$env{'user.domain'}";
 3122: 	}
 3123: 	# unless problem has been graded, set flag to version the submitted files
 3124: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3125: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3126: 	        $dropMenu eq 'reset status')
 3127: 	   {
 3128: 	    push(@version_parts,$new_part);
 3129: 	}
 3130:     }
 3131:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3132:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3133: 
 3134:     if (%newrecord) {
 3135:         if (@version_parts) {
 3136:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3137:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3138: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3139: 	    foreach my $new_part (@version_parts) {
 3140: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3141: 				$new_part,\%newrecord);
 3142: 	    }
 3143:         }
 3144: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3145: 				$env{'request.course.id'},$domain,$stuname);
 3146: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3147: 				     $cdom,$cnum,$domain,$stuname);
 3148:     }
 3149:     if ($aggregateflag) {
 3150:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3151: 			      $cdom,$cnum);
 3152:     }
 3153:     return ('',$pts,$wgt);
 3154: }
 3155: 
 3156: sub check_and_remove_from_queue {
 3157:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3158:     my @ungraded_parts;
 3159:     foreach my $part (@{$parts}) {
 3160: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3161: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3162: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3163: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3164: 		) {
 3165: 	    push(@ungraded_parts, $part);
 3166: 	}
 3167:     }
 3168:     if ( !@ungraded_parts ) {
 3169: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3170: 					       $cnum,$domain,$stuname);
 3171:     }
 3172: }
 3173: 
 3174: sub handback_files {
 3175:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3176:     my $portfolio_root = '/userfiles/portfolio';
 3177:     my $res_error;
 3178:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3179:     if ($res_error) {
 3180:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3181:         return;
 3182:     }
 3183:     my @handedback;
 3184:     my $file_msg;
 3185:     my @part_response_id = &flatten_responseType($responseType);
 3186:     foreach my $part_response_id (@part_response_id) {
 3187:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3188: 	my $part_resp = join('_',@{ $part_response_id });
 3189:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3190:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3191:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3192: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3193:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3194:                     my ($directory,$answer_file) = 
 3195:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3196:                     my ($answer_name,$answer_ver,$answer_ext) =
 3197: 		        &file_name_version_ext($answer_file);
 3198: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3199:                     my $getpropath = 1;
 3200:                     my ($dir_list,$listerror) =
 3201:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3202:                                                  $domain,$stuname,$getpropath);
 3203: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3204:                     # fix file name
 3205:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3206:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3207:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3208:             	                                $save_file_name);
 3209:                     if ($result !~ m|^/uploaded/|) {
 3210:                         $request->print('<br /><span class="LC_error">'.
 3211:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3212:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3213:                                         '</span>');
 3214:                     } else {
 3215:                         # mark the file as read only
 3216:                         push(@handedback,$save_file_name);
 3217: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3218: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3219: 			}
 3220:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3221: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3222: 
 3223:                     }
 3224:                     $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3225:                 }
 3226:             }
 3227:         }
 3228:     }
 3229:     if (@handedback > 0) {
 3230:         $request->print('<br />');
 3231:         my @what = ($symb,$env{'request.course.id'},'handback');
 3232:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3233:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3234:         my ($subject,$message);
 3235:         if (scalar(@handedback) == 1) {
 3236:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3237:         } else {
 3238:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3239:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3240:         }
 3241:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3242:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3243:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3244:         my ($feedurl,$showsymb) =
 3245:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3246:         my $restitle = &Apache::lonnet::gettitle($symb);
 3247:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3248:         my $msgstatus =
 3249:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3250:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3251:                  $restitle);
 3252:         if ($msgstatus) {
 3253:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3254:         }
 3255:     }
 3256:     return;
 3257: }
 3258: 
 3259: sub get_feedurl_and_symb {
 3260:     my ($symb,$uname,$udom) = @_;
 3261:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3262:     $url = &Apache::lonnet::clutter($url);
 3263:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3264: 					$symb,$udom,$uname);
 3265:     if ($encrypturl =~ /^yes$/i) {
 3266: 	&Apache::lonenc::encrypted(\$url,1);
 3267: 	&Apache::lonenc::encrypted(\$symb,1);
 3268:     }
 3269:     return ($url,$symb);
 3270: }
 3271: 
 3272: sub get_submitted_files {
 3273:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3274:     my @files;
 3275:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3276:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3277:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3278:     	    push(@files,$file_url.$file);
 3279:         }
 3280:     }
 3281:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3282:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3283:     }
 3284:     return (\@files);
 3285: }
 3286: 
 3287: # ----------- Provides number of tries since last reset.
 3288: sub get_num_tries {
 3289:     my ($record,$last_reset,$part) = @_;
 3290:     my $timestamp = '';
 3291:     my $num_tries = 0;
 3292:     if ($$record{'version'}) {
 3293:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3294:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3295:                 $timestamp = $$record{$version.':timestamp'};
 3296:                 if ($timestamp > $last_reset) {
 3297:                     $num_tries ++;
 3298:                 } else {
 3299:                     last;
 3300:                 }
 3301:             }
 3302:         }
 3303:     }
 3304:     return $num_tries;
 3305: }
 3306: 
 3307: # ----------- Determine decrements required in aggregate totals 
 3308: sub decrement_aggs {
 3309:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3310:     my %decrement = (
 3311:                         attempts => 0,
 3312:                         users => 0,
 3313:                         correct => 0
 3314:                     );
 3315:     $decrement{'attempts'} = $aggtries;
 3316:     if ($solvedstatus =~ /^correct/) {
 3317:         $decrement{'correct'} = 1;
 3318:     }
 3319:     if ($aggtries == $totaltries) {
 3320:         $decrement{'users'} = 1;
 3321:     }
 3322:     foreach my $type (keys(%decrement)) {
 3323:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3324:     }
 3325:     return;
 3326: }
 3327: 
 3328: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3329: sub get_last_resets {
 3330:     my ($symb,$courseid,$partids) =@_;
 3331:     my %last_resets;
 3332:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3333:     my $cname = $env{'course.'.$courseid.'.num'};
 3334:     my @keys;
 3335:     foreach my $part (@{$partids}) {
 3336: 	push(@keys,"$symb\0$part\0resettime");
 3337:     }
 3338:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3339: 				     $cdom,$cname);
 3340:     foreach my $part (@{$partids}) {
 3341: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3342:     }
 3343:     return %last_resets;
 3344: }
 3345: 
 3346: # ----------- Handles creating versions for portfolio files as answers
 3347: sub version_portfiles {
 3348:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3349:     my $version_parts = join('|',@$v_flag);
 3350:     my @returned_keys;
 3351:     my $parts = join('|', @$parts_graded);
 3352:     my $portfolio_root = '/userfiles/portfolio';
 3353:     foreach my $key (keys(%$record)) {
 3354:         my $new_portfiles;
 3355:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3356:             my @versioned_portfiles;
 3357:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3358:             foreach my $file (@portfiles) {
 3359:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3360:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3361: 		my ($answer_name,$answer_ver,$answer_ext) =
 3362: 		    &file_name_version_ext($answer_file);
 3363:                 my $getpropath = 1;
 3364:                 my ($dir_list,$listerror) =
 3365:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3366:                                              $stu_name,$getpropath);
 3367:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3368:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3369:                 if ($new_answer ne 'problem getting file') {
 3370:                     push(@versioned_portfiles, $directory.$new_answer);
 3371:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3372:                         [$directory.$new_answer],
 3373:                         [$symb,$env{'request.course.id'},'graded']);
 3374:                 }
 3375:             }
 3376:             $$record{$key} = join(',',@versioned_portfiles);
 3377:             push(@returned_keys,$key);
 3378:         }
 3379:     } 
 3380:     return (@returned_keys);   
 3381: }
 3382: 
 3383: sub get_next_version {
 3384:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3385:     my $version;
 3386:     if (ref($dir_list) eq 'ARRAY') {
 3387:         foreach my $row (@{$dir_list}) {
 3388:             my ($file) = split(/\&/,$row,2);
 3389:             my ($file_name,$file_version,$file_ext) =
 3390: 	        &file_name_version_ext($file);
 3391:             if (($file_name eq $answer_name) && 
 3392: 	        ($file_ext eq $answer_ext)) {
 3393:                 # gets here if filename and extension match, 
 3394:                 # regardless of version
 3395:                 if ($file_version ne '') {
 3396:                     # a versioned file is found  so save it for later
 3397:                     if ($file_version > $version) {
 3398: 		        $version = $file_version;
 3399:                     }
 3400: 	        }
 3401:             }
 3402:         }
 3403:     }
 3404:     $version ++;
 3405:     return($version);
 3406: }
 3407: 
 3408: sub version_selected_portfile {
 3409:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3410:     my ($answer_name,$answer_ver,$answer_ext) =
 3411:         &file_name_version_ext($file_name);
 3412:     my $new_answer;
 3413:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3414:     if($env{'form.copy'} eq '-1') {
 3415:         $new_answer = 'problem getting file';
 3416:     } else {
 3417:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3418:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3419:                             $stu_name,$domain,'copy',
 3420: 		        '/portfolio'.$directory.$new_answer);
 3421:     }    
 3422:     return ($new_answer);
 3423: }
 3424: 
 3425: sub file_name_version_ext {
 3426:     my ($file)=@_;
 3427:     my @file_parts = split(/\./, $file);
 3428:     my ($name,$version,$ext);
 3429:     if (@file_parts > 1) {
 3430: 	$ext=pop(@file_parts);
 3431: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3432: 	    $version=pop(@file_parts);
 3433: 	}
 3434: 	$name=join('.',@file_parts);
 3435:     } else {
 3436: 	$name=join('.',@file_parts);
 3437:     }
 3438:     return($name,$version,$ext);
 3439: }
 3440: 
 3441: #--------------------------------------------------------------------------------------
 3442: #
 3443: #-------------------------- Next few routines handles grading by section or whole class
 3444: #
 3445: #--- Javascript to handle grading by section or whole class
 3446: sub viewgrades_js {
 3447:     my ($request) = shift;
 3448: 
 3449:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3450:     $request->print(<<VIEWJAVASCRIPT);
 3451: <script type="text/javascript" language="javascript">
 3452:    function writePoint(partid,weight,point) {
 3453: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3454: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3455: 	if (point == "textval") {
 3456: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3457: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3458: 		alert("$alertmsg"+parseFloat(point));
 3459: 		var resetbox = false;
 3460: 		for (var i=0; i<radioButton.length; i++) {
 3461: 		    if (radioButton[i].checked) {
 3462: 			textbox.value = i;
 3463: 			resetbox = true;
 3464: 		    }
 3465: 		}
 3466: 		if (!resetbox) {
 3467: 		    textbox.value = "";
 3468: 		}
 3469: 		return;
 3470: 	    }
 3471: 	    if (parseFloat(point) > parseFloat(weight)) {
 3472: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3473: 				   ") greater than the weight for the part. Accept?");
 3474: 		if (resp == false) {
 3475: 		    textbox.value = "";
 3476: 		    return;
 3477: 		}
 3478: 	    }
 3479: 	    for (var i=0; i<radioButton.length; i++) {
 3480: 		radioButton[i].checked=false;
 3481: 		if (parseFloat(point) == i) {
 3482: 		    radioButton[i].checked=true;
 3483: 		}
 3484: 	    }
 3485: 
 3486: 	} else {
 3487: 	    textbox.value = parseFloat(point);
 3488: 	}
 3489: 	for (i=0;i<document.classgrade.total.value;i++) {
 3490: 	    var user = document.classgrade["ctr"+i].value;
 3491: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3492: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3493: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3494: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3495: 	    if (saveval != "correct") {
 3496: 		scorename.value = point;
 3497: 		if (selname[0].selected != true) {
 3498: 		    selname[0].selected = true;
 3499: 		}
 3500: 	    }
 3501: 	}
 3502: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3503:     }
 3504: 
 3505:     function writeRadText(partid,weight) {
 3506: 	var selval   = document.classgrade["SELVAL_"+partid];
 3507: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3508:         var override = document.classgrade["FORCE_"+partid].checked;
 3509: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3510: 	if (selval[1].selected || selval[2].selected) {
 3511: 	    for (var i=0; i<radioButton.length; i++) {
 3512: 		radioButton[i].checked=false;
 3513: 
 3514: 	    }
 3515: 	    textbox.value = "";
 3516: 
 3517: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3518: 		var user = document.classgrade["ctr"+i].value;
 3519: 		user = user.replace(new RegExp(':', 'g'),"_");
 3520: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3521: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3522: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3523: 		if ((saveval != "correct") || override) {
 3524: 		    scorename.value = "";
 3525: 		    if (selval[1].selected) {
 3526: 			selname[1].selected = true;
 3527: 		    } else {
 3528: 			selname[2].selected = true;
 3529: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3530: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3531: 		    }
 3532: 		}
 3533: 	    }
 3534: 	} else {
 3535: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3536: 		var user = document.classgrade["ctr"+i].value;
 3537: 		user = user.replace(new RegExp(':', 'g'),"_");
 3538: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3539: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3540: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3541: 		if ((saveval != "correct") || override) {
 3542: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3543: 		    selname[0].selected = true;
 3544: 		}
 3545: 	    }
 3546: 	}	    
 3547:     }
 3548: 
 3549:     function changeSelect(partid,user) {
 3550: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3551: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3552: 	var point  = textbox.value;
 3553: 	var weight = document.classgrade["weight_"+partid].value;
 3554: 
 3555: 	if (isNaN(point) || parseFloat(point) < 0) {
 3556: 	    alert("$alertmsg"+parseFloat(point));
 3557: 	    textbox.value = "";
 3558: 	    return;
 3559: 	}
 3560: 	if (parseFloat(point) > parseFloat(weight)) {
 3561: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3562: 			       ") greater than the weight of the part. Accept?");
 3563: 	    if (resp == false) {
 3564: 		textbox.value = "";
 3565: 		return;
 3566: 	    }
 3567: 	}
 3568: 	selval[0].selected = true;
 3569:     }
 3570: 
 3571:     function changeOneScore(partid,user) {
 3572: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3573: 	if (selval[1].selected || selval[2].selected) {
 3574: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3575: 	    if (selval[2].selected) {
 3576: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3577: 	    }
 3578:         }
 3579:     }
 3580: 
 3581:     function resetEntry(numpart) {
 3582: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3583: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3584: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3585: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3586: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3587: 	    for (var i=0; i<radioButton.length; i++) {
 3588: 		radioButton[i].checked=false;
 3589: 
 3590: 	    }
 3591: 	    textbox.value = "";
 3592: 	    selval[0].selected = true;
 3593: 
 3594: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3595: 		var user = document.classgrade["ctr"+i].value;
 3596: 		user = user.replace(new RegExp(':', 'g'),"_");
 3597: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3598: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3599: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3600: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3601: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3602: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3603: 		if (saveselval == "excused") {
 3604: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3605: 		} else {
 3606: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3607: 		}
 3608: 	    }
 3609: 	}
 3610:     }
 3611: 
 3612: </script>
 3613: VIEWJAVASCRIPT
 3614: }
 3615: 
 3616: #--- show scores for a section or whole class w/ option to change/update a score
 3617: sub viewgrades {
 3618:     my ($request) = shift;
 3619:     &viewgrades_js($request);
 3620: 
 3621:     my ($symb) = &get_symb($request);
 3622:     #need to make sure we have the correct data for later EXT calls, 
 3623:     #thus invalidate the cache
 3624:     &Apache::lonnet::devalidatecourseresdata(
 3625:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3626:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3627:     &Apache::lonnet::clear_EXT_cache_status();
 3628: 
 3629:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3630:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3631: 
 3632:     #view individual student submission form - called using Javascript viewOneStudent
 3633:     $result.=&jscriptNform($symb);
 3634: 
 3635:     #beginning of class grading form
 3636:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3637:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3638: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3639: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3640: 	&build_section_inputs().
 3641: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3642: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3643: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3644: 
 3645:     my ($common_header,$specific_header);
 3646:     if ($env{'form.section'} eq 'all') {
 3647: 	$common_header = &mt('Assign Common Grade to Class');
 3648:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3649:     } elsif ($env{'form.section'} eq 'none') {
 3650:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3651: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3652:     } else {
 3653:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3654:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3655: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3656:     }
 3657:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3658:     #radio buttons/text box for assigning points for a section or class.
 3659:     #handles different parts of a problem
 3660:     my $res_error;
 3661:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3662:     if ($res_error) {
 3663:         return &navmap_errormsg();
 3664:     }
 3665:     my %weight = ();
 3666:     my $ctsparts = 0;
 3667:     my %seen = ();
 3668:     my @part_response_id = &flatten_responseType($responseType);
 3669:     foreach my $part_response_id (@part_response_id) {
 3670:     	my ($partid,$respid) = @{ $part_response_id };
 3671: 	my $part_resp = join('_',@{ $part_response_id });
 3672: 	next if $seen{$partid};
 3673: 	$seen{$partid}++;
 3674: 	my $handgrade=$$handgrade{$part_resp};
 3675: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3676: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3677: 
 3678: 	my $display_part=&get_display_part($partid,$symb);
 3679: 	my $radio.='<table border="0"><tr>';  
 3680: 	my $ctr = 0;
 3681: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3682: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3683: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3684: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3685: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3686: 	    $ctr++;
 3687: 	}
 3688: 	$radio.='</tr></table>';
 3689: 	my $line = '<input type="text" name="TEXTVAL_'.
 3690: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3691: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3692: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3693: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3694: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3695: 		$weight{$partid}.')"> '.
 3696: 	    '<option selected="selected"> </option>'.
 3697: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3698: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3699: 	    '</select></td>'.
 3700:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3701: 	$line.='<input type="hidden" name="partid_'.
 3702: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3703: 	$line.='<input type="hidden" name="weight_'.
 3704: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3705: 
 3706: 	$result.=
 3707: 	    &Apache::loncommon::start_data_table_row()."\n".
 3708: 	    '<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>'.
 3709: 	    &Apache::loncommon::end_data_table_row()."\n";
 3710: 	$ctsparts++;
 3711:     }
 3712:     $result.=&Apache::loncommon::end_data_table()."\n".
 3713: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3714:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3715: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3716: 
 3717:     #table listing all the students in a section/class
 3718:     #header of table
 3719:     $result.= '<h3>'.$specific_header.'</h3>'.
 3720:               &Apache::loncommon::start_data_table().
 3721: 	      &Apache::loncommon::start_data_table_header_row().
 3722: 	      '<th>'.&mt('No.').'</th>'.
 3723: 	      '<th>'.&nameUserString('header')."</th>\n";
 3724:     my $partserror;
 3725:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3726:     if ($partserror) {
 3727:         return &navmap_errormsg();
 3728:     }
 3729:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3730:     my @partids = ();
 3731:     foreach my $part (@parts) {
 3732: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3733:         my $narrowtext = &mt('Tries');
 3734: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3735: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3736: 	my ($partid) = &split_part_type($part);
 3737:         push(@partids,$partid);
 3738: 	my $display_part=&get_display_part($partid,$symb);
 3739: 	if ($display =~ /^Partial Credit Factor/) {
 3740: 	    $result.='<th>'.
 3741: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3742: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3743: 	    next;
 3744: 	    
 3745: 	} else {
 3746: 	    if ($display =~ /Problem Status/) {
 3747: 		my $grade_status_mt = &mt('Grade Status');
 3748: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3749: 	    }
 3750: 	    my $part_mt = &mt('Part:');
 3751: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3752: 	}
 3753: 
 3754: 	$result.='<th>'.$display.'</th>'."\n";
 3755:     }
 3756:     $result.=&Apache::loncommon::end_data_table_header_row();
 3757: 
 3758:     my %last_resets = 
 3759: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3760: 
 3761:     #get info for each student
 3762:     #list all the students - with points and grade status
 3763:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3764:     my $ctr = 0;
 3765:     foreach (sort 
 3766: 	     {
 3767: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3768: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3769: 		 }
 3770: 		 return $a cmp $b;
 3771: 	     } (keys(%$fullname))) {
 3772: 	$ctr++;
 3773: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3774: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3775:     }
 3776:     $result.=&Apache::loncommon::end_data_table();
 3777:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3778:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3779: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3780:     if (scalar(%$fullname) eq 0) {
 3781: 	my $colspan=3+scalar(@parts);
 3782: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3783:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3784: 	$result='<span class="LC_warning">'.
 3785: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3786: 	        $section_display, $stu_status).
 3787: 	    '</span>';
 3788:     }
 3789:     $result.=&show_grading_menu_form($symb);
 3790:     return $result;
 3791: }
 3792: 
 3793: #--- call by previous routine to display each student
 3794: sub viewstudentgrade {
 3795:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3796:     my ($uname,$udom) = split(/:/,$student);
 3797:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3798:     my %aggregates = (); 
 3799:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3800: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3801: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3802: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3803: 	'\');" target="_self">'.$fullname.'</a> '.
 3804: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3805:     $student=~s/:/_/; # colon doen't work in javascript for names
 3806:     foreach my $apart (@$parts) {
 3807: 	my ($part,$type) = &split_part_type($apart);
 3808: 	my $score=$record{"resource.$part.$type"};
 3809:         $result.='<td align="center">';
 3810:         my ($aggtries,$totaltries);
 3811:         unless (exists($aggregates{$part})) {
 3812: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3813: 
 3814: 	    $aggtries = $totaltries;
 3815:             if ($$last_resets{$part}) {  
 3816:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3817: 					   $part);
 3818:             }
 3819:             $result.='<input type="hidden" name="'.
 3820:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3821:             $result.='<input type="hidden" name="'.
 3822:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3823:             $aggregates{$part} = 1;
 3824:         }
 3825: 	if ($type eq 'awarded') {
 3826: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3827: 	    $result.='<input type="hidden" name="'.
 3828: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3829: 	    $result.='<input type="text" name="'.
 3830: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3831:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3832: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3833: 	} elsif ($type eq 'solved') {
 3834: 	    my ($status,$foo)=split(/_/,$score,2);
 3835: 	    $status = 'nothing' if ($status eq '');
 3836: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3837: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3838: 	    $result.='&nbsp;<select name="'.
 3839: 		'GD_'.$student.'_'.$part.'_solved" '.
 3840:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3841: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3842: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3843: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3844: 	    $result.="</select>&nbsp;</td>\n";
 3845: 	} else {
 3846: 	    $result.='<input type="hidden" name="'.
 3847: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3848: 		    "\n";
 3849: 	    $result.='<input type="text" name="'.
 3850: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3851: 		'value="'.$score.'" size="4" /></td>'."\n";
 3852: 	}
 3853:     }
 3854:     $result.=&Apache::loncommon::end_data_table_row();
 3855:     return $result;
 3856: }
 3857: 
 3858: #--- change scores for all the students in a section/class
 3859: #    record does not get update if unchanged
 3860: sub editgrades {
 3861:     my ($request) = @_;
 3862: 
 3863:     my ($symb)=&get_symb($request);
 3864:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3865:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3866:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3867:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3868: 
 3869:     my $result= &Apache::loncommon::start_data_table().
 3870: 	&Apache::loncommon::start_data_table_header_row().
 3871: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3872: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3873:     my %scoreptr = (
 3874: 		    'correct'  =>'correct_by_override',
 3875: 		    'incorrect'=>'incorrect_by_override',
 3876: 		    'excused'  =>'excused',
 3877: 		    'ungraded' =>'ungraded_attempted',
 3878:                     'credited' =>'credit_attempted',
 3879: 		    'nothing'  => '',
 3880: 		    );
 3881:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3882: 
 3883:     my (@partid);
 3884:     my %weight = ();
 3885:     my %columns = ();
 3886:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3887: 
 3888:     my $partserror;
 3889:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3890:     if ($partserror) {
 3891:         return &navmap_errormsg();
 3892:     }
 3893:     my $header;
 3894:     while ($ctr < $env{'form.totalparts'}) {
 3895: 	my $partid = $env{'form.partid_'.$ctr};
 3896: 	push(@partid,$partid);
 3897: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3898: 	$ctr++;
 3899:     }
 3900:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3901:     foreach my $partid (@partid) {
 3902: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3903: 	    '<th align="center">'.&mt('New Score').'</th>';
 3904: 	$columns{$partid}=2;
 3905: 	foreach my $stores (@parts) {
 3906: 	    my ($part,$type) = &split_part_type($stores);
 3907: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3908: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3909: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3910: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3911:             my $narrowtext = &mt('Tries');
 3912: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3913: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3914: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3915: 	    $columns{$partid}+=2;
 3916: 	}
 3917:     }
 3918:     foreach my $partid (@partid) {
 3919: 	my $display_part=&get_display_part($partid,$symb);
 3920: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3921: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3922: 	    '</th>';
 3923: 
 3924:     }
 3925:     $result .= &Apache::loncommon::end_data_table_header_row().
 3926: 	&Apache::loncommon::start_data_table_header_row().
 3927: 	$header.
 3928: 	&Apache::loncommon::end_data_table_header_row();
 3929:     my @noupdate;
 3930:     my ($updateCtr,$noupdateCtr) = (1,1);
 3931:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3932: 	my $line;
 3933: 	my $user = $env{'form.ctr'.$i};
 3934: 	my ($uname,$udom)=split(/:/,$user);
 3935: 	my %newrecord;
 3936: 	my $updateflag = 0;
 3937: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3938: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3939: 	if (!&canmodify($usec)) {
 3940: 	    my $numcols=scalar(@partid)*4+2;
 3941: 	    push(@noupdate,
 3942: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3943: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3944: 	    next;
 3945: 	}
 3946:         my %aggregate = ();
 3947:         my $aggregateflag = 0;
 3948: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3949: 	foreach (@partid) {
 3950: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3951: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3952: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3953: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3954: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3955: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3956: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3957: 	    my $score;
 3958: 	    if ($partial eq '') {
 3959: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3960: 	    } elsif ($partial > 0) {
 3961: 		$score = 'correct_by_override';
 3962: 	    } elsif ($partial == 0) {
 3963: 		$score = 'incorrect_by_override';
 3964: 	    }
 3965: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3966: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3967: 
 3968: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3969: 		"$env{'user.name'}:$env{'user.domain'}";
 3970: 	    if ($dropMenu eq 'reset status' &&
 3971: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3972: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3973: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3974: 		$newrecord{'resource.'.$_.'.award'} = '';
 3975: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3976: 		$updateflag = 1;
 3977:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3978:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3979:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3980:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3981:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3982:                     $aggregateflag = 1;
 3983:                 }
 3984: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3985: 		$updateflag = 1;
 3986: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3987: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3988: 		$rec_update++;
 3989: 	    }
 3990: 
 3991: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3992: 		'<td align="center">'.$awarded.
 3993: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3994: 
 3995: 
 3996: 	    my $partid=$_;
 3997: 	    foreach my $stores (@parts) {
 3998: 		my ($part,$type) = &split_part_type($stores);
 3999: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4000: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4001: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4002: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4003: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4004: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4005: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4006: 		    $updateflag=1;
 4007: 		}
 4008: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4009: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4010: 	    }
 4011: 	}
 4012: 	$line.="\n";
 4013: 
 4014: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4015: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4016: 
 4017: 	if ($updateflag) {
 4018: 	    $count++;
 4019: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4020: 				    $udom,$uname);
 4021: 
 4022: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4023: 					      $cnum,$udom,$uname)) {
 4024: 		# need to figure out if should be in queue.
 4025: 		my %record =  
 4026: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4027: 					     $udom,$uname);
 4028: 		my $all_graded = 1;
 4029: 		my $none_graded = 1;
 4030: 		foreach my $part (@parts) {
 4031: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4032: 			$all_graded = 0;
 4033: 		    } else {
 4034: 			$none_graded = 0;
 4035: 		    }
 4036: 		}
 4037: 
 4038: 		if ($all_graded || $none_graded) {
 4039: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4040: 							   $symb,$cdom,$cnum,
 4041: 							   $udom,$uname);
 4042: 		}
 4043: 	    }
 4044: 
 4045: 	    $result.=&Apache::loncommon::start_data_table_row().
 4046: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4047: 		&Apache::loncommon::end_data_table_row();
 4048: 	    $updateCtr++;
 4049: 	} else {
 4050: 	    push(@noupdate,
 4051: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4052: 	    $noupdateCtr++;
 4053: 	}
 4054:         if ($aggregateflag) {
 4055:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4056: 				  $cdom,$cnum);
 4057:         }
 4058:     }
 4059:     if (@noupdate) {
 4060: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4061: 	my $numcols=scalar(@partid)*4+2;
 4062: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4063: 	    '<td align="center" colspan="'.$numcols.'">'.
 4064: 	    &mt('No Changes Occurred For the Students Below').
 4065: 	    '</td>'.
 4066: 	    &Apache::loncommon::end_data_table_row();
 4067: 	foreach my $line (@noupdate) {
 4068: 	    $result.=
 4069: 		&Apache::loncommon::start_data_table_row().
 4070: 		$line.
 4071: 		&Apache::loncommon::end_data_table_row();
 4072: 	}
 4073:     }
 4074:     $result .= &Apache::loncommon::end_data_table().
 4075: 	&show_grading_menu_form($symb);
 4076:     my $msg = '<p><b>'.
 4077: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4078: 	    $rec_update,$count).'</b><br />'.
 4079: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4080: 	'</b></p>';
 4081:     return $title.$msg.$result;
 4082: }
 4083: 
 4084: sub split_part_type {
 4085:     my ($partstr) = @_;
 4086:     my ($temp,@allparts)=split(/_/,$partstr);
 4087:     my $type=pop(@allparts);
 4088:     my $part=join('_',@allparts);
 4089:     return ($part,$type);
 4090: }
 4091: 
 4092: #------------- end of section for handling grading by section/class ---------
 4093: #
 4094: #----------------------------------------------------------------------------
 4095: 
 4096: 
 4097: #----------------------------------------------------------------------------
 4098: #
 4099: #-------------------------- Next few routines handles grading by csv upload
 4100: #
 4101: #--- Javascript to handle csv upload
 4102: sub csvupload_javascript_reverse_associate {
 4103:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4104:     my $error2=&mt('You need to specify at least one grading field');
 4105:   return(<<ENDPICK);
 4106:   function verify(vf) {
 4107:     var foundsomething=0;
 4108:     var founduname=0;
 4109:     var foundID=0;
 4110:     for (i=0;i<=vf.nfields.value;i++) {
 4111:       tw=eval('vf.f'+i+'.selectedIndex');
 4112:       if (i==0 && tw!=0) { foundID=1; }
 4113:       if (i==1 && tw!=0) { founduname=1; }
 4114:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4115:     }
 4116:     if (founduname==0 && foundID==0) {
 4117: 	alert('$error1');
 4118: 	return;
 4119:     }
 4120:     if (foundsomething==0) {
 4121: 	alert('$error2');
 4122: 	return;
 4123:     }
 4124:     vf.submit();
 4125:   }
 4126:   function flip(vf,tf) {
 4127:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4128:     var i;
 4129:     for (i=0;i<=vf.nfields.value;i++) {
 4130:       //can not pick the same destination field for both name and domain
 4131:       if (((i ==0)||(i ==1)) && 
 4132:           ((tf==0)||(tf==1)) && 
 4133:           (i!=tf) &&
 4134:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4135:         eval('vf.f'+i+'.selectedIndex=0;')
 4136:       }
 4137:     }
 4138:   }
 4139: ENDPICK
 4140: }
 4141: 
 4142: sub csvupload_javascript_forward_associate {
 4143:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4144:     my $error2=&mt('You need to specify at least one grading field');
 4145:   return(<<ENDPICK);
 4146:   function verify(vf) {
 4147:     var foundsomething=0;
 4148:     var founduname=0;
 4149:     var foundID=0;
 4150:     for (i=0;i<=vf.nfields.value;i++) {
 4151:       tw=eval('vf.f'+i+'.selectedIndex');
 4152:       if (tw==1) { foundID=1; }
 4153:       if (tw==2) { founduname=1; }
 4154:       if (tw>3) { foundsomething=1; }
 4155:     }
 4156:     if (founduname==0 && foundID==0) {
 4157: 	alert('$error1');
 4158: 	return;
 4159:     }
 4160:     if (foundsomething==0) {
 4161: 	alert('$error2');
 4162: 	return;
 4163:     }
 4164:     vf.submit();
 4165:   }
 4166:   function flip(vf,tf) {
 4167:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4168:     var i;
 4169:     //can not pick the same destination field twice
 4170:     for (i=0;i<=vf.nfields.value;i++) {
 4171:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4172:         eval('vf.f'+i+'.selectedIndex=0;')
 4173:       }
 4174:     }
 4175:   }
 4176: ENDPICK
 4177: }
 4178: 
 4179: sub csvuploadmap_header {
 4180:     my ($request,$symb,$datatoken,$distotal)= @_;
 4181:     my $javascript;
 4182:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4183: 	$javascript=&csvupload_javascript_reverse_associate();
 4184:     } else {
 4185: 	$javascript=&csvupload_javascript_forward_associate();
 4186:     }
 4187: 
 4188:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4189:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4190:     my $ignore=&mt('Ignore First Line');
 4191:     $symb = &Apache::lonenc::check_encrypt($symb);
 4192:     $request->print(<<ENDPICK);
 4193: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4194: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4195: $result
 4196: <hr />
 4197: <h3>Identify fields</h3>
 4198: Total number of records found in file: $distotal <hr />
 4199: Enter as many fields as you can. The system will inform you and bring you back
 4200: to this page if the data selected is insufficient to run your class.<hr />
 4201: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4202: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4203: <input type="hidden" name="associate"  value="" />
 4204: <input type="hidden" name="phase"      value="three" />
 4205: <input type="hidden" name="datatoken"  value="$datatoken" />
 4206: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4207: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4208: <input type="hidden" name="upfile_associate" 
 4209:                                        value="$env{'form.upfile_associate'}" />
 4210: <input type="hidden" name="symb"       value="$symb" />
 4211: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4212: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4213: <input type="hidden" name="command"    value="csvuploadoptions" />
 4214: <hr />
 4215: <script type="text/javascript" language="Javascript">
 4216: $javascript
 4217: </script>
 4218: ENDPICK
 4219:     return '';
 4220: 
 4221: }
 4222: 
 4223: sub csvupload_fields {
 4224:     my ($symb,$errorref) = @_;
 4225:     my (@parts) = &getpartlist($symb,$errorref);
 4226:     if (ref($errorref)) {
 4227:         if ($$errorref) {
 4228:             return;
 4229:         }
 4230:     }
 4231: 
 4232:     my @fields=(['ID','Student/Employee ID'],
 4233: 		['username','Student Username'],
 4234: 		['domain','Student Domain']);
 4235:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4236:     foreach my $part (sort(@parts)) {
 4237: 	my @datum;
 4238: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4239: 	my $name=$part;
 4240: 	if  (!$display) { $display = $name; }
 4241: 	@datum=($name,$display);
 4242: 	if ($name=~/^stores_(.*)_awarded/) {
 4243: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4244: 	}
 4245: 	push(@fields,\@datum);
 4246:     }
 4247:     return (@fields);
 4248: }
 4249: 
 4250: sub csvuploadmap_footer {
 4251:     my ($request,$i,$keyfields) =@_;
 4252:     $request->print(<<ENDPICK);
 4253: </table>
 4254: <input type="hidden" name="nfields" value="$i" />
 4255: <input type="hidden" name="keyfields" value="$keyfields" />
 4256: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 4257: </form>
 4258: ENDPICK
 4259: }
 4260: 
 4261: sub checkforfile_js {
 4262:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4263:     my $result =<<CSVFORMJS;
 4264: <script type="text/javascript" language="javascript">
 4265:     function checkUpload(formname) {
 4266: 	if (formname.upfile.value == "") {
 4267: 	    alert("$alertmsg");
 4268: 	    return false;
 4269: 	}
 4270: 	formname.submit();
 4271:     }
 4272:     </script>
 4273: CSVFORMJS
 4274:     return $result;
 4275: }
 4276: 
 4277: sub upcsvScores_form {
 4278:     my ($request) = shift;
 4279:     my ($symb)=&get_symb($request);
 4280:     if (!$symb) {return '';}
 4281:     my $result=&checkforfile_js();
 4282:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4283:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4284:     $result.=$table;
 4285:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4286:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4287:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4288: 	'</b></td></tr>'."\n";
 4289:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4290:     my $upload=&mt("Upload Scores");
 4291:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4292:     my $ignore=&mt('Ignore First Line');
 4293:     $symb = &Apache::lonenc::check_encrypt($symb);
 4294:     $result.=<<ENDUPFORM;
 4295: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4296: <input type="hidden" name="symb" value="$symb" />
 4297: <input type="hidden" name="command" value="csvuploadmap" />
 4298: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4299: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4300: $upfile_select
 4301: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4302: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4303: </form>
 4304: ENDUPFORM
 4305:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4306:                            &mt("How do I create a CSV file from a spreadsheet"))
 4307:     .'</td></tr></table>'."\n";
 4308:     $result.='</td></tr></table><br /><br />'."\n";
 4309:     $result.=&show_grading_menu_form($symb);
 4310:     return $result;
 4311: }
 4312: 
 4313: 
 4314: sub csvuploadmap {
 4315:     my ($request)= @_;
 4316:     my ($symb)=&get_symb($request);
 4317:     if (!$symb) {return '';}
 4318: 
 4319:     my $datatoken;
 4320:     if (!$env{'form.datatoken'}) {
 4321: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4322:     } else {
 4323: 	$datatoken=$env{'form.datatoken'};
 4324: 	&Apache::loncommon::load_tmp_file($request);
 4325:     }
 4326:     my @records=&Apache::loncommon::upfile_record_sep();
 4327:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4328:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4329:     my ($i,$keyfields);
 4330:     if (@records) {
 4331:         my $fieldserror;
 4332: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4333:         if ($fieldserror) {
 4334:             $request->print(&navmap_errormsg());
 4335:             return;
 4336:         }
 4337: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4338: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4339: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4340: 							  \@fields);
 4341: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4342: 	    chop($keyfields);
 4343: 	} else {
 4344: 	    unshift(@fields,['none','']);
 4345: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4346: 							    \@fields);
 4347:             foreach my $rec (@records) {
 4348:                 my %temp = &Apache::loncommon::record_sep($rec);
 4349:                 if (%temp) {
 4350:                     $keyfields=join(',',sort(keys(%temp)));
 4351:                     last;
 4352:                 }
 4353:             }
 4354: 	}
 4355:     }
 4356:     &csvuploadmap_footer($request,$i,$keyfields);
 4357:     $request->print(&show_grading_menu_form($symb));
 4358: 
 4359:     return '';
 4360: }
 4361: 
 4362: sub csvuploadoptions {
 4363:     my ($request)= @_;
 4364:     my ($symb)=&get_symb($request);
 4365:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4366:     my $ignore=&mt('Ignore First Line');
 4367:     $request->print(<<ENDPICK);
 4368: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4369: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4370: <input type="hidden" name="command"    value="csvuploadassign" />
 4371: <!--
 4372: <p>
 4373: <label>
 4374:    <input type="checkbox" name="show_full_results" />
 4375:    Show a table of all changes
 4376: </label>
 4377: </p>
 4378: -->
 4379: <p>
 4380: <label>
 4381:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4382:    Overwrite any existing score
 4383: </label>
 4384: </p>
 4385: ENDPICK
 4386:     my %fields=&get_fields();
 4387:     if (!defined($fields{'domain'})) {
 4388: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4389: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4390:     }
 4391:     foreach my $key (sort(keys(%env))) {
 4392: 	if ($key !~ /^form\.(.*)$/) { next; }
 4393: 	my $cleankey=$1;
 4394: 	if ($cleankey eq 'command') { next; }
 4395: 	$request->print('<input type="hidden" name="'.$cleankey.
 4396: 			'"  value="'.$env{$key}.'" />'."\n");
 4397:     }
 4398:     # FIXME do a check for any duplicated user ids...
 4399:     # FIXME do a check for any invalid user ids?...
 4400:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4401: <hr /></form>'."\n");
 4402:     $request->print(&show_grading_menu_form($symb));
 4403:     return '';
 4404: }
 4405: 
 4406: sub get_fields {
 4407:     my %fields;
 4408:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4409:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4410: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4411: 	    if ($env{'form.f'.$i} ne 'none') {
 4412: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4413: 	    }
 4414: 	} else {
 4415: 	    if ($env{'form.f'.$i} ne 'none') {
 4416: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4417: 	    }
 4418: 	}
 4419:     }
 4420:     return %fields;
 4421: }
 4422: 
 4423: sub csvuploadassign {
 4424:     my ($request)= @_;
 4425:     my ($symb)=&get_symb($request);
 4426:     if (!$symb) {return '';}
 4427:     my $error_msg = '';
 4428:     &Apache::loncommon::load_tmp_file($request);
 4429:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4430:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4431:     my %fields=&get_fields();
 4432:     $request->print('<h3>Assigning Grades</h3>');
 4433:     my $courseid=$env{'request.course.id'};
 4434:     my ($classlist) = &getclasslist('all',0);
 4435:     my @notallowed;
 4436:     my @skipped;
 4437:     my @warnings;
 4438:     my $countdone=0;
 4439:     foreach my $grade (@gradedata) {
 4440: 	my %entries=&Apache::loncommon::record_sep($grade);
 4441: 	my $domain;
 4442: 	if ($entries{$fields{'domain'}}) {
 4443: 	    $domain=$entries{$fields{'domain'}};
 4444: 	} else {
 4445: 	    $domain=$env{'form.default_domain'};
 4446: 	}
 4447: 	$domain=~s/\s//g;
 4448: 	my $username=$entries{$fields{'username'}};
 4449: 	$username=~s/\s//g;
 4450: 	if (!$username) {
 4451: 	    my $id=$entries{$fields{'ID'}};
 4452: 	    $id=~s/\s//g;
 4453: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4454: 	    $username=$ids{$id};
 4455: 	}
 4456: 	if (!exists($$classlist{"$username:$domain"})) {
 4457: 	    my $id=$entries{$fields{'ID'}};
 4458: 	    $id=~s/\s//g;
 4459: 	    if ($id) {
 4460: 		push(@skipped,"$id:$domain");
 4461: 	    } else {
 4462: 		push(@skipped,"$username:$domain");
 4463: 	    }
 4464: 	    next;
 4465: 	}
 4466: 	my $usec=$classlist->{"$username:$domain"}[5];
 4467: 	if (!&canmodify($usec)) {
 4468: 	    push(@notallowed,"$username:$domain");
 4469: 	    next;
 4470: 	}
 4471: 	my %points;
 4472: 	my %grades;
 4473: 	foreach my $dest (keys(%fields)) {
 4474: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4475: 		$dest eq 'domain') { next; }
 4476: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4477: 	    if ($dest=~/stores_(.*)_points/) {
 4478: 		my $part=$1;
 4479: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4480: 					      $symb,$domain,$username);
 4481:                 if ($wgt) {
 4482:                     $entries{$fields{$dest}}=~s/\s//g;
 4483:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4484:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4485:                                           : 'correct_by_override';
 4486:                     if ($pcr>1) {
 4487:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4488:                     }
 4489:                     $grades{"resource.$part.awarded"}=$pcr;
 4490:                     $grades{"resource.$part.solved"}=$award;
 4491:                     $points{$part}=1;
 4492:                 } else {
 4493:                     $error_msg = "<br />" .
 4494:                         &mt("Some point values were assigned"
 4495:                             ." for problems with a weight "
 4496:                             ."of zero. These values were "
 4497:                             ."ignored.");
 4498:                 }
 4499: 	    } else {
 4500: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4501: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4502: 		my $store_key=$dest;
 4503: 		$store_key=~s/^stores/resource/;
 4504: 		$store_key=~s/_/\./g;
 4505: 		$grades{$store_key}=$entries{$fields{$dest}};
 4506: 	    }
 4507: 	}
 4508: 	if (! %grades) { 
 4509:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4510:         } else {
 4511: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4512: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4513: 					   $env{'request.course.id'},
 4514: 					   $domain,$username);
 4515: 	   if ($result eq 'ok') {
 4516: 	      $request->print('.');
 4517: # Remove from grading queue
 4518:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4519:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4520:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4521:                                              $domain,$username);
 4522: 	   } else {
 4523: 	      $request->print("<p><span class=\"LC_error\">".
 4524:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4525:                                   "$username:$domain",$result)."</span></p>");
 4526: 	   }
 4527: 	   $request->rflush();
 4528: 	   $countdone++;
 4529:         }
 4530:     }
 4531:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4532:     if (@warnings) {
 4533:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4534:         $request->print(join(', ',@warnings));
 4535:     }
 4536:     if (@skipped) {
 4537: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4538:         $request->print(join(', ',@skipped));
 4539:     }
 4540:     if (@notallowed) {
 4541: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4542: 	$request->print(join(', ',@notallowed));
 4543:     }
 4544:     $request->print("<br />\n");
 4545:     $request->print(&show_grading_menu_form($symb));
 4546:     return $error_msg;
 4547: }
 4548: #------------- end of section for handling csv file upload ---------
 4549: #
 4550: #-------------------------------------------------------------------
 4551: #
 4552: #-------------- Next few routines handle grading by page/sequence
 4553: #
 4554: #--- Select a page/sequence and a student to grade
 4555: sub pickStudentPage {
 4556:     my ($request) = shift;
 4557: 
 4558:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4559:     $request->print(<<LISTJAVASCRIPT);
 4560: <script type="text/javascript" language="javascript">
 4561: 
 4562: function checkPickOne(formname) {
 4563:     if (radioSelection(formname.student) == null) {
 4564: 	alert("$alertmsg");
 4565: 	return;
 4566:     }
 4567:     ptr = pullDownSelection(formname.selectpage);
 4568:     formname.page.value = formname["page"+ptr].value;
 4569:     formname.title.value = formname["title"+ptr].value;
 4570:     formname.submit();
 4571: }
 4572: 
 4573: </script>
 4574: LISTJAVASCRIPT
 4575:     &commonJSfunctions($request);
 4576:     my ($symb) = &get_symb($request);
 4577:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4578:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4579:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4580: 
 4581:     my $result='<h3><span class="LC_info">&nbsp;'.
 4582: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4583: 
 4584:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4585:     my $map_error;
 4586:     my ($titles,$symbx) = &getSymbMap($map_error);
 4587:     if ($map_error) {
 4588:         $request->print(&navmap_errormsg());
 4589:         return; 
 4590:     }
 4591:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4592: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4593: #    my $type=($curpage =~ /\.(page|sequence)/);
 4594:     my $select = '<select name="selectpage">'."\n";
 4595:     my $ctr=0;
 4596:     foreach (@$titles) {
 4597: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4598: 	$select.='<option value="'.$ctr.'" '.
 4599: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4600: 	    '>'.$showtitle.'</option>'."\n";
 4601: 	$ctr++;
 4602:     }
 4603:     $select.= '</select>';
 4604:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4605: 
 4606:     $ctr=0;
 4607:     foreach (@$titles) {
 4608: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4609: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4610: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4611: 	$ctr++;
 4612:     }
 4613:     $result.='<input type="hidden" name="page" />'."\n".
 4614: 	'<input type="hidden" name="title" />'."\n";
 4615: 
 4616:     my $options =
 4617: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4618: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4619:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4620: 
 4621:     $options =
 4622: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4623: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4624: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4625:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4626:     
 4627:     $result.=&build_section_inputs();
 4628:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4629:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4630: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4631: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4632: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4633: 
 4634:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4635: 
 4636:     $result.='&nbsp;<input type="button" '.
 4637:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4638: 
 4639:     $request->print($result);
 4640: 
 4641:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4642: 	&Apache::loncommon::start_data_table().
 4643: 	&Apache::loncommon::start_data_table_header_row().
 4644: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4645: 	'<th>'.&nameUserString('header').'</th>'.
 4646: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4647: 	'<th>'.&nameUserString('header').'</th>'.
 4648: 	&Apache::loncommon::end_data_table_header_row();
 4649:  
 4650:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4651:     my $ptr = 1;
 4652:     foreach my $student (sort 
 4653: 			 {
 4654: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4655: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4656: 			     }
 4657: 			     return $a cmp $b;
 4658: 			 } (keys(%$fullname))) {
 4659: 	my ($uname,$udom) = split(/:/,$student);
 4660: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4661:                                   : '</td>');
 4662: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4663: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4664: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4665: 	$studentTable.=
 4666: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4667:                          : '');
 4668: 	$ptr++;
 4669:     }
 4670:     if ($ptr%2 == 0) {
 4671: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4672: 	    &Apache::loncommon::end_data_table_row();
 4673:     }
 4674:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4675:     $studentTable.='<input type="button" '.
 4676:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4677: 
 4678:     $studentTable.=&show_grading_menu_form($symb);
 4679:     $request->print($studentTable);
 4680: 
 4681:     return '';
 4682: }
 4683: 
 4684: sub getSymbMap {
 4685:     my ($map_error) = @_;
 4686:     my $navmap = Apache::lonnavmaps::navmap->new();
 4687:     unless (ref($navmap)) {
 4688:         if (ref($map_error)) {
 4689:             $$map_error = 'navmap';
 4690:         }
 4691:         return;
 4692:     }
 4693:     my %symbx = ();
 4694:     my @titles = ();
 4695:     my $minder = 0;
 4696: 
 4697:     # Gather every sequence that has problems.
 4698:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4699: 					       1,0,1);
 4700:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4701: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4702: 	    my $title = $minder.'.'.
 4703: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4704: 	    push(@titles, $title); # minder in case two titles are identical
 4705: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4706: 	    $minder++;
 4707: 	}
 4708:     }
 4709:     return \@titles,\%symbx;
 4710: }
 4711: 
 4712: #
 4713: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4714: sub displayPage {
 4715:     my ($request) = shift;
 4716: 
 4717:     my ($symb) = &get_symb($request);
 4718:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4719:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4720:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4721:     my $pageTitle = $env{'form.page'};
 4722:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4723:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4724:     my $usec=$classlist->{$env{'form.student'}}[5];
 4725: 
 4726:     #need to make sure we have the correct data for later EXT calls, 
 4727:     #thus invalidate the cache
 4728:     &Apache::lonnet::devalidatecourseresdata(
 4729:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4730:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4731:     &Apache::lonnet::clear_EXT_cache_status();
 4732: 
 4733:     if (!&canview($usec)) {
 4734: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4735: 	$request->print(&show_grading_menu_form($symb));
 4736: 	return;
 4737:     }
 4738:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4739:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4740: 	'</h3>'."\n";
 4741:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4742:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4743: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4744:     } else {
 4745: 	delete($env{'form.CODE'});
 4746:     }
 4747:     &sub_page_js($request);
 4748:     $request->print($result);
 4749: 
 4750:     my $navmap = Apache::lonnavmaps::navmap->new();
 4751:     unless (ref($navmap)) {
 4752:         $request->print(&navmap_errormsg());
 4753:         $request->print(&show_grading_menu_form($symb));
 4754:         return;
 4755:     }
 4756:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4757:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4758:     if (!$map) {
 4759: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4760: 	$request->print(&show_grading_menu_form($symb));
 4761: 	return; 
 4762:     }
 4763:     my $iterator = $navmap->getIterator($map->map_start(),
 4764: 					$map->map_finish());
 4765: 
 4766:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4767: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4768: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4769: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4770: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4771: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4772: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4773: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4774: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4775: 
 4776:     if (defined($env{'form.CODE'})) {
 4777: 	$studentTable.=
 4778: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4779:     }
 4780:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4781: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4782: 
 4783:     $studentTable.='&nbsp;<span class="LC_info">'.
 4784:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4785:         '</span>'."\n".
 4786: 	&Apache::loncommon::start_data_table().
 4787: 	&Apache::loncommon::start_data_table_header_row().
 4788: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4789: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4790: 	&Apache::loncommon::end_data_table_header_row();
 4791: 
 4792:     &Apache::lonxml::clear_problem_counter();
 4793:     my ($depth,$question,$prob) = (1,1,1);
 4794:     $iterator->next(); # skip the first BEGIN_MAP
 4795:     my $curRes = $iterator->next(); # for "current resource"
 4796:     while ($depth > 0) {
 4797:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4798:         if($curRes == $iterator->END_MAP) { $depth--; }
 4799: 
 4800:         if (ref($curRes) && $curRes->is_problem()) {
 4801: 	    my $parts = $curRes->parts();
 4802:             my $title = $curRes->compTitle();
 4803: 	    my $symbx = $curRes->symb();
 4804: 	    $studentTable.=
 4805: 		&Apache::loncommon::start_data_table_row().
 4806: 		'<td align="center" valign="top" >'.$prob.
 4807: 		(scalar(@{$parts}) == 1 ? '' 
 4808: 		                        : '<br />('.&mt('[_1]parts)',
 4809: 							scalar(@{$parts}).'&nbsp;')
 4810: 		 ).
 4811: 		 '</td>';
 4812: 	    $studentTable.='<td valign="top">';
 4813: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4814: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4815: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4816: 					     undef,'both',\%form);
 4817: 	    } else {
 4818: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4819: 		$companswer =~ s|<form(.*?)>||g;
 4820: 		$companswer =~ s|</form>||g;
 4821: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4822: #		    $companswer =~ s/$1/ /ms;
 4823: #		    $request->print('match='.$1."<br />\n");
 4824: #		}
 4825: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4826: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4827: 	    }
 4828: 
 4829: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4830: 
 4831: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4832: 		if ($record{'version'} eq '') {
 4833: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4834: 		} else {
 4835: 		    my %responseType = ();
 4836: 		    foreach my $partid (@{$parts}) {
 4837: 			my @responseIds =$curRes->responseIds($partid);
 4838: 			my @responseType =$curRes->responseType($partid);
 4839: 			my %responseIds;
 4840: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4841: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4842: 			}
 4843: 			$responseType{$partid} = \%responseIds;
 4844: 		    }
 4845: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4846: 
 4847: 		}
 4848: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4849: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4850: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4851: 									$env{'request.course.id'},
 4852: 									'','.submission');
 4853:  
 4854: 	    }
 4855: 	    if (&canmodify($usec)) {
 4856:             $studentTable.=&gradeBox_start();
 4857: 		foreach my $partid (@{$parts}) {
 4858: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4859: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4860: 		    $question++;
 4861: 		}
 4862:             $studentTable.=&gradeBox_end();
 4863: 		$prob++;
 4864: 	    }
 4865: 	    $studentTable.='</td></tr>';
 4866: 
 4867: 	}
 4868:         $curRes = $iterator->next();
 4869:     }
 4870: 
 4871:     $studentTable.=
 4872:         '</table>'."\n".
 4873:         '<input type="button" value="'.&mt('Save').'" '.
 4874:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4875:         '</form>'."\n";
 4876:     $studentTable.=&show_grading_menu_form($symb);
 4877:     $request->print($studentTable);
 4878: 
 4879:     return '';
 4880: }
 4881: 
 4882: sub displaySubByDates {
 4883:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4884:     my $isCODE=0;
 4885:     my $isTask = ($symb =~/\.task$/);
 4886:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4887:     my $studentTable=&Apache::loncommon::start_data_table().
 4888: 	&Apache::loncommon::start_data_table_header_row().
 4889: 	'<th>'.&mt('Date/Time').'</th>'.
 4890: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4891:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4892: 	'<th>'.&mt('Submission').'</th>'.
 4893: 	'<th>'.&mt('Status').'</th>'.
 4894: 	&Apache::loncommon::end_data_table_header_row();
 4895:     my ($version);
 4896:     my %mark;
 4897:     my %orders;
 4898:     $mark{'correct_by_student'} = $checkIcon;
 4899:     if (!exists($$record{'1:timestamp'})) {
 4900: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4901:     }
 4902: 
 4903:     my $interaction;
 4904:     my $no_increment = 1;
 4905:     my %lastrndseed;
 4906:     for ($version=1;$version<=$$record{'version'};$version++) {
 4907: 	my $timestamp = 
 4908: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4909: 	if (exists($$record{$version.':resource.0.version'})) {
 4910: 	    $interaction = $$record{$version.':resource.0.version'};
 4911: 	}
 4912:         if ($isTask && $env{'form.previousversion'}) {
 4913:             next unless ($interaction == $env{'form.previousversion'});
 4914:         }
 4915: 	my $where = ($isTask ? "$version:resource.$interaction"
 4916: 		             : "$version:resource");
 4917: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4918: 	    '<td>'.$timestamp.'</td>';
 4919: 	if ($isCODE) {
 4920: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4921: 	}
 4922:         if ($isTask) {
 4923:             $studentTable.='<td>'.$interaction.'</td>';
 4924:         }
 4925: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4926: 	my @displaySub = ();
 4927: 	foreach my $partid (@{$parts}) {
 4928:             my ($hidden,$type);
 4929:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4930:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4931:                 $hidden = 1;
 4932:             }
 4933: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4934: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4935: 	    
 4936: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4937: 	    my $display_part=&get_display_part($partid,$symb);
 4938: 	    foreach my $matchKey (@matchKey) {
 4939: 		if (exists($$record{$version.':'.$matchKey}) &&
 4940: 		    $$record{$version.':'.$matchKey} ne '') {
 4941:                     
 4942: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4943: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4944:                     $displaySub[0].='<span class="LC_nobreak">';
 4945:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4946:                                    .' <span class="LC_internal_info">'
 4947:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4948:                                    .'</span>'
 4949:                                    .' <b>';
 4950:                     if ($hidden) {
 4951:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4952:                     } else {
 4953:                         my ($trial,$rndseed,$newvariation);
 4954:                         if ($type eq 'randomizetry') {
 4955:                             $trial = $$record{"$where.$partid.tries"};
 4956:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4957:                         }
 4958: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4959: 			    $displaySub[0].=&mt('Trial not counted');
 4960: 		        } else {
 4961: 			    $displaySub[0].=&mt('Trial: [_1]',
 4962: 					    $$record{"$where.$partid.tries"});
 4963:                             if ($rndseed || $lastrndseed{$partid}) {
 4964:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4965:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4966:                                 }
 4967:                             }
 4968: 		        }
 4969: 		        my $responseType=($isTask ? 'Task'
 4970:                                               : $responseType->{$partid}->{$responseId});
 4971: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4972: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4973: 			    $orders{$partid}->{$responseId}=
 4974: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4975:                                            $no_increment,$type,$trial,$rndseed);
 4976: 		        }
 4977: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4978: 		        $displaySub[0].='&nbsp; '.
 4979: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4980:                     }
 4981: 		}
 4982: 	    }
 4983: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4984: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4985: 				    $$record{"$where.$partid.checkedin"},
 4986: 				    $$record{"$where.$partid.checkedin.slot"}).
 4987: 					'<br />';
 4988: 	    }
 4989: 	    if (exists $$record{"$where.$partid.award"}) {
 4990: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4991: 		    lc($$record{"$where.$partid.award"}).' '.
 4992: 		    $mark{$$record{"$where.$partid.solved"}}.
 4993: 		    '<br />';
 4994: 	    }
 4995: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4996: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4997: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4998: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4999: 		$displaySub[2].=
 5000: 		    $$record{"$version:resource.$partid.regrader"}.
 5001: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5002: 	    }
 5003: 	}
 5004: 	# needed because old essay regrader has not parts info
 5005: 	if (exists $$record{"$version:resource.regrader"}) {
 5006: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5007: 	}
 5008: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5009: 	if ($displaySub[2]) {
 5010: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5011: 	}
 5012: 	$studentTable.='&nbsp;</td>'.
 5013: 	    &Apache::loncommon::end_data_table_row();
 5014:     }
 5015:     $studentTable.=&Apache::loncommon::end_data_table();
 5016:     return $studentTable;
 5017: }
 5018: 
 5019: sub updateGradeByPage {
 5020:     my ($request) = shift;
 5021: 
 5022:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5023:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5024:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5025:     my $pageTitle = $env{'form.page'};
 5026:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5027:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5028:     my $usec=$classlist->{$env{'form.student'}}[5];
 5029:     if (!&canmodify($usec)) {
 5030: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5031: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5032: 	return;
 5033:     }
 5034:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5035:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5036: 	'</h3>'."\n";
 5037: 
 5038:     $request->print($result);
 5039: 
 5040: 
 5041:     my $navmap = Apache::lonnavmaps::navmap->new();
 5042:     unless (ref($navmap)) {
 5043:         $request->print(&navmap_errormsg());
 5044:         return;
 5045:     }
 5046:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5047:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5048:     if (!$map) {
 5049: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5050: 	my ($symb)=&get_symb($request);
 5051: 	$request->print(&show_grading_menu_form($symb));
 5052: 	return; 
 5053:     }
 5054:     my $iterator = $navmap->getIterator($map->map_start(),
 5055: 					$map->map_finish());
 5056: 
 5057:     my $studentTable=
 5058: 	&Apache::loncommon::start_data_table().
 5059: 	&Apache::loncommon::start_data_table_header_row().
 5060: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5061: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5062: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5063: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5064: 	&Apache::loncommon::end_data_table_header_row();
 5065: 
 5066:     $iterator->next(); # skip the first BEGIN_MAP
 5067:     my $curRes = $iterator->next(); # for "current resource"
 5068:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 5069:     while ($depth > 0) {
 5070:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5071:         if($curRes == $iterator->END_MAP) { $depth--; }
 5072: 
 5073:         if (ref($curRes) && $curRes->is_problem()) {
 5074: 	    my $parts = $curRes->parts();
 5075:             my $title = $curRes->compTitle();
 5076: 	    my $symbx = $curRes->symb();
 5077: 	    $studentTable.=
 5078: 		&Apache::loncommon::start_data_table_row().
 5079: 		'<td align="center" valign="top" >'.$prob.
 5080: 		(scalar(@{$parts}) == 1 ? '' 
 5081:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5082: 		.')').'</td>';
 5083: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5084: 
 5085: 	    my %newrecord=();
 5086: 	    my @displayPts=();
 5087:             my %aggregate = ();
 5088:             my $aggregateflag = 0;
 5089: 	    foreach my $partid (@{$parts}) {
 5090: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5091: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5092: 
 5093: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5094: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5095: 		my $partial = $newpts/$wgt;
 5096: 		my $score;
 5097: 		if ($partial > 0) {
 5098: 		    $score = 'correct_by_override';
 5099: 		} elsif ($newpts ne '') { #empty is taken as 0
 5100: 		    $score = 'incorrect_by_override';
 5101: 		}
 5102: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5103: 		if ($dropMenu eq 'excused') {
 5104: 		    $partial = '';
 5105: 		    $score = 'excused';
 5106: 		} elsif ($dropMenu eq 'reset status'
 5107: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5108: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5109: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5110: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5111: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5112: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5113: 		    $changeflag++;
 5114: 		    $newpts = '';
 5115:                     
 5116:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5117:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5118:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5119:                     if ($aggtries > 0) {
 5120:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5121:                         $aggregateflag = 1;
 5122:                     }
 5123: 		}
 5124: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5125: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5126: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5127: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5128: 		    '&nbsp;<br />';
 5129: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5130: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5131: 		    '&nbsp;<br />';
 5132: 		$question++;
 5133: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5134: 
 5135: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5136: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5137: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5138: 		    if (scalar(keys(%newrecord)) > 0);
 5139: 
 5140: 		$changeflag++;
 5141: 	    }
 5142: 	    if (scalar(keys(%newrecord)) > 0) {
 5143: 		my %record = 
 5144: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5145: 					     $udom,$uname);
 5146: 
 5147: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5148: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5149: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5150: 		    $newrecord{'resource.CODE'} = '';
 5151: 		}
 5152: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5153: 					$udom,$uname);
 5154: 		%record = &Apache::lonnet::restore($symbx,
 5155: 						   $env{'request.course.id'},
 5156: 						   $udom,$uname);
 5157: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5158: 					     $cdom,$cnum,$udom,$uname);
 5159: 	    }
 5160: 	    
 5161:             if ($aggregateflag) {
 5162:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5163:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5164:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5165:             }
 5166: 
 5167: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5168: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5169: 		&Apache::loncommon::end_data_table_row();
 5170: 
 5171: 	    $prob++;
 5172: 	}
 5173:         $curRes = $iterator->next();
 5174:     }
 5175: 
 5176:     $studentTable.=&Apache::loncommon::end_data_table();
 5177:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5178:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5179: 		  &mt('The scores were changed for [quant,_1,problem].',
 5180: 		  $changeflag));
 5181:     $request->print($grademsg.$studentTable);
 5182: 
 5183:     return '';
 5184: }
 5185: 
 5186: #-------- end of section for handling grading by page/sequence ---------
 5187: #
 5188: #-------------------------------------------------------------------
 5189: 
 5190: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5191: #
 5192: #------ start of section for handling grading by page/sequence ---------
 5193: 
 5194: =pod
 5195: 
 5196: =head1 Bubble sheet grading routines
 5197: 
 5198:   For this documentation:
 5199: 
 5200:    'scanline' refers to the full line of characters
 5201:    from the file that we are parsing that represents one entire sheet
 5202: 
 5203:    'bubble line' refers to the data
 5204:    representing the line of bubbles that are on the physical bubblesheet
 5205: 
 5206: 
 5207: The overall process is that a scanned in bubblesheet data is uploaded
 5208: into a course. When a user wants to grade, they select a
 5209: sequence/folder of resources, a file of bubblesheet info, and pick
 5210: one of the predefined configurations for what each scanline looks
 5211: like.
 5212: 
 5213: Next each scanline is checked for any errors of either 'missing
 5214: bubbles' (it's an error because it may have been mis-scanned
 5215: because too light bubbling), 'double bubble' (each bubble line should
 5216: have no more that one letter picked), invalid or duplicated CODE,
 5217: invalid student/employee ID
 5218: 
 5219: If the CODE option is used that determines the randomization of the
 5220: homework problems, either way the student/employee ID is looked up into a
 5221: username:domain.
 5222: 
 5223: During the validation phase the instructor can choose to skip scanlines. 
 5224: 
 5225: After the validation phase, there are now 3 bubblesheet files
 5226: 
 5227:   scantron_original_filename (unmodified original file)
 5228:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5229:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5230: 
 5231: Also there is a separate hash nohist_scantrondata that contains extra
 5232: correction information that isn't representable in the bubblesheet
 5233: file (see &scantron_getfile() for more information)
 5234: 
 5235: After all scanlines are either valid, marked as valid or skipped, then
 5236: foreach line foreach problem in the picked sequence, an ssi request is
 5237: made that simulates a user submitting their selected letter(s) against
 5238: the homework problem.
 5239: 
 5240: =over 4
 5241: 
 5242: 
 5243: 
 5244: =item defaultFormData
 5245: 
 5246:   Returns html hidden inputs used to hold context/default values.
 5247: 
 5248:  Arguments:
 5249:   $symb - $symb of the current resource 
 5250: 
 5251: =cut
 5252: 
 5253: sub defaultFormData {
 5254:     my ($symb)=@_;
 5255:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5256:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5257:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5258: }
 5259: 
 5260: 
 5261: =pod 
 5262: 
 5263: =item getSequenceDropDown
 5264: 
 5265:    Return html dropdown of possible sequences to grade
 5266:  
 5267:  Arguments:
 5268:    $symb - $symb of the current resource
 5269:    $map_error - ref to scalar which will container error if
 5270:                 $navmap object is unavailable in &getSymbMap().
 5271: 
 5272: =cut
 5273: 
 5274: sub getSequenceDropDown {
 5275:     my ($symb,$map_error)=@_;
 5276:     my $result='<select name="selectpage">'."\n";
 5277:     my ($titles,$symbx) = &getSymbMap($map_error);
 5278:     if (ref($map_error)) {
 5279:         return if ($$map_error);
 5280:     }
 5281:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5282:     my $ctr=0;
 5283:     foreach (@$titles) {
 5284: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5285: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5286: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5287: 	    '>'.$showtitle.'</option>'."\n";
 5288: 	$ctr++;
 5289:     }
 5290:     $result.= '</select>';
 5291:     return $result;
 5292: }
 5293: 
 5294: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5295:                                    # key is zero-based index - 0, 1, 2 ...
 5296: 
 5297: my %first_bubble_line;             # First bubble line no. for each bubble.
 5298: 
 5299: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5300:                                    # matchresponse or rankresponse, where 
 5301:                                    # an individual response can have multiple 
 5302:                                    # lines
 5303: 
 5304: my %responsetype_per_response;     # responsetype for each response
 5305: 
 5306: # Save and restore the bubble lines array to the form env.
 5307: 
 5308: 
 5309: sub save_bubble_lines {
 5310:     foreach my $line (keys(%bubble_lines_per_response)) {
 5311: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5312: 	$env{"form.scantron.first_bubble_line.$line"} =
 5313: 	    $first_bubble_line{$line};
 5314:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5315:             $subdivided_bubble_lines{$line};
 5316:         $env{"form.scantron.responsetype.$line"} =
 5317:             $responsetype_per_response{$line};
 5318:     }
 5319: }
 5320: 
 5321: 
 5322: sub restore_bubble_lines {
 5323:     my $line = 0;
 5324:     %bubble_lines_per_response = ();
 5325:     while ($env{"form.scantron.bubblelines.$line"}) {
 5326: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5327: 	$bubble_lines_per_response{$line} = $value;
 5328: 	$first_bubble_line{$line}  =
 5329: 	    $env{"form.scantron.first_bubble_line.$line"};
 5330:         $subdivided_bubble_lines{$line} =
 5331:             $env{"form.scantron.sub_bubblelines.$line"};
 5332:         $responsetype_per_response{$line} =
 5333:             $env{"form.scantron.responsetype.$line"};
 5334: 	$line++;
 5335:     }
 5336: }
 5337: 
 5338: #  Given the parsed scanline, get the response for 
 5339: #  'answer' number n:
 5340: 
 5341: sub get_response_bubbles {
 5342:     my ($parsed_line, $response)  = @_;
 5343: 
 5344:     my $bubble_line = $first_bubble_line{$response-1} +1;
 5345:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 5346:     
 5347:     my $selected = "";
 5348: 
 5349:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 5350: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 5351: 	$bubble_line++;
 5352:     }
 5353:     return $selected;
 5354: }
 5355: 
 5356: =pod 
 5357: 
 5358: =item scantron_filenames
 5359: 
 5360:    Returns a list of the scantron files in the current course 
 5361: 
 5362: =cut
 5363: 
 5364: sub scantron_filenames {
 5365:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5366:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5367:     my $getpropath = 1;
 5368:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5369:                                                         $cname,$getpropath);
 5370:     my @possiblenames;
 5371:     if (ref($dirlist) eq 'ARRAY') {
 5372:         foreach my $filename (sort(@{$dirlist})) {
 5373: 	    ($filename)=split(/&/,$filename);
 5374: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5375: 	    $filename=~s/^scantron_orig_//;
 5376: 	    push(@possiblenames,$filename);
 5377:         }
 5378:     }
 5379:     return @possiblenames;
 5380: }
 5381: 
 5382: =pod 
 5383: 
 5384: =item scantron_uploads
 5385: 
 5386:    Returns  html drop-down list of scantron files in current course.
 5387: 
 5388:  Arguments:
 5389:    $file2grade - filename to set as selected in the dropdown
 5390: 
 5391: =cut
 5392: 
 5393: sub scantron_uploads {
 5394:     my ($file2grade) = @_;
 5395:     my $result=	'<select name="scantron_selectfile">';
 5396:     $result.="<option></option>";
 5397:     foreach my $filename (sort(&scantron_filenames())) {
 5398: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5399:     }
 5400:     $result.="</select>";
 5401:     return $result;
 5402: }
 5403: 
 5404: =pod 
 5405: 
 5406: =item scantron_scantab
 5407: 
 5408:   Returns html drop down of the scantron formats in the scantronformat.tab
 5409:   file.
 5410: 
 5411: =cut
 5412: 
 5413: sub scantron_scantab {
 5414:     my $result='<select name="scantron_format">'."\n";
 5415:     $result.='<option></option>'."\n";
 5416:     my @lines = &get_scantronformat_file();
 5417:     if (@lines > 0) {
 5418:         foreach my $line (@lines) {
 5419:             next if (($line =~ /^\#/) || ($line eq ''));
 5420: 	    my ($name,$descrip)=split(/:/,$line);
 5421: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5422:         }
 5423:     }
 5424:     $result.='</select>'."\n";
 5425:     return $result;
 5426: }
 5427: 
 5428: =pod
 5429: 
 5430: =item get_scantronformat_file
 5431: 
 5432:   Returns an array containing lines from the scantron format file for
 5433:   the domain of the course.
 5434: 
 5435:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5436:   lines are from this file.
 5437: 
 5438:   Otherwise, if a default.tab has been published in RES space by the 
 5439:   domainconfig user, lines are from this file.
 5440: 
 5441:   Otherwise, fall back to getting lines from the legacy file on the
 5442:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5443: 
 5444: =cut
 5445: 
 5446: sub get_scantronformat_file {
 5447:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5448:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5449:     my $gottab = 0;
 5450:     my @lines;
 5451:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5452:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5453:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5454:             if ($formatfile ne '-1') {
 5455:                 @lines = split("\n",$formatfile,-1);
 5456:                 $gottab = 1;
 5457:             }
 5458:         }
 5459:     }
 5460:     if (!$gottab) {
 5461:         my $confname = $cdom.'-domainconfig';
 5462:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5463:         my $formatfile =  &Apache::lonnet::getfile($default);
 5464:         if ($formatfile ne '-1') {
 5465:             @lines = split("\n",$formatfile,-1);
 5466:             $gottab = 1;
 5467:         }
 5468:     }
 5469:     if (!$gottab) {
 5470:         my @domains = &Apache::lonnet::current_machine_domains();
 5471:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5472:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5473:             @lines = <$fh>;
 5474:             close($fh);
 5475:         } else {
 5476:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5477:             @lines = <$fh>;
 5478:             close($fh);
 5479:         }
 5480:     }
 5481:     return @lines;
 5482: }
 5483: 
 5484: =pod 
 5485: 
 5486: =item scantron_CODElist
 5487: 
 5488:   Returns html drop down of the saved CODE lists from current course,
 5489:   generated from earlier printings.
 5490: 
 5491: =cut
 5492: 
 5493: sub scantron_CODElist {
 5494:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5495:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5496:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5497:     my $namechoice='<option></option>';
 5498:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5499: 	if ($name =~ /^error: 2 /) { next; }
 5500: 	if ($name =~ /^type\0/) { next; }
 5501: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5502:     }
 5503:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5504:     return $namechoice;
 5505: }
 5506: 
 5507: =pod 
 5508: 
 5509: =item scantron_CODEunique
 5510: 
 5511:   Returns the html for "Each CODE to be used once" radio.
 5512: 
 5513: =cut
 5514: 
 5515: sub scantron_CODEunique {
 5516:     my $result='<span class="LC_nobreak">
 5517:                  <label><input type="radio" name="scantron_CODEunique"
 5518:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5519:                 </span>
 5520:                 <span class="LC_nobreak">
 5521:                  <label><input type="radio" name="scantron_CODEunique"
 5522:                         value="no" />'.&mt('No').' </label>
 5523:                 </span>';
 5524:     return $result;
 5525: }
 5526: 
 5527: =pod 
 5528: 
 5529: =item scantron_selectphase
 5530: 
 5531:   Generates the initial screen to start the bubblesheet process.
 5532:   Allows for - starting a grading run.
 5533:              - downloading existing scan data (original, corrected
 5534:                                                 or skipped info)
 5535: 
 5536:              - uploading new scan data
 5537: 
 5538:  Arguments:
 5539:   $r          - The Apache request object
 5540:   $file2grade - name of the file that contain the scanned data to score
 5541: 
 5542: =cut
 5543: 
 5544: sub scantron_selectphase {
 5545:     my ($r,$file2grade) = @_;
 5546:     my ($symb)=&get_symb($r);
 5547:     if (!$symb) {return '';}
 5548:     my $map_error;
 5549:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5550:     if ($map_error) {
 5551:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5552:         return;
 5553:     }
 5554:     my $default_form_data=&defaultFormData($symb);
 5555:     my $grading_menu_button=&show_grading_menu_form($symb);
 5556:     my $file_selector=&scantron_uploads($file2grade);
 5557:     my $format_selector=&scantron_scantab();
 5558:     my $CODE_selector=&scantron_CODElist();
 5559:     my $CODE_unique=&scantron_CODEunique();
 5560:     my $result;
 5561: 
 5562:     $ssi_error = 0;
 5563: 
 5564:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5565:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5566: 
 5567:         # Chunk of form to prompt for a scantron file upload.
 5568: 
 5569:         $r->print('
 5570:     <br />
 5571:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5572:        '.&Apache::loncommon::start_data_table_header_row().'
 5573:             <th>
 5574:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5575:             </th>
 5576:        '.&Apache::loncommon::end_data_table_header_row().'
 5577:        '.&Apache::loncommon::start_data_table_row().'
 5578:             <td>
 5579: ');
 5580:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5581:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5582:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5583:     $r->print('
 5584:               <script type="text/javascript" language="javascript">
 5585:     function checkUpload(formname) {
 5586:         if (formname.upfile.value == "") {
 5587:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5588:             return false;
 5589:         }
 5590:         formname.submit();
 5591:     }
 5592:               </script>
 5593: 
 5594:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5595:                 '.$default_form_data.'
 5596:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5597:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5598:                 <input name="command" value="scantronupload_save" type="hidden" />
 5599:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5600:                 <br />
 5601:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5602:               </form>
 5603: ');
 5604: 
 5605:         $r->print('
 5606:             </td>
 5607:        '.&Apache::loncommon::end_data_table_row().'
 5608:        '.&Apache::loncommon::end_data_table().'
 5609: ');
 5610:     }
 5611: 
 5612:     # Chunk of form to prompt for a file to grade and how:
 5613: 
 5614:     $result.= '
 5615:     <br />
 5616:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5617:     <input type="hidden" name="command" value="scantron_warning" />
 5618:     '.$default_form_data.'
 5619:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5620:        '.&Apache::loncommon::start_data_table_header_row().'
 5621:             <th colspan="2">
 5622:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5623:             </th>
 5624:        '.&Apache::loncommon::end_data_table_header_row().'
 5625:        '.&Apache::loncommon::start_data_table_row().'
 5626:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5627:        '.&Apache::loncommon::end_data_table_row().'
 5628:        '.&Apache::loncommon::start_data_table_row().'
 5629:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5630:        '.&Apache::loncommon::end_data_table_row().'
 5631:        '.&Apache::loncommon::start_data_table_row().'
 5632:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5633:        '.&Apache::loncommon::end_data_table_row().'
 5634:        '.&Apache::loncommon::start_data_table_row().'
 5635:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5636:        '.&Apache::loncommon::end_data_table_row().'
 5637:        '.&Apache::loncommon::start_data_table_row().'
 5638:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5639:        '.&Apache::loncommon::end_data_table_row().'
 5640:        '.&Apache::loncommon::start_data_table_row().'
 5641: 	    <td> '.&mt('Options:').' </td>
 5642:             <td>
 5643: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5644:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5645:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5646: 	    </td>
 5647:        '.&Apache::loncommon::end_data_table_row().'
 5648:        '.&Apache::loncommon::start_data_table_row().'
 5649:             <td colspan="2">
 5650:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5651:             </td>
 5652:        '.&Apache::loncommon::end_data_table_row().'
 5653:     '.&Apache::loncommon::end_data_table().'
 5654:     </form>
 5655: ';
 5656:    
 5657:     $r->print($result);
 5658: 
 5659:     # Chunk of the form that prompts to view a scoring office file,
 5660:     # corrected file, skipped records in a file.
 5661: 
 5662:     $r->print('
 5663:    <br />
 5664:    <form action="/adm/grades" name="scantron_download">
 5665:      '.$default_form_data.'
 5666:      <input type="hidden" name="command" value="scantron_download" />
 5667:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5668:        '.&Apache::loncommon::start_data_table_header_row().'
 5669:               <th>
 5670:                 &nbsp;'.&mt('Download a scoring office file').'
 5671:               </th>
 5672:        '.&Apache::loncommon::end_data_table_header_row().'
 5673:        '.&Apache::loncommon::start_data_table_row().'
 5674:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5675:                 <br />
 5676:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5677:        '.&Apache::loncommon::end_data_table_row().'
 5678:      '.&Apache::loncommon::end_data_table().'
 5679:    </form>
 5680:    <br />
 5681: ');
 5682: 
 5683:     &Apache::lonpickcode::code_list($r,2);
 5684: 
 5685:     $r->print('<br /><form method="post" name="checkscantron">'.
 5686:              $default_form_data."\n".
 5687:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5688:              &Apache::loncommon::start_data_table_header_row()."\n".
 5689:              '<th colspan="2">
 5690:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5691:              '</th>'."\n".
 5692:               &Apache::loncommon::end_data_table_header_row()."\n".
 5693:               &Apache::loncommon::start_data_table_row()."\n".
 5694:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5695:               '<td> '.$sequence_selector.' </td>'.
 5696:               &Apache::loncommon::end_data_table_row()."\n".
 5697:               &Apache::loncommon::start_data_table_row()."\n".
 5698:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5699:               '<td> '.$file_selector.' </td>'."\n".
 5700:               &Apache::loncommon::end_data_table_row()."\n".
 5701:               &Apache::loncommon::start_data_table_row()."\n".
 5702:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5703:               '<td> '.$format_selector.' </td>'."\n".
 5704:               &Apache::loncommon::end_data_table_row()."\n".
 5705:               &Apache::loncommon::start_data_table_row()."\n".
 5706:               '<td> '.&mt('Options').' </td>'."\n".
 5707:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5708:               &Apache::loncommon::end_data_table_row()."\n".
 5709:               &Apache::loncommon::start_data_table_row()."\n".
 5710:               '<td colspan="2">'."\n".
 5711:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5712:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5713:               '</td>'."\n".
 5714:               &Apache::loncommon::end_data_table_row()."\n".
 5715:               &Apache::loncommon::end_data_table()."\n".
 5716:               '</form><br />');
 5717:     $r->print($grading_menu_button);
 5718:     return;
 5719: }
 5720: 
 5721: =pod
 5722: 
 5723: =item get_scantron_config
 5724: 
 5725:    Parse and return the scantron configuration line selected as a
 5726:    hash of configuration file fields.
 5727: 
 5728:  Arguments:
 5729:     which - the name of the configuration to parse from the file.
 5730: 
 5731: 
 5732:  Returns:
 5733:             If the named configuration is not in the file, an empty
 5734:             hash is returned.
 5735:     a hash with the fields
 5736:       name         - internal name for the this configuration setup
 5737:       description  - text to display to operator that describes this config
 5738:       CODElocation - if 0 or the string 'none'
 5739:                           - no CODE exists for this config
 5740:                      if -1 || the string 'letter'
 5741:                           - a CODE exists for this config and is
 5742:                             a string of letters
 5743:                      Unsupported value (but planned for future support)
 5744:                           if a positive integer
 5745:                                - The CODE exists as the first n items from
 5746:                                  the question section of the form
 5747:                           if the string 'number'
 5748:                                - The CODE exists for this config and is
 5749:                                  a string of numbers
 5750:       CODEstart   - (only matter if a CODE exists) column in the line where
 5751:                      the CODE starts
 5752:       CODElength  - length of the CODE
 5753:       IDstart     - column where the student/employee ID starts
 5754:       IDlength    - length of the student/employee ID info
 5755:       Qstart      - column where the information from the bubbled
 5756:                     'questions' start
 5757:       Qlength     - number of columns comprising a single bubble line from
 5758:                     the sheet. (usually either 1 or 10)
 5759:       Qon         - either a single character representing the character used
 5760:                     to signal a bubble was chosen in the positional setup, or
 5761:                     the string 'letter' if the letter of the chosen bubble is
 5762:                     in the final, or 'number' if a number representing the
 5763:                     chosen bubble is in the file (1->A 0->J)
 5764:       Qoff        - the character used to represent that a bubble was
 5765:                     left blank
 5766:       PaperID     - if the scanning process generates a unique number for each
 5767:                     sheet scanned the column that this ID number starts in
 5768:       PaperIDlength - number of columns that comprise the unique ID number
 5769:                       for the sheet of paper
 5770:       FirstName   - column that the first name starts in
 5771:       FirstNameLength - number of columns that the first name spans
 5772:  
 5773:       LastName    - column that the last name starts in
 5774:       LastNameLength - number of columns that the last name spans
 5775:       BubblesPerRow - number of bubbles available in each row used to
 5776:                       bubble an answer. (If not specified, 10 assumed).
 5777: 
 5778: =cut
 5779: 
 5780: sub get_scantron_config {
 5781:     my ($which) = @_;
 5782:     my @lines = &get_scantronformat_file();
 5783:     my %config;
 5784:     #FIXME probably should move to XML it has already gotten a bit much now
 5785:     foreach my $line (@lines) {
 5786: 	my ($name,$descrip)=split(/:/,$line);
 5787: 	if ($name ne $which ) { next; }
 5788: 	chomp($line);
 5789: 	my @config=split(/:/,$line);
 5790: 	$config{'name'}=$config[0];
 5791: 	$config{'description'}=$config[1];
 5792: 	$config{'CODElocation'}=$config[2];
 5793: 	$config{'CODEstart'}=$config[3];
 5794: 	$config{'CODElength'}=$config[4];
 5795: 	$config{'IDstart'}=$config[5];
 5796: 	$config{'IDlength'}=$config[6];
 5797: 	$config{'Qstart'}=$config[7];
 5798:  	$config{'Qlength'}=$config[8];
 5799: 	$config{'Qoff'}=$config[9];
 5800: 	$config{'Qon'}=$config[10];
 5801: 	$config{'PaperID'}=$config[11];
 5802: 	$config{'PaperIDlength'}=$config[12];
 5803: 	$config{'FirstName'}=$config[13];
 5804: 	$config{'FirstNamelength'}=$config[14];
 5805: 	$config{'LastName'}=$config[15];
 5806: 	$config{'LastNamelength'}=$config[16];
 5807:         $config{'BubblesPerRow'}=$config[17];
 5808: 	last;
 5809:     }
 5810:     return %config;
 5811: }
 5812: 
 5813: =pod 
 5814: 
 5815: =item username_to_idmap
 5816: 
 5817:     creates a hash keyed by student/employee ID with values of the corresponding
 5818:     student username:domain.
 5819: 
 5820:   Arguments:
 5821: 
 5822:     $classlist - reference to the class list hash. This is a hash
 5823:                  keyed by student name:domain  whose elements are references
 5824:                  to arrays containing various chunks of information
 5825:                  about the student. (See loncoursedata for more info).
 5826: 
 5827:   Returns
 5828:     %idmap - the constructed hash
 5829: 
 5830: =cut
 5831: 
 5832: sub username_to_idmap {
 5833:     my ($classlist)= @_;
 5834:     my %idmap;
 5835:     foreach my $student (keys(%$classlist)) {
 5836: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5837: 	    $student;
 5838:     }
 5839:     return %idmap;
 5840: }
 5841: 
 5842: =pod
 5843: 
 5844: =item scantron_fixup_scanline
 5845: 
 5846:    Process a requested correction to a scanline.
 5847: 
 5848:   Arguments:
 5849:     $scantron_config   - hash from &get_scantron_config()
 5850:     $scan_data         - hash of correction information 
 5851:                           (see &scantron_getfile())
 5852:     $line              - existing scanline
 5853:     $whichline         - line number of the passed in scanline
 5854:     $field             - type of change to process 
 5855:                          (either 
 5856:                           'ID'     -> correct the student/employee ID
 5857:                           'CODE'   -> correct the CODE
 5858:                           'answer' -> fixup the submitted answers)
 5859:     
 5860:    $args               - hash of additional info,
 5861:                           - 'ID' 
 5862:                                'newid' -> studentID to use in replacement
 5863:                                           of existing one
 5864:                           - 'CODE' 
 5865:                                'CODE_ignore_dup' - set to true if duplicates
 5866:                                                    should be ignored.
 5867: 	                       'CODE' - is new code or 'use_unfound'
 5868:                                         if the existing unfound code should
 5869:                                         be used as is
 5870:                           - 'answer'
 5871:                                'response' - new answer or 'none' if blank
 5872:                                'question' - the bubble line to change
 5873:                                'questionnum' - the question identifier,
 5874:                                                may include subquestion. 
 5875: 
 5876:   Returns:
 5877:     $line - the modified scanline
 5878: 
 5879:   Side effects: 
 5880:     $scan_data - may be updated
 5881: 
 5882: =cut
 5883: 
 5884: 
 5885: sub scantron_fixup_scanline {
 5886:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5887:     if ($field eq 'ID') {
 5888: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5889: 	    return ($line,1,'New value too large');
 5890: 	}
 5891: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5892: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5893: 				     $args->{'newid'});
 5894: 	}
 5895: 	substr($line,$$scantron_config{'IDstart'}-1,
 5896: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5897: 	if ($args->{'newid'}=~/^\s*$/) {
 5898: 	    &scan_data($scan_data,"$whichline.user",
 5899: 		       $args->{'username'}.':'.$args->{'domain'});
 5900: 	}
 5901:     } elsif ($field eq 'CODE') {
 5902: 	if ($args->{'CODE_ignore_dup'}) {
 5903: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5904: 	}
 5905: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5906: 	if ($args->{'CODE'} ne 'use_unfound') {
 5907: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5908: 		return ($line,1,'New CODE value too large');
 5909: 	    }
 5910: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5911: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5912: 	    }
 5913: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5914: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5915: 	}
 5916:     } elsif ($field eq 'answer') {
 5917: 	my $length=$scantron_config->{'Qlength'};
 5918: 	my $off=$scantron_config->{'Qoff'};
 5919: 	my $on=$scantron_config->{'Qon'};
 5920: 	my $answer=${off}x$length;
 5921: 	if ($args->{'response'} eq 'none') {
 5922: 	    &scan_data($scan_data,
 5923: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5924: 	} else {
 5925: 	    if ($on eq 'letter') {
 5926: 		my @alphabet=('A'..'Z');
 5927: 		$answer=$alphabet[$args->{'response'}];
 5928: 	    } elsif ($on eq 'number') {
 5929: 		$answer=$args->{'response'}+1;
 5930: 		if ($answer == 10) { $answer = '0'; }
 5931: 	    } else {
 5932: 		substr($answer,$args->{'response'},1)=$on;
 5933: 	    }
 5934: 	    &scan_data($scan_data,
 5935: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5936: 	}
 5937: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5938: 	substr($line,$where-1,$length)=$answer;
 5939:     }
 5940:     return $line;
 5941: }
 5942: 
 5943: =pod
 5944: 
 5945: =item scan_data
 5946: 
 5947:     Edit or look up  an item in the scan_data hash.
 5948: 
 5949:   Arguments:
 5950:     $scan_data  - The hash (see scantron_getfile)
 5951:     $key        - shorthand of the key to edit (actual key is
 5952:                   scantronfilename_key).
 5953:     $data        - New value of the hash entry.
 5954:     $delete      - If true, the entry is removed from the hash.
 5955: 
 5956:   Returns:
 5957:     The new value of the hash table field (undefined if deleted).
 5958: 
 5959: =cut
 5960: 
 5961: 
 5962: sub scan_data {
 5963:     my ($scan_data,$key,$value,$delete)=@_;
 5964:     my $filename=$env{'form.scantron_selectfile'};
 5965:     if (defined($value)) {
 5966: 	$scan_data->{$filename.'_'.$key} = $value;
 5967:     }
 5968:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5969:     return $scan_data->{$filename.'_'.$key};
 5970: }
 5971: 
 5972: # ----- These first few routines are general use routines.----
 5973: 
 5974: # Return the number of occurences of a pattern in a string.
 5975: 
 5976: sub occurence_count {
 5977:     my ($string, $pattern) = @_;
 5978: 
 5979:     my @matches = ($string =~ /$pattern/g);
 5980: 
 5981:     return scalar(@matches);
 5982: }
 5983: 
 5984: 
 5985: # Take a string known to have digits and convert all the
 5986: # digits into letters in the range J,A..I.
 5987: 
 5988: sub digits_to_letters {
 5989:     my ($input) = @_;
 5990: 
 5991:     my @alphabet = ('J', 'A'..'I');
 5992: 
 5993:     my @input    = split(//, $input);
 5994:     my $output ='';
 5995:     for (my $i = 0; $i < scalar(@input); $i++) {
 5996: 	if ($input[$i] =~ /\d/) {
 5997: 	    $output .= $alphabet[$input[$i]];
 5998: 	} else {
 5999: 	    $output .= $input[$i];
 6000: 	}
 6001:     }
 6002:     return $output;
 6003: }
 6004: 
 6005: =pod 
 6006: 
 6007: =item scantron_parse_scanline
 6008: 
 6009:   Decodes a scanline from the selected scantron file
 6010: 
 6011:  Arguments:
 6012:     line             - The text of the scantron file line to process
 6013:     whichline        - Line number
 6014:     scantron_config  - Hash describing the format of the scantron lines.
 6015:     scan_data        - Hash of extra information about the scanline
 6016:                        (see scantron_getfile for more information)
 6017:     just_header      - True if should not process question answers but only
 6018:                        the stuff to the left of the answers.
 6019:  Returns:
 6020:    Hash containing the result of parsing the scanline
 6021: 
 6022:    Keys are all proceeded by the string 'scantron.'
 6023: 
 6024:        CODE    - the CODE in use for this scanline
 6025:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6026:                  by the operator
 6027:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6028:                             CODEs were selected, but the usage has been
 6029:                             forced by the operator
 6030:        ID  - student/employee ID
 6031:        PaperID - if used, the ID number printed on the sheet when the 
 6032:                  paper was scanned
 6033:        FirstName - first name from the sheet
 6034:        LastName  - last name from the sheet
 6035: 
 6036:      if just_header was not true these key may also exist
 6037: 
 6038:        missingerror - a list of bubble ranges that are considered to be answers
 6039:                       to a single question that don't have any bubbles filled in.
 6040:                       Of the form questionnumber:firstbubblenumber:count.
 6041:        doubleerror  - a list of bubble ranges that are considered to be answers
 6042:                       to a single question that have more than one bubble filled in.
 6043:                       Of the form questionnumber::firstbubblenumber:count
 6044:    
 6045:                 In the above, count is the number of bubble responses in the
 6046:                 input line needed to represent the possible answers to the question.
 6047:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6048:                 per line would have count = 2.
 6049: 
 6050:        maxquest     - the number of the last bubble line that was parsed
 6051: 
 6052:        (<number> starts at 1)
 6053:        <number>.answer - zero or more letters representing the selected
 6054:                          letters from the scanline for the bubble line 
 6055:                          <number>.
 6056:                          if blank there was either no bubble or there where
 6057:                          multiple bubbles, (consult the keys missingerror and
 6058:                          doubleerror if this is an error condition)
 6059: 
 6060: =cut
 6061: 
 6062: sub scantron_parse_scanline {
 6063:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 6064: 
 6065:     my %record;
 6066:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6067:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6068:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 6069:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6070: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6071: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6072: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6073: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6074: 	    $record{'scantron.CODE'}=substr($data,
 6075: 					    $$scantron_config{'CODEstart'}-1,
 6076: 					    $$scantron_config{'CODElength'});
 6077: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6078: 		$record{'scantron.useCODE'}=1;
 6079: 	    }
 6080: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6081: 		$record{'scantron.CODE_ignore_dup'}=1;
 6082: 	    }
 6083: 	} else {
 6084: 	    #FIXME interpret first N questions
 6085: 	}
 6086:     }
 6087:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6088: 				  $$scantron_config{'IDlength'});
 6089:     $record{'scantron.PaperID'}=
 6090: 	substr($data,$$scantron_config{'PaperID'}-1,
 6091: 	       $$scantron_config{'PaperIDlength'});
 6092:     $record{'scantron.FirstName'}=
 6093: 	substr($data,$$scantron_config{'FirstName'}-1,
 6094: 	       $$scantron_config{'FirstNamelength'});
 6095:     $record{'scantron.LastName'}=
 6096: 	substr($data,$$scantron_config{'LastName'}-1,
 6097: 	       $$scantron_config{'LastNamelength'});
 6098:     if ($just_header) { return \%record; }
 6099: 
 6100:     my @alphabet=('A'..'Z');
 6101:     my $questnum=0;
 6102:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6103: 
 6104:     chomp($questions);		# Get rid of any trailing \n.
 6105:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6106:     while (length($questions)) {
 6107: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 6108:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6109:                              || 1;
 6110:         $questnum++;
 6111:         my $quest_id = $questnum;
 6112:         my $currentquest = substr($questions,0,$answer_length);
 6113:         $questions       = substr($questions,$answer_length);
 6114:         if (length($currentquest) < $answer_length) { next; }
 6115: 
 6116:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 6117:             my $subquestnum = 1;
 6118:             my $subquestions = $currentquest;
 6119:             my @subanswers_needed = 
 6120:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 6121:             foreach my $subans (@subanswers_needed) {
 6122:                 my $subans_length =
 6123:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6124:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6125:                 $subquestions   = substr($subquestions,$subans_length);
 6126:                 $quest_id = "$questnum.$subquestnum";
 6127:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6128:                     ($$scantron_config{'Qon'} eq 'number')) {
 6129:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6130:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6131:                         \@alphabet,\%record,$scantron_config,$scan_data);
 6132:                 } else {
 6133:                     $ansnum = &scantron_validator_positional($ansnum,
 6134:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 6135:                 }
 6136:                 $subquestnum ++;
 6137:             }
 6138:         } else {
 6139:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6140:                 ($$scantron_config{'Qon'} eq 'number')) {
 6141:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6142:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6143:                     \@alphabet,\%record,$scantron_config,$scan_data);
 6144:             } else {
 6145:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6146:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6147:                     \@alphabet,\%record,$scantron_config,$scan_data);
 6148:             }
 6149:         }
 6150:     }
 6151:     $record{'scantron.maxquest'}=$questnum;
 6152:     return \%record;
 6153: }
 6154: 
 6155: sub scantron_validator_lettnum {
 6156:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6157:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 6158: 
 6159:     # Qon 'letter' implies for each slot in currquest we have:
 6160:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6161:     #    about anything else (esp. a value of Qoff) for missing
 6162:     #    bubbles.
 6163:     #
 6164:     # Qon 'number' implies each slot gives a digit that indexes the
 6165:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6166:     #    and * or ? for double bubbles on a single line.
 6167:     #
 6168: 
 6169:     my $matchon;
 6170:     if ($$scantron_config{'Qon'} eq 'letter') {
 6171:         $matchon = '[A-Z]';
 6172:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6173:         $matchon = '\d';
 6174:     }
 6175:     my $occurrences = 0;
 6176:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6177:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6178:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6179:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6180:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6181:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6182:         my @singlelines = split('',$currquest);
 6183:         foreach my $entry (@singlelines) {
 6184:             $occurrences = &occurence_count($entry,$matchon);
 6185:             if ($occurrences > 1) {
 6186:                 last;
 6187:             }
 6188:         } 
 6189:     } else {
 6190:         $occurrences = &occurence_count($currquest,$matchon); 
 6191:     }
 6192:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6193:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6194:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6195:             my $bubble = substr($currquest,$ans,1);
 6196:             if ($bubble =~ /$matchon/ ) {
 6197:                 if ($$scantron_config{'Qon'} eq 'number') {
 6198:                     if ($bubble == 0) {
 6199:                         $bubble = 10; 
 6200:                     }
 6201:                     $record->{"scantron.$ansnum.answer"} = 
 6202:                         $alphabet->[$bubble-1];
 6203:                 } else {
 6204:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6205:                 }
 6206:             } else {
 6207:                 $record->{"scantron.$ansnum.answer"}='';
 6208:             }
 6209:             $ansnum++;
 6210:         }
 6211:     } elsif (!defined($currquest)
 6212:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6213:             || (&occurence_count($currquest,$matchon) == 0)) {
 6214:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6215:             $record->{"scantron.$ansnum.answer"}='';
 6216:             $ansnum++;
 6217:         }
 6218:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6219:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6220:         }
 6221:     } else {
 6222:         if ($$scantron_config{'Qon'} eq 'number') {
 6223:             $currquest = &digits_to_letters($currquest);            
 6224:         }
 6225:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6226:             my $bubble = substr($currquest,$ans,1);
 6227:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6228:             $ansnum++;
 6229:         }
 6230:     }
 6231:     return $ansnum;
 6232: }
 6233: 
 6234: sub scantron_validator_positional {
 6235:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6236:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 6237: 
 6238:     # Otherwise there's a positional notation;
 6239:     # each bubble line requires Qlength items, and there are filled in
 6240:     # bubbles for each case where there 'Qon' characters.
 6241:     #
 6242: 
 6243:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6244: 
 6245:     # If the split only gives us one element.. the full length of the
 6246:     # answer string, no bubbles are filled in:
 6247: 
 6248:     if ($answers_needed eq '') {
 6249:         return;
 6250:     }
 6251: 
 6252:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6253:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6254:             $record->{"scantron.$ansnum.answer"}='';
 6255:             $ansnum++;
 6256:         }
 6257:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6258:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6259:         }
 6260:     } elsif (scalar(@array) == 2) {
 6261:         my $location = length($array[0]);
 6262:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6263:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6264:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6265:             if ($ans eq $line_num) {
 6266:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6267:             } else {
 6268:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6269:             }
 6270:             $ansnum++;
 6271:          }
 6272:     } else {
 6273:         #  If there's more than one instance of a bubble character
 6274:         #  That's a double bubble; with positional notation we can
 6275:         #  record all the bubbles filled in as well as the
 6276:         #  fact this response consists of multiple bubbles.
 6277:         #
 6278:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6279:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6280:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6281:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6282:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6283:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6284:             my $doubleerror = 0;
 6285:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6286:                    (!$doubleerror)) {
 6287:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6288:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6289:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6290:                if (length(@currarray) > 2) {
 6291:                    $doubleerror = 1;
 6292:                } 
 6293:             }
 6294:             if ($doubleerror) {
 6295:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6296:             }
 6297:         } else {
 6298:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6299:         }
 6300:         my $item = $ansnum;
 6301:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6302:             $record->{"scantron.$item.answer"} = '';
 6303:             $item ++;
 6304:         }
 6305: 
 6306:         my @ans=@array;
 6307:         my $i=0;
 6308:         my $increment = 0;
 6309:         while ($#ans) {
 6310:             $i+=length($ans[0]) + $increment;
 6311:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6312:             my $bubble = $i%$$scantron_config{'Qlength'};
 6313:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6314:             shift(@ans);
 6315:             $increment = 1;
 6316:         }
 6317:         $ansnum += $answers_needed;
 6318:     }
 6319:     return $ansnum;
 6320: }
 6321: 
 6322: =pod
 6323: 
 6324: =item scantron_add_delay
 6325: 
 6326:    Adds an error message that occurred during the grading phase to a
 6327:    queue of messages to be shown after grading pass is complete
 6328: 
 6329:  Arguments:
 6330:    $delayqueue  - arrary ref of hash ref of error messages
 6331:    $scanline    - the scanline that caused the error
 6332:    $errormesage - the error message
 6333:    $errorcode   - a numeric code for the error
 6334: 
 6335:  Side Effects:
 6336:    updates the $delayqueue to have a new hash ref of the error
 6337: 
 6338: =cut
 6339: 
 6340: sub scantron_add_delay {
 6341:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6342:     push(@$delayqueue,
 6343: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6344: 	  'ecode' => $errorcode }
 6345: 	 );
 6346: }
 6347: 
 6348: =pod
 6349: 
 6350: =item scantron_find_student
 6351: 
 6352:    Finds the username for the current scanline
 6353: 
 6354:   Arguments:
 6355:    $scantron_record - hash result from scantron_parse_scanline
 6356:    $scan_data       - hash of correction information 
 6357:                       (see &scantron_getfile() form more information)
 6358:    $idmap           - hash from &username_to_idmap()
 6359:    $line            - number of current scanline
 6360:  
 6361:   Returns:
 6362:    Either 'username:domain' or undef if unknown
 6363: 
 6364: =cut
 6365: 
 6366: sub scantron_find_student {
 6367:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6368:     my $scanID=$$scantron_record{'scantron.ID'};
 6369:     if ($scanID =~ /^\s*$/) {
 6370:  	return &scan_data($scan_data,"$line.user");
 6371:     }
 6372:     foreach my $id (keys(%$idmap)) {
 6373:  	if (lc($id) eq lc($scanID)) {
 6374:  	    return $$idmap{$id};
 6375:  	}
 6376:     }
 6377:     return undef;
 6378: }
 6379: 
 6380: =pod
 6381: 
 6382: =item scantron_filter
 6383: 
 6384:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6385:    hidden resources was selected
 6386: 
 6387: =cut
 6388: 
 6389: sub scantron_filter {
 6390:     my ($curres)=@_;
 6391: 
 6392:     if (ref($curres) && $curres->is_problem()) {
 6393: 	# if the user has asked to not have either hidden
 6394: 	# or 'randomout' controlled resources to be graded
 6395: 	# don't include them
 6396: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6397: 	    && $curres->randomout) {
 6398: 	    return 0;
 6399: 	}
 6400: 	return 1;
 6401:     }
 6402:     return 0;
 6403: }
 6404: 
 6405: =pod
 6406: 
 6407: =item scantron_process_corrections
 6408: 
 6409:    Gets correction information out of submitted form data and corrects
 6410:    the scanline
 6411: 
 6412: =cut
 6413: 
 6414: sub scantron_process_corrections {
 6415:     my ($r) = @_;
 6416:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6417:     my ($scanlines,$scan_data)=&scantron_getfile();
 6418:     my $classlist=&Apache::loncoursedata::get_classlist();
 6419:     my $which=$env{'form.scantron_line'};
 6420:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6421:     my ($skip,$err,$errmsg);
 6422:     if ($env{'form.scantron_skip_record'}) {
 6423: 	$skip=1;
 6424:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6425: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6426: 	    $env{'form.scantron_domain'};
 6427: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6428: 	($line,$err,$errmsg)=
 6429: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6430: 				     'ID',{'newid'=>$newid,
 6431: 				    'username'=>$env{'form.scantron_username'},
 6432: 				    'domain'=>$env{'form.scantron_domain'}});
 6433:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6434: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6435: 	my $newCODE;
 6436: 	my %args;
 6437: 	if      ($resolution eq 'use_unfound') {
 6438: 	    $newCODE='use_unfound';
 6439: 	} elsif ($resolution eq 'use_found') {
 6440: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6441: 	} elsif ($resolution eq 'use_typed') {
 6442: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6443: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6444: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6445: 	}
 6446: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6447: 	    $args{'CODE_ignore_dup'}=1;
 6448: 	}
 6449: 	$args{'CODE'}=$newCODE;
 6450: 	($line,$err,$errmsg)=
 6451: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6452: 				     'CODE',\%args);
 6453:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6454: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6455: 	    ($line,$err,$errmsg)=
 6456: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6457: 					 $which,'answer',
 6458: 					 { 'question'=>$question,
 6459: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6460:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6461: 	    if ($err) { last; }
 6462: 	}
 6463:     }
 6464:     if ($err) {
 6465: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6466:     } else {
 6467: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6468: 	&scantron_putfile($scanlines,$scan_data);
 6469:     }
 6470: }
 6471: 
 6472: =pod
 6473: 
 6474: =item reset_skipping_status
 6475: 
 6476:    Forgets the current set of remember skipped scanlines (and thus
 6477:    reverts back to considering all lines in the
 6478:    scantron_skipped_<filename> file)
 6479: 
 6480: =cut
 6481: 
 6482: sub reset_skipping_status {
 6483:     my ($scanlines,$scan_data)=&scantron_getfile();
 6484:     &scan_data($scan_data,'remember_skipping',undef,1);
 6485:     &scantron_putfile(undef,$scan_data);
 6486: }
 6487: 
 6488: =pod
 6489: 
 6490: =item start_skipping
 6491: 
 6492:    Marks a scanline to be skipped. 
 6493: 
 6494: =cut
 6495: 
 6496: sub start_skipping {
 6497:     my ($scan_data,$i)=@_;
 6498:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6499:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6500: 	$remembered{$i}=2;
 6501:     } else {
 6502: 	$remembered{$i}=1;
 6503:     }
 6504:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6505: }
 6506: 
 6507: =pod
 6508: 
 6509: =item should_be_skipped
 6510: 
 6511:    Checks whether a scanline should be skipped.
 6512: 
 6513: =cut
 6514: 
 6515: sub should_be_skipped {
 6516:     my ($scanlines,$scan_data,$i)=@_;
 6517:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6518: 	# not redoing old skips
 6519: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6520: 	return 0;
 6521:     }
 6522:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6523: 
 6524:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6525: 	return 0;
 6526:     }
 6527:     return 1;
 6528: }
 6529: 
 6530: =pod
 6531: 
 6532: =item remember_current_skipped
 6533: 
 6534:    Discovers what scanlines are in the scantron_skipped_<filename>
 6535:    file and remembers them into scan_data for later use.
 6536: 
 6537: =cut
 6538: 
 6539: sub remember_current_skipped {
 6540:     my ($scanlines,$scan_data)=&scantron_getfile();
 6541:     my %to_remember;
 6542:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6543: 	if ($scanlines->{'skipped'}[$i]) {
 6544: 	    $to_remember{$i}=1;
 6545: 	}
 6546:     }
 6547: 
 6548:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6549:     &scantron_putfile(undef,$scan_data);
 6550: }
 6551: 
 6552: =pod
 6553: 
 6554: =item check_for_error
 6555: 
 6556:     Checks if there was an error when attempting to remove a specific
 6557:     scantron_.. bubblesheet data file. Prints out an error if
 6558:     something went wrong.
 6559: 
 6560: =cut
 6561: 
 6562: sub check_for_error {
 6563:     my ($r,$result)=@_;
 6564:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6565: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6566:     }
 6567: }
 6568: 
 6569: =pod
 6570: 
 6571: =item scantron_warning_screen
 6572: 
 6573:    Interstitial screen to make sure the operator has selected the
 6574:    correct options before we start the validation phase.
 6575: 
 6576: =cut
 6577: 
 6578: sub scantron_warning_screen {
 6579:     my ($button_text)=@_;
 6580:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6581:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6582:     my $CODElist;
 6583:     if ($scantron_config{'CODElocation'} &&
 6584: 	$scantron_config{'CODEstart'} &&
 6585: 	$scantron_config{'CODElength'}) {
 6586: 	$CODElist=$env{'form.scantron_CODElist'};
 6587: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6588: 	$CODElist=
 6589: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6590: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6591:     }
 6592:     my $lastbubblepoints;
 6593:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6594:         $lastbubblepoints =
 6595:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6596:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6597:     }
 6598:     return ('
 6599: <p>
 6600: <span class="LC_warning">
 6601: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6602: </p>
 6603: <table>
 6604: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6605: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6606: '.$CODElist.$lastbubblepoints.'
 6607: </table>
 6608: <br />
 6609: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6610: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6611: 
 6612: <br />
 6613: ');
 6614: }
 6615: 
 6616: =pod
 6617: 
 6618: =item scantron_do_warning
 6619: 
 6620:    Check if the operator has picked something for all required
 6621:    fields. Error out if something is missing.
 6622: 
 6623: =cut
 6624: 
 6625: sub scantron_do_warning {
 6626:     my ($r)=@_;
 6627:     my ($symb)=&get_symb($r);
 6628:     if (!$symb) {return '';}
 6629:     my $default_form_data=&defaultFormData($symb);
 6630:     $r->print(&scantron_form_start().$default_form_data);
 6631:     if ( $env{'form.selectpage'} eq '' ||
 6632: 	 $env{'form.scantron_selectfile'} eq '' ||
 6633: 	 $env{'form.scantron_format'} eq '' ) {
 6634: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6635: 	if ( $env{'form.selectpage'} eq '') {
 6636: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6637: 	} 
 6638: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6639: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6640: 	} 
 6641: 	if ( $env{'form.scantron_format'} eq '') {
 6642: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6643: 	} 
 6644:     } else {
 6645: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6646:         my $bubbledbyhand=&hand_bubble_option();
 6647: 	$r->print('
 6648: '.$warning.$bubbledbyhand.'
 6649: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6650: <input type="hidden" name="command" value="scantron_validate" />
 6651: ');
 6652:     }
 6653:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6654:     return '';
 6655: }
 6656: 
 6657: =pod
 6658: 
 6659: =item scantron_form_start
 6660: 
 6661:     html hidden input for remembering all selected grading options
 6662: 
 6663: =cut
 6664: 
 6665: sub scantron_form_start {
 6666:     my ($max_bubble)=@_;
 6667:     my $result= <<SCANTRONFORM;
 6668: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6669:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6670:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6671:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6672:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6673:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6674:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6675:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6676:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6677:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6678: SCANTRONFORM
 6679: 
 6680:   my $line = 0;
 6681:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6682:        my $chunk =
 6683: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6684:        $chunk .=
 6685: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6686:        $chunk .= 
 6687:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6688:        $chunk .=
 6689:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6690:        $result .= $chunk;
 6691:        $line++;
 6692:    }
 6693:     return $result;
 6694: }
 6695: 
 6696: =pod
 6697: 
 6698: =item scantron_validate_file
 6699: 
 6700:     Dispatch routine for doing validation of a bubblesheet data file.
 6701: 
 6702:     Also processes any necessary information resets that need to
 6703:     occur before validation begins (ignore previous corrections,
 6704:     restarting the skipped records processing)
 6705: 
 6706: =cut
 6707: 
 6708: sub scantron_validate_file {
 6709:     my ($r) = @_;
 6710:     my ($symb)=&get_symb($r);
 6711:     if (!$symb) {return '';}
 6712:     my $default_form_data=&defaultFormData($symb);
 6713:     
 6714:     # do the detection of only doing skipped records first befroe we delete
 6715:     # them when doing the corrections reset
 6716:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6717: 	&reset_skipping_status();
 6718:     }
 6719:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6720: 	&remember_current_skipped();
 6721: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6722:     }
 6723: 
 6724:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6725: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6726: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6727: 	&check_for_error($r,&scantron_remove_scan_data());
 6728: 	$env{'form.scantron_options_ignore'}='done';
 6729:     }
 6730: 
 6731:     if ($env{'form.scantron_corrections'}) {
 6732: 	&scantron_process_corrections($r);
 6733:     }
 6734:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6735:     #get the student pick code ready
 6736:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6737:     my $nav_error;
 6738:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6739:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6740:     if ($nav_error) {
 6741:         $r->print(&navmap_errormsg());
 6742:         return '';
 6743:     }
 6744:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6745:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6746:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6747:     }
 6748:     $r->print($result);
 6749:     
 6750:     my @validate_phases=( 'sequence',
 6751: 			  'ID',
 6752: 			  'CODE',
 6753: 			  'doublebubble',
 6754: 			  'missingbubbles');
 6755:     if (!$env{'form.validatepass'}) {
 6756: 	$env{'form.validatepass'} = 0;
 6757:     }
 6758:     my $currentphase=$env{'form.validatepass'};
 6759: 
 6760: 
 6761:     my $stop=0;
 6762:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6763: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6764: 	$r->rflush();
 6765: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6766: 	{
 6767: 	    no strict 'refs';
 6768: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6769: 	}
 6770:     }
 6771:     if (!$stop) {
 6772: 	my $warning=&scantron_warning_screen('Start Grading');
 6773: 	$r->print(&mt('Validation process complete.').'<br />'.
 6774:                   $warning.
 6775:                   &mt('Perform verification for each student after storage of submissions?').
 6776:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6777:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6778:                   ('&nbsp;'x3).'<label>'.
 6779:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6780:                   '</label></span><br />'.
 6781:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6782:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6783:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6784:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6785:     } else {
 6786: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6787: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6788:     }
 6789:     if ($stop) {
 6790: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6791: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6792: 	    $r->print(' '.&mt('this error').' <br />');
 6793: 
 6794: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6795: 	} else {
 6796:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6797: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6798:             } else {
 6799:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6800:             }
 6801: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6802: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6803: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6804: 	}
 6805:     }
 6806:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6807:     return '';
 6808: }
 6809: 
 6810: 
 6811: =pod
 6812: 
 6813: =item scantron_remove_file
 6814: 
 6815:    Removes the requested bubblesheet data file, makes sure that
 6816:    scantron_original_<filename> is never removed
 6817: 
 6818: 
 6819: =cut
 6820: 
 6821: sub scantron_remove_file {
 6822:     my ($which)=@_;
 6823:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6824:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6825:     my $file='scantron_';
 6826:     if ($which eq 'corrected' || $which eq 'skipped') {
 6827: 	$file.=$which.'_';
 6828:     } else {
 6829: 	return 'refused';
 6830:     }
 6831:     $file.=$env{'form.scantron_selectfile'};
 6832:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6833: }
 6834: 
 6835: 
 6836: =pod
 6837: 
 6838: =item scantron_remove_scan_data
 6839: 
 6840:    Removes all scan_data correction for the requested bubblesheet
 6841:    data file.  (In the case that both the are doing skipped records we need
 6842:    to remember the old skipped lines for the time being so that element
 6843:    persists for a while.)
 6844: 
 6845: =cut
 6846: 
 6847: sub scantron_remove_scan_data {
 6848:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6849:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6850:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6851:     my @todelete;
 6852:     my $filename=$env{'form.scantron_selectfile'};
 6853:     foreach my $key (@keys) {
 6854: 	if ($key=~/^\Q$filename\E_/) {
 6855: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6856: 		$key=~/remember_skipping/) {
 6857: 		next;
 6858: 	    }
 6859: 	    push(@todelete,$key);
 6860: 	}
 6861:     }
 6862:     my $result;
 6863:     if (@todelete) {
 6864: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6865: 				       \@todelete,$cdom,$cname);
 6866:     } else {
 6867: 	$result = 'ok';
 6868:     }
 6869:     return $result;
 6870: }
 6871: 
 6872: 
 6873: =pod
 6874: 
 6875: =item scantron_getfile
 6876: 
 6877:     Fetches the requested bubblesheet data file (all 3 versions), and
 6878:     the scan_data hash
 6879:   
 6880:   Arguments:
 6881:     None
 6882: 
 6883:   Returns:
 6884:     2 hash references
 6885: 
 6886:      - first one has 
 6887:          orig      -
 6888:          corrected -
 6889:          skipped   -  each of which points to an array ref of the specified
 6890:                       file broken up into individual lines
 6891:          count     - number of scanlines
 6892:  
 6893:      - second is the scan_data hash possible keys are
 6894:        ($number refers to scanline numbered $number and thus the key affects
 6895:         only that scanline
 6896:         $bubline refers to the specific bubble line element and the aspects
 6897:         refers to that specific bubble line element)
 6898: 
 6899:        $number.user - username:domain to use
 6900:        $number.CODE_ignore_dup 
 6901:                     - ignore the duplicate CODE error 
 6902:        $number.useCODE
 6903:                     - use the CODE in the scanline as is
 6904:        $number.no_bubble.$bubline
 6905:                     - it is valid that there is no bubbled in bubble
 6906:                       at $number $bubline
 6907:        remember_skipping
 6908:                     - a frozen hash containing keys of $number and values
 6909:                       of either 
 6910:                         1 - we are on a 'do skipped records pass' and plan
 6911:                             on processing this line
 6912:                         2 - we are on a 'do skipped records pass' and this
 6913:                             scanline has been marked to skip yet again
 6914: 
 6915: =cut
 6916: 
 6917: sub scantron_getfile {
 6918:     #FIXME really would prefer a scantron directory
 6919:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6920:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6921:     my $lines;
 6922:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6923: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6924:     my %scanlines;
 6925:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6926:     my $temp=$scanlines{'orig'};
 6927:     $scanlines{'count'}=$#$temp;
 6928: 
 6929:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6930: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6931:     if ($lines eq '-1') {
 6932: 	$scanlines{'corrected'}=[];
 6933:     } else {
 6934: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6935:     }
 6936:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6937: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6938:     if ($lines eq '-1') {
 6939: 	$scanlines{'skipped'}=[];
 6940:     } else {
 6941: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6942:     }
 6943:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6944:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6945:     my %scan_data = @tmp;
 6946:     return (\%scanlines,\%scan_data);
 6947: }
 6948: 
 6949: =pod
 6950: 
 6951: =item lonnet_putfile
 6952: 
 6953:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6954: 
 6955:  Arguments:
 6956:    $contents - data to store
 6957:    $filename - filename to store $contents into
 6958: 
 6959:  Returns:
 6960:    result value from &Apache::lonnet::finishuserfileupload
 6961: 
 6962: =cut
 6963: 
 6964: sub lonnet_putfile {
 6965:     my ($contents,$filename)=@_;
 6966:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6967:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6968:     $env{'form.sillywaytopassafilearound'}=$contents;
 6969:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6970: 
 6971: }
 6972: 
 6973: =pod
 6974: 
 6975: =item scantron_putfile
 6976: 
 6977:     Stores the current version of the bubblesheet data files, and the
 6978:     scan_data hash. (Does not modify the original version only the
 6979:     corrected and skipped versions.
 6980: 
 6981:  Arguments:
 6982:     $scanlines - hash ref that looks like the first return value from
 6983:                  &scantron_getfile()
 6984:     $scan_data - hash ref that looks like the second return value from
 6985:                  &scantron_getfile()
 6986: 
 6987: =cut
 6988: 
 6989: sub scantron_putfile {
 6990:     my ($scanlines,$scan_data) = @_;
 6991:     #FIXME really would prefer a scantron directory
 6992:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6993:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6994:     if ($scanlines) {
 6995: 	my $prefix='scantron_';
 6996: # no need to update orig, shouldn't change
 6997: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6998: #		    $env{'form.scantron_selectfile'});
 6999: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7000: 			$prefix.'corrected_'.
 7001: 			$env{'form.scantron_selectfile'});
 7002: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7003: 			$prefix.'skipped_'.
 7004: 			$env{'form.scantron_selectfile'});
 7005:     }
 7006:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7007: }
 7008: 
 7009: =pod
 7010: 
 7011: =item scantron_get_line
 7012: 
 7013:    Returns the correct version of the scanline
 7014: 
 7015:  Arguments:
 7016:     $scanlines - hash ref that looks like the first return value from
 7017:                  &scantron_getfile()
 7018:     $scan_data - hash ref that looks like the second return value from
 7019:                  &scantron_getfile()
 7020:     $i         - number of the requested line (starts at 0)
 7021: 
 7022:  Returns:
 7023:    A scanline, (either the original or the corrected one if it
 7024:    exists), or undef if the requested scanline should be
 7025:    skipped. (Either because it's an skipped scanline, or it's an
 7026:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7027:    pass.
 7028: 
 7029: =cut
 7030: 
 7031: sub scantron_get_line {
 7032:     my ($scanlines,$scan_data,$i)=@_;
 7033:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7034:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7035:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7036:     return $scanlines->{'orig'}[$i]; 
 7037: }
 7038: 
 7039: =pod
 7040: 
 7041: =item scantron_todo_count
 7042: 
 7043:     Counts the number of scanlines that need processing.
 7044: 
 7045:  Arguments:
 7046:     $scanlines - hash ref that looks like the first return value from
 7047:                  &scantron_getfile()
 7048:     $scan_data - hash ref that looks like the second return value from
 7049:                  &scantron_getfile()
 7050: 
 7051:  Returns:
 7052:     $count - number of scanlines to process
 7053: 
 7054: =cut
 7055: 
 7056: sub get_todo_count {
 7057:     my ($scanlines,$scan_data)=@_;
 7058:     my $count=0;
 7059:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7060: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7061: 	if ($line=~/^[\s\cz]*$/) { next; }
 7062: 	$count++;
 7063:     }
 7064:     return $count;
 7065: }
 7066: 
 7067: =pod
 7068: 
 7069: =item scantron_put_line
 7070: 
 7071:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7072:     data file.
 7073: 
 7074:  Arguments:
 7075:     $scanlines - hash ref that looks like the first return value from
 7076:                  &scantron_getfile()
 7077:     $scan_data - hash ref that looks like the second return value from
 7078:                  &scantron_getfile()
 7079:     $i         - line number to update
 7080:     $newline   - contents of the updated scanline
 7081:     $skip      - if true make the line for skipping and update the
 7082:                  'skipped' file
 7083: 
 7084: =cut
 7085: 
 7086: sub scantron_put_line {
 7087:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7088:     if ($skip) {
 7089: 	$scanlines->{'skipped'}[$i]=$newline;
 7090: 	&start_skipping($scan_data,$i);
 7091: 	return;
 7092:     }
 7093:     $scanlines->{'corrected'}[$i]=$newline;
 7094: }
 7095: 
 7096: =pod
 7097: 
 7098: =item scantron_clear_skip
 7099: 
 7100:    Remove a line from the 'skipped' file
 7101: 
 7102:  Arguments:
 7103:     $scanlines - hash ref that looks like the first return value from
 7104:                  &scantron_getfile()
 7105:     $scan_data - hash ref that looks like the second return value from
 7106:                  &scantron_getfile()
 7107:     $i         - line number to update
 7108: 
 7109: =cut
 7110: 
 7111: sub scantron_clear_skip {
 7112:     my ($scanlines,$scan_data,$i)=@_;
 7113:     if (exists($scanlines->{'skipped'}[$i])) {
 7114: 	undef($scanlines->{'skipped'}[$i]);
 7115: 	return 1;
 7116:     }
 7117:     return 0;
 7118: }
 7119: 
 7120: =pod
 7121: 
 7122: =item scantron_filter_not_exam
 7123: 
 7124:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7125:    filter out resources that are not marked as 'exam' mode
 7126: 
 7127: =cut
 7128: 
 7129: sub scantron_filter_not_exam {
 7130:     my ($curres)=@_;
 7131:     
 7132:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7133: 	# if the user has asked to not have either hidden
 7134: 	# or 'randomout' controlled resources to be graded
 7135: 	# don't include them
 7136: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7137: 	    && $curres->randomout) {
 7138: 	    return 0;
 7139: 	}
 7140: 	return 1;
 7141:     }
 7142:     return 0;
 7143: }
 7144: 
 7145: =pod
 7146: 
 7147: =item scantron_validate_sequence
 7148: 
 7149:     Validates the selected sequence, checking for resource that are
 7150:     not set to exam mode.
 7151: 
 7152: =cut
 7153: 
 7154: sub scantron_validate_sequence {
 7155:     my ($r,$currentphase) = @_;
 7156: 
 7157:     my $navmap=Apache::lonnavmaps::navmap->new();
 7158:     unless (ref($navmap)) {
 7159:         $r->print(&navmap_errormsg());
 7160:         return (1,$currentphase);
 7161:     }
 7162:     my (undef,undef,$sequence)=
 7163: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7164: 
 7165:     my $map=$navmap->getResourceByUrl($sequence);
 7166: 
 7167:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7168:                                     value="ignore" />');
 7169:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7170: 	my @resources=
 7171: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7172: 	if (@resources) {
 7173: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
 7174: 	    return (1,$currentphase);
 7175: 	}
 7176:     }
 7177: 
 7178:     return (0,$currentphase+1);
 7179: }
 7180: 
 7181: 
 7182: 
 7183: sub scantron_validate_ID {
 7184:     my ($r,$currentphase) = @_;
 7185:     
 7186:     #get student info
 7187:     my $classlist=&Apache::loncoursedata::get_classlist();
 7188:     my %idmap=&username_to_idmap($classlist);
 7189: 
 7190:     #get scantron line setup
 7191:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7192:     my ($scanlines,$scan_data)=&scantron_getfile();
 7193: 
 7194:     my $nav_error;
 7195:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7196:     if ($nav_error) {
 7197:         $r->print(&navmap_errormsg());
 7198:         return(1,$currentphase);
 7199:     }
 7200: 
 7201:     my %found=('ids'=>{},'usernames'=>{});
 7202:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7203: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7204: 	if ($line=~/^[\s\cz]*$/) { next; }
 7205: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7206: 						 $scan_data);
 7207: 	my $id=$$scan_record{'scantron.ID'};
 7208: 	my $found;
 7209: 	foreach my $checkid (keys(%idmap)) {
 7210: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7211: 	}
 7212: 	if ($found) {
 7213: 	    my $username=$idmap{$found};
 7214: 	    if ($found{'ids'}{$found}) {
 7215: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7216: 					 $line,'duplicateID',$found);
 7217: 		return(1,$currentphase);
 7218: 	    } elsif ($found{'usernames'}{$username}) {
 7219: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7220: 					 $line,'duplicateID',$username);
 7221: 		return(1,$currentphase);
 7222: 	    }
 7223: 	    #FIXME store away line we previously saw the ID on to use above
 7224: 	    $found{'ids'}{$found}++;
 7225: 	    $found{'usernames'}{$username}++;
 7226: 	} else {
 7227: 	    if ($id =~ /^\s*$/) {
 7228: 		my $username=&scan_data($scan_data,"$i.user");
 7229: 		if (defined($username) && $found{'usernames'}{$username}) {
 7230: 		    &scantron_get_correction($r,$i,$scan_record,
 7231: 					     \%scantron_config,
 7232: 					     $line,'duplicateID',$username);
 7233: 		    return(1,$currentphase);
 7234: 		} elsif (!defined($username)) {
 7235: 		    &scantron_get_correction($r,$i,$scan_record,
 7236: 					     \%scantron_config,
 7237: 					     $line,'incorrectID');
 7238: 		    return(1,$currentphase);
 7239: 		}
 7240: 		$found{'usernames'}{$username}++;
 7241: 	    } else {
 7242: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7243: 					 $line,'incorrectID');
 7244: 		return(1,$currentphase);
 7245: 	    }
 7246: 	}
 7247:     }
 7248: 
 7249:     return (0,$currentphase+1);
 7250: }
 7251: 
 7252: 
 7253: sub scantron_get_correction {
 7254:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 7255: #FIXME in the case of a duplicated ID the previous line, probably need
 7256: #to show both the current line and the previous one and allow skipping
 7257: #the previous one or the current one
 7258: 
 7259:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7260:         $r->print(
 7261:             '<p class="LC_warning">'
 7262:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7263:                 "<b>$error</b>",
 7264:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7265:            ."</p> \n");
 7266:     } else {
 7267:         $r->print(
 7268:             '<p class="LC_warning">'
 7269:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7270:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7271:            ."</p> \n");
 7272:     }
 7273:     my $message =
 7274:         '<p>'
 7275:        .&mt('The ID on the form is [_1]',
 7276:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7277:        .'<br />'
 7278:        .&mt('The name on the paper is [_1], [_2]',
 7279:             $$scan_record{'scantron.LastName'},
 7280:             $$scan_record{'scantron.FirstName'})
 7281:        .'</p>';
 7282: 
 7283:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7284:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7285:                            # Array populated for doublebubble or
 7286:     my @lines_to_correct;  # missingbubble errors to build javascript
 7287:                            # to validate radio button checking   
 7288: 
 7289:     if ($error =~ /ID$/) {
 7290: 	if ($error eq 'incorrectID') {
 7291: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7292: 		      "</p>\n");
 7293: 	} elsif ($error eq 'duplicateID') {
 7294: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7295: 	}
 7296: 	$r->print($message);
 7297: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7298: 	$r->print("\n<ul><li> ");
 7299: 	#FIXME it would be nice if this sent back the user ID and
 7300: 	#could do partial userID matches
 7301: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7302: 				       'scantron_username','scantron_domain'));
 7303: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7304: 	$r->print("\n@".
 7305: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7306: 
 7307: 	$r->print('</li>');
 7308:     } elsif ($error =~ /CODE$/) {
 7309: 	if ($error eq 'incorrectCODE') {
 7310: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7311: 	} elsif ($error eq 'duplicateCODE') {
 7312: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 7313: 	}
 7314:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7315:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7316:                  ."</p>\n");
 7317: 	$r->print($message);
 7318: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7319: 	$r->print("\n<br /> ");
 7320: 	my $i=0;
 7321: 	if ($error eq 'incorrectCODE' 
 7322: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7323: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7324: 	    if ($closest > 0) {
 7325: 		foreach my $testcode (@{$closest}) {
 7326: 		    my $checked='';
 7327: 		    if (!$i) { $checked=' checked="checked"'; }
 7328: 		    $r->print("
 7329:    <label>
 7330:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7331:        ".&mt("Use the similar CODE [_1] instead.",
 7332: 	    "<b><tt>".$testcode."</tt></b>")."
 7333:     </label>
 7334:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7335: 		    $r->print("\n<br />");
 7336: 		    $i++;
 7337: 		}
 7338: 	    }
 7339: 	}
 7340: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7341: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7342: 	    $r->print("
 7343:     <label>
 7344:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7345:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7346: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7347:     </label>");
 7348: 	    $r->print("\n<br />");
 7349: 	}
 7350: 
 7351: 	$r->print(<<ENDSCRIPT);
 7352: <script type="text/javascript">
 7353: function change_radio(field) {
 7354:     var slct=document.scantronupload.scantron_CODE_resolution;
 7355:     var i;
 7356:     for (i=0;i<slct.length;i++) {
 7357:         if (slct[i].value==field) { slct[i].checked=true; }
 7358:     }
 7359: }
 7360: </script>
 7361: ENDSCRIPT
 7362: 	my $href="/adm/pickcode?".
 7363: 	   "form=".&escape("scantronupload").
 7364: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7365: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7366: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7367: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7368: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7369: 	    $r->print("
 7370:     <label>
 7371:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7372:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7373: 	     "<a target='_blank' href='$href'>","</a>")."
 7374:     </label> 
 7375:     ".&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\')" />'));
 7376: 	    $r->print("\n<br />");
 7377: 	}
 7378: 	$r->print("
 7379:     <label>
 7380:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7381:        ".&mt("Use [_1] as the CODE.",
 7382: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7383: 	$r->print("\n<br /><br />");
 7384:     } elsif ($error eq 'doublebubble') {
 7385: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7386: 
 7387: 	# The form field scantron_questions is acutally a list of line numbers.
 7388: 	# represented by this form so:
 7389: 
 7390: 	my $line_list = &questions_to_line_list($arg);
 7391: 
 7392: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7393: 		  $line_list.'" />');
 7394: 	$r->print($message);
 7395: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7396: 	foreach my $question (@{$arg}) {
 7397: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7398:                                                    $scan_record, $error);
 7399:             push(@lines_to_correct,@linenums);
 7400: 	}
 7401:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7402:     } elsif ($error eq 'missingbubble') {
 7403: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7404: 	$r->print($message);
 7405: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7406: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7407: 
 7408: 	# The form field scantron_questions is actually a list of line numbers not
 7409: 	# a list of question numbers. Therefore:
 7410: 	#
 7411: 	
 7412: 	my $line_list = &questions_to_line_list($arg);
 7413: 
 7414: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7415: 		  $line_list.'" />');
 7416: 	foreach my $question (@{$arg}) {
 7417: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7418:                                                    $scan_record, $error);
 7419:             push(@lines_to_correct,@linenums);
 7420: 	}
 7421:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7422:     } else {
 7423: 	$r->print("\n<ul>");
 7424:     }
 7425:     $r->print("\n</li></ul>");
 7426: }
 7427: 
 7428: sub verify_bubbles_checked {
 7429:     my (@ansnums) = @_;
 7430:     my $ansnumstr = join('","',@ansnums);
 7431:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7432:     my $output = (<<ENDSCRIPT);
 7433: <script type="text/javascript">
 7434: function verify_bubble_radio(form) {
 7435:     var ansnumArray = new Array ("$ansnumstr");
 7436:     var need_bubble_count = 0;
 7437:     for (var i=0; i<ansnumArray.length; i++) {
 7438:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7439:             var bubble_picked = 0; 
 7440:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7441:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7442:                     bubble_picked = 1;
 7443:                 }
 7444:             }
 7445:             if (bubble_picked == 0) {
 7446:                 need_bubble_count ++;
 7447:             }
 7448:         }
 7449:     }
 7450:     if (need_bubble_count) {
 7451:         alert("$warning");
 7452:         return;
 7453:     }
 7454:     form.submit(); 
 7455: }
 7456: </script>
 7457: ENDSCRIPT
 7458:     return $output;
 7459: }
 7460: 
 7461: =pod
 7462: 
 7463: =item  questions_to_line_list
 7464: 
 7465: Converts a list of questions into a string of comma separated
 7466: line numbers in the answer sheet used by the questions.  This is
 7467: used to fill in the scantron_questions form field.
 7468: 
 7469:   Arguments:
 7470:      questions    - Reference to an array of questions.
 7471: 
 7472: =cut
 7473: 
 7474: 
 7475: sub questions_to_line_list {
 7476:     my ($questions) = @_;
 7477:     my @lines;
 7478: 
 7479:     foreach my $item (@{$questions}) {
 7480:         my $question = $item;
 7481:         my ($first,$count,$last);
 7482:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7483:             $question = $1;
 7484:             my $subquestion = $2;
 7485:             $first = $first_bubble_line{$question-1} + 1;
 7486:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7487:             my $subcount = 1;
 7488:             while ($subcount<$subquestion) {
 7489:                 $first += $subans[$subcount-1];
 7490:                 $subcount ++;
 7491:             }
 7492:             $count = $subans[$subquestion-1];
 7493:         } else {
 7494: 	    $first   = $first_bubble_line{$question-1} + 1;
 7495: 	    $count   = $bubble_lines_per_response{$question-1};
 7496:         }
 7497:         $last = $first+$count-1;
 7498:         push(@lines, ($first..$last));
 7499:     }
 7500:     return join(',', @lines);
 7501: }
 7502: 
 7503: =pod 
 7504: 
 7505: =item prompt_for_corrections
 7506: 
 7507: Prompts for a potentially multiline correction to the
 7508: user's bubbling (factors out common code from scantron_get_correction
 7509: for multi and missing bubble cases).
 7510: 
 7511:  Arguments:
 7512:    $r           - Apache request object.
 7513:    $question    - The question number to prompt for.
 7514:    $scan_config - The scantron file configuration hash.
 7515:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7516:    $error       - Type of error
 7517: 
 7518:  Implicit inputs:
 7519:    %bubble_lines_per_response   - Starting line numbers for each question.
 7520:                                   Numbered from 0 (but question numbers are from
 7521:                                   1.
 7522:    %first_bubble_line           - Starting bubble line for each question.
 7523:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7524:                                   type problems render as separate sub-questions, 
 7525:                                   in exam mode. This hash contains a 
 7526:                                   comma-separated list of the lines per 
 7527:                                   sub-question.
 7528:    %responsetype_per_response   - essayresponse, formularesponse,
 7529:                                   stringresponse, imageresponse, reactionresponse,
 7530:                                   and organicresponse type problem parts can have
 7531:                                   multiple lines per response if the weight
 7532:                                   assigned exceeds 10.  In this case, only
 7533:                                   one bubble per line is permitted, but more 
 7534:                                   than one line might contain bubbles, e.g.
 7535:                                   bubbling of: line 1 - J, line 2 - J, 
 7536:                                   line 3 - B would assign 22 points.  
 7537: 
 7538: =cut
 7539: 
 7540: sub prompt_for_corrections {
 7541:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7542:     my ($current_line,$lines);
 7543:     my @linenums;
 7544:     my $questionnum = $question;
 7545:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7546:         $question = $1;
 7547:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7548:         my $subquestion = $2;
 7549:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7550:         my $subcount = 1;
 7551:         while ($subcount<$subquestion) {
 7552:             $current_line += $subans[$subcount-1];
 7553:             $subcount ++;
 7554:         }
 7555:         $lines = $subans[$subquestion-1];
 7556:     } else {
 7557:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7558:         $lines        = $bubble_lines_per_response{$question-1};
 7559:     }
 7560:     if ($lines > 1) {
 7561:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7562:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7563:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7564:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7565:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7566:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7567:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7568:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the 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 />');
 7569:         } else {
 7570:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7571:         }
 7572:     }
 7573:     for (my $i =0; $i < $lines; $i++) {
 7574:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7575: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7576: 	        		  $questionnum,$error,split('', $selected));
 7577:         push(@linenums,$current_line);
 7578: 	$current_line++;
 7579:     }
 7580:     if ($lines > 1) {
 7581: 	$r->print("<hr /><br />");
 7582:     }
 7583:     return @linenums;
 7584: }
 7585: 
 7586: =pod
 7587: 
 7588: =item scantron_bubble_selector
 7589:   
 7590:    Generates the html radiobuttons to correct a single bubble line
 7591:    possibly showing the existing the selected bubbles if known
 7592: 
 7593:  Arguments:
 7594:     $r           - Apache request object
 7595:     $scan_config - hash from &get_scantron_config()
 7596:     $line        - Number of the line being displayed.
 7597:     $questionnum - Question number (may include subquestion)
 7598:     $error       - Type of error.
 7599:     @selected    - Array of bubbles picked on this line.
 7600: 
 7601: =cut
 7602: 
 7603: sub scantron_bubble_selector {
 7604:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7605:     my $max=$$scan_config{'Qlength'};
 7606: 
 7607:     my $scmode=$$scan_config{'Qon'};
 7608:     if ($scmode eq 'number' || $scmode eq 'letter') {
 7609:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7610:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7611:             $max=$$scan_config{'BubblesPerRow'};
 7612:             if (($scmode eq 'number') && ($max > 10)) {
 7613:                 $max = 10;
 7614:             } elsif (($scmode eq 'letter') && $max > 26) {
 7615:                 $max = 26;
 7616:             }
 7617:         } else {
 7618:             $max = 10;
 7619:         }
 7620:     }
 7621: 
 7622:     my @alphabet=('A'..'Z');
 7623:     $r->print(&Apache::loncommon::start_data_table().
 7624:               &Apache::loncommon::start_data_table_row());
 7625:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7626:     for (my $i=0;$i<$max+1;$i++) {
 7627: 	$r->print("\n".'<td align="center">');
 7628: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7629: 	else { $r->print('&nbsp;'); }
 7630: 	$r->print('</td>');
 7631:     }
 7632:     $r->print(&Apache::loncommon::end_data_table_row().
 7633:               &Apache::loncommon::start_data_table_row());
 7634:     for (my $i=0;$i<$max;$i++) {
 7635: 	$r->print("\n".
 7636: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7637: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7638:     }
 7639:     my $nobub_checked = ' ';
 7640:     if ($error eq 'missingbubble') {
 7641:         $nobub_checked = ' checked = "checked" ';
 7642:     }
 7643:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7644: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7645:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7646:               $line.'" value="'.$questionnum.'" /></td>');
 7647:     $r->print(&Apache::loncommon::end_data_table_row().
 7648:               &Apache::loncommon::end_data_table());
 7649: }
 7650: 
 7651: =pod
 7652: 
 7653: =item num_matches
 7654: 
 7655:    Counts the number of characters that are the same between the two arguments.
 7656: 
 7657:  Arguments:
 7658:    $orig - CODE from the scanline
 7659:    $code - CODE to match against
 7660: 
 7661:  Returns:
 7662:    $count - integer count of the number of same characters between the
 7663:             two arguments
 7664: 
 7665: =cut
 7666: 
 7667: sub num_matches {
 7668:     my ($orig,$code) = @_;
 7669:     my @code=split(//,$code);
 7670:     my @orig=split(//,$orig);
 7671:     my $same=0;
 7672:     for (my $i=0;$i<scalar(@code);$i++) {
 7673: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7674:     }
 7675:     return $same;
 7676: }
 7677: 
 7678: =pod
 7679: 
 7680: =item scantron_get_closely_matching_CODEs
 7681: 
 7682:    Cycles through all CODEs and finds the set that has the greatest
 7683:    number of same characters as the provided CODE
 7684: 
 7685:  Arguments:
 7686:    $allcodes - hash ref returned by &get_codes()
 7687:    $CODE     - CODE from the current scanline
 7688: 
 7689:  Returns:
 7690:    2 element list
 7691:     - first elements is number of how closely matching the best fit is 
 7692:       (5 means best set has 5 matching characters)
 7693:     - second element is an arrary ref containing the set of valid CODEs
 7694:       that best fit the passed in CODE
 7695: 
 7696: =cut
 7697: 
 7698: sub scantron_get_closely_matching_CODEs {
 7699:     my ($allcodes,$CODE)=@_;
 7700:     my @CODEs;
 7701:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7702: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7703:     }
 7704: 
 7705:     return ($#CODEs,$CODEs[-1]);
 7706: }
 7707: 
 7708: =pod
 7709: 
 7710: =item get_codes
 7711: 
 7712:    Builds a hash which has keys of all of the valid CODEs from the selected
 7713:    set of remembered CODEs.
 7714: 
 7715:  Arguments:
 7716:   $old_name - name of the set of remembered CODEs
 7717:   $cdom     - domain of the course
 7718:   $cnum     - internal course name
 7719: 
 7720:  Returns:
 7721:   %allcodes - keys are the valid CODEs, values are all 1
 7722: 
 7723: =cut
 7724: 
 7725: sub get_codes {
 7726:     my ($old_name, $cdom, $cnum) = @_;
 7727:     if (!$old_name) {
 7728: 	$old_name=$env{'form.scantron_CODElist'};
 7729:     }
 7730:     if (!$cdom) {
 7731: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7732:     }
 7733:     if (!$cnum) {
 7734: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7735:     }
 7736:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7737: 				    $cdom,$cnum);
 7738:     my %allcodes;
 7739:     if ($result{"type\0$old_name"} eq 'number') {
 7740: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7741:     } else {
 7742: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7743:     }
 7744:     return %allcodes;
 7745: }
 7746: 
 7747: =pod
 7748: 
 7749: =item scantron_validate_CODE
 7750: 
 7751:    Validates all scanlines in the selected file to not have any
 7752:    invalid or underspecified CODEs and that none of the codes are
 7753:    duplicated if this was requested.
 7754: 
 7755: =cut
 7756: 
 7757: sub scantron_validate_CODE {
 7758:     my ($r,$currentphase) = @_;
 7759:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7760:     if ($scantron_config{'CODElocation'} &&
 7761: 	$scantron_config{'CODEstart'} &&
 7762: 	$scantron_config{'CODElength'}) {
 7763: 	if (!defined($env{'form.scantron_CODElist'})) {
 7764: 	    &FIXME_blow_up()
 7765: 	}
 7766:     } else {
 7767: 	return (0,$currentphase+1);
 7768:     }
 7769:     
 7770:     my %usedCODEs;
 7771: 
 7772:     my %allcodes=&get_codes();
 7773: 
 7774:     my $nav_error;
 7775:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7776:     if ($nav_error) {
 7777:         $r->print(&navmap_errormsg());
 7778:         return(1,$currentphase);
 7779:     }
 7780: 
 7781:     my ($scanlines,$scan_data)=&scantron_getfile();
 7782:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7783: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7784: 	if ($line=~/^[\s\cz]*$/) { next; }
 7785: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7786: 						 $scan_data);
 7787: 	my $CODE=$$scan_record{'scantron.CODE'};
 7788: 	my $error=0;
 7789: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7790: 	    &scantron_get_correction($r,$i,$scan_record,
 7791: 				     \%scantron_config,
 7792: 				     $line,'incorrectCODE',\%allcodes);
 7793: 	    return(1,$currentphase);
 7794: 	}
 7795: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7796: 	    && !$$scan_record{'scantron.useCODE'}) {
 7797: 	    &scantron_get_correction($r,$i,$scan_record,
 7798: 				     \%scantron_config,
 7799: 				     $line,'incorrectCODE',\%allcodes);
 7800: 	    return(1,$currentphase);
 7801: 	}
 7802: 	if (exists($usedCODEs{$CODE}) 
 7803: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7804: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7805: 	    &scantron_get_correction($r,$i,$scan_record,
 7806: 				     \%scantron_config,
 7807: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7808: 	    return(1,$currentphase);
 7809: 	}
 7810: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7811:     }
 7812:     return (0,$currentphase+1);
 7813: }
 7814: 
 7815: =pod
 7816: 
 7817: =item scantron_validate_doublebubble
 7818: 
 7819:    Validates all scanlines in the selected file to not have any
 7820:    bubble lines with multiple bubbles marked.
 7821: 
 7822: =cut
 7823: 
 7824: sub scantron_validate_doublebubble {
 7825:     my ($r,$currentphase) = @_;
 7826:     #get student info
 7827:     my $classlist=&Apache::loncoursedata::get_classlist();
 7828:     my %idmap=&username_to_idmap($classlist);
 7829: 
 7830:     #get scantron line setup
 7831:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7832:     my ($scanlines,$scan_data)=&scantron_getfile();
 7833:     my $nav_error;
 7834:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7835:     if ($nav_error) {
 7836:         $r->print(&navmap_errormsg());
 7837:         return(1,$currentphase);
 7838:     }
 7839: 
 7840:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7841: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7842: 	if ($line=~/^[\s\cz]*$/) { next; }
 7843: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7844: 						 $scan_data);
 7845: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7846: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7847: 				 'doublebubble',
 7848: 				 $$scan_record{'scantron.doubleerror'});
 7849:     	return (1,$currentphase);
 7850:     }
 7851:     return (0,$currentphase+1);
 7852: }
 7853: 
 7854: 
 7855: sub scantron_get_maxbubble {
 7856:     my ($nav_error,$scantron_config) = @_;
 7857:     if (defined($env{'form.scantron_maxbubble'}) &&
 7858: 	$env{'form.scantron_maxbubble'}) {
 7859: 	&restore_bubble_lines();
 7860: 	return $env{'form.scantron_maxbubble'};
 7861:     }
 7862: 
 7863:     my (undef, undef, $sequence) =
 7864: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7865: 
 7866:     my $navmap=Apache::lonnavmaps::navmap->new();
 7867:     unless (ref($navmap)) {
 7868:         if (ref($nav_error)) {
 7869:             $$nav_error = 1;
 7870:         }
 7871:         return;
 7872:     }
 7873:     my $map=$navmap->getResourceByUrl($sequence);
 7874:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7875:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7876: 
 7877:     &Apache::lonxml::clear_problem_counter();
 7878: 
 7879:     my $uname       = $env{'user.name'};
 7880:     my $udom        = $env{'user.domain'};
 7881:     my $cid         = $env{'request.course.id'};
 7882:     my $total_lines = 0;
 7883:     %bubble_lines_per_response = ();
 7884:     %first_bubble_line         = ();
 7885:     %subdivided_bubble_lines   = ();
 7886:     %responsetype_per_response = ();
 7887: 
 7888:     my $response_number = 0;
 7889:     my $bubble_line     = 0;
 7890:     foreach my $resource (@resources) {
 7891:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 7892:                                                           $udom,$bubbles_per_row);
 7893:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7894: 	    foreach my $part_id (@{$parts}) {
 7895:                 my $lines;
 7896: 
 7897: 	        # TODO - make this a persistent hash not an array.
 7898: 
 7899:                 # optionresponse, matchresponse and rankresponse type items 
 7900:                 # render as separate sub-questions in exam mode.
 7901:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7902:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7903:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7904:                     my ($numbub,$numshown);
 7905:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7906:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7907:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7908:                         }
 7909:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7910:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7911:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7912:                         }
 7913:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7914:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7915:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7916:                         }
 7917:                     }
 7918:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7919:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7920:                     }
 7921:                     my $bubbles_per_row =
 7922:                         &bubblesheet_bubbles_per_row($scantron_config);
 7923:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 7924:                     if (($numbub % $bubbles_per_row) != 0) {
 7925:                         $inner_bubble_lines++;
 7926:                     }
 7927:                     for (my $i=0; $i<$numshown; $i++) {
 7928:                         $subdivided_bubble_lines{$response_number} .= 
 7929:                             $inner_bubble_lines.',';
 7930:                     }
 7931:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7932:                     $lines = $numshown * $inner_bubble_lines;
 7933:                 } else {
 7934:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7935:                 }
 7936: 
 7937:                 $first_bubble_line{$response_number} = $bubble_line;
 7938: 	        $bubble_lines_per_response{$response_number} = $lines;
 7939:                 $responsetype_per_response{$response_number} = 
 7940:                     $analysis->{$part_id.'.type'};
 7941: 	        $response_number++;
 7942: 
 7943: 	        $bubble_line +=  $lines;
 7944: 	        $total_lines +=  $lines;
 7945: 	    }
 7946:         }
 7947:     }
 7948:     &Apache::lonnet::delenv('scantron.');
 7949: 
 7950:     &save_bubble_lines();
 7951:     $env{'form.scantron_maxbubble'} =
 7952: 	$total_lines;
 7953:     return $env{'form.scantron_maxbubble'};
 7954: }
 7955: 
 7956: sub bubblesheet_bubbles_per_row {
 7957:     my ($scantron_config) = @_;
 7958:     my $bubbles_per_row;
 7959:     if (ref($scantron_config) eq 'HASH') {
 7960:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 7961:     }
 7962:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 7963:         $bubbles_per_row = 10;
 7964:     }
 7965:     return $bubbles_per_row;
 7966: }
 7967: 
 7968: sub scantron_validate_missingbubbles {
 7969:     my ($r,$currentphase) = @_;
 7970:     #get student info
 7971:     my $classlist=&Apache::loncoursedata::get_classlist();
 7972:     my %idmap=&username_to_idmap($classlist);
 7973: 
 7974:     #get scantron line setup
 7975:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7976:     my ($scanlines,$scan_data)=&scantron_getfile();
 7977:     my $nav_error;
 7978:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7979:     if ($nav_error) {
 7980:         return(1,$currentphase);
 7981:     }
 7982:     if (!$max_bubble) { $max_bubble=2**31; }
 7983:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7984: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7985: 	if ($line=~/^[\s\cz]*$/) { next; }
 7986: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7987: 						 $scan_data);
 7988: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7989: 	my @to_correct;
 7990: 	
 7991: 	# Probably here's where the error is...
 7992: 
 7993: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7994:             my $lastbubble;
 7995:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7996:                my $question = $1;
 7997:                my $subquestion = $2;
 7998:                if (!defined($first_bubble_line{$question -1})) { next; }
 7999:                my $first = $first_bubble_line{$question-1};
 8000:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 8001:                my $subcount = 1;
 8002:                while ($subcount<$subquestion) {
 8003:                    $first += $subans[$subcount-1];
 8004:                    $subcount ++;
 8005:                }
 8006:                my $count = $subans[$subquestion-1];
 8007:                $lastbubble = $first + $count;
 8008:             } else {
 8009:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 8010:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 8011:             }
 8012:             if ($lastbubble > $max_bubble) { next; }
 8013: 	    push(@to_correct,$missing);
 8014: 	}
 8015: 	if (@to_correct) {
 8016: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8017: 				     $line,'missingbubble',\@to_correct);
 8018: 	    return (1,$currentphase);
 8019: 	}
 8020: 
 8021:     }
 8022:     return (0,$currentphase+1);
 8023: }
 8024: 
 8025: sub hand_bubble_option {
 8026:     my (undef, undef, $sequence) =
 8027:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8028:     return if ($sequence eq '');
 8029:     my $navmap = Apache::lonnavmaps::navmap->new();
 8030:     unless (ref($navmap)) {
 8031:         return;
 8032:     }
 8033:     my $needs_hand_bubbles;
 8034:     my $map=$navmap->getResourceByUrl($sequence);
 8035:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8036:     foreach my $res (@resources) {
 8037:         if (ref($res)) {
 8038:             if ($res->is_problem()) {
 8039:                 my $partlist = $res->parts();
 8040:                 foreach my $part (@{ $partlist }) {
 8041:                     my @types = $res->responseType($part);
 8042:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8043:                         $needs_hand_bubbles = 1;
 8044:                         last;
 8045:                     }
 8046:                 }
 8047:             }
 8048:         }
 8049:     }
 8050:     if ($needs_hand_bubbles) {
 8051:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8052:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8053:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8054:                &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 />').
 8055:                '<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;'.
 8056:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 8057:     }
 8058:     return;
 8059: }
 8060: 
 8061: sub scantron_process_students {
 8062:     my ($r) = @_;
 8063: 
 8064:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8065:     my ($symb)=&get_symb($r);
 8066:     if (!$symb) {
 8067: 	return '';
 8068:     }
 8069:     my $default_form_data=&defaultFormData($symb);
 8070: 
 8071:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8072:     my $bubbles_per_row =
 8073:         &bubblesheet_bubbles_per_row(\%scantron_config);
 8074:     my ($scanlines,$scan_data)=&scantron_getfile();
 8075:     my $classlist=&Apache::loncoursedata::get_classlist();
 8076:     my %idmap=&username_to_idmap($classlist);
 8077:     my $navmap=Apache::lonnavmaps::navmap->new();
 8078:     unless (ref($navmap)) {
 8079:         $r->print(&navmap_errormsg());
 8080:         return '';
 8081:     }  
 8082:     my $map=$navmap->getResourceByUrl($sequence);
 8083:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8084:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8085:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8086:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8087:     my $resource_error;
 8088:     foreach my $resource (@resources) {
 8089:         my $ressymb;
 8090:         if (ref($resource)) {
 8091:             $ressymb = $resource->symb();
 8092:         } else {
 8093:             $resource_error = 1;
 8094:             last;
 8095:         }
 8096:         my ($analysis,$parts) =
 8097:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 8098:                                       $env{'user.name'},$env{'user.domain'},
 8099:                                       1,$bubbles_per_row);
 8100:         $grader_partids_by_symb{$ressymb} = $parts;
 8101:         if (ref($analysis) eq 'HASH') {
 8102:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8103:                 $grader_randomlists_by_symb{$ressymb} = 
 8104:                     $analysis->{'parts_withrandomlist'};
 8105:             }
 8106:         }
 8107:     }
 8108:     if ($resource_error) {
 8109:         $r->print(&navmap_errormsg());
 8110:         return '';
 8111:     }
 8112: 
 8113:     my ($uname,$udom);
 8114:     my $result= <<SCANTRONFORM;
 8115: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8116:   <input type="hidden" name="command" value="scantron_configphase" />
 8117:   $default_form_data
 8118: SCANTRONFORM
 8119:     $r->print($result);
 8120: 
 8121:     my @delayqueue;
 8122:     my (%completedstudents,%scandata);
 8123:     
 8124:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8125:     my $count=&get_todo_count($scanlines,$scan_data);
 8126:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8127:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8128: 					  'Processing first student');
 8129:     $r->print('<br />');
 8130:     my $start=&Time::HiRes::time();
 8131:     my $i=-1;
 8132:     my $started;
 8133: 
 8134:     my $nav_error;
 8135:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8136:     if ($nav_error) {
 8137:         $r->print(&navmap_errormsg());
 8138:         return '';
 8139:     }
 8140: 
 8141:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8142:     # the user and return.
 8143: 
 8144:     if ($ssi_error) {
 8145: 	$r->print("</form>");
 8146: 	&ssi_print_error($r);
 8147: 	$r->print(&show_grading_menu_form($symb));
 8148:         &Apache::lonnet::remove_lock($lock);
 8149: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8150:     }
 8151: 
 8152:     my %lettdig = &letter_to_digits();
 8153:     my $numletts = scalar(keys(%lettdig));
 8154: 
 8155:     while ($i<$scanlines->{'count'}) {
 8156:  	($uname,$udom)=('','');
 8157:  	$i++;
 8158:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8159:  	if ($line=~/^[\s\cz]*$/) { next; }
 8160: 	if ($started) {
 8161: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8162: 						     'last student');
 8163: 	}
 8164: 	$started=1;
 8165:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8166:  						 $scan_data);
 8167:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8168:  					      \%idmap,$i)) {
 8169:   	    &scantron_add_delay(\@delayqueue,$line,
 8170:  				'Unable to find a student that matches',1);
 8171:  	    next;
 8172:   	}
 8173:  	if (exists $completedstudents{$uname}) {
 8174:  	    &scantron_add_delay(\@delayqueue,$line,
 8175:  				'Student '.$uname.' has multiple sheets',2);
 8176:  	    next;
 8177:  	}
 8178:   	($uname,$udom)=split(/:/,$uname);
 8179: 
 8180:         my (%partids_by_symb,$res_error);
 8181:         foreach my $resource (@resources) {
 8182:             my $ressymb;
 8183:             if (ref($resource)) {
 8184:                 $ressymb = $resource->symb();
 8185:             } else {
 8186:                 $res_error = 1;
 8187:                 last;
 8188:             }
 8189:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8190:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8191:                 my ($analysis,$parts) =
 8192:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8193:                                               $uname,$udom,undef,$bubbles_per_row);
 8194:                 $partids_by_symb{$ressymb} = $parts;
 8195:             } else {
 8196:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8197:             }
 8198:         }
 8199: 
 8200:         if ($res_error) {
 8201:             &scantron_add_delay(\@delayqueue,$line,
 8202:                                 'An error occurred while grading student '.$uname,2);
 8203:             next;
 8204:         }
 8205: 
 8206: 	&Apache::lonxml::clear_problem_counter();
 8207:   	&Apache::lonnet::appenv($scan_record);
 8208: 
 8209: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8210: 	    &scantron_putfile($scanlines,$scan_data);
 8211: 	}
 8212: 	
 8213:         my $scancode;
 8214:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8215:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8216:             $scancode = $scan_record->{'scantron.CODE'};
 8217:         } else {
 8218:             $scancode = '';
 8219:         }
 8220: 
 8221:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8222:                                    \@resources,\%partids_by_symb,
 8223:                                    $bubbles_per_row) eq 'ssi_error') {
 8224:             $ssi_error = 0; # So end of handler error message does not trigger.
 8225:             $r->print("</form>");
 8226:             &ssi_print_error($r);
 8227:             $r->print(&show_grading_menu_form($symb));
 8228:             &Apache::lonnet::remove_lock($lock);
 8229:             return '';      # Why return ''?  Beats me.
 8230:         }
 8231: 
 8232: 	$completedstudents{$uname}={'line'=>$line};
 8233:         if ($env{'form.verifyrecord'}) {
 8234:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8235:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8236:             chomp($studentdata);
 8237:             $studentdata =~ s/\r$//;
 8238:             my $studentrecord = '';
 8239:             my $counter = -1;
 8240:             foreach my $resource (@resources) {
 8241:                 my $ressymb = $resource->symb();
 8242:                 ($counter,my $recording) =
 8243:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8244:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8245:                                              \%scantron_config,\%lettdig,$numletts);
 8246:                 $studentrecord .= $recording;
 8247:             }
 8248:             if ($studentrecord ne $studentdata) {
 8249:                 &Apache::lonxml::clear_problem_counter();
 8250:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8251:                                            \@resources,\%partids_by_symb,
 8252:                                            $bubbles_per_row) eq 'ssi_error') {
 8253:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8254:                     $r->print("</form>");
 8255:                     &ssi_print_error($r);
 8256:                     $r->print(&show_grading_menu_form($symb));
 8257:                     &Apache::lonnet::remove_lock($lock);
 8258:                     delete($completedstudents{$uname});
 8259:                     return '';
 8260:                 }
 8261:                 $counter = -1;
 8262:                 $studentrecord = '';
 8263:                 foreach my $resource (@resources) {
 8264:                     my $ressymb = $resource->symb();
 8265:                     ($counter,my $recording) =
 8266:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8267:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8268:                                                  \%scantron_config,\%lettdig,$numletts);
 8269:                     $studentrecord .= $recording;
 8270:                 }
 8271:                 if ($studentrecord ne $studentdata) {
 8272:                     $r->print('<p><span class="LC_warning">');
 8273:                     if ($scancode eq '') {
 8274:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8275:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8276:                     } else {
 8277:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8278:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8279:                     }
 8280:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8281:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8282:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8283:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8284:                               &Apache::loncommon::start_data_table_row().
 8285:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8286:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 8287:                               &Apache::loncommon::end_data_table_row().
 8288:                               &Apache::loncommon::start_data_table_row().
 8289:                               '<td>'.&mt('Stored submissions').'</td>'.
 8290:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 8291:                               &Apache::loncommon::end_data_table_row().
 8292:                               &Apache::loncommon::end_data_table().'</p>');
 8293:                 } else {
 8294:                     $r->print('<br /><span class="LC_warning">'.
 8295:                              &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 />'.
 8296:                              &mt("As a consequence, this user's submission history records two tries.").
 8297:                                  '</span><br />');
 8298:                 }
 8299:             }
 8300:         }
 8301:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8302:     } continue {
 8303: 	&Apache::lonxml::clear_problem_counter();
 8304: 	&Apache::lonnet::delenv('scantron.');
 8305:     }
 8306:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8307:     &Apache::lonnet::remove_lock($lock);
 8308: #    my $lasttime = &Time::HiRes::time()-$start;
 8309: #    $r->print("<p>took $lasttime</p>");
 8310: 
 8311:     $r->print("</form>");
 8312:     $r->print(&show_grading_menu_form($symb));
 8313:     return '';
 8314: }
 8315: 
 8316: sub graders_resources_pass {
 8317:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8318:         $bubbles_per_row) = @_;
 8319:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8320:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8321:         foreach my $resource (@{$resources}) {
 8322:             my $ressymb = $resource->symb();
 8323:             my ($analysis,$parts) =
 8324:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8325:                                           $env{'user.name'},$env{'user.domain'},
 8326:                                           1,$bubbles_per_row);
 8327:             $grader_partids_by_symb->{$ressymb} = $parts;
 8328:             if (ref($analysis) eq 'HASH') {
 8329:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8330:                     $grader_randomlists_by_symb->{$ressymb} =
 8331:                         $analysis->{'parts_withrandomlist'};
 8332:                 }
 8333:             }
 8334:         }
 8335:     }
 8336:     return;
 8337: }
 8338: 
 8339: sub grade_student_bubbles {
 8340:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
 8341:     if (ref($resources) eq 'ARRAY') {
 8342:         my $count = 0;
 8343:         foreach my $resource (@{$resources}) {
 8344:             my $ressymb = $resource->symb();
 8345:             my %form = ('submitted'      => 'scantron',
 8346:                         'grade_target'   => 'grade',
 8347:                         'grade_username' => $uname,
 8348:                         'grade_domain'   => $udom,
 8349:                         'grade_courseid' => $env{'request.course.id'},
 8350:                         'grade_symb'     => $ressymb,
 8351:                         'CODE'           => $scancode
 8352:                        );
 8353:             if ($bubbles_per_row ne '') {
 8354:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8355:             }
 8356:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8357:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8358:             }
 8359:             if (ref($parts) eq 'HASH') {
 8360:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8361:                     foreach my $part (@{$parts->{$ressymb}}) {
 8362:                         $form{'scantron_questnum_start.'.$part} =
 8363:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 8364:                         $count++;
 8365:                     }
 8366:                 }
 8367:             }
 8368:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8369:             return 'ssi_error' if ($ssi_error);
 8370:             last if (&Apache::loncommon::connection_aborted($r));
 8371:         }
 8372:     }
 8373:     return;
 8374: }
 8375: 
 8376: sub scantron_upload_scantron_data {
 8377:     my ($r)=@_;
 8378:     my $dom = $env{'request.role.domain'};
 8379:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8380:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8381:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8382: 							  'domainid',
 8383: 							  'coursename',$dom);
 8384:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8385:                        ('&nbsp'x2).&mt('(shows course personnel)');
 8386:     my ($symb) = &get_symb($r,1);
 8387:     my $default_form_data=&defaultFormData($symb);
 8388:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8389:     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.");
 8390:     $r->print('
 8391: <script type="text/javascript" language="javascript">
 8392:     function checkUpload(formname) {
 8393: 	if (formname.upfile.value == "") {
 8394: 	    alert("'.$nofile_alert.'");
 8395: 	    return false;
 8396: 	}
 8397:         if (formname.courseid.value == "") {
 8398:             alert("'.$nocourseid_alert.'");
 8399:             return false;
 8400:         }
 8401: 	formname.submit();
 8402:     }
 8403: 
 8404:     function ToSyllabus() {
 8405:         var cdom = '."'$dom'".';
 8406:         var cnum = document.rules.courseid.value;
 8407:         if (cdom == "" || cdom == null) {
 8408:             return;
 8409:         }
 8410:         if (cnum == "" || cnum == null) {
 8411:            return;
 8412:         }
 8413:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8414:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8415:         return;
 8416:     }
 8417: 
 8418: </script>
 8419: 
 8420: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8421: 
 8422: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8423: '.$default_form_data.
 8424:   &Apache::lonhtmlcommon::start_pick_box().
 8425:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8426:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8427:   &Apache::lonhtmlcommon::row_closure().
 8428:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8429:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8430:   &Apache::lonhtmlcommon::row_closure().
 8431:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8432:   '<input name="domainid" type="hidden" />'.$domdesc.
 8433:   &Apache::lonhtmlcommon::row_closure().
 8434:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8435:   '<input type="file" name="upfile" size="50" />'.
 8436:   &Apache::lonhtmlcommon::row_closure(1).
 8437:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8438: 
 8439: <input name="command" value="scantronupload_save" type="hidden" />
 8440: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8441: </form>
 8442: ');
 8443:     return '';
 8444: }
 8445: 
 8446: 
 8447: sub scantron_upload_scantron_data_save {
 8448:     my($r)=@_;
 8449:     my ($symb)=&get_symb($r,1);
 8450:     my $doanotherupload=
 8451: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8452: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8453: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8454: 	'</form>'."\n";
 8455:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8456: 	!&Apache::lonnet::allowed('usc',
 8457: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8458: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8459: 	if ($symb) {
 8460: 	    $r->print(&show_grading_menu_form($symb));
 8461: 	} else {
 8462: 	    $r->print($doanotherupload);
 8463: 	}
 8464: 	return '';
 8465:     }
 8466:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8467:     my $uploadedfile;
 8468:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8469:     if (length($env{'form.upfile'}) < 2) {
 8470:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8471:     } else {
 8472:         my $result = 
 8473:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8474:                                             $env{'form.courseid'},$env{'form.domainid'});
 8475: 	if ($result =~ m{^/uploaded/}) {
 8476: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8477:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8478: 			  '<span class="LC_filename">'.$result.'</span>'));
 8479:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8480:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8481:                                                        $env{'form.courseid'},$uploadedfile));
 8482: 	} else {
 8483: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8484:                           '<span class="LC_error">','</span>',$result,
 8485: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8486: 	}
 8487:     }
 8488:     if ($symb) {
 8489: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8490:     } else {
 8491: 	$r->print($doanotherupload);
 8492:     }
 8493:     return '';
 8494: }
 8495: 
 8496: sub validate_uploaded_scantron_file {
 8497:     my ($cdom,$cname,$fname) = @_;
 8498:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8499:     my @lines;
 8500:     if ($scanlines ne '-1') {
 8501:         @lines=split("\n",$scanlines,-1);
 8502:     }
 8503:     my $output;
 8504:     if (@lines) {
 8505:         my (%counts,$max_match_format);
 8506:         my ($max_match_count,$max_match_pct) = (0,0);
 8507:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8508:         my %idmap = &username_to_idmap($classlist);
 8509:         foreach my $key (keys(%idmap)) {
 8510:             my $lckey = lc($key);
 8511:             $idmap{$lckey} = $idmap{$key};
 8512:         }
 8513:         my %unique_formats;
 8514:         my @formatlines = &get_scantronformat_file();
 8515:         foreach my $line (@formatlines) {
 8516:             chomp($line);
 8517:             my @config = split(/:/,$line);
 8518:             my $idstart = $config[5];
 8519:             my $idlength = $config[6];
 8520:             if (($idstart ne '') && ($idlength > 0)) {
 8521:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8522:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8523:                 } else {
 8524:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8525:                 }
 8526:             }
 8527:         }
 8528:         foreach my $key (keys(%unique_formats)) {
 8529:             my ($idstart,$idlength) = split(':',$key);
 8530:             %{$counts{$key}} = (
 8531:                                'found'   => 0,
 8532:                                'total'   => 0,
 8533:                               );
 8534:             foreach my $line (@lines) {
 8535:                 next if ($line =~ /^#/);
 8536:                 next if ($line =~ /^[\s\cz]*$/);
 8537:                 my $id = substr($line,$idstart-1,$idlength);
 8538:                 $id = lc($id);
 8539:                 if (exists($idmap{$id})) {
 8540:                     $counts{$key}{'found'} ++;
 8541:                 }
 8542:                 $counts{$key}{'total'} ++;
 8543:             }
 8544:             if ($counts{$key}{'total'}) {
 8545:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8546:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8547:                     $max_match_pct = $percent_match;
 8548:                     $max_match_format = $key;
 8549:                     $max_match_count = $counts{$key}{'total'};
 8550:                 }
 8551:             }
 8552:         }
 8553:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8554:             my $format_descs;
 8555:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8556:             for (my $i=0; $i<$numwithformat; $i++) {
 8557:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8558:                 if ($i<$numwithformat-2) {
 8559:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8560:                 } elsif ($i==$numwithformat-2) {
 8561:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8562:                 } elsif ($i==$numwithformat-1) {
 8563:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8564:                 }
 8565:             }
 8566:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8567:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8568:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8569:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8570:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8571:                                   '<i>'.$cdom.'</i>').'</li>'.
 8572:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8573:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8574:                        '</ul>';
 8575:         }
 8576:     } else {
 8577:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8578:     }
 8579:     return $output;
 8580: }
 8581: 
 8582: sub valid_file {
 8583:     my ($requested_file)=@_;
 8584:     foreach my $filename (sort(&scantron_filenames())) {
 8585: 	if ($requested_file eq $filename) { return 1; }
 8586:     }
 8587:     return 0;
 8588: }
 8589: 
 8590: sub scantron_download_scantron_data {
 8591:     my ($r)=@_;
 8592:     my ($symb) = &get_symb($r,1);
 8593:     my $default_form_data=&defaultFormData($symb);
 8594:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8595:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8596:     my $file=$env{'form.scantron_selectfile'};
 8597:     if (! &valid_file($file)) {
 8598: 	$r->print('
 8599: 	<p>
 8600: 	    '.&mt('The requested file name was invalid.').'
 8601:         </p>
 8602: ');
 8603: 	$r->print(&show_grading_menu_form($symb));
 8604: 	return;
 8605:     }
 8606:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8607:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8608:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8609:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8610:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8611:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8612:     $r->print('
 8613:     <p>
 8614: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8615: 	      '<a href="'.$orig.'">','</a>').'
 8616:     </p>
 8617:     <p>
 8618: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8619: 	      '<a href="'.$corrected.'">','</a>').'
 8620:     </p>
 8621:     <p>
 8622: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8623: 	      '<a href="'.$skipped.'">','</a>').'
 8624:     </p>
 8625: ');
 8626:     $r->print(&show_grading_menu_form($symb));
 8627:     return '';
 8628: }
 8629: 
 8630: sub checkscantron_results {
 8631:     my ($r) = @_;
 8632:     my ($symb)=&get_symb($r);
 8633:     if (!$symb) {return '';}
 8634:     my $grading_menu_button=&show_grading_menu_form($symb);
 8635:     my $cid = $env{'request.course.id'};
 8636:     my %lettdig = &letter_to_digits();
 8637:     my $numletts = scalar(keys(%lettdig));
 8638:     my $cnum = $env{'course.'.$cid.'.num'};
 8639:     my $cdom = $env{'course.'.$cid.'.domain'};
 8640:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8641:     my %record;
 8642:     my %scantron_config =
 8643:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8644:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8645:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8646:     my $classlist=&Apache::loncoursedata::get_classlist();
 8647:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8648:     my $navmap=Apache::lonnavmaps::navmap->new();
 8649:     unless (ref($navmap)) {
 8650:         $r->print(&navmap_errormsg());
 8651:         return '';
 8652:     }
 8653:     my $map=$navmap->getResourceByUrl($sequence);
 8654:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8655:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8656:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8657:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8658: 
 8659:     my ($uname,$udom);
 8660:     my (%scandata,%lastname,%bylast);
 8661:     $r->print('
 8662: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8663: 
 8664:     my @delayqueue;
 8665:     my %completedstudents;
 8666: 
 8667:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8668:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8669:     my ($username,$domain,$started);
 8670:     my $nav_error;
 8671:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8672:     if ($nav_error) {
 8673:         $r->print(&navmap_errormsg());
 8674:         return '';
 8675:     }
 8676: 
 8677:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8678:                                           'Processing first student');
 8679:     my $start=&Time::HiRes::time();
 8680:     my $i=-1;
 8681: 
 8682:     while ($i<$scanlines->{'count'}) {
 8683:         ($username,$domain,$uname)=('','','');
 8684:         $i++;
 8685:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8686:         if ($line=~/^[\s\cz]*$/) { next; }
 8687:         if ($started) {
 8688:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8689:                                                      'last student');
 8690:         }
 8691:         $started=1;
 8692:         my $scan_record=
 8693:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8694:                                                      $scan_data);
 8695:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8696:                                                               \%idmap,$i)) {
 8697:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8698:                                 'Unable to find a student that matches',1);
 8699:             next;
 8700:         }
 8701:         if (exists $completedstudents{$uname}) {
 8702:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8703:                                 'Student '.$uname.' has multiple sheets',2);
 8704:             next;
 8705:         }
 8706:         my $pid = $scan_record->{'scantron.ID'};
 8707:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8708:         push(@{$bylast{$lastname{$pid}}},$pid);
 8709:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8710:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8711:         chomp($scandata{$pid});
 8712:         $scandata{$pid} =~ s/\r$//;
 8713:         ($username,$domain)=split(/:/,$uname);
 8714:         my $counter = -1;
 8715:         foreach my $resource (@resources) {
 8716:             my $parts;
 8717:             my $ressymb = $resource->symb();
 8718:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8719:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8720:                 (my $analysis,$parts) =
 8721:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8722:                                               $username,$domain,undef,
 8723:                                               $bubbles_per_row);
 8724:             } else {
 8725:                 $parts = $grader_partids_by_symb{$ressymb};
 8726:             }
 8727:             ($counter,my $recording) =
 8728:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8729:                                          $scandata{$pid},$parts,
 8730:                                          \%scantron_config,\%lettdig,$numletts);
 8731:             $record{$pid} .= $recording;
 8732:         }
 8733:     }
 8734:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8735:     $r->print('<br />');
 8736:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8737:     $passed = 0;
 8738:     $failed = 0;
 8739:     $numstudents = 0;
 8740:     foreach my $last (sort(keys(%bylast))) {
 8741:         if (ref($bylast{$last}) eq 'ARRAY') {
 8742:             foreach my $pid (sort(@{$bylast{$last}})) {
 8743:                 my $showscandata = $scandata{$pid};
 8744:                 my $showrecord = $record{$pid};
 8745:                 $showscandata =~ s/\s/&nbsp;/g;
 8746:                 $showrecord =~ s/\s/&nbsp;/g;
 8747:                 if ($scandata{$pid} eq $record{$pid}) {
 8748:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8749:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8750: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8751: '</tr>'."\n".
 8752: '<tr class="'.$css_class.'">'."\n".
 8753: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8754:                     $passed ++;
 8755:                 } else {
 8756:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8757:                     $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".
 8758: '</tr>'."\n".
 8759: '<tr class="'.$css_class.'">'."\n".
 8760: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8761: '</tr>'."\n";
 8762:                     $failed ++;
 8763:                 }
 8764:                 $numstudents ++;
 8765:             }
 8766:         }
 8767:     }
 8768:     $r->print('<p>'.
 8769:               &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).',
 8770:                   '<b>',
 8771:                   $numstudents,
 8772:                   '</b>',
 8773:                   $env{'form.scantron_maxbubble'}).
 8774:               '</p>'
 8775:     );
 8776:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
 8777:     if ($passed) {
 8778:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8779:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8780:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8781:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8782:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8783:                  $okstudents."\n".
 8784:                  &Apache::loncommon::end_data_table().'<br />');
 8785:     }
 8786:     if ($failed) {
 8787:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8788:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8789:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8790:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8791:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8792:                  $badstudents."\n".
 8793:                  &Apache::loncommon::end_data_table()).'<br />'.
 8794:                  &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.');  
 8795:     }
 8796:     $r->print('</form><br />'.$grading_menu_button);
 8797:     return;
 8798: }
 8799: 
 8800: sub verify_scantron_grading {
 8801:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8802:         $scantron_config,$lettdig,$numletts) = @_;
 8803:     my ($record,%expected,%startpos);
 8804:     return ($counter,$record) if (!ref($resource));
 8805:     return ($counter,$record) if (!$resource->is_problem());
 8806:     my $symb = $resource->symb();
 8807:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8808:     foreach my $part_id (@{$partids}) {
 8809:         $counter ++;
 8810:         $expected{$part_id} = 0;
 8811:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8812:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8813:             foreach my $item (@sub_lines) {
 8814:                 $expected{$part_id} += $item;
 8815:             }
 8816:         } else {
 8817:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8818:         }
 8819:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8820:     }
 8821:     if ($symb) {
 8822:         my %recorded;
 8823:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8824:         if ($returnhash{'version'}) {
 8825:             my %lasthash=();
 8826:             my $version;
 8827:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8828:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8829:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8830:                 }
 8831:             }
 8832:             foreach my $key (keys(%lasthash)) {
 8833:                 if ($key =~ /\.scantron$/) {
 8834:                     my $value = &unescape($lasthash{$key});
 8835:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8836:                     if ($value eq '') {
 8837:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8838:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8839:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8840:                             }
 8841:                         }
 8842:                     } else {
 8843:                         my @tocheck;
 8844:                         my @items = split(//,$value);
 8845:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8846:                             ($scantron_config->{'Qon'} eq 'number')) {
 8847:                             if (@items < $expected{$part_id}) {
 8848:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8849:                                 my @singles = split(//,$fragment);
 8850:                                 foreach my $pos (@singles) {
 8851:                                     if ($pos eq ' ') {
 8852:                                         push(@tocheck,$pos);
 8853:                                     } else {
 8854:                                         my $next = shift(@items);
 8855:                                         push(@tocheck,$next);
 8856:                                     }
 8857:                                 }
 8858:                             } else {
 8859:                                 @tocheck = @items;
 8860:                             }
 8861:                             foreach my $letter (@tocheck) {
 8862:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8863:                                     if ($letter !~ /^[A-J]$/) {
 8864:                                         $letter = $scantron_config->{'Qoff'};
 8865:                                     }
 8866:                                     $recorded{$part_id} .= $letter;
 8867:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8868:                                     my $digit;
 8869:                                     if ($letter !~ /^[A-J]$/) {
 8870:                                         $digit = $scantron_config->{'Qoff'};
 8871:                                     } else {
 8872:                                         $digit = $lettdig->{$letter};
 8873:                                     }
 8874:                                     $recorded{$part_id} .= $digit;
 8875:                                 }
 8876:                             }
 8877:                         } else {
 8878:                             @tocheck = @items;
 8879:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8880:                                 my $curr_sub = shift(@tocheck);
 8881:                                 my $digit;
 8882:                                 if ($curr_sub =~ /^[A-J]$/) {
 8883:                                     $digit = $lettdig->{$curr_sub}-1;
 8884:                                 }
 8885:                                 if ($curr_sub eq 'J') {
 8886:                                     $digit += scalar($numletts);
 8887:                                 }
 8888:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8889:                                     if ($j == $digit) {
 8890:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8891:                                     } else {
 8892:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8893:                                     }
 8894:                                 }
 8895:                             }
 8896:                         }
 8897:                     }
 8898:                 }
 8899:             }
 8900:         }
 8901:         foreach my $part_id (@{$partids}) {
 8902:             if ($recorded{$part_id} eq '') {
 8903:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8904:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8905:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8906:                     }
 8907:                 }
 8908:             }
 8909:             $record .= $recorded{$part_id};
 8910:         }
 8911:     }
 8912:     return ($counter,$record);
 8913: }
 8914: 
 8915: sub letter_to_digits { 
 8916:     my %lettdig = (
 8917:                     A => 1,
 8918:                     B => 2,
 8919:                     C => 3,
 8920:                     D => 4,
 8921:                     E => 5,
 8922:                     F => 6,
 8923:                     G => 7,
 8924:                     H => 8,
 8925:                     I => 9,
 8926:                     J => 0,
 8927:                   );
 8928:     return %lettdig;
 8929: }
 8930: 
 8931: 
 8932: #-------- end of section for handling grading scantron forms -------
 8933: #
 8934: #-------------------------------------------------------------------
 8935: 
 8936: #-------------------------- Menu interface -------------------------
 8937: #
 8938: #--- Show a Grading Menu button - Calls the next routine ---
 8939: sub show_grading_menu_form {
 8940:     my ($symb)=@_;
 8941:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8942: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8943: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8944: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8945: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8946: 	'</form>'."\n";
 8947:     return $result;
 8948: }
 8949: 
 8950: # -- Retrieve choices for grading form
 8951: sub savedState {
 8952:     my %savedState = ();
 8953:     if ($env{'form.saveState'}) {
 8954: 	foreach (split(/:/,$env{'form.saveState'})) {
 8955: 	    my ($key,$value) = split(/=/,$_,2);
 8956: 	    $savedState{$key} = $value;
 8957: 	}
 8958:     }
 8959:     return \%savedState;
 8960: }
 8961: 
 8962: #--- Href with symb and command ---
 8963: 
 8964: sub href_symb_cmd {
 8965:     my ($symb,$cmd)=@_;
 8966:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 8967: }
 8968: 
 8969: sub grading_menu {
 8970:     my ($request) = @_;
 8971:     my ($symb)=&get_symb($request);
 8972:     if (!$symb) {return '';}
 8973:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8974:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8975: 
 8976:     $request->print($table);
 8977:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8978:                   'handgrade'=>$hdgrade,
 8979:                   'probTitle'=>$probTitle,
 8980:                   'command'=>'submit_options',
 8981:                   'saveState'=>"",
 8982:                   'gradingMenu'=>1,
 8983:                   'showgrading'=>"yes");
 8984:     
 8985:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8986:     
 8987:     $fields{'command'} = 'csvform';
 8988:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8989:     
 8990:     $fields{'command'} = 'processclicker';
 8991:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8992:     
 8993:     $fields{'command'} = 'scantron_selectphase';
 8994:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8995:     
 8996:     my @menu = ({	categorytitle=>'Course Grading',
 8997:             items =>[
 8998:                         {	linktext => 'Manual Grading/View Submissions',
 8999:                     		url => $url1,
 9000:                     		permission => 'F',
 9001:                     		icon => 'edit-find-replace.png',
 9002:                     		linktitle => 'Start the process of hand grading submissions.'
 9003:                         },
 9004:                 	    {	linktext => 'Upload Scores',
 9005:                     		url => $url2,
 9006:                     		permission => 'F',
 9007:                     		icon => 'uploadscores.png',
 9008:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9009:                 	    },
 9010:                 	    {	linktext => 'Process Clicker',
 9011:                     		url => $url3,
 9012:                     		permission => 'F',
 9013:                     		icon => 'addClickerInfoFile.png',
 9014:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9015:                 	    },
 9016:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9017:                     		url => $url4,
 9018:                     		permission => 'F',
 9019:                     		icon => 'stat.png',
 9020:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9021:                 	    }
 9022:                     ]
 9023:             });
 9024: 
 9025:     #$fields{'command'} = 'verify';
 9026:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9027:     #
 9028:     # Create the menu
 9029:     my $Str;
 9030:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9031:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9032:     $Str .= '<input type="hidden" name="command" value="" />'.
 9033:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9034: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9035: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9036: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9037: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9038: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9039: 
 9040:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9041:     #$menudata->{'jscript'}
 9042:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9043:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9044:         ' /> '.
 9045:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9046:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9047: 
 9048:     $Str .="</form>\n";
 9049:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9050:     $request->print(<<GRADINGMENUJS);
 9051: <script type="text/javascript" language="javascript">
 9052:     function checkChoice(formname,val,cmdx) {
 9053: 	if (val <= 2) {
 9054: 	    var cmd = radioSelection(formname.radioChoice);
 9055: 	    var cmdsave = cmd;
 9056: 	} else {
 9057: 	    cmd = cmdx;
 9058: 	    cmdsave = 'submission';
 9059: 	}
 9060: 	formname.command.value = cmd;
 9061: 	if (val < 5) formname.submit();
 9062: 	if (val == 5) {
 9063: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9064: 	        return false;
 9065: 	    } else {
 9066: 	        formname.submit();
 9067: 	    }
 9068: 	}
 9069:     }
 9070: 
 9071:     function checkReceiptNo(formname,nospace) {
 9072: 	var receiptNo = formname.receipt.value;
 9073: 	var checkOpt = false;
 9074: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9075: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9076: 	if (checkOpt) {
 9077: 	    alert("$receiptalert");
 9078: 	    formname.receipt.value = "";
 9079: 	    formname.receipt.focus();
 9080: 	    return false;
 9081: 	}
 9082: 	return true;
 9083:     }
 9084: </script>
 9085: GRADINGMENUJS
 9086:     &commonJSfunctions($request);
 9087:     return $Str;    
 9088: }
 9089: 
 9090: 
 9091: #--- Displays the submissions first page -------
 9092: sub submit_options {
 9093:     my ($request) = @_;
 9094:     my ($symb)=&get_symb($request);
 9095:     if (!$symb) {return '';}
 9096:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9097: 
 9098:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9099:     $request->print(<<GRADINGMENUJS);
 9100: <script type="text/javascript" language="javascript">
 9101:     function checkChoice(formname,val,cmdx) {
 9102: 	if (val <= 2) {
 9103: 	    var cmd = radioSelection(formname.radioChoice);
 9104: 	    var cmdsave = cmd;
 9105: 	} else {
 9106: 	    cmd = cmdx;
 9107: 	    cmdsave = 'submission';
 9108: 	}
 9109: 	formname.command.value = cmd;
 9110: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9111: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9112: 	if (val < 5) formname.submit();
 9113: 	if (val == 5) {
 9114: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9115: 	    formname.submit();
 9116: 	}
 9117: 	if (val < 7) formname.submit();
 9118:     }
 9119: 
 9120:     function checkReceiptNo(formname,nospace) {
 9121: 	var receiptNo = formname.receipt.value;
 9122: 	var checkOpt = false;
 9123: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9124: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9125: 	if (checkOpt) {
 9126: 	    alert("$receiptalert");
 9127: 	    formname.receipt.value = "";
 9128: 	    formname.receipt.focus();
 9129: 	    return false;
 9130: 	}
 9131: 	return true;
 9132:     }
 9133: </script>
 9134: GRADINGMENUJS
 9135:     &commonJSfunctions($request);
 9136:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9137:     my $result;
 9138:     my (undef,$sections) = &getclasslist('all','0');
 9139:     my $savedState = &savedState();
 9140:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9141:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9142:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9143:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9144: 
 9145:     # Preselect sections
 9146:     my $selsec="";
 9147:     if (ref($sections)) {
 9148:         foreach my $section (sort(@$sections)) {
 9149:             $selsec.='<option value="'.$section.'" '.
 9150:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9151:         }
 9152:     }
 9153: 
 9154:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9155: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9156: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9157: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9158: 	'<input type="hidden" name="command"     value="" />'."\n".
 9159: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9160: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9161: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9162: 
 9163:     $result.='
 9164: <h2>
 9165:   '.&mt('Grade Current Resource').'
 9166: </h2>
 9167: <div>
 9168:   '.$table.'
 9169: </div>
 9170: 
 9171: <div class="LC_columnSection">
 9172:   
 9173:     <fieldset>
 9174:       <legend>
 9175:        '.&mt('Sections').'
 9176:       </legend>
 9177:       <select name="section" multiple="multiple" size="5">'."\n";
 9178:     $result.= $selsec;
 9179:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9180:     $result.='
 9181:     </fieldset>
 9182:   
 9183:     <fieldset>
 9184:       <legend>
 9185:         '.&mt('Groups').'
 9186:       </legend>
 9187:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9188:     </fieldset>
 9189:   
 9190:     <fieldset>
 9191:       <legend>
 9192:         '.&mt('Access Status').'
 9193:       </legend>
 9194:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9195:     </fieldset>
 9196:   
 9197:     <fieldset>
 9198:       <legend>
 9199:         '.&mt('Submission Status').'
 9200:       </legend>
 9201:       <select name="submitonly" size="5">
 9202: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9203: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9204: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9205: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9206:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9207:       </select>
 9208:     </fieldset>
 9209:   
 9210: </div>
 9211: 
 9212: <br />
 9213:           <div>
 9214:             <div>
 9215:               <label>
 9216:                 <input type="radio" name="radioChoice" value="submission" '.
 9217:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9218:              &mt('Select individual students to grade and view submissions.').'
 9219: 	      </label> 
 9220:             </div>
 9221:             <div>
 9222: 	      <label>
 9223:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9224:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 9225:                     &mt('Grade all selected students in a grading table.').'
 9226:               </label>
 9227:             </div>
 9228:             <div>
 9229: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9230:             </div>
 9231:           </div>
 9232: 
 9233: 
 9234:         <h2>
 9235:          '.&mt('Grade Complete Folder for One Student').'
 9236:         </h2>
 9237:         <div>
 9238:             <div>
 9239:               <label>
 9240:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 9241: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 9242:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 9243:               </label>
 9244:             </div>
 9245:             <div>
 9246: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 9247:             </div>
 9248:         </div>
 9249:   </form>';
 9250:     $result .= &show_grading_menu_form($symb);
 9251:     return $result;
 9252: }
 9253: 
 9254: sub reset_perm {
 9255:     undef(%perm);
 9256: }
 9257: 
 9258: sub init_perm {
 9259:     &reset_perm();
 9260:     foreach my $test_perm ('vgr','mgr','opa') {
 9261: 
 9262: 	my $scope = $env{'request.course.id'};
 9263: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9264: 
 9265: 	    $scope .= '/'.$env{'request.course.sec'};
 9266: 	    if ( $perm{$test_perm}=
 9267: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9268: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9269: 	    } else {
 9270: 		delete($perm{$test_perm});
 9271: 	    }
 9272: 	}
 9273:     }
 9274: }
 9275: 
 9276: sub gather_clicker_ids {
 9277:     my %clicker_ids;
 9278: 
 9279:     my $classlist = &Apache::loncoursedata::get_classlist();
 9280: 
 9281:     # Set up a couple variables.
 9282:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9283:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9284:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9285: 
 9286:     foreach my $student (keys(%$classlist)) {
 9287:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9288:         my $username = $classlist->{$student}->[$username_idx];
 9289:         my $domain   = $classlist->{$student}->[$domain_idx];
 9290:         my $clickers =
 9291: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9292:         foreach my $id (split(/\,/,$clickers)) {
 9293:             $id=~s/^[\#0]+//;
 9294:             $id=~s/[\-\:]//g;
 9295:             if (exists($clicker_ids{$id})) {
 9296: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9297:             } else {
 9298: 		$clicker_ids{$id}=$username.':'.$domain;
 9299:             }
 9300:         }
 9301:     }
 9302:     return %clicker_ids;
 9303: }
 9304: 
 9305: sub gather_adv_clicker_ids {
 9306:     my %clicker_ids;
 9307:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9308:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9309:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9310:     foreach my $element (sort(keys(%coursepersonnel))) {
 9311:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9312:             my ($puname,$pudom)=split(/\:/,$person);
 9313:             my $clickers =
 9314: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9315:             foreach my $id (split(/\,/,$clickers)) {
 9316: 		$id=~s/^[\#0]+//;
 9317:                 $id=~s/[\-\:]//g;
 9318: 		if (exists($clicker_ids{$id})) {
 9319: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9320: 		} else {
 9321: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9322: 		}
 9323:             }
 9324:         }
 9325:     }
 9326:     return %clicker_ids;
 9327: }
 9328: 
 9329: sub clicker_grading_parameters {
 9330:     return ('gradingmechanism' => 'scalar',
 9331:             'upfiletype' => 'scalar',
 9332:             'specificid' => 'scalar',
 9333:             'pcorrect' => 'scalar',
 9334:             'pincorrect' => 'scalar');
 9335: }
 9336: 
 9337: sub process_clicker {
 9338:     my ($r)=@_;
 9339:     my ($symb)=&get_symb($r);
 9340:     if (!$symb) {return '';}
 9341:     my $result=&checkforfile_js();
 9342:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9343:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9344:     $result.=$table;
 9345:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9346:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9347:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9348:         '</b></td></tr>'."\n";
 9349:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9350: # Attempt to restore parameters from last session, set defaults if not present
 9351:     my %Saveable_Parameters=&clicker_grading_parameters();
 9352:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9353:                                                  \%Saveable_Parameters);
 9354:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9355:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9356:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9357:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9358: 
 9359:     my %checked;
 9360:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9361:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9362:           $checked{$gradingmechanism}=' checked="checked"';
 9363:        }
 9364:     }
 9365: 
 9366:     my $upload=&mt("Upload File");
 9367:     my $type=&mt("Type");
 9368:     my $attendance=&mt("Award points just for participation");
 9369:     my $personnel=&mt("Correctness determined from response by course personnel");
 9370:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9371:     my $given=&mt("Correctness determined from given list of answers").' '.
 9372:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9373:     my $pcorrect=&mt("Percentage points for correct solution");
 9374:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9375:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9376:                                                    {'iclicker' => 'i>clicker',
 9377:                                                     'interwrite' => 'interwrite PRS',
 9378:                                                     'turning' => 'Turning Technologies'});
 9379:     $symb = &Apache::lonenc::check_encrypt($symb);
 9380:     $result.=<<ENDUPFORM;
 9381: <script type="text/javascript">
 9382: function sanitycheck() {
 9383: // Accept only integer percentages
 9384:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9385:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9386: // Find out grading choice
 9387:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9388:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9389:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9390:       }
 9391:    }
 9392: // By default, new choice equals user selection
 9393:    newgradingchoice=gradingchoice;
 9394: // Not good to give more points for false answers than correct ones
 9395:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9396:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9397:    }
 9398: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9399:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9400:       document.forms.gradesupload.pcorrect.value=100;
 9401:       document.forms.gradesupload.pincorrect.value=100;
 9402:    }
 9403: // If the values are different, cannot be attendance only
 9404:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9405:        (gradingchoice=='attendance')) {
 9406:        newgradingchoice='personnel';
 9407:    }
 9408: // Change grading choice to new one
 9409:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9410:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9411:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9412:       } else {
 9413:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9414:       }
 9415:    }
 9416: // Remember the old state
 9417:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9418: }
 9419: </script>
 9420: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9421: <input type="hidden" name="symb" value="$symb" />
 9422: <input type="hidden" name="command" value="processclickerfile" />
 9423: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9424: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9425: <input type="file" name="upfile" size="50" />
 9426: <br /><label>$type: $selectform</label>
 9427: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9428: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9429: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9430: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9431: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9432: <br />&nbsp;&nbsp;&nbsp;
 9433: <input type="text" name="givenanswer" size="50" />
 9434: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9435: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9436: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9437: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9438: </form>
 9439: ENDUPFORM
 9440:     $result.='</td></tr></table>'."\n".
 9441:              '</td></tr></table><br /><br />'."\n";
 9442:     $result.=&show_grading_menu_form($symb);
 9443:     return $result;
 9444: }
 9445: 
 9446: sub process_clicker_file {
 9447:     my ($r)=@_;
 9448:     my ($symb)=&get_symb($r);
 9449:     if (!$symb) {return '';}
 9450: 
 9451:     my %Saveable_Parameters=&clicker_grading_parameters();
 9452:     &Apache::loncommon::store_course_settings('grades_clicker',
 9453:                                               \%Saveable_Parameters);
 9454: 
 9455:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9456:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9457: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9458: 	return $result.&show_grading_menu_form($symb);
 9459:     }
 9460:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9461:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9462:         return $result.&show_grading_menu_form($symb);
 9463:     }
 9464:     my $foundgiven=0;
 9465:     if ($env{'form.gradingmechanism'} eq 'given') {
 9466:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9467:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9468:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9469:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9470:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9471:         $foundgiven=$#answers+1;
 9472:     }
 9473:     my %clicker_ids=&gather_clicker_ids();
 9474:     my %correct_ids;
 9475:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9476: 	%correct_ids=&gather_adv_clicker_ids();
 9477:     }
 9478:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9479: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9480: 	   $correct_id=~tr/a-z/A-Z/;
 9481: 	   $correct_id=~s/\s//gs;
 9482: 	   $correct_id=~s/^[\#0]+//;
 9483:            $correct_id=~s/[\-\:]//g;
 9484:            if ($correct_id) {
 9485: 	      $correct_ids{$correct_id}='specified';
 9486:            }
 9487:         }
 9488:     }
 9489:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9490: 	$result.=&mt('Score based on attendance only');
 9491:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9492:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9493:     } else {
 9494: 	my $number=0;
 9495: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9496: 	foreach my $id (sort(keys(%correct_ids))) {
 9497: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9498: 	    if ($correct_ids{$id} eq 'specified') {
 9499: 		$result.=&mt('specified');
 9500: 	    } else {
 9501: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9502: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9503: 	    }
 9504: 	    $number++;
 9505: 	}
 9506:         $result.="</p>\n";
 9507: 	if ($number==0) {
 9508: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9509: 	    return $result.&show_grading_menu_form($symb);
 9510: 	}
 9511:     }
 9512:     if (length($env{'form.upfile'}) < 2) {
 9513:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9514: 		     '<span class="LC_error">',
 9515: 		     '</span>',
 9516: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9517:         return $result.&show_grading_menu_form($symb);
 9518:     }
 9519: 
 9520: # Were able to get all the info needed, now analyze the file
 9521: 
 9522:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9523:     $symb = &Apache::lonenc::check_encrypt($symb);
 9524:     my $heading=&mt('Scanning clicker file');
 9525:     $result.=(<<ENDHEADER);
 9526: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9527: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9528: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
 9529: <form method="post" action="/adm/grades" name="clickeranalysis">
 9530: <input type="hidden" name="symb" value="$symb" />
 9531: <input type="hidden" name="command" value="assignclickergrades" />
 9532: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9533: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9534: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9535: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9536: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9537: ENDHEADER
 9538:     if ($env{'form.gradingmechanism'} eq 'given') {
 9539:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9540:     } 
 9541:     my %responses;
 9542:     my @questiontitles;
 9543:     my $errormsg='';
 9544:     my $number=0;
 9545:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9546: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9547:     }
 9548:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9549:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9550:     }
 9551:     if ($env{'form.upfiletype'} eq 'turning') {
 9552:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9553:     }
 9554:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9555:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9556:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9557:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9558:              '<br />';
 9559:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9560:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9561:        return $result.&show_grading_menu_form($symb);
 9562:     } 
 9563: # Remember Question Titles
 9564: # FIXME: Possibly need delimiter other than ":"
 9565:     for (my $i=0;$i<$number;$i++) {
 9566:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9567:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9568:     }
 9569:     my $correct_count=0;
 9570:     my $student_count=0;
 9571:     my $unknown_count=0;
 9572: # Match answers with usernames
 9573: # FIXME: Possibly need delimiter other than ":"
 9574:     foreach my $id (keys(%responses)) {
 9575:        if ($correct_ids{$id}) {
 9576:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9577:           $correct_count++;
 9578:        } elsif ($clicker_ids{$id}) {
 9579:           if ($clicker_ids{$id}=~/\,/) {
 9580: # More than one user with the same clicker!
 9581:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9582:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9583:                            "<select name='multi".$id."'>";
 9584:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9585:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9586:              }
 9587:              $result.='</select>';
 9588:              $unknown_count++;
 9589:           } else {
 9590: # Good: found one and only one user with the right clicker
 9591:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9592:              $student_count++;
 9593:           }
 9594:        } else {
 9595:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9596:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9597:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9598:                    "\n".&mt("Domain").": ".
 9599:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9600:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9601:           $unknown_count++;
 9602:        }
 9603:     }
 9604:     $result.='<hr />'.
 9605:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9606:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9607:        if ($correct_count==0) {
 9608:           $errormsg.="Found no correct answers answers for grading!";
 9609:        } elsif ($correct_count>1) {
 9610:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9611:        }
 9612:     }
 9613:     if ($number<1) {
 9614:        $errormsg.="Found no questions.";
 9615:     }
 9616:     if ($errormsg) {
 9617:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9618:     } else {
 9619:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9620:     }
 9621:     $result.='</form></td></tr></table>'."\n".
 9622:              '</td></tr></table><br /><br />'."\n";
 9623:     return $result.&show_grading_menu_form($symb);
 9624: }
 9625: 
 9626: sub iclicker_eval {
 9627:     my ($questiontitles,$responses)=@_;
 9628:     my $number=0;
 9629:     my $errormsg='';
 9630:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9631:         my %components=&Apache::loncommon::record_sep($line);
 9632:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9633: 	if ($entries[0] eq 'Question') {
 9634: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9635: 		$$questiontitles[$number]=$entries[$i];
 9636: 		$number++;
 9637: 	    }
 9638: 	}
 9639: 	if ($entries[0]=~/^\#/) {
 9640: 	    my $id=$entries[0];
 9641: 	    my @idresponses;
 9642: 	    $id=~s/^[\#0]+//;
 9643: 	    for (my $i=0;$i<$number;$i++) {
 9644: 		my $idx=3+$i*6;
 9645:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9646: 		push(@idresponses,$entries[$idx]);
 9647: 	    }
 9648: 	    $$responses{$id}=join(',',@idresponses);
 9649: 	}
 9650:     }
 9651:     return ($errormsg,$number);
 9652: }
 9653: 
 9654: sub interwrite_eval {
 9655:     my ($questiontitles,$responses)=@_;
 9656:     my $number=0;
 9657:     my $errormsg='';
 9658:     my $skipline=1;
 9659:     my $questionnumber=0;
 9660:     my %idresponses=();
 9661:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9662:         my %components=&Apache::loncommon::record_sep($line);
 9663:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9664:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9665:         if ($entries[1] eq 'Response') { $skipline=1; }
 9666:         next if $skipline;
 9667:         if ($entries[0]!=$questionnumber) {
 9668:            $questionnumber=$entries[0];
 9669:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9670:            $number++;
 9671:         }
 9672:         my $id=$entries[4];
 9673:         $id=~s/^[\#0]+//;
 9674:         $id=~s/^v\d*\://i;
 9675:         $id=~s/[\-\:]//g;
 9676:         $idresponses{$id}[$number]=$entries[6];
 9677:     }
 9678:     foreach my $id (keys(%idresponses)) {
 9679:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9680:        $$responses{$id}=~s/^\s*\,//;
 9681:     }
 9682:     return ($errormsg,$number);
 9683: }
 9684: 
 9685: sub turning_eval {
 9686:     my ($questiontitles,$responses)=@_;
 9687:     my $number=0;
 9688:     my $errormsg='';
 9689:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9690:         my %components=&Apache::loncommon::record_sep($line);
 9691:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9692:         if ($#entries>$number) { $number=$#entries; }
 9693:         my $id=$entries[0];
 9694:         my @idresponses;
 9695:         $id=~s/^[\#0]+//;
 9696:         unless ($id) { next; }
 9697:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9698:             $entries[$idx]=~s/\,/\;/g;
 9699:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
 9700:             push(@idresponses,$entries[$idx]);
 9701:         }
 9702:         $$responses{$id}=join(',',@idresponses);
 9703:     }
 9704:     for (my $i=1; $i<=$number; $i++) {
 9705:         $$questiontitles[$i]=&mt('Question [_1]',$i);
 9706:     }
 9707:     return ($errormsg,$number);
 9708: }
 9709: 
 9710: sub assign_clicker_grades {
 9711:     my ($r)=@_;
 9712:     my ($symb)=&get_symb($r);
 9713:     if (!$symb) {return '';}
 9714: # See which part we are saving to
 9715:     my $res_error;
 9716:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9717:     if ($res_error) {
 9718:         return &navmap_errormsg();
 9719:     }
 9720: # FIXME: This should probably look for the first handgradeable part
 9721:     my $part=$$partlist[0];
 9722: # Start screen output
 9723:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9724: 
 9725:     $result .= '<br />'.
 9726:                &Apache::loncommon::start_data_table().
 9727:                &Apache::loncommon::start_data_table_header_row().
 9728:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9729:                &Apache::loncommon::end_data_table_header_row().
 9730:                &Apache::loncommon::start_data_table_row().'<td>';
 9731: 
 9732: # Get correct result
 9733: # FIXME: Possibly need delimiter other than ":"
 9734:     my @correct=();
 9735:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9736:     my $number=$env{'form.number'};
 9737:     if ($gradingmechanism ne 'attendance') {
 9738:        foreach my $key (keys(%env)) {
 9739:           if ($key=~/^form\.correct\:/) {
 9740:              my @input=split(/\,/,$env{$key});
 9741:              for (my $i=0;$i<=$#input;$i++) {
 9742:                  if (($correct[$i]) && ($input[$i]) &&
 9743:                      ($correct[$i] ne $input[$i])) {
 9744:                     $result.='<br /><span class="LC_warning">'.
 9745:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9746:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9747:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9748:                     $correct[$i]=$input[$i];
 9749:                  }
 9750:              }
 9751:           }
 9752:        }
 9753:        for (my $i=0;$i<$number;$i++) {
 9754:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9755:              $result.='<br /><span class="LC_error">'.
 9756:                       &mt('No correct result given for question "[_1]"!',
 9757:                           $env{'form.question:'.$i}).'</span>';
 9758:           }
 9759:        }
 9760:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9761:     }
 9762: # Start grading
 9763:     my $pcorrect=$env{'form.pcorrect'};
 9764:     my $pincorrect=$env{'form.pincorrect'};
 9765:     my $storecount=0;
 9766:     my %users=();
 9767:     foreach my $key (keys(%env)) {
 9768:        my $user='';
 9769:        if ($key=~/^form\.student\:(.*)$/) {
 9770:           $user=$1;
 9771:        }
 9772:        if ($key=~/^form\.unknown\:(.*)$/) {
 9773:           my $id=$1;
 9774:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9775:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9776:           } elsif ($env{'form.multi'.$id}) {
 9777:              $user=$env{'form.multi'.$id};
 9778:           }
 9779:        }
 9780:        if ($user) {
 9781:           if ($users{$user}) {
 9782:              $result.='<br /><span class="LC_warning">'.
 9783:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9784:                       '</span><br />';
 9785:           }
 9786:           $users{$user}=1;
 9787:           my @answer=split(/\,/,$env{$key});
 9788:           my $sum=0;
 9789:           my $realnumber=$number;
 9790:           for (my $i=0;$i<$number;$i++) {
 9791:              if  ($correct[$i] eq '-') {
 9792:                 $realnumber--;
 9793:              } elsif ($answer[$i]) {
 9794:                 if ($gradingmechanism eq 'attendance') {
 9795:                    $sum+=$pcorrect;
 9796:                 } elsif ($correct[$i] eq '*') {
 9797:                    $sum+=$pcorrect;
 9798:                 } else {
 9799: # We actually grade if correct or not
 9800:                    my $increment=$pincorrect;
 9801: # Special case: numerical answer "0"
 9802:                    if ($correct[$i] eq '0') {
 9803:                       if ($answer[$i]=~/^[0\.]+$/) {
 9804:                          $increment=$pcorrect;
 9805:                       }
 9806: # General numerical answer, both evaluate to something non-zero
 9807:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9808:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9809:                          $increment=$pcorrect;
 9810:                       }
 9811: # Must be just alphanumeric
 9812:                    } elsif ($answer[$i] eq $correct[$i]) {
 9813:                       $increment=$pcorrect;
 9814:                    }
 9815:                    $sum+=$increment;
 9816:                 }
 9817:              }
 9818:           }
 9819:           my $ave=$sum/(100*$realnumber);
 9820: # Store
 9821:           my ($username,$domain)=split(/\:/,$user);
 9822:           my %grades=();
 9823:           $grades{"resource.$part.solved"}='correct_by_override';
 9824:           $grades{"resource.$part.awarded"}=$ave;
 9825:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9826:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9827:                                                  $env{'request.course.id'},
 9828:                                                  $domain,$username);
 9829:           if ($returncode ne 'ok') {
 9830:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9831:           } else {
 9832:              $storecount++;
 9833:           }
 9834:        }
 9835:     }
 9836: # We are done
 9837:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9838:              '</td>'.
 9839:              &Apache::loncommon::end_data_table_row().
 9840:              &Apache::loncommon::end_data_table()."<br /><br />\n";
 9841:     return $result.&show_grading_menu_form($symb);
 9842: }
 9843: 
 9844: sub navmap_errormsg {
 9845:     return '<div class="LC_error">'.
 9846:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9847:            &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>').
 9848:            '</div>';
 9849: }
 9850: 
 9851: sub startpage {
 9852:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
 9853:     if ($nomenu) {
 9854:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
 9855:     } else {
 9856:         $r->print(&Apache::loncommon::start_page('Grading',$js,
 9857:                                                  {'bread_crumbs' => $crumbs}));
 9858:     }
 9859:     unless ($nodisplayflag) {
 9860:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
 9861:     }
 9862: }
 9863: 
 9864: sub handler {
 9865:     my $request=$_[0];
 9866:     &reset_caches();
 9867:     if ($request->header_only) {
 9868:         &Apache::loncommon::content_type($request,'text/html');
 9869:         $request->send_http_header;
 9870:         return OK;
 9871:     }
 9872:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9873: 
 9874:     my $symb=&get_symb($request,1);
 9875:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9876:     my $command=$commands[0];
 9877: 
 9878:     if ($#commands > 0) {
 9879: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9880:     }
 9881: 
 9882:     $ssi_error = 0;
 9883:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9884:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
 9885:                                                     {'bread_crumbs' => $brcrum});
 9886:     if ($symb eq '' && $command eq '') {
 9887: 	if ($env{'user.adv'}) {
 9888:             &Apache::loncommon::content_type($request,'text/html');
 9889:             $request->send_http_header;
 9890:             $request->print($start_page);
 9891: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9892: 		($env{'form.codethree'})) {
 9893: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9894: 		    $env{'form.codethree'};
 9895: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9896: 		    &Apache::lonnet::checkin($token);
 9897: 		if ($tsymb) {
 9898: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9899: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9900: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9901: 					  ('grade_username' => $tuname,
 9902: 					   'grade_domain' => $tudom,
 9903: 					   'grade_courseid' => $tcrsid,
 9904: 					   'grade_symb' => $tsymb)));
 9905: 		    } else {
 9906: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9907: 		    }
 9908: 		} else {
 9909: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9910: 		}
 9911: 	    } else {
 9912: 		$request->print(&Apache::lonxml::tokeninputfield());
 9913: 	    }
 9914:         } elsif ($env{'request.course.id'}) {
 9915:             &init_perm(); 
 9916:             if (!%perm) {
 9917:                 $request->internal_redirect('/adm/quickgrades');
 9918:             } else {
 9919:                 &Apache::loncommon::content_type($request,'text/html');
 9920:                 $request->send_http_header;
 9921:                 $request->print($start_page);
 9922:             }
 9923:         }
 9924:     } else {
 9925:         &init_perm();
 9926:         if (!$env{'request.course.id'}) {
 9927:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
 9928:                     ($command =~ /^scantronupload/)) {
 9929:                 # Not in a course.
 9930:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
 9931:                 return HTTP_NOT_ACCEPTABLE;
 9932:             }
 9933:         } elsif (!%perm) {
 9934:             $request->internal_redirect('/adm/quickgrades');
 9935:         }
 9936:         &Apache::loncommon::content_type($request,'text/html');
 9937:         $request->send_http_header;
 9938:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
 9939:             $request->print($start_page); 
 9940:         }
 9941: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9942:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
 9943:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
 9944:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
 9945:                     &choose_task_version_form($symb,$env{'form.student'},
 9946:                                               $env{'form.userdom'});
 9947:             }
 9948:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
 9949:             if ($versionform) {
 9950:                 $request->print($versionform);
 9951:             }
 9952:             $request->print('<br clear="all" />');
 9953: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9954:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
 9955:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
 9956:                 &choose_task_version_form($symb,$env{'form.student'},
 9957:                                           $env{'form.userdom'},
 9958:                                           $env{'form.inhibitmenu'});
 9959:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
 9960:             if ($versionform) {
 9961:                 $request->print($versionform);
 9962:             }
 9963:             $request->print('<br clear="all" />');
 9964:             $request->print(&show_previous_task_version($request,$symb));
 9965: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9966: 	    &pickStudentPage($request);
 9967: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9968: 	    &displayPage($request);
 9969: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9970: 	    &updateGradeByPage($request);
 9971: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9972: 	    &processGroup($request);
 9973: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9974: 	    $request->print(&grading_menu($request));
 9975: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9976: 	    $request->print(&submit_options($request));
 9977: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9978: 	    $request->print(&viewgrades($request));
 9979: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9980: 	    $request->print(&processHandGrade($request));
 9981: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9982: 	    $request->print(&editgrades($request));
 9983: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9984: 	    $request->print(&verifyreceipt($request));
 9985:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9986:             $request->print(&process_clicker($request));
 9987:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9988:             $request->print(&process_clicker_file($request));
 9989:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9990:             $request->print(&assign_clicker_grades($request));
 9991: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9992: 	    $request->print(&upcsvScores_form($request));
 9993: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9994: 	    $request->print(&csvupload($request));
 9995: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9996: 	    $request->print(&csvuploadmap($request));
 9997: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9998: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9999: 		$request->print(&csvuploadoptions($request));
10000: 	    } else {
10001: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10002: 		    $env{'form.upfile_associate'} = 'reverse';
10003: 		} else {
10004: 		    $env{'form.upfile_associate'} = 'forward';
10005: 		}
10006: 		$request->print(&csvuploadmap($request));
10007: 	    }
10008: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10009: 	    $request->print(&csvuploadassign($request));
10010: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10011: 	    $request->print(&scantron_selectphase($request));
10012:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10013:  	    $request->print(&scantron_do_warning($request));
10014: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10015: 	    $request->print(&scantron_validate_file($request));
10016: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10017: 	    $request->print(&scantron_process_students($request));
10018:  	} elsif ($command eq 'scantronupload' && 
10019:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10020: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10021:  	    $request->print(&scantron_upload_scantron_data($request)); 
10022:  	} elsif ($command eq 'scantronupload_save' &&
10023:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10024: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10025:  	    $request->print(&scantron_upload_scantron_data_save($request));
10026:  	} elsif ($command eq 'scantron_download' &&
10027: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10028:  	    $request->print(&scantron_download_scantron_data($request));
10029:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10030:             $request->print(&checkscantron_results($request));     
10031: 	} elsif ($command) {
10032: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10033: 	}
10034:     }
10035:     if ($ssi_error) {
10036: 	&ssi_print_error($request);
10037:     }
10038:     $request->print(&Apache::loncommon::end_page());
10039:     &reset_caches();
10040:     return OK;
10041: }
10042: 
10043: 1;
10044: 
10045: __END__;
10046: 
10047: 
10048: =head1 NAME
10049: 
10050: Apache::grades
10051: 
10052: =head1 SYNOPSIS
10053: 
10054: Handles the viewing of grades.
10055: 
10056: This is part of the LearningOnline Network with CAPA project
10057: described at http://www.lon-capa.org.
10058: 
10059: =head1 OVERVIEW
10060: 
10061: Do an ssi with retries:
10062: While I'd love to factor out this with the vesrion in lonprintout,
10063: 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
10064: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10065: 
10066: At least the logic that drives this has been pulled out into loncommon.
10067: 
10068: 
10069: 
10070: ssi_with_retries - Does the server side include of a resource.
10071:                      if the ssi call returns an error we'll retry it up to
10072:                      the number of times requested by the caller.
10073:                      If we still have a proble, no text is appended to the
10074:                      output and we set some global variables.
10075:                      to indicate to the caller an SSI error occurred.  
10076:                      All of this is supposed to deal with the issues described
10077:                      in LonCAPA BZ 5631 see:
10078:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10079:                      by informing the user that this happened.
10080: 
10081: Parameters:
10082:   resource   - The resource to include.  This is passed directly, without
10083:                interpretation to lonnet::ssi.
10084:   form       - The form hash parameters that guide the interpretation of the resource
10085:                
10086:   retries    - Number of retries allowed before giving up completely.
10087: Returns:
10088:   On success, returns the rendered resource identified by the resource parameter.
10089: Side Effects:
10090:   The following global variables can be set:
10091:    ssi_error                - If an unrecoverable error occurred this becomes true.
10092:                               It is up to the caller to initialize this to false
10093:                               if desired.
10094:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10095:                               of the resource that could not be rendered by the ssi
10096:                               call.
10097:    ssi_error_message   - The error string fetched from the ssi response
10098:                               in the event of an error.
10099: 
10100: 
10101: =head1 HANDLER SUBROUTINE
10102: 
10103: ssi_with_retries()
10104: 
10105: =head1 SUBROUTINES
10106: 
10107: =over
10108: 
10109: =item scantron_get_correction() : 
10110: 
10111:    Builds the interface screen to interact with the operator to fix a
10112:    specific error condition in a specific scanline
10113: 
10114:  Arguments:
10115:     $r           - Apache request object
10116:     $i           - number of the current scanline
10117:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10118:     $scan_config - hash ref as returned from &get_scantron_config()
10119:     $line        - full contents of the current scanline
10120:     $error       - error condition, valid values are
10121:                    'incorrectCODE', 'duplicateCODE',
10122:                    'doublebubble', 'missingbubble',
10123:                    'duplicateID', 'incorrectID'
10124:     $arg         - extra information needed
10125:        For errors:
10126:          - duplicateID   - paper number that this studentID was seen before on
10127:          - duplicateCODE - array ref of the paper numbers this CODE was
10128:                            seen on before
10129:          - incorrectCODE - current incorrect CODE 
10130:          - doublebubble  - array ref of the bubble lines that have double
10131:                            bubble errors
10132:          - missingbubble - array ref of the bubble lines that have missing
10133:                            bubble errors
10134: 
10135: =item  scantron_get_maxbubble() : 
10136: 
10137:    Arguments:
10138:        $nav_error  - Reference to scalar which is a flag to indicate a
10139:                       failure to retrieve a navmap object.
10140:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10141:        calling routine should trap the error condition and display the warning
10142:        found in &navmap_errormsg().
10143: 
10144:        $scantron_config - Reference to bubblesheet format configuration hash.
10145: 
10146:    Returns the maximum number of bubble lines that are expected to
10147:    occur. Does this by walking the selected sequence rendering the
10148:    resource and then checking &Apache::lonxml::get_problem_counter()
10149:    for what the current value of the problem counter is.
10150: 
10151:    Caches the results to $env{'form.scantron_maxbubble'},
10152:    $env{'form.scantron.bubble_lines.n'}, 
10153:    $env{'form.scantron.first_bubble_line.n'} and
10154:    $env{"form.scantron.sub_bubblelines.n"}
10155:    which are the total number of bubble, lines, the number of bubble
10156:    lines for response n and number of the first bubble line for response n,
10157:    and a comma separated list of numbers of bubble lines for sub-questions
10158:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10159: 
10160: 
10161: =item  scantron_validate_missingbubbles() : 
10162: 
10163:    Validates all scanlines in the selected file to not have any
10164:     answers that don't have bubbles that have not been verified
10165:     to be bubble free.
10166: 
10167: =item  scantron_process_students() : 
10168: 
10169:    Routine that does the actual grading of the bubblesheet information.
10170: 
10171:    The parsed scanline hash is added to %env 
10172: 
10173:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10174:    foreach resource , with the form data of
10175: 
10176: 	'submitted'     =>'scantron' 
10177: 	'grade_target'  =>'grade',
10178: 	'grade_username'=> username of student
10179: 	'grade_domain'  => domain of student
10180: 	'grade_courseid'=> of course
10181: 	'grade_symb'    => symb of resource to grade
10182: 
10183:     This triggers a grading pass. The problem grading code takes care
10184:     of converting the bubbled letter information (now in %env) into a
10185:     valid submission.
10186: 
10187: =item  scantron_upload_scantron_data() :
10188: 
10189:     Creates the screen for adding a new bubblesheet data file to a course.
10190: 
10191: =item  scantron_upload_scantron_data_save() : 
10192: 
10193:    Adds a provided bubble information data file to the course if user
10194:    has the correct privileges to do so. 
10195: 
10196: =item  valid_file() :
10197: 
10198:    Validates that the requested bubble data file exists in the course.
10199: 
10200: =item  scantron_download_scantron_data() : 
10201: 
10202:    Shows a list of the three internal files (original, corrected,
10203:    skipped) for a specific bubblesheet data file that exists in the
10204:    course.
10205: 
10206: =item  scantron_validate_ID() : 
10207: 
10208:    Validates all scanlines in the selected file to not have any
10209:    invalid or underspecified student/employee IDs
10210: 
10211: =item navmap_errormsg() :
10212: 
10213:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10214:    Should be called whenever the request to instantiate a navmap object fails.  
10215: 
10216: =back
10217: 
10218: =cut

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