File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.13: download - view: text, annotated - select for diffs
Thu Aug 9 23:25:48 2012 UTC (11 years, 8 months ago) by raeburn
Branches: version_2_10_X
- For 2.10.X branch
  - backport 1.674.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.13 2012/08/09 23:25:48 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::bridgetask();
   47: use String::Similarity;
   48: use LONCAPA;
   49: 
   50: use POSIX qw(floor);
   51: 
   52: 
   53: 
   54: my %perm=();
   55: my %old_essays=();
   56: 
   57: #  These variables are used to recover from ssi errors
   58: 
   59: my $ssi_retries = 5;
   60: my $ssi_error;
   61: my $ssi_error_resource;
   62: my $ssi_error_message;
   63: 
   64: 
   65: sub ssi_with_retries {
   66:     my ($resource, $retries, %form) = @_;
   67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   68:     if ($response->is_error) {
   69: 	$ssi_error          = 1;
   70: 	$ssi_error_resource = $resource;
   71: 	$ssi_error_message  = $response->code . " " . $response->message;
   72:     }
   73: 
   74:     return $content;
   75: 
   76: }
   77: #
   78: #  Prodcuces an ssi retry failure error message to the user:
   79: #
   80: 
   81: sub ssi_print_error {
   82:     my ($r) = @_;
   83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   84:     $r->print('
   85: <br />
   86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   87: <p>
   88: '.&mt('Unable to retrieve a resource from a server:').'<br />
   89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   90: '.&mt('Error:').' '.$ssi_error_message.'
   91: </p>
   92: <p>'.
   93: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   95: '</p>');
   96:     return;
   97: }
   98: 
   99: #
  100: # --- Retrieve the parts from the metadata file.---
  101: sub getpartlist {
  102:     my ($symb,$errorref) = @_;
  103: 
  104:     my $navmap   = Apache::lonnavmaps::navmap->new();
  105:     unless (ref($navmap)) {
  106:         if (ref($errorref)) { 
  107:             $$errorref = 'navmap';
  108:             return;
  109:         }
  110:     }
  111:     my $res      = $navmap->getBySymb($symb);
  112:     my $partlist = $res->parts();
  113:     my $url      = $res->src();
  114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  115: 
  116:     my @stores;
  117:     foreach my $part (@{ $partlist }) {
  118: 	foreach my $key (@metakeys) {
  119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  120: 	}
  121:     }
  122:     return @stores;
  123: }
  124: 
  125: # --- Get the symbolic name of a problem and the url
  126: sub get_symb {
  127:     my ($request,$silent) = @_;
  128:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  129:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  130:     if ($symb eq '') { 
  131: 	if (!$silent) {
  132:             $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  133: 	    return ();
  134: 	}
  135:     }
  136:     &Apache::lonenc::check_decrypt(\$symb);
  137:     return ($symb);
  138: }
  139: 
  140: #--- Format fullname, username:domain if different for display
  141: #--- Use anywhere where the student names are listed
  142: sub nameUserString {
  143:     my ($type,$fullname,$uname,$udom) = @_;
  144:     if ($type eq 'header') {
  145: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  146:     } else {
  147: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  148: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  149:     }
  150: }
  151: 
  152: #--- Get the partlist and the response type for a given problem. ---
  153: #--- Indicate if a response type is coded handgraded or not. ---
  154: sub response_type {
  155:     my ($symb,$response_error) = @_;
  156: 
  157:     my $navmap = Apache::lonnavmaps::navmap->new();
  158:     unless (ref($navmap)) {
  159:         if (ref($response_error)) {
  160:             $$response_error = 1;
  161:         }
  162:         return;
  163:     }
  164:     my $res = $navmap->getBySymb($symb);
  165:     unless (ref($res)) {
  166:         $$response_error = 1;
  167:         return;
  168:     }
  169:     my $partlist = $res->parts();
  170:     my %vPart = 
  171: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  172:     my (%response_types,%handgrade);
  173:     foreach my $part (@{ $partlist }) {
  174: 	next if (%vPart && !exists($vPart{$part}));
  175: 
  176: 	my @types = $res->responseType($part);
  177: 	my @ids = $res->responseIds($part);
  178: 	for (my $i=0; $i < scalar(@ids); $i++) {
  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  180: 	    $handgrade{$part.'_'.$ids[$i]} = 
  181: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  182: 				     '.handgrade',$symb);
  183: 	}
  184:     }
  185:     return ($partlist,\%handgrade,\%response_types);
  186: }
  187: 
  188: sub flatten_responseType {
  189:     my ($responseType) = @_;
  190:     my @part_response_id =
  191: 	map { 
  192: 	    my $part = $_;
  193: 	    map {
  194: 		[$part,$_]
  195: 		} sort(keys(%{ $responseType->{$part} }));
  196: 	} sort(keys(%$responseType));
  197:     return @part_response_id;
  198: }
  199: 
  200: sub get_display_part {
  201:     my ($partID,$symb)=@_;
  202:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  203:     if (defined($display) and $display ne '') {
  204:         $display.= ' (<span class="LC_internal_info">'
  205:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  206:     } else {
  207: 	$display=$partID;
  208:     }
  209:     return $display;
  210: }
  211: 
  212: #--- Show resource title
  213: #--- and parts and response type
  214: sub showResourceInfo {
  215:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  216:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  217:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  218:     if (ref($res_error)) {
  219:         if ($$res_error) {
  220:             return;
  221:         }
  222:     }
  223:     $result.=&Apache::loncommon::start_data_table()
  224:             .&Apache::loncommon::start_data_table_header_row();
  225:     if ($checkboxes) {
  226:         $result.='<th>&nbsp;</th>';
  227:     }
  228:     $result.='<th>'.&mt('Problem Part').'</th>'
  229:             .'<th>'.&mt('Res. ID').'</th>'
  230:             .'<th>'.&mt('Type').'</th>'
  231:             .&Apache::loncommon::end_data_table_header_row();
  232:     my %resptype = ();
  233:     my $hdgrade='no';
  234:     my %partsseen;
  235:     foreach my $partID (sort(keys(%$responseType))) {
  236:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  237:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  238:             my $responsetype = $responseType->{$partID}->{$resID};
  239:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  240:             $result.=&Apache::loncommon::start_data_table_row();
  241:             if ($checkboxes) {
  242:                 if (exists($partsseen{$partID})) {
  243:                     $result.="<td>&nbsp;</td>";
  244:                 } else {
  245:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  246:                 }
  247:                 $partsseen{$partID}=1;
  248:             }
  249:             my $display_part=&get_display_part($partID,$symb);
  250:             $result.='<td>'.$display_part.'</td>'
  251:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  252:                     .'<td>'.&mt($responsetype).'</td>'
  253: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
  254:                     .&Apache::loncommon::end_data_table_row();
  255:         }
  256:     }
  257:     $result.=&Apache::loncommon::end_data_table();
  258:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  259: }
  260: 
  261: sub reset_caches {
  262:     &reset_analyze_cache();
  263:     &reset_perm();
  264:     &reset_old_essays();
  265: }
  266: 
  267: {
  268:     my %analyze_cache;
  269:     my %analyze_cache_formkeys;
  270: 
  271:     sub reset_analyze_cache {
  272: 	undef(%analyze_cache);
  273:         undef(%analyze_cache_formkeys);
  274:     }
  275: 
  276:     sub get_analyze {
  277: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed)=@_;
  278: 	my $key = "$symb\0$uname\0$udom";
  279:         if ($type eq 'randomizetry') {
  280:             if ($trial ne '') {
  281:                 $key .= "\0".$trial;
  282:             }
  283:         }
  284: 	if (exists($analyze_cache{$key})) {
  285:             my $getupdate = 0;
  286:             if (ref($add_to_hash) eq 'HASH') {
  287:                 foreach my $item (keys(%{$add_to_hash})) {
  288:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  289:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  290:                             $getupdate = 1;
  291:                             last;
  292:                         }
  293:                     } else {
  294:                         $getupdate = 1;
  295:                     }
  296:                 }
  297:             }
  298:             if (!$getupdate) {
  299:                 return $analyze_cache{$key};
  300:             }
  301:         }
  302: 
  303: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  304: 	$url=&Apache::lonnet::clutter($url);
  305:         my %form = ('grade_target'      => 'analyze',
  306:                     'grade_domain'      => $udom,
  307:                     'grade_symb'        => $symb,
  308:                     'grade_courseid'    =>  $env{'request.course.id'},
  309:                     'grade_username'    => $uname,
  310:                     'grade_noincrement' => $no_increment);
  311:         if ($type eq 'randomizetry') {
  312:             $form{'grade_questiontype'} = $type;
  313:             if ($rndseed ne '') {
  314:                 $form{'grade_rndseed'} = $rndseed;
  315:             }
  316:         }
  317:         if (ref($add_to_hash)) {
  318:             %form = (%form,%{$add_to_hash});
  319:         }
  320: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  321: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  322: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  323:         if (ref($add_to_hash) eq 'HASH') {
  324:             $analyze_cache_formkeys{$key} = $add_to_hash;
  325:         } else {
  326:             $analyze_cache_formkeys{$key} = {};
  327:         }
  328: 	return $analyze_cache{$key} = \%analyze;
  329:     }
  330: 
  331:     sub get_order {
  332: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  333: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  334: 	return $analyze->{"$partid.$respid.shown"};
  335:     }
  336: 
  337:     sub get_radiobutton_correct_foil {
  338: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  339: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  340:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  341:         if (ref($foils) eq 'ARRAY') {
  342: 	    foreach my $foil (@{$foils}) {
  343: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  344: 		    return $foil;
  345: 	        }
  346: 	    }
  347: 	}
  348:     }
  349: 
  350:     sub scantron_partids_tograde {
  351:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  352:         my (%analysis,@parts);
  353:         if (ref($resource)) {
  354:             my $symb = $resource->symb();
  355:             my $add_to_form;
  356:             if ($check_for_randomlist) {
  357:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  358:             }
  359:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  360:             if (ref($analyze) eq 'HASH') {
  361:                 %analysis = %{$analyze};
  362:             }
  363:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  364:                 foreach my $part (@{$analysis{'parts'}}) {
  365:                     my ($id,$respid) = split(/\./,$part);
  366:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  367:                         push(@parts,$part);
  368:                     }
  369:                 }
  370:             }
  371:         }
  372:         return (\%analysis,\@parts);
  373:     }
  374: 
  375: }
  376: 
  377: #--- Clean response type for display
  378: #--- Currently filters option/rank/radiobutton/match/essay/Task
  379: #        response types only.
  380: sub cleanRecord {
  381:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  382: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  383:     my $grayFont = '<span class="LC_internal_info">';
  384:     if ($response =~ /^(option|rank)$/) {
  385: 	my %answer=&Apache::lonnet::str2hash($answer);
  386: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  387: 	my ($toprow,$bottomrow);
  388: 	foreach my $foil (@$order) {
  389: 	    if ($grading{$foil} == 1) {
  390: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  391: 	    } else {
  392: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  393: 	    }
  394: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  395: 	}
  396: 	return '<blockquote><table border="1">'.
  397: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  398: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  399: 	    $bottomrow.'</tr></table></blockquote>';
  400:     } elsif ($response eq 'match') {
  401: 	my %answer=&Apache::lonnet::str2hash($answer);
  402: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  403: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  404: 	my ($toprow,$middlerow,$bottomrow);
  405: 	foreach my $foil (@$order) {
  406: 	    my $item=shift(@items);
  407: 	    if ($grading{$foil} == 1) {
  408: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  409: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  410: 	    } else {
  411: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  412: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  413: 	    }
  414: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  415: 	}
  416: 	return '<blockquote><table border="1">'.
  417: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  418: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  419: 	    $middlerow.'</tr>'.
  420: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  421: 	    $bottomrow.'</tr></table></blockquote>';
  422:     } elsif ($response eq 'radiobutton') {
  423: 	my %answer=&Apache::lonnet::str2hash($answer);
  424: 	my ($toprow,$bottomrow);
  425: 	my $correct = 
  426: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  427: 	foreach my $foil (@$order) {
  428: 	    if (exists($answer{$foil})) {
  429: 		if ($foil eq $correct) {
  430: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  431: 		} else {
  432: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  433: 		}
  434: 	    } else {
  435: 		$toprow.='<td>'.&mt('false').'</td>';
  436: 	    }
  437: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  438: 	}
  439: 	return '<blockquote><table border="1">'.
  440: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  441: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  442: 	    $bottomrow.'</tr></table></blockquote>';
  443:     } elsif ($response eq 'essay') {
  444: 	if (! exists ($env{'form.'.$symb})) {
  445: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  446: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  447: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  448: 
  449: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  450: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  451: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  452: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  453: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  454: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  455: 	}
  456: 	$answer =~ s-\n-<br />-g;
  457: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  458:     } elsif ( $response eq 'organic') {
  459: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  460: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  461: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  462: 	return $result;
  463:     } elsif ( $response eq 'Task') {
  464: 	if ( $answer eq 'SUBMITTED') {
  465: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  466: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  467: 	    return $result;
  468: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  469: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  470: 			       keys(%{$record}));
  471: 	    return join('<br />',($version,@matches));
  472: 			       
  473: 			       
  474: 	} else {
  475: 	    my $result =
  476: 		'<p>'
  477: 		.&mt('Overall result: [_1]',
  478: 		     $record->{$version."resource.$respid.$partid.status"})
  479: 		.'</p>';
  480: 	    
  481: 	    $result .= '<ul>';
  482: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  483: 			     keys(%{$record}));
  484: 	    foreach my $grade (sort(@grade)) {
  485: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  486: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  487: 				     $dim, $record->{$grade}).
  488: 			  '</li>';
  489: 	    }
  490: 	    $result.='</ul>';
  491: 	    return $result;
  492: 	}
  493:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  494: 	$answer = 
  495: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  496: 							      $answer);
  497:     }
  498:     return $answer;
  499: }
  500: 
  501: #-- A couple of common js functions
  502: sub commonJSfunctions {
  503:     my $request = shift;
  504:     $request->print(<<COMMONJSFUNCTIONS);
  505: <script type="text/javascript" language="javascript">
  506:     function radioSelection(radioButton) {
  507: 	var selection=null;
  508: 	if (radioButton.length > 1) {
  509: 	    for (var i=0; i<radioButton.length; i++) {
  510: 		if (radioButton[i].checked) {
  511: 		    return radioButton[i].value;
  512: 		}
  513: 	    }
  514: 	} else {
  515: 	    if (radioButton.checked) return radioButton.value;
  516: 	}
  517: 	return selection;
  518:     }
  519: 
  520:     function pullDownSelection(selectOne) {
  521: 	var selection="";
  522: 	if (selectOne.length > 1) {
  523: 	    for (var i=0; i<selectOne.length; i++) {
  524: 		if (selectOne[i].selected) {
  525: 		    return selectOne[i].value;
  526: 		}
  527: 	    }
  528: 	} else {
  529:             // only one value it must be the selected one
  530: 	    return selectOne.value;
  531: 	}
  532:     }
  533: </script>
  534: COMMONJSFUNCTIONS
  535: }
  536: 
  537: #--- Dumps the class list with usernames,list of sections,
  538: #--- section, ids and fullnames for each user.
  539: sub getclasslist {
  540:     my ($getsec,$filterlist,$getgroup) = @_;
  541:     my @getsec;
  542:     my @getgroup;
  543:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  544:     if (!ref($getsec)) {
  545: 	if ($getsec ne '' && $getsec ne 'all') {
  546: 	    @getsec=($getsec);
  547: 	}
  548:     } else {
  549: 	@getsec=@{$getsec};
  550:     }
  551:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  552:     if (!ref($getgroup)) {
  553: 	if ($getgroup ne '' && $getgroup ne 'all') {
  554: 	    @getgroup=($getgroup);
  555: 	}
  556:     } else {
  557: 	@getgroup=@{$getgroup};
  558:     }
  559:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  560: 
  561:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  562:     # Bail out if we were unable to get the classlist
  563:     return if (! defined($classlist));
  564:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  565:     #
  566:     my %sections;
  567:     my %fullnames;
  568:     foreach my $student (keys(%$classlist)) {
  569:         my $end      = 
  570:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  571:         my $start    = 
  572:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  573:         my $id       = 
  574:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  575:         my $section  = 
  576:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  577:         my $fullname = 
  578:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  579:         my $status   = 
  580:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  581:         my $group   = 
  582:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  583: 	# filter students according to status selected
  584: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  585: 	    if (!($stu_status =~ $status)) {
  586: 		delete($classlist->{$student});
  587: 		next;
  588: 	    }
  589: 	}
  590: 	# filter students according to groups selected
  591: 	my @stu_groups = split(/,/,$group);
  592: 	if (@getgroup) {
  593: 	    my $exclude = 1;
  594: 	    foreach my $grp (@getgroup) {
  595: 	        foreach my $stu_group (@stu_groups) {
  596: 	            if ($stu_group eq $grp) {
  597: 	                $exclude = 0;
  598:     	            } 
  599: 	        }
  600:     	        if (($grp eq 'none') && !$group) {
  601:         	        $exclude = 0;
  602:         	}
  603: 	    }
  604: 	    if ($exclude) {
  605: 	        delete($classlist->{$student});
  606: 	    }
  607: 	}
  608: 	$section = ($section ne '' ? $section : 'none');
  609: 	if (&canview($section)) {
  610: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  611: 		$sections{$section}++;
  612: 		if ($classlist->{$student}) {
  613: 		    $fullnames{$student}=$fullname;
  614: 		}
  615: 	    } else {
  616: 		delete($classlist->{$student});
  617: 	    }
  618: 	} else {
  619: 	    delete($classlist->{$student});
  620: 	}
  621:     }
  622:     my %seen = ();
  623:     my @sections = sort(keys(%sections));
  624:     return ($classlist,\@sections,\%fullnames);
  625: }
  626: 
  627: sub canmodify {
  628:     my ($sec)=@_;
  629:     if ($perm{'mgr'}) {
  630: 	if (!defined($perm{'mgr_section'})) {
  631: 	    # can modify whole class
  632: 	    return 1;
  633: 	} else {
  634: 	    if ($sec eq $perm{'mgr_section'}) {
  635: 		#can modify the requested section
  636: 		return 1;
  637: 	    } else {
  638: 		# can't modify the request section
  639: 		return 0;
  640: 	    }
  641: 	}
  642:     }
  643:     #can't modify
  644:     return 0;
  645: }
  646: 
  647: sub canview {
  648:     my ($sec)=@_;
  649:     if ($perm{'vgr'}) {
  650: 	if (!defined($perm{'vgr_section'})) {
  651: 	    # can modify whole class
  652: 	    return 1;
  653: 	} else {
  654: 	    if ($sec eq $perm{'vgr_section'}) {
  655: 		#can modify the requested section
  656: 		return 1;
  657: 	    } else {
  658: 		# can't modify the request section
  659: 		return 0;
  660: 	    }
  661: 	}
  662:     }
  663:     #can't modify
  664:     return 0;
  665: }
  666: 
  667: #--- Retrieve the grade status of a student for all the parts
  668: sub student_gradeStatus {
  669:     my ($symb,$udom,$uname,$partlist) = @_;
  670:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  671:     my %partstatus = ();
  672:     foreach (@$partlist) {
  673: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  674: 	$status              = 'nothing' if ($status eq '');
  675: 	$partstatus{$_}      = $status;
  676: 	my $subkey           = "resource.$_.submitted_by";
  677: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  678:     }
  679:     return %partstatus;
  680: }
  681: 
  682: # hidden form and javascript that calls the form
  683: # Use by verifyscript and viewgrades
  684: # Shows a student's view of problem and submission
  685: sub jscriptNform {
  686:     my ($symb) = @_;
  687:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  688:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  689: 	'    function viewOneStudent(user,domain) {'."\n".
  690: 	'	document.onestudent.student.value = user;'."\n".
  691: 	'	document.onestudent.userdom.value = domain;'."\n".
  692: 	'	document.onestudent.submit();'."\n".
  693: 	'    }'."\n".
  694: 	'</script>'."\n";
  695:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  696: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  697: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  698: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  699: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  700: 	'<input type="hidden" name="command" value="submission" />'."\n".
  701: 	'<input type="hidden" name="student" value="" />'."\n".
  702: 	'<input type="hidden" name="userdom" value="" />'."\n".
  703: 	'</form>'."\n";
  704:     return $jscript;
  705: }
  706: 
  707: 
  708: 
  709: # Given the score (as a number [0-1] and the weight) what is the final
  710: # point value? This function will round to the nearest tenth, third,
  711: # or quarter if one of those is within the tolerance of .00001.
  712: sub compute_points {
  713:     my ($score, $weight) = @_;
  714:     
  715:     my $tolerance = .00001;
  716:     my $points = $score * $weight;
  717: 
  718:     # Check for nearness to 1/x.
  719:     my $check_for_nearness = sub {
  720:         my ($factor) = @_;
  721:         my $num = ($points * $factor) + $tolerance;
  722:         my $floored_num = floor($num);
  723:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  724:             return $floored_num / $factor;
  725:         }
  726:         return $points;
  727:     };
  728: 
  729:     $points = $check_for_nearness->(10);
  730:     $points = $check_for_nearness->(3);
  731:     $points = $check_for_nearness->(4);
  732:     
  733:     return $points;
  734: }
  735: 
  736: #------------------ End of general use routines --------------------
  737: 
  738: #
  739: # Find most similar essay
  740: #
  741: 
  742: sub most_similar {
  743:     my ($uname,$udom,$symb,$uessay)=@_;
  744: 
  745:     unless ($symb) { return ''; }
  746: 
  747:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  748: 
  749: # ignore spaces and punctuation
  750: 
  751:     $uessay=~s/\W+/ /gs;
  752: 
  753: # ignore empty submissions (occuring when only files are sent)
  754: 
  755:     unless ($uessay=~/\w+/s) { return ''; }
  756: 
  757: # these will be returned. Do not care if not at least 50 percent similar
  758:     my $limit=0.6;
  759:     my $sname='';
  760:     my $sdom='';
  761:     my $scrsid='';
  762:     my $sessay='';
  763: # go through all essays ...
  764:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  765: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  766: # ... except the same student
  767:         next if (($tname eq $uname) && ($tdom eq $udom));
  768: 	my $tessay=$old_essays{$symb}{$tkey};
  769: 	$tessay=~s/\W+/ /gs;
  770: # String similarity gives up if not even limit
  771: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  772: # Found one
  773: 	if ($tsimilar>$limit) {
  774: 	    $limit=$tsimilar;
  775: 	    $sname=$tname;
  776: 	    $sdom=$tdom;
  777: 	    $scrsid=$tcrsid;
  778: 	    $sessay=$old_essays{$symb}{$tkey};
  779: 	}
  780:     }
  781:     if ($limit>0.6) {
  782:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  783:     } else {
  784:        return ('','','','',0);
  785:     }
  786: }
  787: 
  788: #-------------------------------------------------------------------
  789: 
  790: #------------------------------------ Receipt Verification Routines
  791: #
  792: #--- Check whether a receipt number is valid.---
  793: sub verifyreceipt {
  794:     my $request  = shift;
  795: 
  796:     my $courseid = $env{'request.course.id'};
  797:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  798: 	$env{'form.receipt'};
  799:     $receipt     =~ s/[^\-\d]//g;
  800:     my ($symb)   = &get_symb($request);
  801: 
  802:     my $title.=
  803: 	'<h3><span class="LC_info">'.
  804: 	&mt('Verifying Receipt No. [_1]',$receipt).
  805: 	'</span></h3>'."\n".
  806: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  807: 	'</h4>'."\n";
  808: 
  809:     my ($string,$contents,$matches) = ('','',0);
  810:     my (undef,undef,$fullname) = &getclasslist('all','0');
  811:     
  812:     my $receiptparts=0;
  813:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  814: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  815:     my $parts=['0'];
  816:     if ($receiptparts) {
  817:         my $res_error; 
  818:         ($parts)=&response_type($symb,\$res_error);
  819:         if ($res_error) {
  820:             return &navmap_errormsg();
  821:         } 
  822:     }
  823:     
  824:     my $header = 
  825: 	&Apache::loncommon::start_data_table().
  826: 	&Apache::loncommon::start_data_table_header_row().
  827: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  828: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  829: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  830:     if ($receiptparts) {
  831: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  832:     }
  833:     $header.=
  834: 	&Apache::loncommon::end_data_table_header_row();
  835: 
  836:     foreach (sort 
  837: 	     {
  838: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  839: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  840: 		 }
  841: 		 return $a cmp $b;
  842: 	     } (keys(%$fullname))) {
  843: 	my ($uname,$udom)=split(/\:/);
  844: 	foreach my $part (@$parts) {
  845: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  846: 		$contents.=
  847: 		    &Apache::loncommon::start_data_table_row().
  848: 		    '<td>&nbsp;'."\n".
  849: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  850: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  851: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  852: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  853: 		if ($receiptparts) {
  854: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  855: 		}
  856: 		$contents.= 
  857: 		    &Apache::loncommon::end_data_table_row()."\n";
  858: 		
  859: 		$matches++;
  860: 	    }
  861: 	}
  862:     }
  863:     if ($matches == 0) {
  864:         $string = $title
  865:                  .'<p class="LC_warning">'
  866:                  .&mt('No match found for the above receipt number.')
  867:                  .'</p>';
  868:     } else {
  869: 	$string = &jscriptNform($symb).$title.
  870: 	    '<p>'.
  871: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  872: 	    '</p>'.
  873: 	    $header.
  874: 	    $contents.
  875: 	    &Apache::loncommon::end_data_table()."\n";
  876:     }
  877:     return $string.&show_grading_menu_form($symb);
  878: }
  879: 
  880: #--- This is called by a number of programs.
  881: #--- Called from the Grading Menu - View/Grade an individual student
  882: #--- Also called directly when one clicks on the subm button 
  883: #    on the problem page.
  884: sub listStudents {
  885:     my ($request) = shift;
  886: 
  887:     my ($symb) = &get_symb($request);
  888:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  889:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  890:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  891:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  892:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  893:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  894:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  895: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  896: 
  897:     my $result='<h3><span class="LC_info">&nbsp;'
  898: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  899: 	.'</span></h3>';
  900: 
  901:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  902: 
  903:     my %lt = &Apache::lonlocal::texthash (
  904: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  905: 		'single'   => 'Please select the student before clicking on the Next button.',
  906: 	     );
  907:     $request->print(<<LISTJAVASCRIPT);
  908: <script type="text/javascript" language="javascript">
  909:     function checkSelect(checkBox) {
  910: 	var ctr=0;
  911: 	var sense="";
  912: 	if (checkBox.length > 1) {
  913: 	    for (var i=0; i<checkBox.length; i++) {
  914: 		if (checkBox[i].checked) {
  915: 		    ctr++;
  916: 		}
  917: 	    }
  918: 	    sense = '$lt{'multiple'}';
  919: 	} else {
  920: 	    if (checkBox.checked) {
  921: 		ctr = 1;
  922: 	    }
  923: 	    sense = '$lt{'single'}';
  924: 	}
  925: 	if (ctr == 0) {
  926: 	    alert(sense);
  927: 	    return false;
  928: 	}
  929: 	document.gradesub.submit();
  930:     }
  931: 
  932:     function reLoadList(formname) {
  933: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  934: 	formname.command.value = 'submission';
  935: 	formname.submit();
  936:     }
  937: </script>
  938: LISTJAVASCRIPT
  939: 
  940:     &commonJSfunctions($request);
  941:     $request->print($result);
  942: 
  943:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  944:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  945:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  946: 	"\n".$table;
  947: 	
  948:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  949:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  950:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  951:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  952:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  953:                   .&Apache::lonhtmlcommon::row_closure();
  954:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  955:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  956:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  957:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  958:                   .&Apache::lonhtmlcommon::row_closure();
  959: 
  960:     my $submission_options;
  961:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  962: 	$submission_options.=
  963: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  964:     }
  965:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  966:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  967:     $env{'form.Status'} = $saveStatus;
  968:     $submission_options.=
  969:         '<span class="LC_nobreak">'.
  970:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  971:         &mt('last submission only').' </label></span>'."\n".
  972:         '<span class="LC_nobreak">'.
  973:         '<label><input type="radio" name="lastSub" value="last" /> '.
  974:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  975:         '<span class="LC_nobreak">'.
  976:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  977:         &mt('by dates and submissions').'</label></span>'."\n".
  978:         '<span class="LC_nobreak">'.
  979:         '<label><input type="radio" name="lastSub" value="all" /> '.
  980:         &mt('all details').'</label></span>';
  981:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  982:                   .$submission_options
  983:                   .&Apache::lonhtmlcommon::row_closure();
  984: 
  985:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  986:                   .'<select name="increment">'
  987:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  988:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  989:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  990:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  991:                   .'</select>'
  992:                   .&Apache::lonhtmlcommon::row_closure();
  993: 
  994:     $gradeTable .= 
  995:         &build_section_inputs().
  996: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  997: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  998: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  999: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1000: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1001: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1002: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1003: 
 1004:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1005: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1006:     } else {
 1007:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1008:                       .&Apache::lonhtmlcommon::StatusOptions(
 1009:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1010:                       .&Apache::lonhtmlcommon::row_closure();
 1011:     }
 1012: 
 1013:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1014:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1015:                   .&Apache::lonhtmlcommon::row_closure(1)
 1016:                   .&Apache::lonhtmlcommon::end_pick_box();
 1017: 
 1018:     $gradeTable .= '<p>'
 1019:                   .&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"
 1020:                   .'<input type="hidden" name="command" value="processGroup" />'
 1021:                   .'</p>';
 1022: 
 1023: # checkall buttons
 1024:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1025:     $gradeTable.='<input type="button" '."\n".
 1026:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1027:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1028:     $gradeTable.=&check_buttons();
 1029:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1030:     $gradeTable.= &Apache::loncommon::start_data_table().
 1031: 	&Apache::loncommon::start_data_table_header_row();
 1032:     my $loop = 0;
 1033:     while ($loop < 2) {
 1034: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1035: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1036: 	if ($env{'form.showgrading'} eq 'yes' 
 1037: 	    && $submitonly ne 'queued'
 1038: 	    && $submitonly ne 'all') {
 1039: 	    foreach my $part (sort(@$partlist)) {
 1040: 		my $display_part=
 1041: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1042: 		$gradeTable.=
 1043: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1044: 	    }
 1045: 	} elsif ($submitonly eq 'queued') {
 1046: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1047: 	}
 1048: 	$loop++;
 1049: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1050:     }
 1051:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1052: 
 1053:     my $ctr = 0;
 1054:     foreach my $student (sort 
 1055: 			 {
 1056: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1057: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1058: 			     }
 1059: 			     return $a cmp $b;
 1060: 			 }
 1061: 			 (keys(%$fullname))) {
 1062: 	my ($uname,$udom) = split(/:/,$student);
 1063: 
 1064: 	my %status = ();
 1065: 
 1066: 	if ($submitonly eq 'queued') {
 1067: 	    my %queue_status = 
 1068: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1069: 							$udom,$uname);
 1070: 	    next if (!defined($queue_status{'gradingqueue'}));
 1071: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1072: 	}
 1073: 
 1074: 	if ($env{'form.showgrading'} eq 'yes' 
 1075: 	    && $submitonly ne 'queued'
 1076: 	    && $submitonly ne 'all') {
 1077: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1078: 	    my $submitted = 0;
 1079: 	    my $graded = 0;
 1080: 	    my $incorrect = 0;
 1081: 	    foreach (keys(%status)) {
 1082: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1083: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1084: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1085: 		
 1086: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1087: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1088: 		    $submitted = 0;
 1089: 		    my ($part)=split(/\./,$partid);
 1090: 		    $gradeTable.='<input type="hidden" name="'.
 1091: 			$student.':'.$part.':submitted_by" value="'.
 1092: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1093: 		}
 1094: 	    }
 1095: 	    
 1096: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1097: 				     $submitonly eq 'incorrect' ||
 1098: 				     $submitonly eq 'graded'));
 1099: 	    next if (!$graded && ($submitonly eq 'graded'));
 1100: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1101: 	}
 1102: 
 1103: 	$ctr++;
 1104: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1105:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1106: 	if ( $perm{'vgr'} eq 'F' ) {
 1107: 	    if ($ctr%2 ==1) {
 1108: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1109: 	    }
 1110: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1111:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1112:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1113: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1114: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1115: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1116: 
 1117: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1118: 		foreach (sort(keys(%status))) {
 1119: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1120: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1121: 		}
 1122: 	    }
 1123: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1124: 	    if ($ctr%2 ==0) {
 1125: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1126: 	    }
 1127: 	}
 1128:     }
 1129:     if ($ctr%2 ==1) {
 1130: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1131: 	    if ($env{'form.showgrading'} eq 'yes' 
 1132: 		&& $submitonly ne 'queued'
 1133: 		&& $submitonly ne 'all') {
 1134: 		foreach (@$partlist) {
 1135: 		    $gradeTable.='<td>&nbsp;</td>';
 1136: 		}
 1137: 	    } elsif ($submitonly eq 'queued') {
 1138: 		$gradeTable.='<td>&nbsp;</td>';
 1139: 	    }
 1140: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1141:     }
 1142: 
 1143:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1144:         '<input type="button" '.
 1145:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1146:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1147:     if ($ctr == 0) {
 1148: 	my $num_students=(scalar(keys(%$fullname)));
 1149: 	if ($num_students eq 0) {
 1150: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1151: 	} else {
 1152: 	    my $submissions='submissions';
 1153: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1154: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1155: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1156: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1157: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1158: 		    $num_students).
 1159: 		'</span><br />';
 1160: 	}
 1161:     } elsif ($ctr == 1) {
 1162: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1163:     }
 1164:     $gradeTable.=&show_grading_menu_form($symb);
 1165:     $request->print($gradeTable);
 1166:     return '';
 1167: }
 1168: 
 1169: #---- Called from the listStudents routine
 1170: 
 1171: sub check_script {
 1172:     my ($form, $type)=@_;
 1173:     my $chkallscript='<script type="text/javascript">
 1174:     function checkall() {
 1175:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1176:             ele = document.forms.'.$form.'.elements[i];
 1177:             if (ele.name == "'.$type.'") {
 1178:             document.forms.'.$form.'.elements[i].checked=true;
 1179:                                        }
 1180:         }
 1181:     }
 1182: 
 1183:     function checksec() {
 1184:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1185:             ele = document.forms.'.$form.'.elements[i];
 1186:            string = document.forms.'.$form.'.chksec.value;
 1187:            if
 1188:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1189:               document.forms.'.$form.'.elements[i].checked=true;
 1190:             }
 1191:         }
 1192:     }
 1193: 
 1194: 
 1195:     function uncheckall() {
 1196:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1197:             ele = document.forms.'.$form.'.elements[i];
 1198:             if (ele.name == "'.$type.'") {
 1199:             document.forms.'.$form.'.elements[i].checked=false;
 1200:                                        }
 1201:         }
 1202:     }
 1203: 
 1204: </script>'."\n";
 1205:     return $chkallscript;
 1206: }
 1207: 
 1208: sub check_buttons {
 1209:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1210:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1211:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1212:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1213:     return $buttons;
 1214: }
 1215: 
 1216: #     Displays the submissions for one student or a group of students
 1217: sub processGroup {
 1218:     my ($request)  = shift;
 1219:     my $ctr        = 0;
 1220:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1221:     my $total      = scalar(@stuchecked)-1;
 1222: 
 1223:     foreach my $student (@stuchecked) {
 1224: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1225: 	$env{'form.student'}        = $uname;
 1226: 	$env{'form.userdom'}        = $udom;
 1227: 	$env{'form.fullname'}       = $fullname;
 1228: 	&submission($request,$ctr,$total);
 1229: 	$ctr++;
 1230:     }
 1231:     return '';
 1232: }
 1233: 
 1234: #------------------------------------------------------------------------------------
 1235: #
 1236: #-------------------------- Next few routines handles grading by student, essentially
 1237: #                           handles essay response type problem/part
 1238: #
 1239: #--- Javascript to handle the submission page functionality ---
 1240: sub sub_page_js {
 1241:     my $request = shift;
 1242: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1243:     $request->print(<<SUBJAVASCRIPT);
 1244: <script type="text/javascript" language="javascript">
 1245:     function updateRadio(formname,id,weight) {
 1246: 	var gradeBox = formname["GD_BOX"+id];
 1247: 	var radioButton = formname["RADVAL"+id];
 1248: 	var oldpts = formname["oldpts"+id].value;
 1249: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1250: 	gradeBox.value = pts;
 1251: 	var resetbox = false;
 1252: 	if (isNaN(pts) || pts < 0) {
 1253: 	    alert("$alertmsg"+pts);
 1254: 	    for (var i=0; i<radioButton.length; i++) {
 1255: 		if (radioButton[i].checked) {
 1256: 		    gradeBox.value = i;
 1257: 		    resetbox = true;
 1258: 		}
 1259: 	    }
 1260: 	    if (!resetbox) {
 1261: 		formtextbox.value = "";
 1262: 	    }
 1263: 	    return;
 1264: 	}
 1265: 
 1266: 	if (pts > weight) {
 1267: 	    var resp = confirm("You entered a value ("+pts+
 1268: 			       ") greater than the weight for the part. Accept?");
 1269: 	    if (resp == false) {
 1270: 		gradeBox.value = oldpts;
 1271: 		return;
 1272: 	    }
 1273: 	}
 1274: 
 1275: 	for (var i=0; i<radioButton.length; i++) {
 1276: 	    radioButton[i].checked=false;
 1277: 	    if (pts == i && pts != "") {
 1278: 		radioButton[i].checked=true;
 1279: 	    }
 1280: 	}
 1281: 	updateSelect(formname,id);
 1282: 	formname["stores"+id].value = "0";
 1283:     }
 1284: 
 1285:     function writeBox(formname,id,pts) {
 1286: 	var gradeBox = formname["GD_BOX"+id];
 1287: 	if (checkSolved(formname,id) == 'update') {
 1288: 	    gradeBox.value = pts;
 1289: 	} else {
 1290: 	    var oldpts = formname["oldpts"+id].value;
 1291: 	    gradeBox.value = oldpts;
 1292: 	    var radioButton = formname["RADVAL"+id];
 1293: 	    for (var i=0; i<radioButton.length; i++) {
 1294: 		radioButton[i].checked=false;
 1295: 		if (i == oldpts) {
 1296: 		    radioButton[i].checked=true;
 1297: 		}
 1298: 	    }
 1299: 	}
 1300: 	formname["stores"+id].value = "0";
 1301: 	updateSelect(formname,id);
 1302: 	return;
 1303:     }
 1304: 
 1305:     function clearRadBox(formname,id) {
 1306: 	if (checkSolved(formname,id) == 'noupdate') {
 1307: 	    updateSelect(formname,id);
 1308: 	    return;
 1309: 	}
 1310: 	gradeSelect = formname["GD_SEL"+id];
 1311: 	for (var i=0; i<gradeSelect.length; i++) {
 1312: 	    if (gradeSelect[i].selected) {
 1313: 		var selectx=i;
 1314: 	    }
 1315: 	}
 1316: 	var stores = formname["stores"+id];
 1317: 	if (selectx == stores.value) { return };
 1318: 	var gradeBox = formname["GD_BOX"+id];
 1319: 	gradeBox.value = "";
 1320: 	var radioButton = formname["RADVAL"+id];
 1321: 	for (var i=0; i<radioButton.length; i++) {
 1322: 	    radioButton[i].checked=false;
 1323: 	}
 1324: 	stores.value = selectx;
 1325:     }
 1326: 
 1327:     function checkSolved(formname,id) {
 1328: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1329: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1330: 	    if (!reply) {return "noupdate";}
 1331: 	    formname.overRideScore.value = 'yes';
 1332: 	}
 1333: 	return "update";
 1334:     }
 1335: 
 1336:     function updateSelect(formname,id) {
 1337: 	formname["GD_SEL"+id][0].selected = true;
 1338: 	return;
 1339:     }
 1340: 
 1341: //=========== Check that a point is assigned for all the parts  ============
 1342:     function checksubmit(formname,val,total,parttot) {
 1343: 	formname.gradeOpt.value = val;
 1344: 	if (val == "Save & Next") {
 1345: 	    for (i=0;i<=total;i++) {
 1346: 		for (j=0;j<parttot;j++) {
 1347: 		    var partid = formname["partid"+i+"_"+j].value;
 1348: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1349: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1350: 			if (points == "") {
 1351: 			    var name = formname["name"+i].value;
 1352: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1353: 			    var resp = confirm("You did not assign a score for "+studentID+
 1354: 					       ", part "+partid+". Continue?");
 1355: 			    if (resp == false) {
 1356: 				formname["GD_BOX"+i+"_"+partid].focus();
 1357: 				return false;
 1358: 			    }
 1359: 			}
 1360: 		    }
 1361: 		    
 1362: 		}
 1363: 	    }
 1364: 	    
 1365: 	}
 1366: 	if (val == "Grade Student") {
 1367: 	    formname.showgrading.value = "yes";
 1368: 	    if (formname.Status.value == "") {
 1369: 		formname.Status.value = "Active";
 1370: 	    }
 1371: 	    formname.studentNo.value = total;
 1372: 	}
 1373: 	formname.submit();
 1374:     }
 1375: 
 1376: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1377:     function checkSubmitPage(formname,total) {
 1378: 	noscore = new Array(100);
 1379: 	var ptr = 0;
 1380: 	for (i=1;i<total;i++) {
 1381: 	    var partid = formname["q_"+i].value;
 1382: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1383: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1384: 		var status = formname["solved"+i+"_"+partid].value;
 1385: 		if (points == "" && status != "correct_by_student") {
 1386: 		    noscore[ptr] = i;
 1387: 		    ptr++;
 1388: 		}
 1389: 	    }
 1390: 	}
 1391: 	if (ptr != 0) {
 1392: 	    var sense = ptr == 1 ? ": " : "s: ";
 1393: 	    var prolist = "";
 1394: 	    if (ptr == 1) {
 1395: 		prolist = noscore[0];
 1396: 	    } else {
 1397: 		var i = 0;
 1398: 		while (i < ptr-1) {
 1399: 		    prolist += noscore[i]+", ";
 1400: 		    i++;
 1401: 		}
 1402: 		prolist += "and "+noscore[i];
 1403: 	    }
 1404: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1405: 	    if (resp == false) {
 1406: 		return false;
 1407: 	    }
 1408: 	}
 1409: 
 1410: 	formname.submit();
 1411:     }
 1412: </script>
 1413: SUBJAVASCRIPT
 1414: }
 1415: 
 1416: #--- javascript for essay type problem --
 1417: sub sub_page_kw_js {
 1418:     my $request = shift;
 1419:     my $iconpath = $request->dir_config('lonIconsURL');
 1420:     &commonJSfunctions($request);
 1421: 
 1422:     my $inner_js_msg_central=<<INNERJS;
 1423:     <script text="text/javascript">
 1424:     function checkInput() {
 1425:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1426:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1427:       var usrctr = document.msgcenter.usrctr.value;
 1428:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1429:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1430: 
 1431:       var msgchk = "";
 1432:       if (document.msgcenter.subchk.checked) {
 1433:          msgchk = "msgsub,";
 1434:       }
 1435:       var includemsg = 0;
 1436:       for (var i=1; i<=nmsg; i++) {
 1437:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1438:           var frmmsg = document.msgcenter["msg"+i];
 1439:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1440:           var showflg = opener.document.SCORE["shownOnce"+i];
 1441:           showflg.value = "1";
 1442:           var chkbox = document.msgcenter["msgn"+i];
 1443:           if (chkbox.checked) {
 1444:              msgchk += "savemsg"+i+",";
 1445:              includemsg = 1;
 1446:           }
 1447:       }
 1448:       if (document.msgcenter.newmsgchk.checked) {
 1449:          msgchk += "newmsg"+usrctr;
 1450:          includemsg = 1;
 1451:       }
 1452:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1453:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1454:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1455:       includemsg.value = msgchk;
 1456: 
 1457:       self.close()
 1458: 
 1459:     }
 1460:     </script>
 1461: INNERJS
 1462: 
 1463:     my $inner_js_highlight_central=<<INNERJS;
 1464:  <script type="text/javascript">
 1465:     function updateChoice(flag) {
 1466:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1467:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1468:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1469:       opener.document.SCORE.refresh.value = "on";
 1470:       if (opener.document.SCORE.keywords.value!=""){
 1471:          opener.document.SCORE.submit();
 1472:       }
 1473:       self.close()
 1474:     }
 1475: </script>
 1476: INNERJS
 1477: 
 1478:     my $start_page_msg_central = 
 1479:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1480: 				       {'js_ready'  => 1,
 1481: 					'only_body' => 1,
 1482: 					'bgcolor'   =>'#FFFFFF',});
 1483:     my $end_page_msg_central = 
 1484: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1485: 
 1486: 
 1487:     my $start_page_highlight_central = 
 1488:         &Apache::loncommon::start_page('Highlight Central',
 1489: 				       $inner_js_highlight_central,
 1490: 				       {'js_ready'  => 1,
 1491: 					'only_body' => 1,
 1492: 					'bgcolor'   =>'#FFFFFF',});
 1493:     my $end_page_highlight_central = 
 1494: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1495: 
 1496:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1497:     $docopen=~s/^document\.//;
 1498:     my %lt = &Apache::lonlocal::texthash(
 1499:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1500:                 plse => 'Please select a word or group of words from document and then click this link.',
 1501:                 adds => 'Add selection to keyword list? Edit if desired.',
 1502:                 comp => 'Compose Message for: ',
 1503:                 incl => 'Include',
 1504:                 type => 'Type',
 1505:                 subj => 'Subject',
 1506:                 mesa => 'Message',
 1507:                 new  => 'New',
 1508:                 save => 'Save',
 1509:                 canc => 'Cancel',
 1510:                 kehi => 'Keyword Highlight Options',
 1511:                 txtc => 'Text Color',
 1512:                 font => 'Font Size',
 1513:                 fnst => 'Font Style',
 1514:              );
 1515:     $request->print(<<SUBJAVASCRIPT);
 1516: <script type="text/javascript" language="javascript">
 1517: 
 1518: //===================== Show list of keywords ====================
 1519:   function keywords(formname) {
 1520:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1521:     if (nret==null) return;
 1522:     formname.keywords.value = nret;
 1523: 
 1524:     if (formname.keywords.value != "") {
 1525: 	formname.refresh.value = "on";
 1526: 	formname.submit();
 1527:     }
 1528:     return;
 1529:   }
 1530: 
 1531: //===================== Script to view submitted by ==================
 1532:   function viewSubmitter(submitter) {
 1533:     document.SCORE.refresh.value = "on";
 1534:     document.SCORE.NCT.value = "1";
 1535:     document.SCORE.unamedom0.value = submitter;
 1536:     document.SCORE.submit();
 1537:     return;
 1538:   }
 1539: 
 1540: //===================== Script to add keyword(s) ==================
 1541:   function getSel() {
 1542:     if (document.getSelection) txt = document.getSelection();
 1543:     else if (document.selection) txt = document.selection.createRange().text;
 1544:     else return;
 1545:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1546:     if (cleantxt=="") {
 1547: 	alert("$lt{'plse'}");
 1548: 	return;
 1549:     }
 1550:     var nret = prompt("$lt{'adds'}",cleantxt);
 1551:     if (nret==null) return;
 1552:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1553:     if (document.SCORE.keywords.value != "") {
 1554: 	document.SCORE.refresh.value = "on";
 1555: 	document.SCORE.submit();
 1556:     }
 1557:     return;
 1558:   }
 1559: 
 1560: //====================== Script for composing message ==============
 1561:    // preload images
 1562:    img1 = new Image();
 1563:    img1.src = "$iconpath/mailbkgrd.gif";
 1564:    img2 = new Image();
 1565:    img2.src = "$iconpath/mailto.gif";
 1566: 
 1567:   function msgCenter(msgform,usrctr,fullname) {
 1568:     var Nmsg  = msgform.savemsgN.value;
 1569:     savedMsgHeader(Nmsg,usrctr,fullname);
 1570:     var subject = msgform.msgsub.value;
 1571:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1572:     re = /msgsub/;
 1573:     var shwsel = "";
 1574:     if (re.test(msgchk)) { shwsel = "checked" }
 1575:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1576:     displaySubject(checkEntities(subject),shwsel);
 1577:     for (var i=1; i<=Nmsg; i++) {
 1578: 	var testmsg = "savemsg"+i+",";
 1579: 	re = new RegExp(testmsg,"g");
 1580: 	shwsel = "";
 1581: 	if (re.test(msgchk)) { shwsel = "checked" }
 1582: 	var message = document.SCORE["savemsg"+i].value;
 1583: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1584: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1585: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1586:     }
 1587:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1588:     shwsel = "";
 1589:     re = /newmsg/;
 1590:     if (re.test(msgchk)) { shwsel = "checked" }
 1591:     newMsg(newmsg,shwsel);
 1592:     msgTail(); 
 1593:     return;
 1594:   }
 1595: 
 1596:   function checkEntities(strx) {
 1597:     if (strx.length == 0) return strx;
 1598:     var orgStr = ["&", "<", ">", '"']; 
 1599:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1600:     var counter = 0;
 1601:     while (counter < 4) {
 1602: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1603: 	counter++;
 1604:     }
 1605:     return strx;
 1606:   }
 1607: 
 1608:   function strReplace(strx, orgStr, newStr) {
 1609:     return strx.split(orgStr).join(newStr);
 1610:   }
 1611: 
 1612:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1613:     var height = 70*Nmsg+250;
 1614:     var scrollbar = "no";
 1615:     if (height > 600) {
 1616: 	height = 600;
 1617: 	scrollbar = "yes";
 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='+scrollbar+',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: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
 1835:     $result .= 
 1836: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1837:     $result.=&Apache::loncommon::end_data_table_row();
 1838:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1839: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1840: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1841: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1842:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1843:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1844:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1845:         $aggtries.'" />'."\n";
 1846:     my $res_error;
 1847:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1848:     if ($res_error) {
 1849:         return &navmap_errormsg();
 1850:     }
 1851:     return $result;
 1852: }
 1853: 
 1854: sub handback_box {
 1855:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1856:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1857:     my (@respids);
 1858:     my @part_response_id = &flatten_responseType($responseType);
 1859:     foreach my $part_response_id (@part_response_id) {
 1860:     	my ($part,$resp) = @{ $part_response_id };
 1861:         if ($part eq $partid) {
 1862:             push(@respids,$resp);
 1863:         }
 1864:     }
 1865:     my $result;
 1866:     foreach my $respid (@respids) {
 1867: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1868: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1869: 	next if (!@$files);
 1870: 	my $file_counter = 0;
 1871: 	foreach my $file (@$files) {
 1872: 	    if ($file =~ /\/portfolio\//) {
 1873:                 $file_counter++;
 1874:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1875:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1876:     	        $file_disp = "$name.$ext";
 1877:     	        $file = $file_path.$file_disp;
 1878:     	        $result.=&mt('Return commented version of [_1] to student.',
 1879:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1880:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1881:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1882: 	    }
 1883: 	}
 1884:         if ($file_counter) {
 1885:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1886:                        '<span class="LC_info">'.
 1887:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1888:         }
 1889:     }
 1890:     return $result;    
 1891: }
 1892: 
 1893: sub show_problem {
 1894:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1895:     my $rendered;
 1896:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1897:     &Apache::lonxml::remember_problem_counter();
 1898:     if ($mode eq 'both' or $mode eq 'text') {
 1899: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1900: 						       $env{'request.course.id'},
 1901: 						       undef,\%form);
 1902:     }
 1903:     if ($removeform) {
 1904: 	$rendered=~s|<form(.*?)>||g;
 1905: 	$rendered=~s|</form>||g;
 1906: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1907:     }
 1908:     my $companswer;
 1909:     if ($mode eq 'both' or $mode eq 'answer') {
 1910: 	&Apache::lonxml::restore_problem_counter();
 1911: 	$companswer=
 1912: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1913: 						    $env{'request.course.id'},
 1914: 						    %form);
 1915:     }
 1916:     if ($removeform) {
 1917: 	$companswer=~s|<form(.*?)>||g;
 1918: 	$companswer=~s|</form>||g;
 1919: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1920:     }
 1921:     $rendered=
 1922:         '<div class="LC_Box">'
 1923:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1924:        .$rendered
 1925:        .'</div>';
 1926:     $companswer=
 1927:         '<div class="LC_Box">'
 1928:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1929:        .$companswer
 1930:        .'</div>';
 1931:     my $result;
 1932:     if ($mode eq 'both') {
 1933:         $result=$rendered.$companswer;
 1934:     } elsif ($mode eq 'text') {
 1935:         $result=$rendered;
 1936:     } elsif ($mode eq 'answer') {
 1937:         $result=$companswer;
 1938:     }
 1939:     return $result;
 1940: }
 1941: 
 1942: sub files_exist {
 1943:     my ($r, $symb) = @_;
 1944:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1945: 
 1946:     foreach my $student (@students) {
 1947:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1948:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1949: 					      $udom,$uname);
 1950:         my ($string,$timestamp)= &get_last_submission(\%record);
 1951:         foreach my $submission (@$string) {
 1952:             my ($partid,$respid) =
 1953: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1954:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1955: 					   \%record);
 1956:             return 1 if (@$files);
 1957:         }
 1958:     }
 1959:     return 0;
 1960: }
 1961: 
 1962: sub download_all_link {
 1963:     my ($r,$symb) = @_;
 1964:     my $all_students = 
 1965: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1966: 
 1967:     my $parts =
 1968: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1969: 
 1970:     my $identifier = &Apache::loncommon::get_cgi_id();
 1971:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1972:                              'cgi.'.$identifier.'.symb' => $symb,
 1973:                              'cgi.'.$identifier.'.parts' => $parts,});
 1974:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1975: 	      &mt('Download All Submitted Documents').'</a>');
 1976:     return
 1977: }
 1978: 
 1979: sub build_section_inputs {
 1980:     my $section_inputs;
 1981:     if ($env{'form.section'} eq '') {
 1982:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1983:     } else {
 1984:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1985:         foreach my $section (@sections) {
 1986:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1987:         }
 1988:     }
 1989:     return $section_inputs;
 1990: }
 1991: 
 1992: # --------------------------- show submissions of a student, option to grade 
 1993: sub submission {
 1994:     my ($request,$counter,$total) = @_;
 1995:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1996:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1997:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1998:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1999:     my $symb = &get_symb($request); 
 2000:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2001: 
 2002:     if (!&canview($usec)) {
 2003: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 2004: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 2005: 			$env{'request.course.id'}.')</span>');
 2006: 	$request->print(&show_grading_menu_form($symb));
 2007: 	return;
 2008:     }
 2009: 
 2010:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2011:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2012:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2013:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2014:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2015: 	'" src="'.$request->dir_config('lonIconsURL').
 2016: 	'/check.gif" height="16" border="0" />';
 2017: 
 2018:     # header info
 2019:     if ($counter == 0) {
 2020: 	&sub_page_js($request);
 2021: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2022: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2023: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2024: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2025: 	    &download_all_link($request, $symb);
 2026: 	}
 2027: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2028: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 2029: 
 2030: 	# option to display problem, only once else it cause problems 
 2031:         # with the form later since the problem has a form.
 2032: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2033: 	    my $mode;
 2034: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2035: 		$mode='both';
 2036: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2037: 		$mode='text';
 2038: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2039: 		$mode='answer';
 2040: 	    }
 2041: 	    &Apache::lonxml::clear_problem_counter();
 2042: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2043: 	}
 2044: 
 2045: 	# kwclr is the only variable that is guaranteed to be non blank 
 2046:         # if this subroutine has been called once.
 2047: 	my %keyhash = ();
 2048: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2049: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2050: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2051: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2052: 
 2053: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2054: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2055: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2056: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2057: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2058: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2059: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2060: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2061: 	}
 2062: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2063: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2064: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2065: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2066: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2067: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2068: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2069: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2070: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2071: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2072: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2073: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2074: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2075: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2076: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2077: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2078: 			&build_section_inputs().
 2079: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2080: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2081: 			'<input type="hidden" name="NCT"'.
 2082: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2083: 	if ($env{'form.handgrade'} eq 'yes') {
 2084: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2085: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2086: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2087: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2088: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2089: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2090: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2091: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2092: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2093: 	    }
 2094: 	}
 2095: 	
 2096: 	my ($cts,$prnmsg) = (1,'');
 2097: 	while ($cts <= $env{'form.savemsgN'}) {
 2098: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2099: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2100: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2101: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2102: 		'" />'."\n".
 2103: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2104: 	    $cts++;
 2105: 	}
 2106: 	$request->print($prnmsg);
 2107: 
 2108: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2109: 
 2110:             my %lt = &Apache::lonlocal::texthash(
 2111:                           keyw => 'Keyword Options',
 2112:                           list => 'List',
 2113:                           past => 'Paste Selection to List',
 2114:                           high => 'Highlight Attribute',
 2115:                      );
 2116: #
 2117: # Print out the keyword options line
 2118: #
 2119: 	    $request->print(<<KEYWORDS);
 2120: &nbsp;<b>$lt{'keyw'}:</b>&nbsp;
 2121: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2122: <a href="#" onmousedown="javascript:getSel(); return false"
 2123:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
 2124: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2125: KEYWORDS
 2126: #
 2127: # Load the other essays for similarity check
 2128: #
 2129:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2130: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2131: 	    $apath=&escape($apath);
 2132: 	    $apath=~s/\W/\_/gs;
 2133: 	    &init_old_essays($symb,$apath,$adom,$aname);
 2134:         }
 2135:     }
 2136: 
 2137: # This is where output for one specific student would start
 2138:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2139:     $request->print(
 2140:         "\n\n"
 2141:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2142:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2143:        ."\n"
 2144:     );
 2145: 
 2146:     # Show additional functions if allowed
 2147:     if ($perm{'vgr'}) {
 2148:         $request->print(
 2149:             &Apache::loncommon::track_student_link(
 2150:                 &mt('View recent activity'),
 2151:                 $uname,$udom,'check')
 2152:            .' '
 2153:         );
 2154:     }
 2155:     if ($perm{'opa'}) {
 2156:         $request->print(
 2157:             &Apache::loncommon::pprmlink(
 2158:                 &mt('Set/Change parameters'),
 2159:                 $uname,$udom,$symb,'check'));
 2160:     }
 2161: 
 2162:     # Show Problem
 2163:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2164: 	my $mode;
 2165: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2166: 	    $mode='both';
 2167: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2168: 	    $mode='text';
 2169: 	} elsif ($env{'form.vAns'} eq 'all') {
 2170: 	    $mode='answer';
 2171: 	}
 2172: 	&Apache::lonxml::clear_problem_counter();
 2173: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2174:     }
 2175: 
 2176:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2177:     my $res_error;
 2178:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2179:     if ($res_error) {
 2180:         $request->print(&navmap_errormsg());
 2181:         return;
 2182:     }
 2183: 
 2184:     # Display student info
 2185:     $request->print(($counter == 0 ? '' : '<br />'));
 2186: 
 2187:     my $result='<div class="LC_Box">'
 2188:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2189:     $result.='<input type="hidden" name="name'.$counter.
 2190:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2191:     if ($env{'form.handgrade'} eq 'no') {
 2192:         $result.='<p class="LC_info">'
 2193:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2194:                 ."</p>\n";
 2195:     }
 2196: 
 2197:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2198:     my $fullname;
 2199:     my $col_fullnames = [];
 2200:     if ($env{'form.handgrade'} eq 'yes') {
 2201: 	(my $sub_result,$fullname,$col_fullnames)=
 2202: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2203: 				 $counter);
 2204: 	$result.=$sub_result;
 2205:     }
 2206:     $request->print($result."\n");
 2207: 
 2208:     # print student answer/submission
 2209:     # Options are (1) Handgraded submission only
 2210:     #             (2) Last submission, includes submission that is not handgraded 
 2211:     #                  (for multi-response type part)
 2212:     #             (3) Last submission plus the parts info
 2213:     #             (4) The whole record for this student
 2214:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2215: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2216: 	
 2217: 	my $lastsubonly;
 2218: 
 2219:         if ($$timestamp eq '') {
 2220:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2221:         } else {
 2222:             $lastsubonly =
 2223:                 '<div class="LC_grade_submissions_body">'
 2224:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2225: 
 2226: 	    my %seenparts;
 2227: 	    my @part_response_id = &flatten_responseType($responseType);
 2228: 	    foreach my $part (@part_response_id) {
 2229: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2230: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2231: 
 2232: 		my ($partid,$respid) = @{ $part };
 2233: 		my $display_part=&get_display_part($partid,$symb);
 2234: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2235: 		    if (exists($seenparts{$partid})) { next; }
 2236: 		    $seenparts{$partid}=1;
 2237: 		    my $submitby='<b>Part:</b> '.$display_part.
 2238: 			' <b>Collaborative submission by:</b> '.
 2239: 			'<a href="javascript:viewSubmitter(\''.
 2240: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2241: 			'\');" target="_self">'.
 2242: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2243: 		    $request->print($submitby);
 2244: 		    next;
 2245: 		}
 2246: 		my $responsetype = $responseType->{$partid}->{$respid};
 2247: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2248:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2249:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2250:                         ' <span class="LC_internal_info">'.
 2251:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2252:                         '</span>&nbsp; &nbsp;'.
 2253: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2254: 		    next;
 2255: 		}
 2256: 		foreach my $submission (@$string) {
 2257: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2258: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2259: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2260: 		    # Similarity check
 2261: 		    my $similar='';
 2262:                     my ($type,$trial,$rndseed);
 2263:                     if ($hide eq 'rand') {
 2264:                         $type = 'randomizetry';
 2265:                         $trial = $record{"resource.$partid.tries"};
 2266:                         $rndseed = $record{"resource.$partid.rndseed"};
 2267:                     }
 2268: 		    if($env{'form.checkPlag'}){
 2269: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2270: 			    &most_similar($uname,$udom,$symb,$subval);
 2271: 			if ($osim) {
 2272: 			    $osim=int($osim*100.0);
 2273: 			    my %old_course_desc = 
 2274: 				&Apache::lonnet::coursedescription($ocrsid,
 2275: 								   {'one_time' => 1});
 2276: 
 2277:                             if ($hide eq 'anon') {
 2278:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2279:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2280:                             } else {
 2281: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2282: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2283: 				        $osim,
 2284: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2285: 				        $old_course_desc{'description'},
 2286: 				        $old_course_desc{'num'},
 2287: 				        $old_course_desc{'domain'}).
 2288: 				    '</span></h3><blockquote><i>'.
 2289: 				    &keywords_highlight($oessay).
 2290: 				    '</i></blockquote><hr />';
 2291:                             }
 2292: 			}
 2293: 		    }
 2294: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2295:                                          undef,$type,$trial,$rndseed);
 2296: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2297: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2298: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2299: 			my $display_part=&get_display_part($partid,$symb);
 2300:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2301:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2302:                             ' <span class="LC_internal_info">'.
 2303:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2304:                             '</span>&nbsp; &nbsp;';
 2305: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2306: 			if (@$files) {
 2307:                             if ($hide eq 'anon') {
 2308:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2309:                             } else {
 2310:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2311:                                 foreach my $file (@$files) {
 2312:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2313:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2314:                                 }
 2315:                             }
 2316: 			    $lastsubonly.='<br />';
 2317: 			}
 2318:                         if ($hide eq 'anon') {
 2319:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2320:                         } else {
 2321: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2322: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2323: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2324:                         }
 2325: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2326: 			$lastsubonly.='</div>';
 2327: 		    }
 2328: 		}
 2329: 	    }
 2330: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2331: 	}
 2332: 	$request->print($lastsubonly);
 2333:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2334: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2335: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2336:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2337: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2338: 								 $env{'request.course.id'},
 2339: 								 $last,'.submission',
 2340: 								 'Apache::grades::keywords_highlight'));
 2341:     }
 2342: 
 2343:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2344: 	.$udom.'" />'."\n");
 2345:     # return if view submission with no grading option
 2346:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2347: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2348: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2349: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2350: 	$toGrade.='</div>'."\n";
 2351: 	if (($env{'form.command'} eq 'submission') || 
 2352: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2353: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2354: 	}
 2355: 	$request->print($toGrade);
 2356: 	return;
 2357:     } else {
 2358: 	$request->print('</div>'."\n");
 2359:     }
 2360: 
 2361:     # essay grading message center
 2362:     if ($env{'form.handgrade'} eq 'yes') {
 2363: 	my $result='<div class="LC_grade_message_center">';
 2364:     
 2365: 	$result.='<div class="LC_grade_message_center_header">'.
 2366: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2367: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2368: 	my $msgfor = $givenn.' '.$lastname;
 2369: 	if (scalar(@$col_fullnames) > 0) {
 2370: 	    my $lastone = pop(@$col_fullnames);
 2371: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2372: 	}
 2373: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2374: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2375: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2376: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2377: 	    ',\''.$msgfor.'\');" target="_self">'.
 2378: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2379: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2380: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2381: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2382: 	    '<br />&nbsp;('.
 2383: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2384: 	$result.='</div></div>';
 2385: 	$request->print($result);
 2386:     }
 2387: 
 2388:     my %seen = ();
 2389:     my @partlist;
 2390:     my @gradePartRespid;
 2391:     my @part_response_id = &flatten_responseType($responseType);
 2392:     $request->print(
 2393:         '<div class="LC_Box">'
 2394:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2395:     );
 2396:     $request->print(&gradeBox_start());
 2397:     foreach my $part_response_id (@part_response_id) {
 2398:     	my ($partid,$respid) = @{ $part_response_id };
 2399: 	my $part_resp = join('_',@{ $part_response_id });
 2400: 	next if ($seen{$partid} > 0);
 2401: 	$seen{$partid}++;
 2402: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2403: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2404: 	push(@partlist,$partid);
 2405: 	push(@gradePartRespid,$partid.'.'.$respid);
 2406: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2407:     }
 2408:     $request->print(&gradeBox_end()); # </div>
 2409:     $request->print('</div>');
 2410: 
 2411:     $request->print('<div class="LC_grade_info_links">');
 2412:     $request->print('</div>');
 2413: 
 2414:     $result='<input type="hidden" name="partlist'.$counter.
 2415: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2416:     $result.='<input type="hidden" name="gradePartRespid'.
 2417: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2418:     my $ctr = 0;
 2419:     while ($ctr < scalar(@partlist)) {
 2420: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2421: 	    $partlist[$ctr].'" />'."\n";
 2422: 	$ctr++;
 2423:     }
 2424:     $request->print($result.''."\n");
 2425: 
 2426: # Done with printing info for one student
 2427: 
 2428:     $request->print('</div>');#LC_grade_show_user
 2429: 
 2430: 
 2431:     # print end of form
 2432:     if ($counter == $total) {
 2433:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2434: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2435: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2436: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2437: 	my $ntstu ='<select name="NTSTU">'.
 2438: 	    '<option>1</option><option>2</option>'.
 2439: 	    '<option>3</option><option>5</option>'.
 2440: 	    '<option>7</option><option>10</option></select>'."\n";
 2441: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2442: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2443:         $endform.=&mt('[_1]student(s)',$ntstu);
 2444: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2445: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2446: 	    '<input type="button" value="'.&mt('Next').'" '.
 2447: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2448:         $endform.='<span class="LC_warning">'.
 2449:                   &mt('(Next and Previous (student) do not save the scores.)').
 2450:                   '</span>'."\n" ;
 2451:         $endform.="<input type='hidden' value='".&get_increment().
 2452:             "' name='increment' />";
 2453: 	$endform.='</td></tr></table></form>';
 2454: 	$endform.=&show_grading_menu_form($symb);
 2455: 	$request->print($endform);
 2456:     }
 2457:     return '';
 2458: }
 2459: 
 2460: sub check_collaborators {
 2461:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2462:     my ($result,@col_fullnames);
 2463:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2464:     foreach my $part (keys(%$handgrade)) {
 2465: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2466: 					'.maxcollaborators',
 2467: 					$symb,$udom,$uname);
 2468: 	next if ($ncol <= 0);
 2469: 	$part =~ s/\_/\./g;
 2470: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2471: 	my (@good_collaborators, @bad_collaborators);
 2472: 	foreach my $possible_collaborator
 2473: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2474: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2475: 	    next if ($possible_collaborator eq '');
 2476: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2477: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2478: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2479: 	    # Doing this grep allows 'fuzzy' specification
 2480: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2481: 			       keys(%$classlist));
 2482: 	    if (! scalar(@matches)) {
 2483: 		push(@bad_collaborators, $possible_collaborator);
 2484: 	    } else {
 2485: 		push(@good_collaborators, @matches);
 2486: 	    }
 2487: 	}
 2488: 	if (scalar(@good_collaborators) != 0) {
 2489: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2490: 	    foreach my $name (@good_collaborators) {
 2491: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2492: 		push(@col_fullnames, $givenn.' '.$lastname);
 2493: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2494: 	    }
 2495: 	    $result.='</ol><br />'."\n";
 2496: 	    my ($part)=split(/\./,$part);
 2497: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2498: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2499: 		"\n";
 2500: 	}
 2501: 	if (scalar(@bad_collaborators) > 0) {
 2502: 	    $result.='<div class="LC_warning">';
 2503: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2504: 	    $result .= '</div>';
 2505: 	}         
 2506: 	if (scalar(@bad_collaborators > $ncol)) {
 2507: 	    $result .= '<div class="LC_warning">';
 2508: 	    $result .= &mt('This student has submitted too many '.
 2509: 		'collaborators.  Maximum is [_1].',$ncol);
 2510: 	    $result .= '</div>';
 2511: 	}
 2512:     }
 2513:     return ($result,$fullname,\@col_fullnames);
 2514: }
 2515: 
 2516: #--- Retrieve the last submission for all the parts
 2517: sub get_last_submission {
 2518:     my ($returnhash)=@_;
 2519:     my (@string,$timestamp,%lasthidden);
 2520:     if ($$returnhash{'version'}) {
 2521: 	my %lasthash=();
 2522: 	my ($version);
 2523: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2524: 	    foreach my $key (sort(split(/\:/,
 2525: 					$$returnhash{$version.':keys'}))) {
 2526: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2527: 		$timestamp = 
 2528: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2529: 	    }
 2530: 	}
 2531:         my (%typeparts,%randombytry);
 2532:         my $showsurv = 
 2533:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2534:         foreach my $key (sort(keys(%lasthash))) {
 2535:             if ($key =~ /\.type$/) {
 2536:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2537:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2538:                     ($lasthash{$key} eq 'randomizetry')) {
 2539:                     my ($ign,@parts) = split(/\./,$key);
 2540:                     pop(@parts);
 2541:                     my $id = join('.',@parts);
 2542:                     if ($lasthash{$key} eq 'randomizetry') {
 2543:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2544:                     } else {
 2545:                         unless ($showsurv) {
 2546:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2547:                         }
 2548:                     }
 2549:                     delete($lasthash{$key});
 2550:                 }
 2551:             }
 2552:         }
 2553:         my @hidden = keys(%typeparts);
 2554:         my @randomize = keys(%randombytry);
 2555: 	foreach my $key (keys(%lasthash)) {
 2556: 	    next if ($key !~ /\.submission$/);
 2557:             my $hide;
 2558:             if (@hidden) {
 2559:                 foreach my $id (@hidden) {
 2560:                     if ($key =~ /^\Q$id\E/) {
 2561:                         $hide = 'anon';
 2562:                         last;
 2563:                     }
 2564:                 }
 2565:             }
 2566:             unless ($hide) {
 2567:                 if (@randomize) {
 2568:                     foreach my $id (@hidden) {
 2569:                         if ($key =~ /^\Q$id\E/) {
 2570:                             $hide = 'rand';
 2571:                             last;
 2572:                         }
 2573:                     }
 2574:                 }
 2575:             }
 2576: 	    my ($partid,$foo) = split(/submission$/,$key);
 2577: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2578: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2579: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2580: 	}
 2581:     }
 2582:     if (!@string) {
 2583: 	$string[0] =
 2584: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2585:     }
 2586:     return (\@string,\$timestamp);
 2587: }
 2588: 
 2589: #--- High light keywords, with style choosen by user.
 2590: sub keywords_highlight {
 2591:     my $string    = shift;
 2592:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2593:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2594:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2595:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2596:     foreach my $keyword (@keylist) {
 2597: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2598:     }
 2599:     return $string;
 2600: }
 2601: 
 2602: #--- Called from submission routine
 2603: sub processHandGrade {
 2604:     my ($request) = shift;
 2605:     my $symb   = &get_symb($request);
 2606:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2607:     my $button = $env{'form.gradeOpt'};
 2608:     my $ngrade = $env{'form.NCT'};
 2609:     my $ntstu  = $env{'form.NTSTU'};
 2610:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2611:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2612: 
 2613:     if ($button eq 'Save & Next') {
 2614: 	my $ctr = 0;
 2615: 	while ($ctr < $ngrade) {
 2616: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2617: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2618: 	    if ($errorflag eq 'no_score') {
 2619: 		$ctr++;
 2620: 		next;
 2621: 	    }
 2622: 	    if ($errorflag eq 'not_allowed') {
 2623: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2624: 		$ctr++;
 2625: 		next;
 2626: 	    }
 2627: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2628: 	    my ($subject,$message,$msgstatus) = ('','','');
 2629: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2630:             my ($feedurl,$showsymb) =
 2631: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2632: 	    my $messagetail;
 2633: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2634: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2635: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2636: 		$subject.=' ['.$restitle.']';
 2637: 		my (@msgnum) = split(/,/,$includemsg);
 2638: 		foreach (@msgnum) {
 2639: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2640: 		}
 2641: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2642: 		if ($env{'form.withgrades'.$ctr}) {
 2643: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2644: 		    $messagetail = " for <a href=\"".
 2645: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2646: 		}
 2647: 		$msgstatus = 
 2648:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2649: 						     $message.$messagetail,
 2650:                                                      undef,$feedurl,undef,
 2651:                                                      undef,undef,$showsymb,
 2652:                                                      $restitle);
 2653: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2654: 				$msgstatus.'<br />');
 2655: 	    }
 2656: 	    if ($env{'form.collaborator'.$ctr}) {
 2657: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2658: 		foreach my $collabstr (@collabstrs) {
 2659: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2660: 		    foreach my $collaborator (@collaborators) {
 2661: 			my ($errorflag,$pts,$wgt) = 
 2662: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2663: 					   $env{'form.unamedom'.$ctr},$part);
 2664: 			if ($errorflag eq 'not_allowed') {
 2665: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2666: 			    next;
 2667: 			} elsif ($message ne '') {
 2668: 			    my ($baseurl,$showsymb) = 
 2669: 				&get_feedurl_and_symb($symb,$collaborator,
 2670: 						      $udom);
 2671: 			    if ($env{'form.withgrades'.$ctr}) {
 2672: 				$messagetail = " for <a href=\"".
 2673:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2674: 			    }
 2675: 			    $msgstatus = 
 2676: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2677: 			}
 2678: 		    }
 2679: 		}
 2680: 	    }
 2681: 	    $ctr++;
 2682: 	}
 2683:     }
 2684: 
 2685:     if ($env{'form.handgrade'} eq 'yes') {
 2686: 	# Keywords sorted in alphabatical order
 2687: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2688: 	my %keyhash = ();
 2689: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2690: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2691: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2692: 	$env{'form.keywords'} = join(' ',@keywords);
 2693: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2694: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2695: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2696: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2697: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2698: 
 2699: 	# message center - Order of message gets changed. Blank line is eliminated.
 2700: 	# New messages are saved in env for the next student.
 2701: 	# All messages are saved in nohist_handgrade.db
 2702: 	my ($ctr,$idx) = (1,1);
 2703: 	while ($ctr <= $env{'form.savemsgN'}) {
 2704: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2705: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2706: 		$idx++;
 2707: 	    }
 2708: 	    $ctr++;
 2709: 	}
 2710: 	$ctr = 0;
 2711: 	while ($ctr < $ngrade) {
 2712: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2713: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2714: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2715: 		$idx++;
 2716: 	    }
 2717: 	    $ctr++;
 2718: 	}
 2719: 	$env{'form.savemsgN'} = --$idx;
 2720: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2721: 	my $putresult = &Apache::lonnet::put
 2722: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2723:     }
 2724:     # Called by Save & Refresh from Highlight Attribute Window
 2725:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2726:     if ($env{'form.refresh'} eq 'on') {
 2727: 	my ($ctr,$total) = (0,0);
 2728: 	while ($ctr < $ngrade) {
 2729: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2730: 	    $ctr++;
 2731: 	}
 2732: 	$env{'form.NTSTU'}=$ngrade;
 2733: 	$ctr = 0;
 2734: 	while ($ctr < $total) {
 2735: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2736: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2737: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2738: 	    &submission($request,$ctr,$total-1);
 2739: 	    $ctr++;
 2740: 	}
 2741: 	return '';
 2742:     }
 2743: 
 2744: # Go directly to grade student - from submission or link from chart page
 2745:     if ($button eq 'Grade Student') {
 2746: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2747: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2748: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2749: 	$env{'form.fullname'} = $$fullname{$processUser};
 2750: 	&submission($request,0,0);
 2751: 	return '';
 2752:     }
 2753: 
 2754:     # Get the next/previous one or group of students
 2755:     my $firststu = $env{'form.unamedom0'};
 2756:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2757:     my $ctr = 2;
 2758:     while ($laststu eq '') {
 2759: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2760: 	$ctr++;
 2761: 	$laststu = $firststu if ($ctr > $ngrade);
 2762:     }
 2763: 
 2764:     my (@parsedlist,@nextlist);
 2765:     my ($nextflg) = 0;
 2766:     foreach my $item (sort 
 2767: 	     {
 2768: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2769: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2770: 		 }
 2771: 		 return $a cmp $b;
 2772: 	     } (keys(%$fullname))) {
 2773: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2774: 	    push(@parsedlist,$item);
 2775: 	}
 2776: 	$nextflg = 1 if ($item eq $laststu);
 2777: 	if ($button eq 'Previous') {
 2778: 	    last if ($item eq $firststu);
 2779: 	    push(@parsedlist,$item);
 2780: 	}
 2781:     }
 2782:     $ctr = 0;
 2783:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2784:     my $res_error;
 2785:     my ($partlist) = &response_type($symb,\$res_error);
 2786:     if ($res_error) {
 2787:         $request->print(&navmap_errormsg());
 2788:         return;
 2789:     }
 2790:     foreach my $student (@parsedlist) {
 2791: 	my $submitonly=$env{'form.submitonly'};
 2792: 	my ($uname,$udom) = split(/:/,$student);
 2793: 	
 2794: 	if ($submitonly eq 'queued') {
 2795: 	    my %queue_status = 
 2796: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2797: 							$udom,$uname);
 2798: 	    next if (!defined($queue_status{'gradingqueue'}));
 2799: 	}
 2800: 
 2801: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2802: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2803: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2804: 	    my $submitted = 0;
 2805: 	    my $ungraded = 0;
 2806: 	    my $incorrect = 0;
 2807: 	    foreach my $item (keys(%status)) {
 2808: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2809: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2810: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2811: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2812: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2813: 		    $submitted = 0;
 2814: 		}
 2815: 	    }
 2816: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2817: 				     $submitonly eq 'incorrect' ||
 2818: 				     $submitonly eq 'graded'));
 2819: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2820: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2821: 	}
 2822: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2823: 	last if ($ctr == $ntstu);
 2824: 	$ctr++;
 2825:     }
 2826: 
 2827:     $ctr = 0;
 2828:     my $total = scalar(@nextlist)-1;
 2829: 
 2830:     foreach (sort(@nextlist)) {
 2831: 	my ($uname,$udom,$submitter) = split(/:/);
 2832: 	$env{'form.student'}  = $uname;
 2833: 	$env{'form.userdom'}  = $udom;
 2834: 	$env{'form.fullname'} = $$fullname{$_};
 2835: 	&submission($request,$ctr,$total);
 2836: 	$ctr++;
 2837:     }
 2838:     if ($total < 0) {
 2839: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2840: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2841: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2842: 	$the_end.=&show_grading_menu_form($symb);
 2843: 	$request->print($the_end);
 2844:     }
 2845:     return '';
 2846: }
 2847: 
 2848: #---- Save the score and award for each student, if changed
 2849: sub saveHandGrade {
 2850:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2851:     my @version_parts;
 2852:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2853: 					   $env{'request.course.id'});
 2854:     if (!&canmodify($usec)) { return('not_allowed'); }
 2855:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2856:     my @parts_graded;
 2857:     my %newrecord  = ();
 2858:     my ($pts,$wgt) = ('','');
 2859:     my %aggregate = ();
 2860:     my $aggregateflag = 0;
 2861:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2862:     foreach my $new_part (@parts) {
 2863: 	#collaborator ($submi may vary for different parts
 2864: 	if ($submitter && $new_part ne $part) { next; }
 2865: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2866: 	if ($dropMenu eq 'excused') {
 2867: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2868: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2869: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2870: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2871: 		}
 2872: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2873: 	    }
 2874: 	} elsif ($dropMenu eq 'reset status'
 2875: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2876: 	    foreach my $key (keys(%record)) {
 2877: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2878: 	    }
 2879: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2880: 		"$env{'user.name'}:$env{'user.domain'}";
 2881:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2882: 
 2883:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2884: 					       [$new_part]);
 2885:             my $aggtries =$totaltries;
 2886:             if ($last_resets{$new_part}) {
 2887:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2888: 					   $new_part);
 2889:             }
 2890: 
 2891:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2892:             if ($aggtries > 0) {
 2893:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2894:                 $aggregateflag = 1;
 2895:             }
 2896: 	} elsif ($dropMenu eq '') {
 2897: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2898: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2899: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2900: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2901: 		next;
 2902: 	    }
 2903: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2904: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2905: 	    my $partial= $pts/$wgt;
 2906: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2907: 		#do not update score for part if not changed.
 2908:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2909: 		next;
 2910: 	    } else {
 2911: 	        push(@parts_graded,$new_part);
 2912: 	    }
 2913: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2914: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2915: 	    }
 2916: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2917: 	    if ($partial == 0) {
 2918: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2919: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2920: 		}
 2921: 	    } else {
 2922: 		if ($record{$reckey} ne 'correct_by_override') {
 2923: 		    $newrecord{$reckey} = 'correct_by_override';
 2924: 		}
 2925: 	    }	    
 2926: 	    if ($submitter && 
 2927: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2928: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2929: 	    }
 2930: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2931: 		"$env{'user.name'}:$env{'user.domain'}";
 2932: 	}
 2933: 	# unless problem has been graded, set flag to version the submitted files
 2934: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2935: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2936: 	        $dropMenu eq 'reset status')
 2937: 	   {
 2938: 	    push(@version_parts,$new_part);
 2939: 	}
 2940:     }
 2941:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2942:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2943: 
 2944:     if (%newrecord) {
 2945:         if (@version_parts) {
 2946:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2947:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2948: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2949: 	    foreach my $new_part (@version_parts) {
 2950: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2951: 				$new_part,\%newrecord);
 2952: 	    }
 2953:         }
 2954: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2955: 				$env{'request.course.id'},$domain,$stuname);
 2956: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2957: 				     $cdom,$cnum,$domain,$stuname);
 2958:     }
 2959:     if ($aggregateflag) {
 2960:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2961: 			      $cdom,$cnum);
 2962:     }
 2963:     return ('',$pts,$wgt);
 2964: }
 2965: 
 2966: sub check_and_remove_from_queue {
 2967:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2968:     my @ungraded_parts;
 2969:     foreach my $part (@{$parts}) {
 2970: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2971: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2972: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2973: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2974: 		) {
 2975: 	    push(@ungraded_parts, $part);
 2976: 	}
 2977:     }
 2978:     if ( !@ungraded_parts ) {
 2979: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2980: 					       $cnum,$domain,$stuname);
 2981:     }
 2982: }
 2983: 
 2984: sub handback_files {
 2985:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2986:     my $portfolio_root = '/userfiles/portfolio';
 2987:     my $res_error;
 2988:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2989:     if ($res_error) {
 2990:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2991:         return;
 2992:     }
 2993:     my @handedback;
 2994:     my $file_msg;
 2995:     my @part_response_id = &flatten_responseType($responseType);
 2996:     foreach my $part_response_id (@part_response_id) {
 2997:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2998: 	my $part_resp = join('_',@{ $part_response_id });
 2999:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3000:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3001:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3002: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3003:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3004:                     my ($directory,$answer_file) = 
 3005:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3006:                     my ($answer_name,$answer_ver,$answer_ext) =
 3007: 		        &file_name_version_ext($answer_file);
 3008: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3009:                     my $getpropath = 1;
 3010: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 3011: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3012:                     # fix file name
 3013:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3014:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3015:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3016:             	                                $save_file_name);
 3017:                     if ($result !~ m|^/uploaded/|) {
 3018:                         $request->print('<br /><span class="LC_error">'.
 3019:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3020:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3021:                                         '</span>');
 3022:                     } else {
 3023:                         # mark the file as read only
 3024:                         push(@handedback,$save_file_name);
 3025: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3026: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3027: 			}
 3028:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3029: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3030: 
 3031:                     }
 3032:                     $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>'));
 3033:                 }
 3034:             }
 3035:         }
 3036:     }
 3037:     if (@handedback > 0) {
 3038:         $request->print('<br />');
 3039:         my @what = ($symb,$env{'request.course.id'},'handback');
 3040:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3041:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3042:         my ($subject,$message);
 3043:         if (scalar(@handedback) == 1) {
 3044:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3045:         } else {
 3046:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3047:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3048:         }
 3049:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3050:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3051:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3052:         my ($feedurl,$showsymb) =
 3053:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3054:         my $restitle = &Apache::lonnet::gettitle($symb);
 3055:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3056:         my $msgstatus =
 3057:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3058:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3059:                  $restitle);
 3060:         if ($msgstatus) {
 3061:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3062:         }
 3063:     }
 3064:     return;
 3065: }
 3066: 
 3067: sub get_feedurl_and_symb {
 3068:     my ($symb,$uname,$udom) = @_;
 3069:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3070:     $url = &Apache::lonnet::clutter($url);
 3071:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3072: 					$symb,$udom,$uname);
 3073:     if ($encrypturl =~ /^yes$/i) {
 3074: 	&Apache::lonenc::encrypted(\$url,1);
 3075: 	&Apache::lonenc::encrypted(\$symb,1);
 3076:     }
 3077:     return ($url,$symb);
 3078: }
 3079: 
 3080: sub get_submitted_files {
 3081:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3082:     my @files;
 3083:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3084:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3085:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3086:     	    push(@files,$file_url.$file);
 3087:         }
 3088:     }
 3089:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3090:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3091:     }
 3092:     return (\@files);
 3093: }
 3094: 
 3095: # ----------- Provides number of tries since last reset.
 3096: sub get_num_tries {
 3097:     my ($record,$last_reset,$part) = @_;
 3098:     my $timestamp = '';
 3099:     my $num_tries = 0;
 3100:     if ($$record{'version'}) {
 3101:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3102:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3103:                 $timestamp = $$record{$version.':timestamp'};
 3104:                 if ($timestamp > $last_reset) {
 3105:                     $num_tries ++;
 3106:                 } else {
 3107:                     last;
 3108:                 }
 3109:             }
 3110:         }
 3111:     }
 3112:     return $num_tries;
 3113: }
 3114: 
 3115: # ----------- Determine decrements required in aggregate totals 
 3116: sub decrement_aggs {
 3117:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3118:     my %decrement = (
 3119:                         attempts => 0,
 3120:                         users => 0,
 3121:                         correct => 0
 3122:                     );
 3123:     $decrement{'attempts'} = $aggtries;
 3124:     if ($solvedstatus =~ /^correct/) {
 3125:         $decrement{'correct'} = 1;
 3126:     }
 3127:     if ($aggtries == $totaltries) {
 3128:         $decrement{'users'} = 1;
 3129:     }
 3130:     foreach my $type (keys(%decrement)) {
 3131:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3132:     }
 3133:     return;
 3134: }
 3135: 
 3136: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3137: sub get_last_resets {
 3138:     my ($symb,$courseid,$partids) =@_;
 3139:     my %last_resets;
 3140:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3141:     my $cname = $env{'course.'.$courseid.'.num'};
 3142:     my @keys;
 3143:     foreach my $part (@{$partids}) {
 3144: 	push(@keys,"$symb\0$part\0resettime");
 3145:     }
 3146:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3147: 				     $cdom,$cname);
 3148:     foreach my $part (@{$partids}) {
 3149: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3150:     }
 3151:     return %last_resets;
 3152: }
 3153: 
 3154: # ----------- Handles creating versions for portfolio files as answers
 3155: sub version_portfiles {
 3156:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3157:     my $version_parts = join('|',@$v_flag);
 3158:     my @returned_keys;
 3159:     my $parts = join('|', @$parts_graded);
 3160:     my $portfolio_root = '/userfiles/portfolio';
 3161:     foreach my $key (keys(%$record)) {
 3162:         my $new_portfiles;
 3163:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3164:             my @versioned_portfiles;
 3165:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3166:             foreach my $file (@portfiles) {
 3167:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3168:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3169: 		my ($answer_name,$answer_ver,$answer_ext) =
 3170: 		    &file_name_version_ext($answer_file);
 3171:                 my $getpropath = 1;    
 3172:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3173:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3174:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3175:                 if ($new_answer ne 'problem getting file') {
 3176:                     push(@versioned_portfiles, $directory.$new_answer);
 3177:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3178:                         [$directory.$new_answer],
 3179:                         [$symb,$env{'request.course.id'},'graded']);
 3180:                 }
 3181:             }
 3182:             $$record{$key} = join(',',@versioned_portfiles);
 3183:             push(@returned_keys,$key);
 3184:         }
 3185:     } 
 3186:     return (@returned_keys);   
 3187: }
 3188: 
 3189: sub get_next_version {
 3190:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3191:     my $version;
 3192:     foreach my $row (@$dir_list) {
 3193:         my ($file) = split(/\&/,$row,2);
 3194:         my ($file_name,$file_version,$file_ext) =
 3195: 	    &file_name_version_ext($file);
 3196:         if (($file_name eq $answer_name) && 
 3197: 	    ($file_ext eq $answer_ext)) {
 3198:                 # gets here if filename and extension match, regardless of version
 3199:                 if ($file_version ne '') {
 3200:                 # a versioned file is found  so save it for later
 3201:                 if ($file_version > $version) {
 3202: 		    $version = $file_version;
 3203: 	        }
 3204:             }
 3205:         }
 3206:     } 
 3207:     $version ++;
 3208:     return($version);
 3209: }
 3210: 
 3211: sub version_selected_portfile {
 3212:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3213:     my ($answer_name,$answer_ver,$answer_ext) =
 3214:         &file_name_version_ext($file_name);
 3215:     my $new_answer;
 3216:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3217:     if($env{'form.copy'} eq '-1') {
 3218:         $new_answer = 'problem getting file';
 3219:     } else {
 3220:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3221:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3222:                             $stu_name,$domain,'copy',
 3223: 		        '/portfolio'.$directory.$new_answer);
 3224:     }    
 3225:     return ($new_answer);
 3226: }
 3227: 
 3228: sub file_name_version_ext {
 3229:     my ($file)=@_;
 3230:     my @file_parts = split(/\./, $file);
 3231:     my ($name,$version,$ext);
 3232:     if (@file_parts > 1) {
 3233: 	$ext=pop(@file_parts);
 3234: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3235: 	    $version=pop(@file_parts);
 3236: 	}
 3237: 	$name=join('.',@file_parts);
 3238:     } else {
 3239: 	$name=join('.',@file_parts);
 3240:     }
 3241:     return($name,$version,$ext);
 3242: }
 3243: 
 3244: #--------------------------------------------------------------------------------------
 3245: #
 3246: #-------------------------- Next few routines handles grading by section or whole class
 3247: #
 3248: #--- Javascript to handle grading by section or whole class
 3249: sub viewgrades_js {
 3250:     my ($request) = shift;
 3251: 
 3252:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3253:     $request->print(<<VIEWJAVASCRIPT);
 3254: <script type="text/javascript" language="javascript">
 3255:    function writePoint(partid,weight,point) {
 3256: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3257: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3258: 	if (point == "textval") {
 3259: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3260: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3261: 		alert("$alertmsg"+parseFloat(point));
 3262: 		var resetbox = false;
 3263: 		for (var i=0; i<radioButton.length; i++) {
 3264: 		    if (radioButton[i].checked) {
 3265: 			textbox.value = i;
 3266: 			resetbox = true;
 3267: 		    }
 3268: 		}
 3269: 		if (!resetbox) {
 3270: 		    textbox.value = "";
 3271: 		}
 3272: 		return;
 3273: 	    }
 3274: 	    if (parseFloat(point) > parseFloat(weight)) {
 3275: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3276: 				   ") greater than the weight for the part. Accept?");
 3277: 		if (resp == false) {
 3278: 		    textbox.value = "";
 3279: 		    return;
 3280: 		}
 3281: 	    }
 3282: 	    for (var i=0; i<radioButton.length; i++) {
 3283: 		radioButton[i].checked=false;
 3284: 		if (parseFloat(point) == i) {
 3285: 		    radioButton[i].checked=true;
 3286: 		}
 3287: 	    }
 3288: 
 3289: 	} else {
 3290: 	    textbox.value = parseFloat(point);
 3291: 	}
 3292: 	for (i=0;i<document.classgrade.total.value;i++) {
 3293: 	    var user = document.classgrade["ctr"+i].value;
 3294: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3295: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3296: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3297: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3298: 	    if (saveval != "correct") {
 3299: 		scorename.value = point;
 3300: 		if (selname[0].selected != true) {
 3301: 		    selname[0].selected = true;
 3302: 		}
 3303: 	    }
 3304: 	}
 3305: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3306:     }
 3307: 
 3308:     function writeRadText(partid,weight) {
 3309: 	var selval   = document.classgrade["SELVAL_"+partid];
 3310: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3311:         var override = document.classgrade["FORCE_"+partid].checked;
 3312: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3313: 	if (selval[1].selected || selval[2].selected) {
 3314: 	    for (var i=0; i<radioButton.length; i++) {
 3315: 		radioButton[i].checked=false;
 3316: 
 3317: 	    }
 3318: 	    textbox.value = "";
 3319: 
 3320: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3321: 		var user = document.classgrade["ctr"+i].value;
 3322: 		user = user.replace(new RegExp(':', 'g'),"_");
 3323: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3324: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3325: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3326: 		if ((saveval != "correct") || override) {
 3327: 		    scorename.value = "";
 3328: 		    if (selval[1].selected) {
 3329: 			selname[1].selected = true;
 3330: 		    } else {
 3331: 			selname[2].selected = true;
 3332: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3333: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3334: 		    }
 3335: 		}
 3336: 	    }
 3337: 	} else {
 3338: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3339: 		var user = document.classgrade["ctr"+i].value;
 3340: 		user = user.replace(new RegExp(':', 'g'),"_");
 3341: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3342: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3343: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3344: 		if ((saveval != "correct") || override) {
 3345: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3346: 		    selname[0].selected = true;
 3347: 		}
 3348: 	    }
 3349: 	}	    
 3350:     }
 3351: 
 3352:     function changeSelect(partid,user) {
 3353: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3354: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3355: 	var point  = textbox.value;
 3356: 	var weight = document.classgrade["weight_"+partid].value;
 3357: 
 3358: 	if (isNaN(point) || parseFloat(point) < 0) {
 3359: 	    alert("$alertmsg"+parseFloat(point));
 3360: 	    textbox.value = "";
 3361: 	    return;
 3362: 	}
 3363: 	if (parseFloat(point) > parseFloat(weight)) {
 3364: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3365: 			       ") greater than the weight of the part. Accept?");
 3366: 	    if (resp == false) {
 3367: 		textbox.value = "";
 3368: 		return;
 3369: 	    }
 3370: 	}
 3371: 	selval[0].selected = true;
 3372:     }
 3373: 
 3374:     function changeOneScore(partid,user) {
 3375: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3376: 	if (selval[1].selected || selval[2].selected) {
 3377: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3378: 	    if (selval[2].selected) {
 3379: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3380: 	    }
 3381:         }
 3382:     }
 3383: 
 3384:     function resetEntry(numpart) {
 3385: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3386: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3387: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3388: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3389: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3390: 	    for (var i=0; i<radioButton.length; i++) {
 3391: 		radioButton[i].checked=false;
 3392: 
 3393: 	    }
 3394: 	    textbox.value = "";
 3395: 	    selval[0].selected = true;
 3396: 
 3397: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3398: 		var user = document.classgrade["ctr"+i].value;
 3399: 		user = user.replace(new RegExp(':', 'g'),"_");
 3400: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3401: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3402: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3403: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3404: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3405: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3406: 		if (saveselval == "excused") {
 3407: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3408: 		} else {
 3409: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3410: 		}
 3411: 	    }
 3412: 	}
 3413:     }
 3414: 
 3415: </script>
 3416: VIEWJAVASCRIPT
 3417: }
 3418: 
 3419: #--- show scores for a section or whole class w/ option to change/update a score
 3420: sub viewgrades {
 3421:     my ($request) = shift;
 3422:     &viewgrades_js($request);
 3423: 
 3424:     my ($symb) = &get_symb($request);
 3425:     #need to make sure we have the correct data for later EXT calls, 
 3426:     #thus invalidate the cache
 3427:     &Apache::lonnet::devalidatecourseresdata(
 3428:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3429:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3430:     &Apache::lonnet::clear_EXT_cache_status();
 3431: 
 3432:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3433:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3434: 
 3435:     #view individual student submission form - called using Javascript viewOneStudent
 3436:     $result.=&jscriptNform($symb);
 3437: 
 3438:     #beginning of class grading form
 3439:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3440:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3441: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3442: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3443: 	&build_section_inputs().
 3444: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3445: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3446: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3447: 
 3448:     my ($common_header,$specific_header);
 3449:     if ($env{'form.section'} eq 'all') {
 3450: 	$common_header = &mt('Assign Common Grade to Class');
 3451:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3452:     } elsif ($env{'form.section'} eq 'none') {
 3453:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3454: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3455:     } else {
 3456:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3457:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3458: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3459:     }
 3460:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3461:     #radio buttons/text box for assigning points for a section or class.
 3462:     #handles different parts of a problem
 3463:     my $res_error;
 3464:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3465:     if ($res_error) {
 3466:         return &navmap_errormsg();
 3467:     }
 3468:     my %weight = ();
 3469:     my $ctsparts = 0;
 3470:     my %seen = ();
 3471:     my @part_response_id = &flatten_responseType($responseType);
 3472:     foreach my $part_response_id (@part_response_id) {
 3473:     	my ($partid,$respid) = @{ $part_response_id };
 3474: 	my $part_resp = join('_',@{ $part_response_id });
 3475: 	next if $seen{$partid};
 3476: 	$seen{$partid}++;
 3477: 	my $handgrade=$$handgrade{$part_resp};
 3478: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3479: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3480: 
 3481: 	my $display_part=&get_display_part($partid,$symb);
 3482: 	my $radio.='<table border="0"><tr>';  
 3483: 	my $ctr = 0;
 3484: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3485: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3486: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3487: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3488: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3489: 	    $ctr++;
 3490: 	}
 3491: 	$radio.='</tr></table>';
 3492: 	my $line = '<input type="text" name="TEXTVAL_'.
 3493: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3494: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3495: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3496: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3497: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3498: 		$weight{$partid}.')"> '.
 3499: 	    '<option selected="selected"> </option>'.
 3500: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3501: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3502: 	    '</select></td>'.
 3503:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3504: 	$line.='<input type="hidden" name="partid_'.
 3505: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3506: 	$line.='<input type="hidden" name="weight_'.
 3507: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3508: 
 3509: 	$result.=
 3510: 	    &Apache::loncommon::start_data_table_row()."\n".
 3511: 	    '<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>'.
 3512: 	    &Apache::loncommon::end_data_table_row()."\n";
 3513: 	$ctsparts++;
 3514:     }
 3515:     $result.=&Apache::loncommon::end_data_table()."\n".
 3516: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3517:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3518: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3519: 
 3520:     #table listing all the students in a section/class
 3521:     #header of table
 3522:     $result.= '<h3>'.$specific_header.'</h3>'.
 3523:               &Apache::loncommon::start_data_table().
 3524: 	      &Apache::loncommon::start_data_table_header_row().
 3525: 	      '<th>'.&mt('No.').'</th>'.
 3526: 	      '<th>'.&nameUserString('header')."</th>\n";
 3527:     my $partserror;
 3528:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3529:     if ($partserror) {
 3530:         return &navmap_errormsg();
 3531:     }
 3532:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3533:     my @partids = ();
 3534:     foreach my $part (@parts) {
 3535: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3536:         my $narrowtext = &mt('Tries');
 3537: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3538: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3539: 	my ($partid) = &split_part_type($part);
 3540:         push(@partids,$partid);
 3541: 	my $display_part=&get_display_part($partid,$symb);
 3542: 	if ($display =~ /^Partial Credit Factor/) {
 3543: 	    $result.='<th>'.
 3544: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3545: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3546: 	    next;
 3547: 	    
 3548: 	} else {
 3549: 	    if ($display =~ /Problem Status/) {
 3550: 		my $grade_status_mt = &mt('Grade Status');
 3551: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3552: 	    }
 3553: 	    my $part_mt = &mt('Part:');
 3554: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3555: 	}
 3556: 
 3557: 	$result.='<th>'.$display.'</th>'."\n";
 3558:     }
 3559:     $result.=&Apache::loncommon::end_data_table_header_row();
 3560: 
 3561:     my %last_resets = 
 3562: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3563: 
 3564:     #get info for each student
 3565:     #list all the students - with points and grade status
 3566:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3567:     my $ctr = 0;
 3568:     foreach (sort 
 3569: 	     {
 3570: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3571: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3572: 		 }
 3573: 		 return $a cmp $b;
 3574: 	     } (keys(%$fullname))) {
 3575: 	$ctr++;
 3576: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3577: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3578:     }
 3579:     $result.=&Apache::loncommon::end_data_table();
 3580:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3581:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3582: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3583:     if (scalar(%$fullname) eq 0) {
 3584: 	my $colspan=3+scalar(@parts);
 3585: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3586:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3587: 	$result='<span class="LC_warning">'.
 3588: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3589: 	        $section_display, $stu_status).
 3590: 	    '</span>';
 3591:     }
 3592:     $result.=&show_grading_menu_form($symb);
 3593:     return $result;
 3594: }
 3595: 
 3596: #--- call by previous routine to display each student
 3597: sub viewstudentgrade {
 3598:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3599:     my ($uname,$udom) = split(/:/,$student);
 3600:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3601:     my %aggregates = (); 
 3602:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3603: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3604: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3605: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3606: 	'\');" target="_self">'.$fullname.'</a> '.
 3607: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3608:     $student=~s/:/_/; # colon doen't work in javascript for names
 3609:     foreach my $apart (@$parts) {
 3610: 	my ($part,$type) = &split_part_type($apart);
 3611: 	my $score=$record{"resource.$part.$type"};
 3612:         $result.='<td align="center">';
 3613:         my ($aggtries,$totaltries);
 3614:         unless (exists($aggregates{$part})) {
 3615: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3616: 
 3617: 	    $aggtries = $totaltries;
 3618:             if ($$last_resets{$part}) {  
 3619:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3620: 					   $part);
 3621:             }
 3622:             $result.='<input type="hidden" name="'.
 3623:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3624:             $result.='<input type="hidden" name="'.
 3625:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3626:             $aggregates{$part} = 1;
 3627:         }
 3628: 	if ($type eq 'awarded') {
 3629: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3630: 	    $result.='<input type="hidden" name="'.
 3631: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3632: 	    $result.='<input type="text" name="'.
 3633: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3634:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3635: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3636: 	} elsif ($type eq 'solved') {
 3637: 	    my ($status,$foo)=split(/_/,$score,2);
 3638: 	    $status = 'nothing' if ($status eq '');
 3639: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3640: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3641: 	    $result.='&nbsp;<select name="'.
 3642: 		'GD_'.$student.'_'.$part.'_solved" '.
 3643:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3644: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3645: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3646: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3647: 	    $result.="</select>&nbsp;</td>\n";
 3648: 	} else {
 3649: 	    $result.='<input type="hidden" name="'.
 3650: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3651: 		    "\n";
 3652: 	    $result.='<input type="text" name="'.
 3653: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3654: 		'value="'.$score.'" size="4" /></td>'."\n";
 3655: 	}
 3656:     }
 3657:     $result.=&Apache::loncommon::end_data_table_row();
 3658:     return $result;
 3659: }
 3660: 
 3661: #--- change scores for all the students in a section/class
 3662: #    record does not get update if unchanged
 3663: sub editgrades {
 3664:     my ($request) = @_;
 3665: 
 3666:     my $symb=&get_symb($request);
 3667:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3668:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3669:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3670:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3671: 
 3672:     my $result= &Apache::loncommon::start_data_table().
 3673: 	&Apache::loncommon::start_data_table_header_row().
 3674: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3675: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3676:     my %scoreptr = (
 3677: 		    'correct'  =>'correct_by_override',
 3678: 		    'incorrect'=>'incorrect_by_override',
 3679: 		    'excused'  =>'excused',
 3680: 		    'ungraded' =>'ungraded_attempted',
 3681:                     'credited' =>'credit_attempted',
 3682: 		    'nothing'  => '',
 3683: 		    );
 3684:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3685: 
 3686:     my (@partid);
 3687:     my %weight = ();
 3688:     my %columns = ();
 3689:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3690: 
 3691:     my $partserror;
 3692:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3693:     if ($partserror) {
 3694:         return &navmap_errormsg();
 3695:     }
 3696:     my $header;
 3697:     while ($ctr < $env{'form.totalparts'}) {
 3698: 	my $partid = $env{'form.partid_'.$ctr};
 3699: 	push(@partid,$partid);
 3700: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3701: 	$ctr++;
 3702:     }
 3703:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3704:     foreach my $partid (@partid) {
 3705: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3706: 	    '<th align="center">'.&mt('New Score').'</th>';
 3707: 	$columns{$partid}=2;
 3708: 	foreach my $stores (@parts) {
 3709: 	    my ($part,$type) = &split_part_type($stores);
 3710: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3711: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3712: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3713: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3714:             my $narrowtext = &mt('Tries');
 3715: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3716: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3717: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3718: 	    $columns{$partid}+=2;
 3719: 	}
 3720:     }
 3721:     foreach my $partid (@partid) {
 3722: 	my $display_part=&get_display_part($partid,$symb);
 3723: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3724: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3725: 	    '</th>';
 3726: 
 3727:     }
 3728:     $result .= &Apache::loncommon::end_data_table_header_row().
 3729: 	&Apache::loncommon::start_data_table_header_row().
 3730: 	$header.
 3731: 	&Apache::loncommon::end_data_table_header_row();
 3732:     my @noupdate;
 3733:     my ($updateCtr,$noupdateCtr) = (1,1);
 3734:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3735: 	my $line;
 3736: 	my $user = $env{'form.ctr'.$i};
 3737: 	my ($uname,$udom)=split(/:/,$user);
 3738: 	my %newrecord;
 3739: 	my $updateflag = 0;
 3740: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3741: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3742: 	if (!&canmodify($usec)) {
 3743: 	    my $numcols=scalar(@partid)*4+2;
 3744: 	    push(@noupdate,
 3745: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3746: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3747: 	    next;
 3748: 	}
 3749:         my %aggregate = ();
 3750:         my $aggregateflag = 0;
 3751: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3752: 	foreach (@partid) {
 3753: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3754: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3755: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3756: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3757: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3758: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3759: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3760: 	    my $score;
 3761: 	    if ($partial eq '') {
 3762: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3763: 	    } elsif ($partial > 0) {
 3764: 		$score = 'correct_by_override';
 3765: 	    } elsif ($partial == 0) {
 3766: 		$score = 'incorrect_by_override';
 3767: 	    }
 3768: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3769: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3770: 
 3771: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3772: 		"$env{'user.name'}:$env{'user.domain'}";
 3773: 	    if ($dropMenu eq 'reset status' &&
 3774: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3775: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3776: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3777: 		$newrecord{'resource.'.$_.'.award'} = '';
 3778: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3779: 		$updateflag = 1;
 3780:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3781:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3782:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3783:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3784:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3785:                     $aggregateflag = 1;
 3786:                 }
 3787: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3788: 		$updateflag = 1;
 3789: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3790: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3791: 		$rec_update++;
 3792: 	    }
 3793: 
 3794: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3795: 		'<td align="center">'.$awarded.
 3796: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3797: 
 3798: 
 3799: 	    my $partid=$_;
 3800: 	    foreach my $stores (@parts) {
 3801: 		my ($part,$type) = &split_part_type($stores);
 3802: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3803: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3804: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3805: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3806: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3807: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3808: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3809: 		    $updateflag=1;
 3810: 		}
 3811: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3812: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3813: 	    }
 3814: 	}
 3815: 	$line.="\n";
 3816: 
 3817: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3818: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3819: 
 3820: 	if ($updateflag) {
 3821: 	    $count++;
 3822: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3823: 				    $udom,$uname);
 3824: 
 3825: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3826: 					      $cnum,$udom,$uname)) {
 3827: 		# need to figure out if should be in queue.
 3828: 		my %record =  
 3829: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3830: 					     $udom,$uname);
 3831: 		my $all_graded = 1;
 3832: 		my $none_graded = 1;
 3833: 		foreach my $part (@parts) {
 3834: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3835: 			$all_graded = 0;
 3836: 		    } else {
 3837: 			$none_graded = 0;
 3838: 		    }
 3839: 		}
 3840: 
 3841: 		if ($all_graded || $none_graded) {
 3842: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3843: 							   $symb,$cdom,$cnum,
 3844: 							   $udom,$uname);
 3845: 		}
 3846: 	    }
 3847: 
 3848: 	    $result.=&Apache::loncommon::start_data_table_row().
 3849: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3850: 		&Apache::loncommon::end_data_table_row();
 3851: 	    $updateCtr++;
 3852: 	} else {
 3853: 	    push(@noupdate,
 3854: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3855: 	    $noupdateCtr++;
 3856: 	}
 3857:         if ($aggregateflag) {
 3858:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3859: 				  $cdom,$cnum);
 3860:         }
 3861:     }
 3862:     if (@noupdate) {
 3863: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3864: 	my $numcols=scalar(@partid)*4+2;
 3865: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3866: 	    '<td align="center" colspan="'.$numcols.'">'.
 3867: 	    &mt('No Changes Occurred For the Students Below').
 3868: 	    '</td>'.
 3869: 	    &Apache::loncommon::end_data_table_row();
 3870: 	foreach my $line (@noupdate) {
 3871: 	    $result.=
 3872: 		&Apache::loncommon::start_data_table_row().
 3873: 		$line.
 3874: 		&Apache::loncommon::end_data_table_row();
 3875: 	}
 3876:     }
 3877:     $result .= &Apache::loncommon::end_data_table().
 3878: 	&show_grading_menu_form($symb);
 3879:     my $msg = '<p><b>'.
 3880: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3881: 	    $rec_update,$count).'</b><br />'.
 3882: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3883: 	'</b></p>';
 3884:     return $title.$msg.$result;
 3885: }
 3886: 
 3887: sub split_part_type {
 3888:     my ($partstr) = @_;
 3889:     my ($temp,@allparts)=split(/_/,$partstr);
 3890:     my $type=pop(@allparts);
 3891:     my $part=join('_',@allparts);
 3892:     return ($part,$type);
 3893: }
 3894: 
 3895: #------------- end of section for handling grading by section/class ---------
 3896: #
 3897: #----------------------------------------------------------------------------
 3898: 
 3899: 
 3900: #----------------------------------------------------------------------------
 3901: #
 3902: #-------------------------- Next few routines handles grading by csv upload
 3903: #
 3904: #--- Javascript to handle csv upload
 3905: sub csvupload_javascript_reverse_associate {
 3906:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3907:     my $error2=&mt('You need to specify at least one grading field');
 3908:   return(<<ENDPICK);
 3909:   function verify(vf) {
 3910:     var foundsomething=0;
 3911:     var founduname=0;
 3912:     var foundID=0;
 3913:     for (i=0;i<=vf.nfields.value;i++) {
 3914:       tw=eval('vf.f'+i+'.selectedIndex');
 3915:       if (i==0 && tw!=0) { foundID=1; }
 3916:       if (i==1 && tw!=0) { founduname=1; }
 3917:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3918:     }
 3919:     if (founduname==0 && foundID==0) {
 3920: 	alert('$error1');
 3921: 	return;
 3922:     }
 3923:     if (foundsomething==0) {
 3924: 	alert('$error2');
 3925: 	return;
 3926:     }
 3927:     vf.submit();
 3928:   }
 3929:   function flip(vf,tf) {
 3930:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3931:     var i;
 3932:     for (i=0;i<=vf.nfields.value;i++) {
 3933:       //can not pick the same destination field for both name and domain
 3934:       if (((i ==0)||(i ==1)) && 
 3935:           ((tf==0)||(tf==1)) && 
 3936:           (i!=tf) &&
 3937:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3938:         eval('vf.f'+i+'.selectedIndex=0;')
 3939:       }
 3940:     }
 3941:   }
 3942: ENDPICK
 3943: }
 3944: 
 3945: sub csvupload_javascript_forward_associate {
 3946:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3947:     my $error2=&mt('You need to specify at least one grading field');
 3948:   return(<<ENDPICK);
 3949:   function verify(vf) {
 3950:     var foundsomething=0;
 3951:     var founduname=0;
 3952:     var foundID=0;
 3953:     for (i=0;i<=vf.nfields.value;i++) {
 3954:       tw=eval('vf.f'+i+'.selectedIndex');
 3955:       if (tw==1) { foundID=1; }
 3956:       if (tw==2) { founduname=1; }
 3957:       if (tw>3) { foundsomething=1; }
 3958:     }
 3959:     if (founduname==0 && foundID==0) {
 3960: 	alert('$error1');
 3961: 	return;
 3962:     }
 3963:     if (foundsomething==0) {
 3964: 	alert('$error2');
 3965: 	return;
 3966:     }
 3967:     vf.submit();
 3968:   }
 3969:   function flip(vf,tf) {
 3970:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3971:     var i;
 3972:     //can not pick the same destination field twice
 3973:     for (i=0;i<=vf.nfields.value;i++) {
 3974:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3975:         eval('vf.f'+i+'.selectedIndex=0;')
 3976:       }
 3977:     }
 3978:   }
 3979: ENDPICK
 3980: }
 3981: 
 3982: sub csvuploadmap_header {
 3983:     my ($request,$symb,$datatoken,$distotal)= @_;
 3984:     my $javascript;
 3985:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3986: 	$javascript=&csvupload_javascript_reverse_associate();
 3987:     } else {
 3988: 	$javascript=&csvupload_javascript_forward_associate();
 3989:     }
 3990: 
 3991:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3992:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3993:     my $ignore=&mt('Ignore First Line');
 3994:     $symb = &Apache::lonenc::check_encrypt($symb);
 3995:     $request->print(<<ENDPICK);
 3996: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3997: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3998: $result
 3999: <hr />
 4000: <h3>Identify fields</h3>
 4001: Total number of records found in file: $distotal <hr />
 4002: Enter as many fields as you can. The system will inform you and bring you back
 4003: to this page if the data selected is insufficient to run your class.<hr />
 4004: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4005: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4006: <input type="hidden" name="associate"  value="" />
 4007: <input type="hidden" name="phase"      value="three" />
 4008: <input type="hidden" name="datatoken"  value="$datatoken" />
 4009: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4010: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4011: <input type="hidden" name="upfile_associate" 
 4012:                                        value="$env{'form.upfile_associate'}" />
 4013: <input type="hidden" name="symb"       value="$symb" />
 4014: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4015: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4016: <input type="hidden" name="command"    value="csvuploadoptions" />
 4017: <hr />
 4018: <script type="text/javascript" language="Javascript">
 4019: $javascript
 4020: </script>
 4021: ENDPICK
 4022:     return '';
 4023: 
 4024: }
 4025: 
 4026: sub csvupload_fields {
 4027:     my ($symb,$errorref) = @_;
 4028:     my (@parts) = &getpartlist($symb,$errorref);
 4029:     if (ref($errorref)) {
 4030:         if ($$errorref) {
 4031:             return;
 4032:         }
 4033:     }
 4034: 
 4035:     my @fields=(['ID','Student/Employee ID'],
 4036: 		['username','Student Username'],
 4037: 		['domain','Student Domain']);
 4038:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4039:     foreach my $part (sort(@parts)) {
 4040: 	my @datum;
 4041: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4042: 	my $name=$part;
 4043: 	if  (!$display) { $display = $name; }
 4044: 	@datum=($name,$display);
 4045: 	if ($name=~/^stores_(.*)_awarded/) {
 4046: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4047: 	}
 4048: 	push(@fields,\@datum);
 4049:     }
 4050:     return (@fields);
 4051: }
 4052: 
 4053: sub csvuploadmap_footer {
 4054:     my ($request,$i,$keyfields) =@_;
 4055:     $request->print(<<ENDPICK);
 4056: </table>
 4057: <input type="hidden" name="nfields" value="$i" />
 4058: <input type="hidden" name="keyfields" value="$keyfields" />
 4059: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 4060: </form>
 4061: ENDPICK
 4062: }
 4063: 
 4064: sub checkforfile_js {
 4065:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4066:     my $result =<<CSVFORMJS;
 4067: <script type="text/javascript" language="javascript">
 4068:     function checkUpload(formname) {
 4069: 	if (formname.upfile.value == "") {
 4070: 	    alert("$alertmsg");
 4071: 	    return false;
 4072: 	}
 4073: 	formname.submit();
 4074:     }
 4075:     </script>
 4076: CSVFORMJS
 4077:     return $result;
 4078: }
 4079: 
 4080: sub upcsvScores_form {
 4081:     my ($request) = shift;
 4082:     my ($symb)=&get_symb($request);
 4083:     if (!$symb) {return '';}
 4084:     my $result=&checkforfile_js();
 4085:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4086:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4087:     $result.=$table;
 4088:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4089:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4090:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4091: 	'</b></td></tr>'."\n";
 4092:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4093:     my $upload=&mt("Upload Scores");
 4094:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4095:     my $ignore=&mt('Ignore First Line');
 4096:     $symb = &Apache::lonenc::check_encrypt($symb);
 4097:     $result.=<<ENDUPFORM;
 4098: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4099: <input type="hidden" name="symb" value="$symb" />
 4100: <input type="hidden" name="command" value="csvuploadmap" />
 4101: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4102: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4103: $upfile_select
 4104: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4105: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4106: </form>
 4107: ENDUPFORM
 4108:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4109:                            &mt("How do I create a CSV file from a spreadsheet"))
 4110:     .'</td></tr></table>'."\n";
 4111:     $result.='</td></tr></table><br /><br />'."\n";
 4112:     $result.=&show_grading_menu_form($symb);
 4113:     return $result;
 4114: }
 4115: 
 4116: 
 4117: sub csvuploadmap {
 4118:     my ($request)= @_;
 4119:     my ($symb)=&get_symb($request);
 4120:     if (!$symb) {return '';}
 4121: 
 4122:     my $datatoken;
 4123:     if (!$env{'form.datatoken'}) {
 4124: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4125:     } else {
 4126: 	$datatoken=$env{'form.datatoken'};
 4127: 	&Apache::loncommon::load_tmp_file($request);
 4128:     }
 4129:     my @records=&Apache::loncommon::upfile_record_sep();
 4130:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4131:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4132:     my ($i,$keyfields);
 4133:     if (@records) {
 4134:         my $fieldserror;
 4135: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4136:         if ($fieldserror) {
 4137:             $request->print(&navmap_errormsg());
 4138:             return;
 4139:         }
 4140: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4141: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4142: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4143: 							  \@fields);
 4144: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4145: 	    chop($keyfields);
 4146: 	} else {
 4147: 	    unshift(@fields,['none','']);
 4148: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4149: 							    \@fields);
 4150:             foreach my $rec (@records) {
 4151:                 my %temp = &Apache::loncommon::record_sep($rec);
 4152:                 if (%temp) {
 4153:                     $keyfields=join(',',sort(keys(%temp)));
 4154:                     last;
 4155:                 }
 4156:             }
 4157: 	}
 4158:     }
 4159:     &csvuploadmap_footer($request,$i,$keyfields);
 4160:     $request->print(&show_grading_menu_form($symb));
 4161: 
 4162:     return '';
 4163: }
 4164: 
 4165: sub csvuploadoptions {
 4166:     my ($request)= @_;
 4167:     my ($symb)=&get_symb($request);
 4168:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4169:     my $ignore=&mt('Ignore First Line');
 4170:     $request->print(<<ENDPICK);
 4171: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4172: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4173: <input type="hidden" name="command"    value="csvuploadassign" />
 4174: <!--
 4175: <p>
 4176: <label>
 4177:    <input type="checkbox" name="show_full_results" />
 4178:    Show a table of all changes
 4179: </label>
 4180: </p>
 4181: -->
 4182: <p>
 4183: <label>
 4184:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4185:    Overwrite any existing score
 4186: </label>
 4187: </p>
 4188: ENDPICK
 4189:     my %fields=&get_fields();
 4190:     if (!defined($fields{'domain'})) {
 4191: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4192: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4193:     }
 4194:     foreach my $key (sort(keys(%env))) {
 4195: 	if ($key !~ /^form\.(.*)$/) { next; }
 4196: 	my $cleankey=$1;
 4197: 	if ($cleankey eq 'command') { next; }
 4198: 	$request->print('<input type="hidden" name="'.$cleankey.
 4199: 			'"  value="'.$env{$key}.'" />'."\n");
 4200:     }
 4201:     # FIXME do a check for any duplicated user ids...
 4202:     # FIXME do a check for any invalid user ids?...
 4203:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4204: <hr /></form>'."\n");
 4205:     $request->print(&show_grading_menu_form($symb));
 4206:     return '';
 4207: }
 4208: 
 4209: sub get_fields {
 4210:     my %fields;
 4211:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4212:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4213: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4214: 	    if ($env{'form.f'.$i} ne 'none') {
 4215: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4216: 	    }
 4217: 	} else {
 4218: 	    if ($env{'form.f'.$i} ne 'none') {
 4219: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4220: 	    }
 4221: 	}
 4222:     }
 4223:     return %fields;
 4224: }
 4225: 
 4226: sub csvuploadassign {
 4227:     my ($request)= @_;
 4228:     my ($symb)=&get_symb($request);
 4229:     if (!$symb) {return '';}
 4230:     my $error_msg = '';
 4231:     &Apache::loncommon::load_tmp_file($request);
 4232:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4233:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4234:     my %fields=&get_fields();
 4235:     $request->print('<h3>Assigning Grades</h3>');
 4236:     my $courseid=$env{'request.course.id'};
 4237:     my ($classlist) = &getclasslist('all',0);
 4238:     my @notallowed;
 4239:     my @skipped;
 4240:     my @warnings;
 4241:     my $countdone=0;
 4242:     foreach my $grade (@gradedata) {
 4243: 	my %entries=&Apache::loncommon::record_sep($grade);
 4244: 	my $domain;
 4245: 	if ($entries{$fields{'domain'}}) {
 4246: 	    $domain=$entries{$fields{'domain'}};
 4247: 	} else {
 4248: 	    $domain=$env{'form.default_domain'};
 4249: 	}
 4250: 	$domain=~s/\s//g;
 4251: 	my $username=$entries{$fields{'username'}};
 4252: 	$username=~s/\s//g;
 4253: 	if (!$username) {
 4254: 	    my $id=$entries{$fields{'ID'}};
 4255: 	    $id=~s/\s//g;
 4256: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4257: 	    $username=$ids{$id};
 4258: 	}
 4259: 	if (!exists($$classlist{"$username:$domain"})) {
 4260: 	    my $id=$entries{$fields{'ID'}};
 4261: 	    $id=~s/\s//g;
 4262: 	    if ($id) {
 4263: 		push(@skipped,"$id:$domain");
 4264: 	    } else {
 4265: 		push(@skipped,"$username:$domain");
 4266: 	    }
 4267: 	    next;
 4268: 	}
 4269: 	my $usec=$classlist->{"$username:$domain"}[5];
 4270: 	if (!&canmodify($usec)) {
 4271: 	    push(@notallowed,"$username:$domain");
 4272: 	    next;
 4273: 	}
 4274: 	my %points;
 4275: 	my %grades;
 4276: 	foreach my $dest (keys(%fields)) {
 4277: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4278: 		$dest eq 'domain') { next; }
 4279: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4280: 	    if ($dest=~/stores_(.*)_points/) {
 4281: 		my $part=$1;
 4282: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4283: 					      $symb,$domain,$username);
 4284:                 if ($wgt) {
 4285:                     $entries{$fields{$dest}}=~s/\s//g;
 4286:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4287:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4288:                                           : 'correct_by_override';
 4289:                     if ($pcr>1) {
 4290:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4291:                     }
 4292:                     $grades{"resource.$part.awarded"}=$pcr;
 4293:                     $grades{"resource.$part.solved"}=$award;
 4294:                     $points{$part}=1;
 4295:                 } else {
 4296:                     $error_msg = "<br />" .
 4297:                         &mt("Some point values were assigned"
 4298:                             ." for problems with a weight "
 4299:                             ."of zero. These values were "
 4300:                             ."ignored.");
 4301:                 }
 4302: 	    } else {
 4303: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4304: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4305: 		my $store_key=$dest;
 4306: 		$store_key=~s/^stores/resource/;
 4307: 		$store_key=~s/_/\./g;
 4308: 		$grades{$store_key}=$entries{$fields{$dest}};
 4309: 	    }
 4310: 	}
 4311: 	if (! %grades) { 
 4312:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4313:         } else {
 4314: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4315: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4316: 					   $env{'request.course.id'},
 4317: 					   $domain,$username);
 4318: 	   if ($result eq 'ok') {
 4319: 	      $request->print('.');
 4320: # Remove from grading queue
 4321:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4322:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4323:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4324:                                              $domain,$username);
 4325: 	   } else {
 4326: 	      $request->print("<p><span class=\"LC_error\">".
 4327:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4328:                                   "$username:$domain",$result)."</span></p>");
 4329: 	   }
 4330: 	   $request->rflush();
 4331: 	   $countdone++;
 4332:         }
 4333:     }
 4334:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4335:     if (@warnings) {
 4336:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4337:         $request->print(join(', ',@warnings));
 4338:     }
 4339:     if (@skipped) {
 4340: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4341:         $request->print(join(', ',@skipped));
 4342:     }
 4343:     if (@notallowed) {
 4344: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4345: 	$request->print(join(', ',@notallowed));
 4346:     }
 4347:     $request->print("<br />\n");
 4348:     $request->print(&show_grading_menu_form($symb));
 4349:     return $error_msg;
 4350: }
 4351: #------------- end of section for handling csv file upload ---------
 4352: #
 4353: #-------------------------------------------------------------------
 4354: #
 4355: #-------------- Next few routines handle grading by page/sequence
 4356: #
 4357: #--- Select a page/sequence and a student to grade
 4358: sub pickStudentPage {
 4359:     my ($request) = shift;
 4360: 
 4361:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4362:     $request->print(<<LISTJAVASCRIPT);
 4363: <script type="text/javascript" language="javascript">
 4364: 
 4365: function checkPickOne(formname) {
 4366:     if (radioSelection(formname.student) == null) {
 4367: 	alert("$alertmsg");
 4368: 	return;
 4369:     }
 4370:     ptr = pullDownSelection(formname.selectpage);
 4371:     formname.page.value = formname["page"+ptr].value;
 4372:     formname.title.value = formname["title"+ptr].value;
 4373:     formname.submit();
 4374: }
 4375: 
 4376: </script>
 4377: LISTJAVASCRIPT
 4378:     &commonJSfunctions($request);
 4379:     my ($symb) = &get_symb($request);
 4380:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4381:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4382:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4383: 
 4384:     my $result='<h3><span class="LC_info">&nbsp;'.
 4385: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4386: 
 4387:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4388:     my $map_error;
 4389:     my ($titles,$symbx) = &getSymbMap($map_error);
 4390:     if ($map_error) {
 4391:         $request->print(&navmap_errormsg());
 4392:         return; 
 4393:     }
 4394:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4395: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4396: #    my $type=($curpage =~ /\.(page|sequence)/);
 4397:     my $select = '<select name="selectpage">'."\n";
 4398:     my $ctr=0;
 4399:     foreach (@$titles) {
 4400: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4401: 	$select.='<option value="'.$ctr.'" '.
 4402: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4403: 	    '>'.$showtitle.'</option>'."\n";
 4404: 	$ctr++;
 4405:     }
 4406:     $select.= '</select>';
 4407:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4408: 
 4409:     $ctr=0;
 4410:     foreach (@$titles) {
 4411: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4412: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4413: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4414: 	$ctr++;
 4415:     }
 4416:     $result.='<input type="hidden" name="page" />'."\n".
 4417: 	'<input type="hidden" name="title" />'."\n";
 4418: 
 4419:     my $options =
 4420: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4421: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4422:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4423: 
 4424:     $options =
 4425: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4426: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4427: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4428:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4429:     
 4430:     $result.=&build_section_inputs();
 4431:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4432:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4433: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4434: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4435: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4436: 
 4437:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4438: 
 4439:     $result.='&nbsp;<input type="button" '.
 4440:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4441: 
 4442:     $request->print($result);
 4443: 
 4444:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4445: 	&Apache::loncommon::start_data_table().
 4446: 	&Apache::loncommon::start_data_table_header_row().
 4447: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4448: 	'<th>'.&nameUserString('header').'</th>'.
 4449: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4450: 	'<th>'.&nameUserString('header').'</th>'.
 4451: 	&Apache::loncommon::end_data_table_header_row();
 4452:  
 4453:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4454:     my $ptr = 1;
 4455:     foreach my $student (sort 
 4456: 			 {
 4457: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4458: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4459: 			     }
 4460: 			     return $a cmp $b;
 4461: 			 } (keys(%$fullname))) {
 4462: 	my ($uname,$udom) = split(/:/,$student);
 4463: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4464:                                   : '</td>');
 4465: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4466: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4467: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4468: 	$studentTable.=
 4469: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4470:                          : '');
 4471: 	$ptr++;
 4472:     }
 4473:     if ($ptr%2 == 0) {
 4474: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4475: 	    &Apache::loncommon::end_data_table_row();
 4476:     }
 4477:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4478:     $studentTable.='<input type="button" '.
 4479:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4480: 
 4481:     $studentTable.=&show_grading_menu_form($symb);
 4482:     $request->print($studentTable);
 4483: 
 4484:     return '';
 4485: }
 4486: 
 4487: sub getSymbMap {
 4488:     my ($map_error) = @_;
 4489:     my $navmap = Apache::lonnavmaps::navmap->new();
 4490:     unless (ref($navmap)) {
 4491:         if (ref($map_error)) {
 4492:             $$map_error = 'navmap';
 4493:         }
 4494:         return;
 4495:     }
 4496:     my %symbx = ();
 4497:     my @titles = ();
 4498:     my $minder = 0;
 4499: 
 4500:     # Gather every sequence that has problems.
 4501:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4502: 					       1,0,1);
 4503:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4504: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4505: 	    my $title = $minder.'.'.
 4506: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4507: 	    push(@titles, $title); # minder in case two titles are identical
 4508: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4509: 	    $minder++;
 4510: 	}
 4511:     }
 4512:     return \@titles,\%symbx;
 4513: }
 4514: 
 4515: #
 4516: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4517: sub displayPage {
 4518:     my ($request) = shift;
 4519: 
 4520:     my ($symb) = &get_symb($request);
 4521:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4522:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4523:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4524:     my $pageTitle = $env{'form.page'};
 4525:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4526:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4527:     my $usec=$classlist->{$env{'form.student'}}[5];
 4528: 
 4529:     #need to make sure we have the correct data for later EXT calls, 
 4530:     #thus invalidate the cache
 4531:     &Apache::lonnet::devalidatecourseresdata(
 4532:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4533:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4534:     &Apache::lonnet::clear_EXT_cache_status();
 4535: 
 4536:     if (!&canview($usec)) {
 4537: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4538: 	$request->print(&show_grading_menu_form($symb));
 4539: 	return;
 4540:     }
 4541:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4542:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4543: 	'</h3>'."\n";
 4544:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4545:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4546: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4547:     } else {
 4548: 	delete($env{'form.CODE'});
 4549:     }
 4550:     &sub_page_js($request);
 4551:     $request->print($result);
 4552: 
 4553:     my $navmap = Apache::lonnavmaps::navmap->new();
 4554:     unless (ref($navmap)) {
 4555:         $request->print(&navmap_errormsg());
 4556:         $request->print(&show_grading_menu_form($symb));
 4557:         return;
 4558:     }
 4559:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4560:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4561:     if (!$map) {
 4562: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4563: 	$request->print(&show_grading_menu_form($symb));
 4564: 	return; 
 4565:     }
 4566:     my $iterator = $navmap->getIterator($map->map_start(),
 4567: 					$map->map_finish());
 4568: 
 4569:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4570: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4571: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4572: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4573: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4574: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4575: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4576: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4577: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4578: 
 4579:     if (defined($env{'form.CODE'})) {
 4580: 	$studentTable.=
 4581: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4582:     }
 4583:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4584: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4585: 
 4586:     $studentTable.='&nbsp;<span class="LC_info">'.
 4587:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4588:         '</span>'."\n".
 4589: 	&Apache::loncommon::start_data_table().
 4590: 	&Apache::loncommon::start_data_table_header_row().
 4591: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4592: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4593: 	&Apache::loncommon::end_data_table_header_row();
 4594: 
 4595:     &Apache::lonxml::clear_problem_counter();
 4596:     my ($depth,$question,$prob) = (1,1,1);
 4597:     $iterator->next(); # skip the first BEGIN_MAP
 4598:     my $curRes = $iterator->next(); # for "current resource"
 4599:     while ($depth > 0) {
 4600:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4601:         if($curRes == $iterator->END_MAP) { $depth--; }
 4602: 
 4603:         if (ref($curRes) && $curRes->is_problem()) {
 4604: 	    my $parts = $curRes->parts();
 4605:             my $title = $curRes->compTitle();
 4606: 	    my $symbx = $curRes->symb();
 4607: 	    $studentTable.=
 4608: 		&Apache::loncommon::start_data_table_row().
 4609: 		'<td align="center" valign="top" >'.$prob.
 4610: 		(scalar(@{$parts}) == 1 ? '' 
 4611: 		                        : '<br />('.&mt('[_1]parts)',
 4612: 							scalar(@{$parts}).'&nbsp;')
 4613: 		 ).
 4614: 		 '</td>';
 4615: 	    $studentTable.='<td valign="top">';
 4616: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4617: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4618: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4619: 					     undef,'both',\%form);
 4620: 	    } else {
 4621: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4622: 		$companswer =~ s|<form(.*?)>||g;
 4623: 		$companswer =~ s|</form>||g;
 4624: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4625: #		    $companswer =~ s/$1/ /ms;
 4626: #		    $request->print('match='.$1."<br />\n");
 4627: #		}
 4628: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4629: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4630: 	    }
 4631: 
 4632: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4633: 
 4634: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4635: 		if ($record{'version'} eq '') {
 4636: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4637: 		} else {
 4638: 		    my %responseType = ();
 4639: 		    foreach my $partid (@{$parts}) {
 4640: 			my @responseIds =$curRes->responseIds($partid);
 4641: 			my @responseType =$curRes->responseType($partid);
 4642: 			my %responseIds;
 4643: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4644: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4645: 			}
 4646: 			$responseType{$partid} = \%responseIds;
 4647: 		    }
 4648: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4649: 
 4650: 		}
 4651: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4652: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4653: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4654: 									$env{'request.course.id'},
 4655: 									'','.submission');
 4656:  
 4657: 	    }
 4658: 	    if (&canmodify($usec)) {
 4659:             $studentTable.=&gradeBox_start();
 4660: 		foreach my $partid (@{$parts}) {
 4661: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4662: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4663: 		    $question++;
 4664: 		}
 4665:             $studentTable.=&gradeBox_end();
 4666: 		$prob++;
 4667: 	    }
 4668: 	    $studentTable.='</td></tr>';
 4669: 
 4670: 	}
 4671:         $curRes = $iterator->next();
 4672:     }
 4673: 
 4674:     $studentTable.=
 4675:         '</table>'."\n".
 4676:         '<input type="button" value="'.&mt('Save').'" '.
 4677:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4678:         '</form>'."\n";
 4679:     $studentTable.=&show_grading_menu_form($symb);
 4680:     $request->print($studentTable);
 4681: 
 4682:     return '';
 4683: }
 4684: 
 4685: sub displaySubByDates {
 4686:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4687:     my $isCODE=0;
 4688:     my $isTask = ($symb =~/\.task$/);
 4689:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4690:     my $studentTable=&Apache::loncommon::start_data_table().
 4691: 	&Apache::loncommon::start_data_table_header_row().
 4692: 	'<th>'.&mt('Date/Time').'</th>'.
 4693: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4694: 	'<th>'.&mt('Submission').'</th>'.
 4695: 	'<th>'.&mt('Status').'</th>'.
 4696: 	&Apache::loncommon::end_data_table_header_row();
 4697:     my ($version);
 4698:     my %mark;
 4699:     my %orders;
 4700:     $mark{'correct_by_student'} = $checkIcon;
 4701:     if (!exists($$record{'1:timestamp'})) {
 4702: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4703:     }
 4704: 
 4705:     my $interaction;
 4706:     my $no_increment = 1;
 4707:     my %lastrndseed;
 4708:     for ($version=1;$version<=$$record{'version'};$version++) {
 4709: 	my $timestamp = 
 4710: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4711: 	if (exists($$record{$version.':resource.0.version'})) {
 4712: 	    $interaction = $$record{$version.':resource.0.version'};
 4713: 	}
 4714: 
 4715: 	my $where = ($isTask ? "$version:resource.$interaction"
 4716: 		             : "$version:resource");
 4717: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4718: 	    '<td>'.$timestamp.'</td>';
 4719: 	if ($isCODE) {
 4720: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4721: 	}
 4722: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4723: 	my @displaySub = ();
 4724: 	foreach my $partid (@{$parts}) {
 4725:             my ($hidden,$type);
 4726:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4727:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4728:                 $hidden = 1;
 4729:             }
 4730: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4731: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4732: 	    
 4733: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4734: 	    my $display_part=&get_display_part($partid,$symb);
 4735: 	    foreach my $matchKey (@matchKey) {
 4736: 		if (exists($$record{$version.':'.$matchKey}) &&
 4737: 		    $$record{$version.':'.$matchKey} ne '') {
 4738:                     
 4739: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4740: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4741:                     $displaySub[0].='<span class="LC_nobreak"';
 4742:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4743:                                    .' <span class="LC_internal_info">'
 4744:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4745:                                    .'</span>'
 4746:                                    .' <b>';
 4747:                     if ($hidden) {
 4748:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4749:                     } else {
 4750:                         my ($trial,$rndseed,$newvariation);
 4751:                         if ($type eq 'randomizetry') {
 4752:                             $trial = $$record{"$where.$partid.tries"};
 4753:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4754:                         }
 4755: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4756: 			    $displaySub[0].=&mt('Trial not counted');
 4757: 		        } else {
 4758: 			    $displaySub[0].=&mt('Trial: [_1]',
 4759: 					    $$record{"$where.$partid.tries"});
 4760:                             if ($rndseed || $lastrndseed{$partid}) {
 4761:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4762:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4763:                                 }
 4764:                             }
 4765: 		        }
 4766: 		        my $responseType=($isTask ? 'Task'
 4767:                                               : $responseType->{$partid}->{$responseId});
 4768: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4769: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4770: 			    $orders{$partid}->{$responseId}=
 4771: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4772:                                            $no_increment,$type,$trial,$rndseed);
 4773: 		        }
 4774: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4775: 		        $displaySub[0].='&nbsp; '.
 4776: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4777:                     }
 4778: 		}
 4779: 	    }
 4780: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4781: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4782: 				    $$record{"$where.$partid.checkedin"},
 4783: 				    $$record{"$where.$partid.checkedin.slot"}).
 4784: 					'<br />';
 4785: 	    }
 4786: 	    if (exists $$record{"$where.$partid.award"}) {
 4787: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4788: 		    lc($$record{"$where.$partid.award"}).' '.
 4789: 		    $mark{$$record{"$where.$partid.solved"}}.
 4790: 		    '<br />';
 4791: 	    }
 4792: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4793: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4794: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4795: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4796: 		$displaySub[2].=
 4797: 		    $$record{"$version:resource.$partid.regrader"}.
 4798: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4799: 	    }
 4800: 	}
 4801: 	# needed because old essay regrader has not parts info
 4802: 	if (exists $$record{"$version:resource.regrader"}) {
 4803: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4804: 	}
 4805: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4806: 	if ($displaySub[2]) {
 4807: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4808: 	}
 4809: 	$studentTable.='&nbsp;</td>'.
 4810: 	    &Apache::loncommon::end_data_table_row();
 4811:     }
 4812:     $studentTable.=&Apache::loncommon::end_data_table();
 4813:     return $studentTable;
 4814: }
 4815: 
 4816: sub updateGradeByPage {
 4817:     my ($request) = shift;
 4818: 
 4819:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4820:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4821:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4822:     my $pageTitle = $env{'form.page'};
 4823:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4824:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4825:     my $usec=$classlist->{$env{'form.student'}}[5];
 4826:     if (!&canmodify($usec)) {
 4827: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4828: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4829: 	return;
 4830:     }
 4831:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4832:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4833: 	'</h3>'."\n";
 4834: 
 4835:     $request->print($result);
 4836: 
 4837: 
 4838:     my $navmap = Apache::lonnavmaps::navmap->new();
 4839:     unless (ref($navmap)) {
 4840:         $request->print(&navmap_errormsg());
 4841:         return;
 4842:     }
 4843:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4844:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4845:     if (!$map) {
 4846: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4847: 	my ($symb)=&get_symb($request);
 4848: 	$request->print(&show_grading_menu_form($symb));
 4849: 	return; 
 4850:     }
 4851:     my $iterator = $navmap->getIterator($map->map_start(),
 4852: 					$map->map_finish());
 4853: 
 4854:     my $studentTable=
 4855: 	&Apache::loncommon::start_data_table().
 4856: 	&Apache::loncommon::start_data_table_header_row().
 4857: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4858: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4859: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4860: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4861: 	&Apache::loncommon::end_data_table_header_row();
 4862: 
 4863:     $iterator->next(); # skip the first BEGIN_MAP
 4864:     my $curRes = $iterator->next(); # for "current resource"
 4865:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4866:     while ($depth > 0) {
 4867:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4868:         if($curRes == $iterator->END_MAP) { $depth--; }
 4869: 
 4870:         if (ref($curRes) && $curRes->is_problem()) {
 4871: 	    my $parts = $curRes->parts();
 4872:             my $title = $curRes->compTitle();
 4873: 	    my $symbx = $curRes->symb();
 4874: 	    $studentTable.=
 4875: 		&Apache::loncommon::start_data_table_row().
 4876: 		'<td align="center" valign="top" >'.$prob.
 4877: 		(scalar(@{$parts}) == 1 ? '' 
 4878:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4879: 		.')').'</td>';
 4880: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4881: 
 4882: 	    my %newrecord=();
 4883: 	    my @displayPts=();
 4884:             my %aggregate = ();
 4885:             my $aggregateflag = 0;
 4886: 	    foreach my $partid (@{$parts}) {
 4887: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4888: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4889: 
 4890: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4891: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4892: 		my $partial = $newpts/$wgt;
 4893: 		my $score;
 4894: 		if ($partial > 0) {
 4895: 		    $score = 'correct_by_override';
 4896: 		} elsif ($newpts ne '') { #empty is taken as 0
 4897: 		    $score = 'incorrect_by_override';
 4898: 		}
 4899: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4900: 		if ($dropMenu eq 'excused') {
 4901: 		    $partial = '';
 4902: 		    $score = 'excused';
 4903: 		} elsif ($dropMenu eq 'reset status'
 4904: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4905: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4906: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4907: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4908: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4909: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4910: 		    $changeflag++;
 4911: 		    $newpts = '';
 4912:                     
 4913:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4914:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4915:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4916:                     if ($aggtries > 0) {
 4917:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4918:                         $aggregateflag = 1;
 4919:                     }
 4920: 		}
 4921: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4922: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4923: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4924: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4925: 		    '&nbsp;<br />';
 4926: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4927: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4928: 		    '&nbsp;<br />';
 4929: 		$question++;
 4930: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4931: 
 4932: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4933: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4934: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4935: 		    if (scalar(keys(%newrecord)) > 0);
 4936: 
 4937: 		$changeflag++;
 4938: 	    }
 4939: 	    if (scalar(keys(%newrecord)) > 0) {
 4940: 		my %record = 
 4941: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4942: 					     $udom,$uname);
 4943: 
 4944: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4945: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4946: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4947: 		    $newrecord{'resource.CODE'} = '';
 4948: 		}
 4949: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4950: 					$udom,$uname);
 4951: 		%record = &Apache::lonnet::restore($symbx,
 4952: 						   $env{'request.course.id'},
 4953: 						   $udom,$uname);
 4954: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4955: 					     $cdom,$cnum,$udom,$uname);
 4956: 	    }
 4957: 	    
 4958:             if ($aggregateflag) {
 4959:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4960:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4961:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4962:             }
 4963: 
 4964: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4965: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4966: 		&Apache::loncommon::end_data_table_row();
 4967: 
 4968: 	    $prob++;
 4969: 	}
 4970:         $curRes = $iterator->next();
 4971:     }
 4972: 
 4973:     $studentTable.=&Apache::loncommon::end_data_table();
 4974:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4975:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4976: 		  &mt('The scores were changed for [quant,_1,problem].',
 4977: 		  $changeflag));
 4978:     $request->print($grademsg.$studentTable);
 4979: 
 4980:     return '';
 4981: }
 4982: 
 4983: #-------- end of section for handling grading by page/sequence ---------
 4984: #
 4985: #-------------------------------------------------------------------
 4986: 
 4987: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4988: #
 4989: #------ start of section for handling grading by page/sequence ---------
 4990: 
 4991: =pod
 4992: 
 4993: =head1 Bubble sheet grading routines
 4994: 
 4995:   For this documentation:
 4996: 
 4997:    'scanline' refers to the full line of characters
 4998:    from the file that we are parsing that represents one entire sheet
 4999: 
 5000:    'bubble line' refers to the data
 5001:    representing the line of bubbles that are on the physical bubblesheet
 5002: 
 5003: 
 5004: The overall process is that a scanned in bubblesheet data is uploaded
 5005: into a course. When a user wants to grade, they select a
 5006: sequence/folder of resources, a file of bubblesheet info, and pick
 5007: one of the predefined configurations for what each scanline looks
 5008: like.
 5009: 
 5010: Next each scanline is checked for any errors of either 'missing
 5011: bubbles' (it's an error because it may have been mis-scanned
 5012: because too light bubbling), 'double bubble' (each bubble line should
 5013: have no more that one letter picked), invalid or duplicated CODE,
 5014: invalid student/employee ID
 5015: 
 5016: If the CODE option is used that determines the randomization of the
 5017: homework problems, either way the student/employee ID is looked up into a
 5018: username:domain.
 5019: 
 5020: During the validation phase the instructor can choose to skip scanlines. 
 5021: 
 5022: After the validation phase, there are now 3 bubblesheet files
 5023: 
 5024:   scantron_original_filename (unmodified original file)
 5025:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5026:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5027: 
 5028: Also there is a separate hash nohist_scantrondata that contains extra
 5029: correction information that isn't representable in the bubblesheet
 5030: file (see &scantron_getfile() for more information)
 5031: 
 5032: After all scanlines are either valid, marked as valid or skipped, then
 5033: foreach line foreach problem in the picked sequence, an ssi request is
 5034: made that simulates a user submitting their selected letter(s) against
 5035: the homework problem.
 5036: 
 5037: =over 4
 5038: 
 5039: 
 5040: 
 5041: =item defaultFormData
 5042: 
 5043:   Returns html hidden inputs used to hold context/default values.
 5044: 
 5045:  Arguments:
 5046:   $symb - $symb of the current resource 
 5047: 
 5048: =cut
 5049: 
 5050: sub defaultFormData {
 5051:     my ($symb)=@_;
 5052:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5053:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5054:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5055: }
 5056: 
 5057: 
 5058: =pod 
 5059: 
 5060: =item getSequenceDropDown
 5061: 
 5062:    Return html dropdown of possible sequences to grade
 5063:  
 5064:  Arguments:
 5065:    $symb - $symb of the current resource
 5066:    $map_error - ref to scalar which will container error if
 5067:                 $navmap object is unavailable in &getSymbMap().
 5068: 
 5069: =cut
 5070: 
 5071: sub getSequenceDropDown {
 5072:     my ($symb,$map_error)=@_;
 5073:     my $result='<select name="selectpage">'."\n";
 5074:     my ($titles,$symbx) = &getSymbMap($map_error);
 5075:     if (ref($map_error)) {
 5076:         return if ($$map_error);
 5077:     }
 5078:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5079:     my $ctr=0;
 5080:     foreach (@$titles) {
 5081: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5082: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5083: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5084: 	    '>'.$showtitle.'</option>'."\n";
 5085: 	$ctr++;
 5086:     }
 5087:     $result.= '</select>';
 5088:     return $result;
 5089: }
 5090: 
 5091: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5092:                                    # key is zero-based index - 0, 1, 2 ...
 5093: 
 5094: my %first_bubble_line;             # First bubble line no. for each bubble.
 5095: 
 5096: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5097:                                    # matchresponse or rankresponse, where 
 5098:                                    # an individual response can have multiple 
 5099:                                    # lines
 5100: 
 5101: my %responsetype_per_response;     # responsetype for each response
 5102: 
 5103: # Save and restore the bubble lines array to the form env.
 5104: 
 5105: 
 5106: sub save_bubble_lines {
 5107:     foreach my $line (keys(%bubble_lines_per_response)) {
 5108: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5109: 	$env{"form.scantron.first_bubble_line.$line"} =
 5110: 	    $first_bubble_line{$line};
 5111:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5112:             $subdivided_bubble_lines{$line};
 5113:         $env{"form.scantron.responsetype.$line"} =
 5114:             $responsetype_per_response{$line};
 5115:     }
 5116: }
 5117: 
 5118: 
 5119: sub restore_bubble_lines {
 5120:     my $line = 0;
 5121:     %bubble_lines_per_response = ();
 5122:     while ($env{"form.scantron.bubblelines.$line"}) {
 5123: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5124: 	$bubble_lines_per_response{$line} = $value;
 5125: 	$first_bubble_line{$line}  =
 5126: 	    $env{"form.scantron.first_bubble_line.$line"};
 5127:         $subdivided_bubble_lines{$line} =
 5128:             $env{"form.scantron.sub_bubblelines.$line"};
 5129:         $responsetype_per_response{$line} =
 5130:             $env{"form.scantron.responsetype.$line"};
 5131: 	$line++;
 5132:     }
 5133: }
 5134: 
 5135: #  Given the parsed scanline, get the response for 
 5136: #  'answer' number n:
 5137: 
 5138: sub get_response_bubbles {
 5139:     my ($parsed_line, $response)  = @_;
 5140: 
 5141:     my $bubble_line = $first_bubble_line{$response-1} +1;
 5142:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 5143:     
 5144:     my $selected = "";
 5145: 
 5146:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 5147: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 5148: 	$bubble_line++;
 5149:     }
 5150:     return $selected;
 5151: }
 5152: 
 5153: =pod 
 5154: 
 5155: =item scantron_filenames
 5156: 
 5157:    Returns a list of the scantron files in the current course 
 5158: 
 5159: =cut
 5160: 
 5161: sub scantron_filenames {
 5162:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5163:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5164:     my $getpropath = 1;
 5165:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 5166:                                        $getpropath);
 5167:     my @possiblenames;
 5168:     foreach my $filename (sort(@files)) {
 5169: 	($filename)=split(/&/,$filename);
 5170: 	if ($filename!~/^scantron_orig_/) { next ; }
 5171: 	$filename=~s/^scantron_orig_//;
 5172: 	push(@possiblenames,$filename);
 5173:     }
 5174:     return @possiblenames;
 5175: }
 5176: 
 5177: =pod 
 5178: 
 5179: =item scantron_uploads
 5180: 
 5181:    Returns  html drop-down list of scantron files in current course.
 5182: 
 5183:  Arguments:
 5184:    $file2grade - filename to set as selected in the dropdown
 5185: 
 5186: =cut
 5187: 
 5188: sub scantron_uploads {
 5189:     my ($file2grade) = @_;
 5190:     my $result=	'<select name="scantron_selectfile">';
 5191:     $result.="<option></option>";
 5192:     foreach my $filename (sort(&scantron_filenames())) {
 5193: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5194:     }
 5195:     $result.="</select>";
 5196:     return $result;
 5197: }
 5198: 
 5199: =pod 
 5200: 
 5201: =item scantron_scantab
 5202: 
 5203:   Returns html drop down of the scantron formats in the scantronformat.tab
 5204:   file.
 5205: 
 5206: =cut
 5207: 
 5208: sub scantron_scantab {
 5209:     my $result='<select name="scantron_format">'."\n";
 5210:     $result.='<option></option>'."\n";
 5211:     my @lines = &get_scantronformat_file();
 5212:     if (@lines > 0) {
 5213:         foreach my $line (@lines) {
 5214:             next if (($line =~ /^\#/) || ($line eq ''));
 5215: 	    my ($name,$descrip)=split(/:/,$line);
 5216: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5217:         }
 5218:     }
 5219:     $result.='</select>'."\n";
 5220:     return $result;
 5221: }
 5222: 
 5223: =pod
 5224: 
 5225: =item get_scantronformat_file
 5226: 
 5227:   Returns an array containing lines from the scantron format file for
 5228:   the domain of the course.
 5229: 
 5230:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5231:   lines are from this file.
 5232: 
 5233:   Otherwise, if a default.tab has been published in RES space by the 
 5234:   domainconfig user, lines are from this file.
 5235: 
 5236:   Otherwise, fall back to getting lines from the legacy file on the
 5237:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5238: 
 5239: =cut
 5240: 
 5241: sub get_scantronformat_file {
 5242:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5243:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5244:     my $gottab = 0;
 5245:     my @lines;
 5246:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5247:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5248:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5249:             if ($formatfile ne '-1') {
 5250:                 @lines = split("\n",$formatfile,-1);
 5251:                 $gottab = 1;
 5252:             }
 5253:         }
 5254:     }
 5255:     if (!$gottab) {
 5256:         my $confname = $cdom.'-domainconfig';
 5257:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5258:         my $formatfile =  &Apache::lonnet::getfile($default);
 5259:         if ($formatfile ne '-1') {
 5260:             @lines = split("\n",$formatfile,-1);
 5261:             $gottab = 1;
 5262:         }
 5263:     }
 5264:     if (!$gottab) {
 5265:         my @domains = &Apache::lonnet::current_machine_domains();
 5266:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5267:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5268:             @lines = <$fh>;
 5269:             close($fh);
 5270:         } else {
 5271:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5272:             @lines = <$fh>;
 5273:             close($fh);
 5274:         }
 5275:     }
 5276:     return @lines;
 5277: }
 5278: 
 5279: =pod 
 5280: 
 5281: =item scantron_CODElist
 5282: 
 5283:   Returns html drop down of the saved CODE lists from current course,
 5284:   generated from earlier printings.
 5285: 
 5286: =cut
 5287: 
 5288: sub scantron_CODElist {
 5289:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5290:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5291:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5292:     my $namechoice='<option></option>';
 5293:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5294: 	if ($name =~ /^error: 2 /) { next; }
 5295: 	if ($name =~ /^type\0/) { next; }
 5296: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5297:     }
 5298:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5299:     return $namechoice;
 5300: }
 5301: 
 5302: =pod 
 5303: 
 5304: =item scantron_CODEunique
 5305: 
 5306:   Returns the html for "Each CODE to be used once" radio.
 5307: 
 5308: =cut
 5309: 
 5310: sub scantron_CODEunique {
 5311:     my $result='<span class="LC_nobreak">
 5312:                  <label><input type="radio" name="scantron_CODEunique"
 5313:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5314:                 </span>
 5315:                 <span class="LC_nobreak">
 5316:                  <label><input type="radio" name="scantron_CODEunique"
 5317:                         value="no" />'.&mt('No').' </label>
 5318:                 </span>';
 5319:     return $result;
 5320: }
 5321: 
 5322: =pod 
 5323: 
 5324: =item scantron_selectphase
 5325: 
 5326:   Generates the initial screen to start the bubblesheet process.
 5327:   Allows for - starting a grading run.
 5328:              - downloading existing scan data (original, corrected
 5329:                                                 or skipped info)
 5330: 
 5331:              - uploading new scan data
 5332: 
 5333:  Arguments:
 5334:   $r          - The Apache request object
 5335:   $file2grade - name of the file that contain the scanned data to score
 5336: 
 5337: =cut
 5338: 
 5339: sub scantron_selectphase {
 5340:     my ($r,$file2grade) = @_;
 5341:     my ($symb)=&get_symb($r);
 5342:     if (!$symb) {return '';}
 5343:     my $map_error;
 5344:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5345:     if ($map_error) {
 5346:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5347:         return;
 5348:     }
 5349:     my $default_form_data=&defaultFormData($symb);
 5350:     my $grading_menu_button=&show_grading_menu_form($symb);
 5351:     my $file_selector=&scantron_uploads($file2grade);
 5352:     my $format_selector=&scantron_scantab();
 5353:     my $CODE_selector=&scantron_CODElist();
 5354:     my $CODE_unique=&scantron_CODEunique();
 5355:     my $result;
 5356: 
 5357:     $ssi_error = 0;
 5358: 
 5359:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5360:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5361: 
 5362:         # Chunk of form to prompt for a scantron file upload.
 5363: 
 5364:         $r->print('
 5365:     <br />
 5366:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5367:        '.&Apache::loncommon::start_data_table_header_row().'
 5368:             <th>
 5369:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5370:             </th>
 5371:        '.&Apache::loncommon::end_data_table_header_row().'
 5372:        '.&Apache::loncommon::start_data_table_row().'
 5373:             <td>
 5374: ');
 5375:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5376:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5377:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5378:     $r->print('
 5379:               <script type="text/javascript" language="javascript">
 5380:     function checkUpload(formname) {
 5381:         if (formname.upfile.value == "") {
 5382:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5383:             return false;
 5384:         }
 5385:         formname.submit();
 5386:     }
 5387:               </script>
 5388: 
 5389:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5390:                 '.$default_form_data.'
 5391:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5392:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5393:                 <input name="command" value="scantronupload_save" type="hidden" />
 5394:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5395:                 <br />
 5396:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5397:               </form>
 5398: ');
 5399: 
 5400:         $r->print('
 5401:             </td>
 5402:        '.&Apache::loncommon::end_data_table_row().'
 5403:        '.&Apache::loncommon::end_data_table().'
 5404: ');
 5405:     }
 5406: 
 5407:     # Chunk of form to prompt for a file to grade and how:
 5408: 
 5409:     $result.= '
 5410:     <br />
 5411:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5412:     <input type="hidden" name="command" value="scantron_warning" />
 5413:     '.$default_form_data.'
 5414:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5415:        '.&Apache::loncommon::start_data_table_header_row().'
 5416:             <th colspan="2">
 5417:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5418:             </th>
 5419:        '.&Apache::loncommon::end_data_table_header_row().'
 5420:        '.&Apache::loncommon::start_data_table_row().'
 5421:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5422:        '.&Apache::loncommon::end_data_table_row().'
 5423:        '.&Apache::loncommon::start_data_table_row().'
 5424:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5425:        '.&Apache::loncommon::end_data_table_row().'
 5426:        '.&Apache::loncommon::start_data_table_row().'
 5427:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5428:        '.&Apache::loncommon::end_data_table_row().'
 5429:        '.&Apache::loncommon::start_data_table_row().'
 5430:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5431:        '.&Apache::loncommon::end_data_table_row().'
 5432:        '.&Apache::loncommon::start_data_table_row().'
 5433:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5434:        '.&Apache::loncommon::end_data_table_row().'
 5435:        '.&Apache::loncommon::start_data_table_row().'
 5436: 	    <td> '.&mt('Options:').' </td>
 5437:             <td>
 5438: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5439:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5440:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5441: 	    </td>
 5442:        '.&Apache::loncommon::end_data_table_row().'
 5443:        '.&Apache::loncommon::start_data_table_row().'
 5444:             <td colspan="2">
 5445:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5446:             </td>
 5447:        '.&Apache::loncommon::end_data_table_row().'
 5448:     '.&Apache::loncommon::end_data_table().'
 5449:     </form>
 5450: ';
 5451:    
 5452:     $r->print($result);
 5453: 
 5454:     # Chunk of the form that prompts to view a scoring office file,
 5455:     # corrected file, skipped records in a file.
 5456: 
 5457:     $r->print('
 5458:    <br />
 5459:    <form action="/adm/grades" name="scantron_download">
 5460:      '.$default_form_data.'
 5461:      <input type="hidden" name="command" value="scantron_download" />
 5462:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5463:        '.&Apache::loncommon::start_data_table_header_row().'
 5464:               <th>
 5465:                 &nbsp;'.&mt('Download a scoring office file').'
 5466:               </th>
 5467:        '.&Apache::loncommon::end_data_table_header_row().'
 5468:        '.&Apache::loncommon::start_data_table_row().'
 5469:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5470:                 <br />
 5471:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5472:        '.&Apache::loncommon::end_data_table_row().'
 5473:      '.&Apache::loncommon::end_data_table().'
 5474:    </form>
 5475:    <br />
 5476: ');
 5477: 
 5478:     &Apache::lonpickcode::code_list($r,2);
 5479: 
 5480:     $r->print('<br /><form method="post" name="checkscantron">'.
 5481:              $default_form_data."\n".
 5482:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5483:              &Apache::loncommon::start_data_table_header_row()."\n".
 5484:              '<th colspan="2">
 5485:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5486:              '</th>'."\n".
 5487:               &Apache::loncommon::end_data_table_header_row()."\n".
 5488:               &Apache::loncommon::start_data_table_row()."\n".
 5489:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5490:               '<td> '.$sequence_selector.' </td>'.
 5491:               &Apache::loncommon::end_data_table_row()."\n".
 5492:               &Apache::loncommon::start_data_table_row()."\n".
 5493:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5494:               '<td> '.$file_selector.' </td>'."\n".
 5495:               &Apache::loncommon::end_data_table_row()."\n".
 5496:               &Apache::loncommon::start_data_table_row()."\n".
 5497:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5498:               '<td> '.$format_selector.' </td>'."\n".
 5499:               &Apache::loncommon::end_data_table_row()."\n".
 5500:               &Apache::loncommon::start_data_table_row()."\n".
 5501:               '<td> '.&mt('Options').' </td>'."\n".
 5502:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5503:               &Apache::loncommon::end_data_table_row()."\n".
 5504:               &Apache::loncommon::start_data_table_row()."\n".
 5505:               '<td colspan="2">'."\n".
 5506:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5507:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5508:               '</td>'."\n".
 5509:               &Apache::loncommon::end_data_table_row()."\n".
 5510:               &Apache::loncommon::end_data_table()."\n".
 5511:               '</form><br />');
 5512:     $r->print($grading_menu_button);
 5513:     return;
 5514: }
 5515: 
 5516: =pod
 5517: 
 5518: =item get_scantron_config
 5519: 
 5520:    Parse and return the scantron configuration line selected as a
 5521:    hash of configuration file fields.
 5522: 
 5523:  Arguments:
 5524:     which - the name of the configuration to parse from the file.
 5525: 
 5526: 
 5527:  Returns:
 5528:             If the named configuration is not in the file, an empty
 5529:             hash is returned.
 5530:     a hash with the fields
 5531:       name         - internal name for the this configuration setup
 5532:       description  - text to display to operator that describes this config
 5533:       CODElocation - if 0 or the string 'none'
 5534:                           - no CODE exists for this config
 5535:                      if -1 || the string 'letter'
 5536:                           - a CODE exists for this config and is
 5537:                             a string of letters
 5538:                      Unsupported value (but planned for future support)
 5539:                           if a positive integer
 5540:                                - The CODE exists as the first n items from
 5541:                                  the question section of the form
 5542:                           if the string 'number'
 5543:                                - The CODE exists for this config and is
 5544:                                  a string of numbers
 5545:       CODEstart   - (only matter if a CODE exists) column in the line where
 5546:                      the CODE starts
 5547:       CODElength  - length of the CODE
 5548:       IDstart     - column where the student/employee ID starts
 5549:       IDlength    - length of the student/employee ID info
 5550:       Qstart      - column where the information from the bubbled
 5551:                     'questions' start
 5552:       Qlength     - number of columns comprising a single bubble line from
 5553:                     the sheet. (usually either 1 or 10)
 5554:       Qon         - either a single character representing the character used
 5555:                     to signal a bubble was chosen in the positional setup, or
 5556:                     the string 'letter' if the letter of the chosen bubble is
 5557:                     in the final, or 'number' if a number representing the
 5558:                     chosen bubble is in the file (1->A 0->J)
 5559:       Qoff        - the character used to represent that a bubble was
 5560:                     left blank
 5561:       PaperID     - if the scanning process generates a unique number for each
 5562:                     sheet scanned the column that this ID number starts in
 5563:       PaperIDlength - number of columns that comprise the unique ID number
 5564:                       for the sheet of paper
 5565:       FirstName   - column that the first name starts in
 5566:       FirstNameLength - number of columns that the first name spans
 5567:  
 5568:       LastName    - column that the last name starts in
 5569:       LastNameLength - number of columns that the last name spans
 5570: 
 5571: =cut
 5572: 
 5573: sub get_scantron_config {
 5574:     my ($which) = @_;
 5575:     my @lines = &get_scantronformat_file();
 5576:     my %config;
 5577:     #FIXME probably should move to XML it has already gotten a bit much now
 5578:     foreach my $line (@lines) {
 5579: 	my ($name,$descrip)=split(/:/,$line);
 5580: 	if ($name ne $which ) { next; }
 5581: 	chomp($line);
 5582: 	my @config=split(/:/,$line);
 5583: 	$config{'name'}=$config[0];
 5584: 	$config{'description'}=$config[1];
 5585: 	$config{'CODElocation'}=$config[2];
 5586: 	$config{'CODEstart'}=$config[3];
 5587: 	$config{'CODElength'}=$config[4];
 5588: 	$config{'IDstart'}=$config[5];
 5589: 	$config{'IDlength'}=$config[6];
 5590: 	$config{'Qstart'}=$config[7];
 5591:  	$config{'Qlength'}=$config[8];
 5592: 	$config{'Qoff'}=$config[9];
 5593: 	$config{'Qon'}=$config[10];
 5594: 	$config{'PaperID'}=$config[11];
 5595: 	$config{'PaperIDlength'}=$config[12];
 5596: 	$config{'FirstName'}=$config[13];
 5597: 	$config{'FirstNamelength'}=$config[14];
 5598: 	$config{'LastName'}=$config[15];
 5599: 	$config{'LastNamelength'}=$config[16];
 5600: 	last;
 5601:     }
 5602:     return %config;
 5603: }
 5604: 
 5605: =pod 
 5606: 
 5607: =item username_to_idmap
 5608: 
 5609:     creates a hash keyed by student/employee ID with values of the corresponding
 5610:     student username:domain.
 5611: 
 5612:   Arguments:
 5613: 
 5614:     $classlist - reference to the class list hash. This is a hash
 5615:                  keyed by student name:domain  whose elements are references
 5616:                  to arrays containing various chunks of information
 5617:                  about the student. (See loncoursedata for more info).
 5618: 
 5619:   Returns
 5620:     %idmap - the constructed hash
 5621: 
 5622: =cut
 5623: 
 5624: sub username_to_idmap {
 5625:     my ($classlist)= @_;
 5626:     my %idmap;
 5627:     foreach my $student (keys(%$classlist)) {
 5628: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5629: 	    $student;
 5630:     }
 5631:     return %idmap;
 5632: }
 5633: 
 5634: =pod
 5635: 
 5636: =item scantron_fixup_scanline
 5637: 
 5638:    Process a requested correction to a scanline.
 5639: 
 5640:   Arguments:
 5641:     $scantron_config   - hash from &get_scantron_config()
 5642:     $scan_data         - hash of correction information 
 5643:                           (see &scantron_getfile())
 5644:     $line              - existing scanline
 5645:     $whichline         - line number of the passed in scanline
 5646:     $field             - type of change to process 
 5647:                          (either 
 5648:                           'ID'     -> correct the student/employee ID
 5649:                           'CODE'   -> correct the CODE
 5650:                           'answer' -> fixup the submitted answers)
 5651:     
 5652:    $args               - hash of additional info,
 5653:                           - 'ID' 
 5654:                                'newid' -> studentID to use in replacement
 5655:                                           of existing one
 5656:                           - 'CODE' 
 5657:                                'CODE_ignore_dup' - set to true if duplicates
 5658:                                                    should be ignored.
 5659: 	                       'CODE' - is new code or 'use_unfound'
 5660:                                         if the existing unfound code should
 5661:                                         be used as is
 5662:                           - 'answer'
 5663:                                'response' - new answer or 'none' if blank
 5664:                                'question' - the bubble line to change
 5665:                                'questionnum' - the question identifier,
 5666:                                                may include subquestion. 
 5667: 
 5668:   Returns:
 5669:     $line - the modified scanline
 5670: 
 5671:   Side effects: 
 5672:     $scan_data - may be updated
 5673: 
 5674: =cut
 5675: 
 5676: 
 5677: sub scantron_fixup_scanline {
 5678:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5679:     if ($field eq 'ID') {
 5680: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5681: 	    return ($line,1,'New value too large');
 5682: 	}
 5683: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5684: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5685: 				     $args->{'newid'});
 5686: 	}
 5687: 	substr($line,$$scantron_config{'IDstart'}-1,
 5688: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5689: 	if ($args->{'newid'}=~/^\s*$/) {
 5690: 	    &scan_data($scan_data,"$whichline.user",
 5691: 		       $args->{'username'}.':'.$args->{'domain'});
 5692: 	}
 5693:     } elsif ($field eq 'CODE') {
 5694: 	if ($args->{'CODE_ignore_dup'}) {
 5695: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5696: 	}
 5697: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5698: 	if ($args->{'CODE'} ne 'use_unfound') {
 5699: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5700: 		return ($line,1,'New CODE value too large');
 5701: 	    }
 5702: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5703: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5704: 	    }
 5705: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5706: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5707: 	}
 5708:     } elsif ($field eq 'answer') {
 5709: 	my $length=$scantron_config->{'Qlength'};
 5710: 	my $off=$scantron_config->{'Qoff'};
 5711: 	my $on=$scantron_config->{'Qon'};
 5712: 	my $answer=${off}x$length;
 5713: 	if ($args->{'response'} eq 'none') {
 5714: 	    &scan_data($scan_data,
 5715: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5716: 	} else {
 5717: 	    if ($on eq 'letter') {
 5718: 		my @alphabet=('A'..'Z');
 5719: 		$answer=$alphabet[$args->{'response'}];
 5720: 	    } elsif ($on eq 'number') {
 5721: 		$answer=$args->{'response'}+1;
 5722: 		if ($answer == 10) { $answer = '0'; }
 5723: 	    } else {
 5724: 		substr($answer,$args->{'response'},1)=$on;
 5725: 	    }
 5726: 	    &scan_data($scan_data,
 5727: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5728: 	}
 5729: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5730: 	substr($line,$where-1,$length)=$answer;
 5731:     }
 5732:     return $line;
 5733: }
 5734: 
 5735: =pod
 5736: 
 5737: =item scan_data
 5738: 
 5739:     Edit or look up  an item in the scan_data hash.
 5740: 
 5741:   Arguments:
 5742:     $scan_data  - The hash (see scantron_getfile)
 5743:     $key        - shorthand of the key to edit (actual key is
 5744:                   scantronfilename_key).
 5745:     $data        - New value of the hash entry.
 5746:     $delete      - If true, the entry is removed from the hash.
 5747: 
 5748:   Returns:
 5749:     The new value of the hash table field (undefined if deleted).
 5750: 
 5751: =cut
 5752: 
 5753: 
 5754: sub scan_data {
 5755:     my ($scan_data,$key,$value,$delete)=@_;
 5756:     my $filename=$env{'form.scantron_selectfile'};
 5757:     if (defined($value)) {
 5758: 	$scan_data->{$filename.'_'.$key} = $value;
 5759:     }
 5760:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5761:     return $scan_data->{$filename.'_'.$key};
 5762: }
 5763: 
 5764: # ----- These first few routines are general use routines.----
 5765: 
 5766: # Return the number of occurences of a pattern in a string.
 5767: 
 5768: sub occurence_count {
 5769:     my ($string, $pattern) = @_;
 5770: 
 5771:     my @matches = ($string =~ /$pattern/g);
 5772: 
 5773:     return scalar(@matches);
 5774: }
 5775: 
 5776: 
 5777: # Take a string known to have digits and convert all the
 5778: # digits into letters in the range J,A..I.
 5779: 
 5780: sub digits_to_letters {
 5781:     my ($input) = @_;
 5782: 
 5783:     my @alphabet = ('J', 'A'..'I');
 5784: 
 5785:     my @input    = split(//, $input);
 5786:     my $output ='';
 5787:     for (my $i = 0; $i < scalar(@input); $i++) {
 5788: 	if ($input[$i] =~ /\d/) {
 5789: 	    $output .= $alphabet[$input[$i]];
 5790: 	} else {
 5791: 	    $output .= $input[$i];
 5792: 	}
 5793:     }
 5794:     return $output;
 5795: }
 5796: 
 5797: =pod 
 5798: 
 5799: =item scantron_parse_scanline
 5800: 
 5801:   Decodes a scanline from the selected scantron file
 5802: 
 5803:  Arguments:
 5804:     line             - The text of the scantron file line to process
 5805:     whichline        - Line number
 5806:     scantron_config  - Hash describing the format of the scantron lines.
 5807:     scan_data        - Hash of extra information about the scanline
 5808:                        (see scantron_getfile for more information)
 5809:     just_header      - True if should not process question answers but only
 5810:                        the stuff to the left of the answers.
 5811:  Returns:
 5812:    Hash containing the result of parsing the scanline
 5813: 
 5814:    Keys are all proceeded by the string 'scantron.'
 5815: 
 5816:        CODE    - the CODE in use for this scanline
 5817:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5818:                  by the operator
 5819:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5820:                             CODEs were selected, but the usage has been
 5821:                             forced by the operator
 5822:        ID  - student/employee ID
 5823:        PaperID - if used, the ID number printed on the sheet when the 
 5824:                  paper was scanned
 5825:        FirstName - first name from the sheet
 5826:        LastName  - last name from the sheet
 5827: 
 5828:      if just_header was not true these key may also exist
 5829: 
 5830:        missingerror - a list of bubble ranges that are considered to be answers
 5831:                       to a single question that don't have any bubbles filled in.
 5832:                       Of the form questionnumber:firstbubblenumber:count.
 5833:        doubleerror  - a list of bubble ranges that are considered to be answers
 5834:                       to a single question that have more than one bubble filled in.
 5835:                       Of the form questionnumber::firstbubblenumber:count
 5836:    
 5837:                 In the above, count is the number of bubble responses in the
 5838:                 input line needed to represent the possible answers to the question.
 5839:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5840:                 per line would have count = 2.
 5841: 
 5842:        maxquest     - the number of the last bubble line that was parsed
 5843: 
 5844:        (<number> starts at 1)
 5845:        <number>.answer - zero or more letters representing the selected
 5846:                          letters from the scanline for the bubble line 
 5847:                          <number>.
 5848:                          if blank there was either no bubble or there where
 5849:                          multiple bubbles, (consult the keys missingerror and
 5850:                          doubleerror if this is an error condition)
 5851: 
 5852: =cut
 5853: 
 5854: sub scantron_parse_scanline {
 5855:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5856: 
 5857:     my %record;
 5858:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5859:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5860:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5861:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5862: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5863: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5864: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5865: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5866: 	    $record{'scantron.CODE'}=substr($data,
 5867: 					    $$scantron_config{'CODEstart'}-1,
 5868: 					    $$scantron_config{'CODElength'});
 5869: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5870: 		$record{'scantron.useCODE'}=1;
 5871: 	    }
 5872: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5873: 		$record{'scantron.CODE_ignore_dup'}=1;
 5874: 	    }
 5875: 	} else {
 5876: 	    #FIXME interpret first N questions
 5877: 	}
 5878:     }
 5879:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5880: 				  $$scantron_config{'IDlength'});
 5881:     $record{'scantron.PaperID'}=
 5882: 	substr($data,$$scantron_config{'PaperID'}-1,
 5883: 	       $$scantron_config{'PaperIDlength'});
 5884:     $record{'scantron.FirstName'}=
 5885: 	substr($data,$$scantron_config{'FirstName'}-1,
 5886: 	       $$scantron_config{'FirstNamelength'});
 5887:     $record{'scantron.LastName'}=
 5888: 	substr($data,$$scantron_config{'LastName'}-1,
 5889: 	       $$scantron_config{'LastNamelength'});
 5890:     if ($just_header) { return \%record; }
 5891: 
 5892:     my @alphabet=('A'..'Z');
 5893:     my $questnum=0;
 5894:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5895: 
 5896:     chomp($questions);		# Get rid of any trailing \n.
 5897:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5898:     while (length($questions)) {
 5899: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5900:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5901:                              || 1;
 5902:         $questnum++;
 5903:         my $quest_id = $questnum;
 5904:         my $currentquest = substr($questions,0,$answer_length);
 5905:         $questions       = substr($questions,$answer_length);
 5906:         if (length($currentquest) < $answer_length) { next; }
 5907: 
 5908:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5909:             my $subquestnum = 1;
 5910:             my $subquestions = $currentquest;
 5911:             my @subanswers_needed = 
 5912:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5913:             foreach my $subans (@subanswers_needed) {
 5914:                 my $subans_length =
 5915:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5916:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5917:                 $subquestions   = substr($subquestions,$subans_length);
 5918:                 $quest_id = "$questnum.$subquestnum";
 5919:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5920:                     ($$scantron_config{'Qon'} eq 'number')) {
 5921:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5922:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5923:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5924:                 } else {
 5925:                     $ansnum = &scantron_validator_positional($ansnum,
 5926:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5927:                 }
 5928:                 $subquestnum ++;
 5929:             }
 5930:         } else {
 5931:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5932:                 ($$scantron_config{'Qon'} eq 'number')) {
 5933:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5934:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5935:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5936:             } else {
 5937:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5938:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5939:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5940:             }
 5941:         }
 5942:     }
 5943:     $record{'scantron.maxquest'}=$questnum;
 5944:     return \%record;
 5945: }
 5946: 
 5947: sub scantron_validator_lettnum {
 5948:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5949:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5950: 
 5951:     # Qon 'letter' implies for each slot in currquest we have:
 5952:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5953:     #    about anything else (esp. a value of Qoff) for missing
 5954:     #    bubbles.
 5955:     #
 5956:     # Qon 'number' implies each slot gives a digit that indexes the
 5957:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5958:     #    and * or ? for double bubbles on a single line.
 5959:     #
 5960: 
 5961:     my $matchon;
 5962:     if ($$scantron_config{'Qon'} eq 'letter') {
 5963:         $matchon = '[A-Z]';
 5964:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5965:         $matchon = '\d';
 5966:     }
 5967:     my $occurrences = 0;
 5968:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5969:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5970:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5971:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5972:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5973:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5974:         my @singlelines = split('',$currquest);
 5975:         foreach my $entry (@singlelines) {
 5976:             $occurrences = &occurence_count($entry,$matchon);
 5977:             if ($occurrences > 1) {
 5978:                 last;
 5979:             }
 5980:         } 
 5981:     } else {
 5982:         $occurrences = &occurence_count($currquest,$matchon); 
 5983:     }
 5984:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5985:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5986:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5987:             my $bubble = substr($currquest,$ans,1);
 5988:             if ($bubble =~ /$matchon/ ) {
 5989:                 if ($$scantron_config{'Qon'} eq 'number') {
 5990:                     if ($bubble == 0) {
 5991:                         $bubble = 10; 
 5992:                     }
 5993:                     $record->{"scantron.$ansnum.answer"} = 
 5994:                         $alphabet->[$bubble-1];
 5995:                 } else {
 5996:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5997:                 }
 5998:             } else {
 5999:                 $record->{"scantron.$ansnum.answer"}='';
 6000:             }
 6001:             $ansnum++;
 6002:         }
 6003:     } elsif (!defined($currquest)
 6004:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6005:             || (&occurence_count($currquest,$matchon) == 0)) {
 6006:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6007:             $record->{"scantron.$ansnum.answer"}='';
 6008:             $ansnum++;
 6009:         }
 6010:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6011:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6012:         }
 6013:     } else {
 6014:         if ($$scantron_config{'Qon'} eq 'number') {
 6015:             $currquest = &digits_to_letters($currquest);            
 6016:         }
 6017:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6018:             my $bubble = substr($currquest,$ans,1);
 6019:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6020:             $ansnum++;
 6021:         }
 6022:     }
 6023:     return $ansnum;
 6024: }
 6025: 
 6026: sub scantron_validator_positional {
 6027:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6028:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 6029: 
 6030:     # Otherwise there's a positional notation;
 6031:     # each bubble line requires Qlength items, and there are filled in
 6032:     # bubbles for each case where there 'Qon' characters.
 6033:     #
 6034: 
 6035:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6036: 
 6037:     # If the split only gives us one element.. the full length of the
 6038:     # answer string, no bubbles are filled in:
 6039: 
 6040:     if ($answers_needed eq '') {
 6041:         return;
 6042:     }
 6043: 
 6044:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6045:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6046:             $record->{"scantron.$ansnum.answer"}='';
 6047:             $ansnum++;
 6048:         }
 6049:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6050:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6051:         }
 6052:     } elsif (scalar(@array) == 2) {
 6053:         my $location = length($array[0]);
 6054:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6055:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6056:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6057:             if ($ans eq $line_num) {
 6058:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6059:             } else {
 6060:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6061:             }
 6062:             $ansnum++;
 6063:          }
 6064:     } else {
 6065:         #  If there's more than one instance of a bubble character
 6066:         #  That's a double bubble; with positional notation we can
 6067:         #  record all the bubbles filled in as well as the
 6068:         #  fact this response consists of multiple bubbles.
 6069:         #
 6070:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6071:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6072:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6073:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6074:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6075:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6076:             my $doubleerror = 0;
 6077:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6078:                    (!$doubleerror)) {
 6079:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6080:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6081:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6082:                if (length(@currarray) > 2) {
 6083:                    $doubleerror = 1;
 6084:                } 
 6085:             }
 6086:             if ($doubleerror) {
 6087:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6088:             }
 6089:         } else {
 6090:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6091:         }
 6092:         my $item = $ansnum;
 6093:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6094:             $record->{"scantron.$item.answer"} = '';
 6095:             $item ++;
 6096:         }
 6097: 
 6098:         my @ans=@array;
 6099:         my $i=0;
 6100:         my $increment = 0;
 6101:         while ($#ans) {
 6102:             $i+=length($ans[0]) + $increment;
 6103:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6104:             my $bubble = $i%$$scantron_config{'Qlength'};
 6105:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6106:             shift(@ans);
 6107:             $increment = 1;
 6108:         }
 6109:         $ansnum += $answers_needed;
 6110:     }
 6111:     return $ansnum;
 6112: }
 6113: 
 6114: =pod
 6115: 
 6116: =item scantron_add_delay
 6117: 
 6118:    Adds an error message that occurred during the grading phase to a
 6119:    queue of messages to be shown after grading pass is complete
 6120: 
 6121:  Arguments:
 6122:    $delayqueue  - arrary ref of hash ref of error messages
 6123:    $scanline    - the scanline that caused the error
 6124:    $errormesage - the error message
 6125:    $errorcode   - a numeric code for the error
 6126: 
 6127:  Side Effects:
 6128:    updates the $delayqueue to have a new hash ref of the error
 6129: 
 6130: =cut
 6131: 
 6132: sub scantron_add_delay {
 6133:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6134:     push(@$delayqueue,
 6135: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6136: 	  'ecode' => $errorcode }
 6137: 	 );
 6138: }
 6139: 
 6140: =pod
 6141: 
 6142: =item scantron_find_student
 6143: 
 6144:    Finds the username for the current scanline
 6145: 
 6146:   Arguments:
 6147:    $scantron_record - hash result from scantron_parse_scanline
 6148:    $scan_data       - hash of correction information 
 6149:                       (see &scantron_getfile() form more information)
 6150:    $idmap           - hash from &username_to_idmap()
 6151:    $line            - number of current scanline
 6152:  
 6153:   Returns:
 6154:    Either 'username:domain' or undef if unknown
 6155: 
 6156: =cut
 6157: 
 6158: sub scantron_find_student {
 6159:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6160:     my $scanID=$$scantron_record{'scantron.ID'};
 6161:     if ($scanID =~ /^\s*$/) {
 6162:  	return &scan_data($scan_data,"$line.user");
 6163:     }
 6164:     foreach my $id (keys(%$idmap)) {
 6165:  	if (lc($id) eq lc($scanID)) {
 6166:  	    return $$idmap{$id};
 6167:  	}
 6168:     }
 6169:     return undef;
 6170: }
 6171: 
 6172: =pod
 6173: 
 6174: =item scantron_filter
 6175: 
 6176:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6177:    hidden resources was selected
 6178: 
 6179: =cut
 6180: 
 6181: sub scantron_filter {
 6182:     my ($curres)=@_;
 6183: 
 6184:     if (ref($curres) && $curres->is_problem()) {
 6185: 	# if the user has asked to not have either hidden
 6186: 	# or 'randomout' controlled resources to be graded
 6187: 	# don't include them
 6188: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6189: 	    && $curres->randomout) {
 6190: 	    return 0;
 6191: 	}
 6192: 	return 1;
 6193:     }
 6194:     return 0;
 6195: }
 6196: 
 6197: =pod
 6198: 
 6199: =item scantron_process_corrections
 6200: 
 6201:    Gets correction information out of submitted form data and corrects
 6202:    the scanline
 6203: 
 6204: =cut
 6205: 
 6206: sub scantron_process_corrections {
 6207:     my ($r) = @_;
 6208:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6209:     my ($scanlines,$scan_data)=&scantron_getfile();
 6210:     my $classlist=&Apache::loncoursedata::get_classlist();
 6211:     my $which=$env{'form.scantron_line'};
 6212:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6213:     my ($skip,$err,$errmsg);
 6214:     if ($env{'form.scantron_skip_record'}) {
 6215: 	$skip=1;
 6216:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6217: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6218: 	    $env{'form.scantron_domain'};
 6219: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6220: 	($line,$err,$errmsg)=
 6221: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6222: 				     'ID',{'newid'=>$newid,
 6223: 				    'username'=>$env{'form.scantron_username'},
 6224: 				    'domain'=>$env{'form.scantron_domain'}});
 6225:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6226: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6227: 	my $newCODE;
 6228: 	my %args;
 6229: 	if      ($resolution eq 'use_unfound') {
 6230: 	    $newCODE='use_unfound';
 6231: 	} elsif ($resolution eq 'use_found') {
 6232: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6233: 	} elsif ($resolution eq 'use_typed') {
 6234: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6235: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6236: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6237: 	}
 6238: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6239: 	    $args{'CODE_ignore_dup'}=1;
 6240: 	}
 6241: 	$args{'CODE'}=$newCODE;
 6242: 	($line,$err,$errmsg)=
 6243: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6244: 				     'CODE',\%args);
 6245:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6246: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6247: 	    ($line,$err,$errmsg)=
 6248: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6249: 					 $which,'answer',
 6250: 					 { 'question'=>$question,
 6251: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6252:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6253: 	    if ($err) { last; }
 6254: 	}
 6255:     }
 6256:     if ($err) {
 6257: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6258:     } else {
 6259: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6260: 	&scantron_putfile($scanlines,$scan_data);
 6261:     }
 6262: }
 6263: 
 6264: =pod
 6265: 
 6266: =item reset_skipping_status
 6267: 
 6268:    Forgets the current set of remember skipped scanlines (and thus
 6269:    reverts back to considering all lines in the
 6270:    scantron_skipped_<filename> file)
 6271: 
 6272: =cut
 6273: 
 6274: sub reset_skipping_status {
 6275:     my ($scanlines,$scan_data)=&scantron_getfile();
 6276:     &scan_data($scan_data,'remember_skipping',undef,1);
 6277:     &scantron_putfile(undef,$scan_data);
 6278: }
 6279: 
 6280: =pod
 6281: 
 6282: =item start_skipping
 6283: 
 6284:    Marks a scanline to be skipped. 
 6285: 
 6286: =cut
 6287: 
 6288: sub start_skipping {
 6289:     my ($scan_data,$i)=@_;
 6290:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6291:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6292: 	$remembered{$i}=2;
 6293:     } else {
 6294: 	$remembered{$i}=1;
 6295:     }
 6296:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6297: }
 6298: 
 6299: =pod
 6300: 
 6301: =item should_be_skipped
 6302: 
 6303:    Checks whether a scanline should be skipped.
 6304: 
 6305: =cut
 6306: 
 6307: sub should_be_skipped {
 6308:     my ($scanlines,$scan_data,$i)=@_;
 6309:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6310: 	# not redoing old skips
 6311: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6312: 	return 0;
 6313:     }
 6314:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6315: 
 6316:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6317: 	return 0;
 6318:     }
 6319:     return 1;
 6320: }
 6321: 
 6322: =pod
 6323: 
 6324: =item remember_current_skipped
 6325: 
 6326:    Discovers what scanlines are in the scantron_skipped_<filename>
 6327:    file and remembers them into scan_data for later use.
 6328: 
 6329: =cut
 6330: 
 6331: sub remember_current_skipped {
 6332:     my ($scanlines,$scan_data)=&scantron_getfile();
 6333:     my %to_remember;
 6334:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6335: 	if ($scanlines->{'skipped'}[$i]) {
 6336: 	    $to_remember{$i}=1;
 6337: 	}
 6338:     }
 6339: 
 6340:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6341:     &scantron_putfile(undef,$scan_data);
 6342: }
 6343: 
 6344: =pod
 6345: 
 6346: =item check_for_error
 6347: 
 6348:     Checks if there was an error when attempting to remove a specific
 6349:     scantron_.. bubblesheet data file. Prints out an error if
 6350:     something went wrong.
 6351: 
 6352: =cut
 6353: 
 6354: sub check_for_error {
 6355:     my ($r,$result)=@_;
 6356:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6357: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6358:     }
 6359: }
 6360: 
 6361: =pod
 6362: 
 6363: =item scantron_warning_screen
 6364: 
 6365:    Interstitial screen to make sure the operator has selected the
 6366:    correct options before we start the validation phase.
 6367: 
 6368: =cut
 6369: 
 6370: sub scantron_warning_screen {
 6371:     my ($button_text)=@_;
 6372:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6373:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6374:     my $CODElist;
 6375:     if ($scantron_config{'CODElocation'} &&
 6376: 	$scantron_config{'CODEstart'} &&
 6377: 	$scantron_config{'CODElength'}) {
 6378: 	$CODElist=$env{'form.scantron_CODElist'};
 6379: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6380: 	$CODElist=
 6381: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6382: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6383:     }
 6384:     return ('
 6385: <p>
 6386: <span class="LC_warning">
 6387: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6388: </p>
 6389: <table>
 6390: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6391: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6392: '.$CODElist.'
 6393: </table>
 6394: <br />
 6395: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6396: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6397: 
 6398: <br />
 6399: ');
 6400: }
 6401: 
 6402: =pod
 6403: 
 6404: =item scantron_do_warning
 6405: 
 6406:    Check if the operator has picked something for all required
 6407:    fields. Error out if something is missing.
 6408: 
 6409: =cut
 6410: 
 6411: sub scantron_do_warning {
 6412:     my ($r)=@_;
 6413:     my ($symb)=&get_symb($r);
 6414:     if (!$symb) {return '';}
 6415:     my $default_form_data=&defaultFormData($symb);
 6416:     $r->print(&scantron_form_start().$default_form_data);
 6417:     if ( $env{'form.selectpage'} eq '' ||
 6418: 	 $env{'form.scantron_selectfile'} eq '' ||
 6419: 	 $env{'form.scantron_format'} eq '' ) {
 6420: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6421: 	if ( $env{'form.selectpage'} eq '') {
 6422: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6423: 	} 
 6424: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6425: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6426: 	} 
 6427: 	if ( $env{'form.scantron_format'} eq '') {
 6428: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6429: 	} 
 6430:     } else {
 6431: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6432: 	$r->print('
 6433: '.$warning.'
 6434: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6435: <input type="hidden" name="command" value="scantron_validate" />
 6436: ');
 6437:     }
 6438:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6439:     return '';
 6440: }
 6441: 
 6442: =pod
 6443: 
 6444: =item scantron_form_start
 6445: 
 6446:     html hidden input for remembering all selected grading options
 6447: 
 6448: =cut
 6449: 
 6450: sub scantron_form_start {
 6451:     my ($max_bubble)=@_;
 6452:     my $result= <<SCANTRONFORM;
 6453: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6454:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6455:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6456:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6457:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6458:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6459:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6460:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6461:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6462:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6463: SCANTRONFORM
 6464: 
 6465:   my $line = 0;
 6466:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6467:        my $chunk =
 6468: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6469:        $chunk .=
 6470: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6471:        $chunk .= 
 6472:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6473:        $chunk .=
 6474:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6475:        $result .= $chunk;
 6476:        $line++;
 6477:    }
 6478:     return $result;
 6479: }
 6480: 
 6481: =pod
 6482: 
 6483: =item scantron_validate_file
 6484: 
 6485:     Dispatch routine for doing validation of a bubblesheet data file.
 6486: 
 6487:     Also processes any necessary information resets that need to
 6488:     occur before validation begins (ignore previous corrections,
 6489:     restarting the skipped records processing)
 6490: 
 6491: =cut
 6492: 
 6493: sub scantron_validate_file {
 6494:     my ($r) = @_;
 6495:     my ($symb)=&get_symb($r);
 6496:     if (!$symb) {return '';}
 6497:     my $default_form_data=&defaultFormData($symb);
 6498:     
 6499:     # do the detection of only doing skipped records first befroe we delete
 6500:     # them when doing the corrections reset
 6501:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6502: 	&reset_skipping_status();
 6503:     }
 6504:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6505: 	&remember_current_skipped();
 6506: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6507:     }
 6508: 
 6509:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6510: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6511: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6512: 	&check_for_error($r,&scantron_remove_scan_data());
 6513: 	$env{'form.scantron_options_ignore'}='done';
 6514:     }
 6515: 
 6516:     if ($env{'form.scantron_corrections'}) {
 6517: 	&scantron_process_corrections($r);
 6518:     }
 6519:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6520:     #get the student pick code ready
 6521:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6522:     my $nav_error;
 6523:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6524:     if ($nav_error) {
 6525:         $r->print(&navmap_errormsg());
 6526:         return '';
 6527:     }
 6528:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6529:     $r->print($result);
 6530:     
 6531:     my @validate_phases=( 'sequence',
 6532: 			  'ID',
 6533: 			  'CODE',
 6534: 			  'doublebubble',
 6535: 			  'missingbubbles');
 6536:     if (!$env{'form.validatepass'}) {
 6537: 	$env{'form.validatepass'} = 0;
 6538:     }
 6539:     my $currentphase=$env{'form.validatepass'};
 6540: 
 6541: 
 6542:     my $stop=0;
 6543:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6544: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6545: 	$r->rflush();
 6546: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6547: 	{
 6548: 	    no strict 'refs';
 6549: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6550: 	}
 6551:     }
 6552:     if (!$stop) {
 6553: 	my $warning=&scantron_warning_screen('Start Grading');
 6554: 	$r->print(&mt('Validation process complete.').'<br />'.
 6555:                   $warning.
 6556:                   &mt('Perform verification for each student after storage of submissions?').
 6557:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6558:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6559:                   ('&nbsp;'x3).'<label>'.
 6560:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6561:                   '</label></span><br />'.
 6562:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6563:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6564:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6565:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6566:     } else {
 6567: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6568: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6569:     }
 6570:     if ($stop) {
 6571: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6572: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6573: 	    $r->print(' '.&mt('this error').' <br />');
 6574: 
 6575: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6576: 	} else {
 6577:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6578: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6579:             } else {
 6580:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6581:             }
 6582: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6583: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6584: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6585: 	}
 6586:     }
 6587:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6588:     return '';
 6589: }
 6590: 
 6591: 
 6592: =pod
 6593: 
 6594: =item scantron_remove_file
 6595: 
 6596:    Removes the requested bubblesheet data file, makes sure that
 6597:    scantron_original_<filename> is never removed
 6598: 
 6599: 
 6600: =cut
 6601: 
 6602: sub scantron_remove_file {
 6603:     my ($which)=@_;
 6604:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6605:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6606:     my $file='scantron_';
 6607:     if ($which eq 'corrected' || $which eq 'skipped') {
 6608: 	$file.=$which.'_';
 6609:     } else {
 6610: 	return 'refused';
 6611:     }
 6612:     $file.=$env{'form.scantron_selectfile'};
 6613:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6614: }
 6615: 
 6616: 
 6617: =pod
 6618: 
 6619: =item scantron_remove_scan_data
 6620: 
 6621:    Removes all scan_data correction for the requested bubblesheet
 6622:    data file.  (In the case that both the are doing skipped records we need
 6623:    to remember the old skipped lines for the time being so that element
 6624:    persists for a while.)
 6625: 
 6626: =cut
 6627: 
 6628: sub scantron_remove_scan_data {
 6629:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6630:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6631:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6632:     my @todelete;
 6633:     my $filename=$env{'form.scantron_selectfile'};
 6634:     foreach my $key (@keys) {
 6635: 	if ($key=~/^\Q$filename\E_/) {
 6636: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6637: 		$key=~/remember_skipping/) {
 6638: 		next;
 6639: 	    }
 6640: 	    push(@todelete,$key);
 6641: 	}
 6642:     }
 6643:     my $result;
 6644:     if (@todelete) {
 6645: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6646: 				       \@todelete,$cdom,$cname);
 6647:     } else {
 6648: 	$result = 'ok';
 6649:     }
 6650:     return $result;
 6651: }
 6652: 
 6653: 
 6654: =pod
 6655: 
 6656: =item scantron_getfile
 6657: 
 6658:     Fetches the requested bubblesheet data file (all 3 versions), and
 6659:     the scan_data hash
 6660:   
 6661:   Arguments:
 6662:     None
 6663: 
 6664:   Returns:
 6665:     2 hash references
 6666: 
 6667:      - first one has 
 6668:          orig      -
 6669:          corrected -
 6670:          skipped   -  each of which points to an array ref of the specified
 6671:                       file broken up into individual lines
 6672:          count     - number of scanlines
 6673:  
 6674:      - second is the scan_data hash possible keys are
 6675:        ($number refers to scanline numbered $number and thus the key affects
 6676:         only that scanline
 6677:         $bubline refers to the specific bubble line element and the aspects
 6678:         refers to that specific bubble line element)
 6679: 
 6680:        $number.user - username:domain to use
 6681:        $number.CODE_ignore_dup 
 6682:                     - ignore the duplicate CODE error 
 6683:        $number.useCODE
 6684:                     - use the CODE in the scanline as is
 6685:        $number.no_bubble.$bubline
 6686:                     - it is valid that there is no bubbled in bubble
 6687:                       at $number $bubline
 6688:        remember_skipping
 6689:                     - a frozen hash containing keys of $number and values
 6690:                       of either 
 6691:                         1 - we are on a 'do skipped records pass' and plan
 6692:                             on processing this line
 6693:                         2 - we are on a 'do skipped records pass' and this
 6694:                             scanline has been marked to skip yet again
 6695: 
 6696: =cut
 6697: 
 6698: sub scantron_getfile {
 6699:     #FIXME really would prefer a scantron directory
 6700:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6701:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6702:     my $lines;
 6703:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6704: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6705:     my %scanlines;
 6706:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6707:     my $temp=$scanlines{'orig'};
 6708:     $scanlines{'count'}=$#$temp;
 6709: 
 6710:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6711: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6712:     if ($lines eq '-1') {
 6713: 	$scanlines{'corrected'}=[];
 6714:     } else {
 6715: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6716:     }
 6717:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6718: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6719:     if ($lines eq '-1') {
 6720: 	$scanlines{'skipped'}=[];
 6721:     } else {
 6722: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6723:     }
 6724:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6725:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6726:     my %scan_data = @tmp;
 6727:     return (\%scanlines,\%scan_data);
 6728: }
 6729: 
 6730: =pod
 6731: 
 6732: =item lonnet_putfile
 6733: 
 6734:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6735: 
 6736:  Arguments:
 6737:    $contents - data to store
 6738:    $filename - filename to store $contents into
 6739: 
 6740:  Returns:
 6741:    result value from &Apache::lonnet::finishuserfileupload
 6742: 
 6743: =cut
 6744: 
 6745: sub lonnet_putfile {
 6746:     my ($contents,$filename)=@_;
 6747:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6748:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6749:     $env{'form.sillywaytopassafilearound'}=$contents;
 6750:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6751: 
 6752: }
 6753: 
 6754: =pod
 6755: 
 6756: =item scantron_putfile
 6757: 
 6758:     Stores the current version of the bubblesheet data files, and the
 6759:     scan_data hash. (Does not modify the original version only the
 6760:     corrected and skipped versions.
 6761: 
 6762:  Arguments:
 6763:     $scanlines - hash ref that looks like the first return value from
 6764:                  &scantron_getfile()
 6765:     $scan_data - hash ref that looks like the second return value from
 6766:                  &scantron_getfile()
 6767: 
 6768: =cut
 6769: 
 6770: sub scantron_putfile {
 6771:     my ($scanlines,$scan_data) = @_;
 6772:     #FIXME really would prefer a scantron directory
 6773:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6774:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6775:     if ($scanlines) {
 6776: 	my $prefix='scantron_';
 6777: # no need to update orig, shouldn't change
 6778: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6779: #		    $env{'form.scantron_selectfile'});
 6780: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6781: 			$prefix.'corrected_'.
 6782: 			$env{'form.scantron_selectfile'});
 6783: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6784: 			$prefix.'skipped_'.
 6785: 			$env{'form.scantron_selectfile'});
 6786:     }
 6787:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6788: }
 6789: 
 6790: =pod
 6791: 
 6792: =item scantron_get_line
 6793: 
 6794:    Returns the correct version of the scanline
 6795: 
 6796:  Arguments:
 6797:     $scanlines - hash ref that looks like the first return value from
 6798:                  &scantron_getfile()
 6799:     $scan_data - hash ref that looks like the second return value from
 6800:                  &scantron_getfile()
 6801:     $i         - number of the requested line (starts at 0)
 6802: 
 6803:  Returns:
 6804:    A scanline, (either the original or the corrected one if it
 6805:    exists), or undef if the requested scanline should be
 6806:    skipped. (Either because it's an skipped scanline, or it's an
 6807:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6808:    pass.
 6809: 
 6810: =cut
 6811: 
 6812: sub scantron_get_line {
 6813:     my ($scanlines,$scan_data,$i)=@_;
 6814:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6815:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6816:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6817:     return $scanlines->{'orig'}[$i]; 
 6818: }
 6819: 
 6820: =pod
 6821: 
 6822: =item scantron_todo_count
 6823: 
 6824:     Counts the number of scanlines that need processing.
 6825: 
 6826:  Arguments:
 6827:     $scanlines - hash ref that looks like the first return value from
 6828:                  &scantron_getfile()
 6829:     $scan_data - hash ref that looks like the second return value from
 6830:                  &scantron_getfile()
 6831: 
 6832:  Returns:
 6833:     $count - number of scanlines to process
 6834: 
 6835: =cut
 6836: 
 6837: sub get_todo_count {
 6838:     my ($scanlines,$scan_data)=@_;
 6839:     my $count=0;
 6840:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6841: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6842: 	if ($line=~/^[\s\cz]*$/) { next; }
 6843: 	$count++;
 6844:     }
 6845:     return $count;
 6846: }
 6847: 
 6848: =pod
 6849: 
 6850: =item scantron_put_line
 6851: 
 6852:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 6853:     data file.
 6854: 
 6855:  Arguments:
 6856:     $scanlines - hash ref that looks like the first return value from
 6857:                  &scantron_getfile()
 6858:     $scan_data - hash ref that looks like the second return value from
 6859:                  &scantron_getfile()
 6860:     $i         - line number to update
 6861:     $newline   - contents of the updated scanline
 6862:     $skip      - if true make the line for skipping and update the
 6863:                  'skipped' file
 6864: 
 6865: =cut
 6866: 
 6867: sub scantron_put_line {
 6868:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6869:     if ($skip) {
 6870: 	$scanlines->{'skipped'}[$i]=$newline;
 6871: 	&start_skipping($scan_data,$i);
 6872: 	return;
 6873:     }
 6874:     $scanlines->{'corrected'}[$i]=$newline;
 6875: }
 6876: 
 6877: =pod
 6878: 
 6879: =item scantron_clear_skip
 6880: 
 6881:    Remove a line from the 'skipped' file
 6882: 
 6883:  Arguments:
 6884:     $scanlines - hash ref that looks like the first return value from
 6885:                  &scantron_getfile()
 6886:     $scan_data - hash ref that looks like the second return value from
 6887:                  &scantron_getfile()
 6888:     $i         - line number to update
 6889: 
 6890: =cut
 6891: 
 6892: sub scantron_clear_skip {
 6893:     my ($scanlines,$scan_data,$i)=@_;
 6894:     if (exists($scanlines->{'skipped'}[$i])) {
 6895: 	undef($scanlines->{'skipped'}[$i]);
 6896: 	return 1;
 6897:     }
 6898:     return 0;
 6899: }
 6900: 
 6901: =pod
 6902: 
 6903: =item scantron_filter_not_exam
 6904: 
 6905:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6906:    filter out resources that are not marked as 'exam' mode
 6907: 
 6908: =cut
 6909: 
 6910: sub scantron_filter_not_exam {
 6911:     my ($curres)=@_;
 6912:     
 6913:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6914: 	# if the user has asked to not have either hidden
 6915: 	# or 'randomout' controlled resources to be graded
 6916: 	# don't include them
 6917: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6918: 	    && $curres->randomout) {
 6919: 	    return 0;
 6920: 	}
 6921: 	return 1;
 6922:     }
 6923:     return 0;
 6924: }
 6925: 
 6926: =pod
 6927: 
 6928: =item scantron_validate_sequence
 6929: 
 6930:     Validates the selected sequence, checking for resource that are
 6931:     not set to exam mode.
 6932: 
 6933: =cut
 6934: 
 6935: sub scantron_validate_sequence {
 6936:     my ($r,$currentphase) = @_;
 6937: 
 6938:     my $navmap=Apache::lonnavmaps::navmap->new();
 6939:     unless (ref($navmap)) {
 6940:         $r->print(&navmap_errormsg());
 6941:         return (1,$currentphase);
 6942:     }
 6943:     my (undef,undef,$sequence)=
 6944: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6945: 
 6946:     my $map=$navmap->getResourceByUrl($sequence);
 6947: 
 6948:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6949:                                     value="ignore" />');
 6950:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6951: 	my @resources=
 6952: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6953: 	if (@resources) {
 6954: 	    $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>");
 6955: 	    return (1,$currentphase);
 6956: 	}
 6957:     }
 6958: 
 6959:     return (0,$currentphase+1);
 6960: }
 6961: 
 6962: 
 6963: 
 6964: sub scantron_validate_ID {
 6965:     my ($r,$currentphase) = @_;
 6966:     
 6967:     #get student info
 6968:     my $classlist=&Apache::loncoursedata::get_classlist();
 6969:     my %idmap=&username_to_idmap($classlist);
 6970: 
 6971:     #get scantron line setup
 6972:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6973:     my ($scanlines,$scan_data)=&scantron_getfile();
 6974: 
 6975:     my $nav_error;
 6976:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6977:     if ($nav_error) {
 6978:         $r->print(&navmap_errormsg());
 6979:         return(1,$currentphase);
 6980:     }
 6981: 
 6982:     my %found=('ids'=>{},'usernames'=>{});
 6983:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6984: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6985: 	if ($line=~/^[\s\cz]*$/) { next; }
 6986: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6987: 						 $scan_data);
 6988: 	my $id=$$scan_record{'scantron.ID'};
 6989: 	my $found;
 6990: 	foreach my $checkid (keys(%idmap)) {
 6991: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6992: 	}
 6993: 	if ($found) {
 6994: 	    my $username=$idmap{$found};
 6995: 	    if ($found{'ids'}{$found}) {
 6996: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6997: 					 $line,'duplicateID',$found);
 6998: 		return(1,$currentphase);
 6999: 	    } elsif ($found{'usernames'}{$username}) {
 7000: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7001: 					 $line,'duplicateID',$username);
 7002: 		return(1,$currentphase);
 7003: 	    }
 7004: 	    #FIXME store away line we previously saw the ID on to use above
 7005: 	    $found{'ids'}{$found}++;
 7006: 	    $found{'usernames'}{$username}++;
 7007: 	} else {
 7008: 	    if ($id =~ /^\s*$/) {
 7009: 		my $username=&scan_data($scan_data,"$i.user");
 7010: 		if (defined($username) && $found{'usernames'}{$username}) {
 7011: 		    &scantron_get_correction($r,$i,$scan_record,
 7012: 					     \%scantron_config,
 7013: 					     $line,'duplicateID',$username);
 7014: 		    return(1,$currentphase);
 7015: 		} elsif (!defined($username)) {
 7016: 		    &scantron_get_correction($r,$i,$scan_record,
 7017: 					     \%scantron_config,
 7018: 					     $line,'incorrectID');
 7019: 		    return(1,$currentphase);
 7020: 		}
 7021: 		$found{'usernames'}{$username}++;
 7022: 	    } else {
 7023: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7024: 					 $line,'incorrectID');
 7025: 		return(1,$currentphase);
 7026: 	    }
 7027: 	}
 7028:     }
 7029: 
 7030:     return (0,$currentphase+1);
 7031: }
 7032: 
 7033: 
 7034: sub scantron_get_correction {
 7035:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 7036: #FIXME in the case of a duplicated ID the previous line, probably need
 7037: #to show both the current line and the previous one and allow skipping
 7038: #the previous one or the current one
 7039: 
 7040:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7041:         $r->print(
 7042:             '<p class="LC_warning">'
 7043:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7044:                 "<b>$error</b>",
 7045:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7046:            ."</p> \n");
 7047:     } else {
 7048:         $r->print(
 7049:             '<p class="LC_warning">'
 7050:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7051:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7052:            ."</p> \n");
 7053:     }
 7054:     my $message =
 7055:         '<p>'
 7056:        .&mt('The ID on the form is [_1]',
 7057:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7058:        .'<br />'
 7059:        .&mt('The name on the paper is [_1], [_2]',
 7060:             $$scan_record{'scantron.LastName'},
 7061:             $$scan_record{'scantron.FirstName'})
 7062:        .'</p>';
 7063: 
 7064:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7065:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7066:                            # Array populated for doublebubble or
 7067:     my @lines_to_correct;  # missingbubble errors to build javascript
 7068:                            # to validate radio button checking   
 7069: 
 7070:     if ($error =~ /ID$/) {
 7071: 	if ($error eq 'incorrectID') {
 7072: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7073: 		      "</p>\n");
 7074: 	} elsif ($error eq 'duplicateID') {
 7075: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7076: 	}
 7077: 	$r->print($message);
 7078: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7079: 	$r->print("\n<ul><li> ");
 7080: 	#FIXME it would be nice if this sent back the user ID and
 7081: 	#could do partial userID matches
 7082: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7083: 				       'scantron_username','scantron_domain'));
 7084: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7085: 	$r->print("\n@".
 7086: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7087: 
 7088: 	$r->print('</li>');
 7089:     } elsif ($error =~ /CODE$/) {
 7090: 	if ($error eq 'incorrectCODE') {
 7091: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7092: 	} elsif ($error eq 'duplicateCODE') {
 7093: 	    $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");
 7094: 	}
 7095:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7096:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7097:                  ."</p>\n");
 7098: 	$r->print($message);
 7099: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7100: 	$r->print("\n<br /> ");
 7101: 	my $i=0;
 7102: 	if ($error eq 'incorrectCODE' 
 7103: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7104: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7105: 	    if ($closest > 0) {
 7106: 		foreach my $testcode (@{$closest}) {
 7107: 		    my $checked='';
 7108: 		    if (!$i) { $checked=' checked="checked"'; }
 7109: 		    $r->print("
 7110:    <label>
 7111:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7112:        ".&mt("Use the similar CODE [_1] instead.",
 7113: 	    "<b><tt>".$testcode."</tt></b>")."
 7114:     </label>
 7115:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7116: 		    $r->print("\n<br />");
 7117: 		    $i++;
 7118: 		}
 7119: 	    }
 7120: 	}
 7121: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7122: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7123: 	    $r->print("
 7124:     <label>
 7125:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7126:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7127: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7128:     </label>");
 7129: 	    $r->print("\n<br />");
 7130: 	}
 7131: 
 7132: 	$r->print(<<ENDSCRIPT);
 7133: <script type="text/javascript">
 7134: function change_radio(field) {
 7135:     var slct=document.scantronupload.scantron_CODE_resolution;
 7136:     var i;
 7137:     for (i=0;i<slct.length;i++) {
 7138:         if (slct[i].value==field) { slct[i].checked=true; }
 7139:     }
 7140: }
 7141: </script>
 7142: ENDSCRIPT
 7143: 	my $href="/adm/pickcode?".
 7144: 	   "form=".&escape("scantronupload").
 7145: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7146: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7147: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7148: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7149: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7150: 	    $r->print("
 7151:     <label>
 7152:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7153:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7154: 	     "<a target='_blank' href='$href'>","</a>")."
 7155:     </label> 
 7156:     ".&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\')" />'));
 7157: 	    $r->print("\n<br />");
 7158: 	}
 7159: 	$r->print("
 7160:     <label>
 7161:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7162:        ".&mt("Use [_1] as the CODE.",
 7163: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7164: 	$r->print("\n<br /><br />");
 7165:     } elsif ($error eq 'doublebubble') {
 7166: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7167: 
 7168: 	# The form field scantron_questions is acutally a list of line numbers.
 7169: 	# represented by this form so:
 7170: 
 7171: 	my $line_list = &questions_to_line_list($arg);
 7172: 
 7173: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7174: 		  $line_list.'" />');
 7175: 	$r->print($message);
 7176: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7177: 	foreach my $question (@{$arg}) {
 7178: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7179:                                                    $scan_record, $error);
 7180:             push(@lines_to_correct,@linenums);
 7181: 	}
 7182:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7183:     } elsif ($error eq 'missingbubble') {
 7184: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7185: 	$r->print($message);
 7186: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7187: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7188: 
 7189: 	# The form field scantron_questions is actually a list of line numbers not
 7190: 	# a list of question numbers. Therefore:
 7191: 	#
 7192: 	
 7193: 	my $line_list = &questions_to_line_list($arg);
 7194: 
 7195: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7196: 		  $line_list.'" />');
 7197: 	foreach my $question (@{$arg}) {
 7198: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7199:                                                    $scan_record, $error);
 7200:             push(@lines_to_correct,@linenums);
 7201: 	}
 7202:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7203:     } else {
 7204: 	$r->print("\n<ul>");
 7205:     }
 7206:     $r->print("\n</li></ul>");
 7207: }
 7208: 
 7209: sub verify_bubbles_checked {
 7210:     my (@ansnums) = @_;
 7211:     my $ansnumstr = join('","',@ansnums);
 7212:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7213:     my $output = (<<ENDSCRIPT);
 7214: <script type="text/javascript">
 7215: function verify_bubble_radio(form) {
 7216:     var ansnumArray = new Array ("$ansnumstr");
 7217:     var need_bubble_count = 0;
 7218:     for (var i=0; i<ansnumArray.length; i++) {
 7219:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7220:             var bubble_picked = 0; 
 7221:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7222:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7223:                     bubble_picked = 1;
 7224:                 }
 7225:             }
 7226:             if (bubble_picked == 0) {
 7227:                 need_bubble_count ++;
 7228:             }
 7229:         }
 7230:     }
 7231:     if (need_bubble_count) {
 7232:         alert("$warning");
 7233:         return;
 7234:     }
 7235:     form.submit(); 
 7236: }
 7237: </script>
 7238: ENDSCRIPT
 7239:     return $output;
 7240: }
 7241: 
 7242: =pod
 7243: 
 7244: =item  questions_to_line_list
 7245: 
 7246: Converts a list of questions into a string of comma separated
 7247: line numbers in the answer sheet used by the questions.  This is
 7248: used to fill in the scantron_questions form field.
 7249: 
 7250:   Arguments:
 7251:      questions    - Reference to an array of questions.
 7252: 
 7253: =cut
 7254: 
 7255: 
 7256: sub questions_to_line_list {
 7257:     my ($questions) = @_;
 7258:     my @lines;
 7259: 
 7260:     foreach my $item (@{$questions}) {
 7261:         my $question = $item;
 7262:         my ($first,$count,$last);
 7263:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7264:             $question = $1;
 7265:             my $subquestion = $2;
 7266:             $first = $first_bubble_line{$question-1} + 1;
 7267:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7268:             my $subcount = 1;
 7269:             while ($subcount<$subquestion) {
 7270:                 $first += $subans[$subcount-1];
 7271:                 $subcount ++;
 7272:             }
 7273:             $count = $subans[$subquestion-1];
 7274:         } else {
 7275: 	    $first   = $first_bubble_line{$question-1} + 1;
 7276: 	    $count   = $bubble_lines_per_response{$question-1};
 7277:         }
 7278:         $last = $first+$count-1;
 7279:         push(@lines, ($first..$last));
 7280:     }
 7281:     return join(',', @lines);
 7282: }
 7283: 
 7284: =pod 
 7285: 
 7286: =item prompt_for_corrections
 7287: 
 7288: Prompts for a potentially multiline correction to the
 7289: user's bubbling (factors out common code from scantron_get_correction
 7290: for multi and missing bubble cases).
 7291: 
 7292:  Arguments:
 7293:    $r           - Apache request object.
 7294:    $question    - The question number to prompt for.
 7295:    $scan_config - The scantron file configuration hash.
 7296:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7297:    $error       - Type of error
 7298: 
 7299:  Implicit inputs:
 7300:    %bubble_lines_per_response   - Starting line numbers for each question.
 7301:                                   Numbered from 0 (but question numbers are from
 7302:                                   1.
 7303:    %first_bubble_line           - Starting bubble line for each question.
 7304:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7305:                                   type problems render as separate sub-questions, 
 7306:                                   in exam mode. This hash contains a 
 7307:                                   comma-separated list of the lines per 
 7308:                                   sub-question.
 7309:    %responsetype_per_response   - essayresponse, formularesponse,
 7310:                                   stringresponse, imageresponse, reactionresponse,
 7311:                                   and organicresponse type problem parts can have
 7312:                                   multiple lines per response if the weight
 7313:                                   assigned exceeds 10.  In this case, only
 7314:                                   one bubble per line is permitted, but more 
 7315:                                   than one line might contain bubbles, e.g.
 7316:                                   bubbling of: line 1 - J, line 2 - J, 
 7317:                                   line 3 - B would assign 22 points.  
 7318: 
 7319: =cut
 7320: 
 7321: sub prompt_for_corrections {
 7322:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7323:     my ($current_line,$lines);
 7324:     my @linenums;
 7325:     my $questionnum = $question;
 7326:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7327:         $question = $1;
 7328:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7329:         my $subquestion = $2;
 7330:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7331:         my $subcount = 1;
 7332:         while ($subcount<$subquestion) {
 7333:             $current_line += $subans[$subcount-1];
 7334:             $subcount ++;
 7335:         }
 7336:         $lines = $subans[$subquestion-1];
 7337:     } else {
 7338:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7339:         $lines        = $bubble_lines_per_response{$question-1};
 7340:     }
 7341:     if ($lines > 1) {
 7342:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7343:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7344:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7345:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7346:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7347:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7348:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7349:             $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 />');
 7350:         } else {
 7351:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7352:         }
 7353:     }
 7354:     for (my $i =0; $i < $lines; $i++) {
 7355:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7356: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7357: 	        		  $questionnum,$error,split('', $selected));
 7358:         push(@linenums,$current_line);
 7359: 	$current_line++;
 7360:     }
 7361:     if ($lines > 1) {
 7362: 	$r->print("<hr /><br />");
 7363:     }
 7364:     return @linenums;
 7365: }
 7366: 
 7367: =pod
 7368: 
 7369: =item scantron_bubble_selector
 7370:   
 7371:    Generates the html radiobuttons to correct a single bubble line
 7372:    possibly showing the existing the selected bubbles if known
 7373: 
 7374:  Arguments:
 7375:     $r           - Apache request object
 7376:     $scan_config - hash from &get_scantron_config()
 7377:     $line        - Number of the line being displayed.
 7378:     $questionnum - Question number (may include subquestion)
 7379:     $error       - Type of error.
 7380:     @selected    - Array of bubbles picked on this line.
 7381: 
 7382: =cut
 7383: 
 7384: sub scantron_bubble_selector {
 7385:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7386:     my $max=$$scan_config{'Qlength'};
 7387: 
 7388:     my $scmode=$$scan_config{'Qon'};
 7389:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7390: 
 7391:     my @alphabet=('A'..'Z');
 7392:     $r->print(&Apache::loncommon::start_data_table().
 7393:               &Apache::loncommon::start_data_table_row());
 7394:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7395:     for (my $i=0;$i<$max+1;$i++) {
 7396: 	$r->print("\n".'<td align="center">');
 7397: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7398: 	else { $r->print('&nbsp;'); }
 7399: 	$r->print('</td>');
 7400:     }
 7401:     $r->print(&Apache::loncommon::end_data_table_row().
 7402:               &Apache::loncommon::start_data_table_row());
 7403:     for (my $i=0;$i<$max;$i++) {
 7404: 	$r->print("\n".
 7405: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7406: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7407:     }
 7408:     my $nobub_checked = ' ';
 7409:     if ($error eq 'missingbubble') {
 7410:         $nobub_checked = ' checked = "checked" ';
 7411:     }
 7412:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7413: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7414:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7415:               $line.'" value="'.$questionnum.'" /></td>');
 7416:     $r->print(&Apache::loncommon::end_data_table_row().
 7417:               &Apache::loncommon::end_data_table());
 7418: }
 7419: 
 7420: =pod
 7421: 
 7422: =item num_matches
 7423: 
 7424:    Counts the number of characters that are the same between the two arguments.
 7425: 
 7426:  Arguments:
 7427:    $orig - CODE from the scanline
 7428:    $code - CODE to match against
 7429: 
 7430:  Returns:
 7431:    $count - integer count of the number of same characters between the
 7432:             two arguments
 7433: 
 7434: =cut
 7435: 
 7436: sub num_matches {
 7437:     my ($orig,$code) = @_;
 7438:     my @code=split(//,$code);
 7439:     my @orig=split(//,$orig);
 7440:     my $same=0;
 7441:     for (my $i=0;$i<scalar(@code);$i++) {
 7442: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7443:     }
 7444:     return $same;
 7445: }
 7446: 
 7447: =pod
 7448: 
 7449: =item scantron_get_closely_matching_CODEs
 7450: 
 7451:    Cycles through all CODEs and finds the set that has the greatest
 7452:    number of same characters as the provided CODE
 7453: 
 7454:  Arguments:
 7455:    $allcodes - hash ref returned by &get_codes()
 7456:    $CODE     - CODE from the current scanline
 7457: 
 7458:  Returns:
 7459:    2 element list
 7460:     - first elements is number of how closely matching the best fit is 
 7461:       (5 means best set has 5 matching characters)
 7462:     - second element is an arrary ref containing the set of valid CODEs
 7463:       that best fit the passed in CODE
 7464: 
 7465: =cut
 7466: 
 7467: sub scantron_get_closely_matching_CODEs {
 7468:     my ($allcodes,$CODE)=@_;
 7469:     my @CODEs;
 7470:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7471: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7472:     }
 7473: 
 7474:     return ($#CODEs,$CODEs[-1]);
 7475: }
 7476: 
 7477: =pod
 7478: 
 7479: =item get_codes
 7480: 
 7481:    Builds a hash which has keys of all of the valid CODEs from the selected
 7482:    set of remembered CODEs.
 7483: 
 7484:  Arguments:
 7485:   $old_name - name of the set of remembered CODEs
 7486:   $cdom     - domain of the course
 7487:   $cnum     - internal course name
 7488: 
 7489:  Returns:
 7490:   %allcodes - keys are the valid CODEs, values are all 1
 7491: 
 7492: =cut
 7493: 
 7494: sub get_codes {
 7495:     my ($old_name, $cdom, $cnum) = @_;
 7496:     if (!$old_name) {
 7497: 	$old_name=$env{'form.scantron_CODElist'};
 7498:     }
 7499:     if (!$cdom) {
 7500: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7501:     }
 7502:     if (!$cnum) {
 7503: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7504:     }
 7505:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7506: 				    $cdom,$cnum);
 7507:     my %allcodes;
 7508:     if ($result{"type\0$old_name"} eq 'number') {
 7509: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7510:     } else {
 7511: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7512:     }
 7513:     return %allcodes;
 7514: }
 7515: 
 7516: =pod
 7517: 
 7518: =item scantron_validate_CODE
 7519: 
 7520:    Validates all scanlines in the selected file to not have any
 7521:    invalid or underspecified CODEs and that none of the codes are
 7522:    duplicated if this was requested.
 7523: 
 7524: =cut
 7525: 
 7526: sub scantron_validate_CODE {
 7527:     my ($r,$currentphase) = @_;
 7528:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7529:     if ($scantron_config{'CODElocation'} &&
 7530: 	$scantron_config{'CODEstart'} &&
 7531: 	$scantron_config{'CODElength'}) {
 7532: 	if (!defined($env{'form.scantron_CODElist'})) {
 7533: 	    &FIXME_blow_up()
 7534: 	}
 7535:     } else {
 7536: 	return (0,$currentphase+1);
 7537:     }
 7538:     
 7539:     my %usedCODEs;
 7540: 
 7541:     my %allcodes=&get_codes();
 7542: 
 7543:     my $nav_error;
 7544:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7545:     if ($nav_error) {
 7546:         $r->print(&navmap_errormsg());
 7547:         return(1,$currentphase);
 7548:     }
 7549: 
 7550:     my ($scanlines,$scan_data)=&scantron_getfile();
 7551:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7552: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7553: 	if ($line=~/^[\s\cz]*$/) { next; }
 7554: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7555: 						 $scan_data);
 7556: 	my $CODE=$$scan_record{'scantron.CODE'};
 7557: 	my $error=0;
 7558: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7559: 	    &scantron_get_correction($r,$i,$scan_record,
 7560: 				     \%scantron_config,
 7561: 				     $line,'incorrectCODE',\%allcodes);
 7562: 	    return(1,$currentphase);
 7563: 	}
 7564: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7565: 	    && !$$scan_record{'scantron.useCODE'}) {
 7566: 	    &scantron_get_correction($r,$i,$scan_record,
 7567: 				     \%scantron_config,
 7568: 				     $line,'incorrectCODE',\%allcodes);
 7569: 	    return(1,$currentphase);
 7570: 	}
 7571: 	if (exists($usedCODEs{$CODE}) 
 7572: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7573: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7574: 	    &scantron_get_correction($r,$i,$scan_record,
 7575: 				     \%scantron_config,
 7576: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7577: 	    return(1,$currentphase);
 7578: 	}
 7579: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7580:     }
 7581:     return (0,$currentphase+1);
 7582: }
 7583: 
 7584: =pod
 7585: 
 7586: =item scantron_validate_doublebubble
 7587: 
 7588:    Validates all scanlines in the selected file to not have any
 7589:    bubble lines with multiple bubbles marked.
 7590: 
 7591: =cut
 7592: 
 7593: sub scantron_validate_doublebubble {
 7594:     my ($r,$currentphase) = @_;
 7595:     #get student info
 7596:     my $classlist=&Apache::loncoursedata::get_classlist();
 7597:     my %idmap=&username_to_idmap($classlist);
 7598: 
 7599:     #get scantron line setup
 7600:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7601:     my ($scanlines,$scan_data)=&scantron_getfile();
 7602:     my $nav_error;
 7603:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7604:     if ($nav_error) {
 7605:         $r->print(&navmap_errormsg());
 7606:         return(1,$currentphase);
 7607:     }
 7608: 
 7609:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7610: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7611: 	if ($line=~/^[\s\cz]*$/) { next; }
 7612: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7613: 						 $scan_data);
 7614: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7615: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7616: 				 'doublebubble',
 7617: 				 $$scan_record{'scantron.doubleerror'});
 7618:     	return (1,$currentphase);
 7619:     }
 7620:     return (0,$currentphase+1);
 7621: }
 7622: 
 7623: 
 7624: sub scantron_get_maxbubble {
 7625:     my ($nav_error) = @_;
 7626:     if (defined($env{'form.scantron_maxbubble'}) &&
 7627: 	$env{'form.scantron_maxbubble'}) {
 7628: 	&restore_bubble_lines();
 7629: 	return $env{'form.scantron_maxbubble'};
 7630:     }
 7631: 
 7632:     my (undef, undef, $sequence) =
 7633: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7634: 
 7635:     my $navmap=Apache::lonnavmaps::navmap->new();
 7636:     unless (ref($navmap)) {
 7637:         if (ref($nav_error)) {
 7638:             $$nav_error = 1;
 7639:         }
 7640:         return;
 7641:     }
 7642:     my $map=$navmap->getResourceByUrl($sequence);
 7643:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7644: 
 7645:     &Apache::lonxml::clear_problem_counter();
 7646: 
 7647:     my $uname       = $env{'user.name'};
 7648:     my $udom        = $env{'user.domain'};
 7649:     my $cid         = $env{'request.course.id'};
 7650:     my $total_lines = 0;
 7651:     %bubble_lines_per_response = ();
 7652:     %first_bubble_line         = ();
 7653:     %subdivided_bubble_lines   = ();
 7654:     %responsetype_per_response = ();
 7655: 
 7656:     my $response_number = 0;
 7657:     my $bubble_line     = 0;
 7658:     foreach my $resource (@resources) {
 7659:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7660:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7661: 	    foreach my $part_id (@{$parts}) {
 7662:                 my $lines;
 7663: 
 7664: 	        # TODO - make this a persistent hash not an array.
 7665: 
 7666:                 # optionresponse, matchresponse and rankresponse type items 
 7667:                 # render as separate sub-questions in exam mode.
 7668:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7669:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7670:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7671:                     my ($numbub,$numshown);
 7672:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7673:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7674:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7675:                         }
 7676:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7677:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7678:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7679:                         }
 7680:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7681:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7682:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7683:                         }
 7684:                     }
 7685:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7686:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7687:                     }
 7688:                     my $bubbles_per_line = 10;
 7689:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7690:                     if (($numbub % $bubbles_per_line) != 0) {
 7691:                         $inner_bubble_lines++;
 7692:                     }
 7693:                     for (my $i=0; $i<$numshown; $i++) {
 7694:                         $subdivided_bubble_lines{$response_number} .= 
 7695:                             $inner_bubble_lines.',';
 7696:                     }
 7697:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7698:                     $lines = $numshown * $inner_bubble_lines;
 7699:                 } else {
 7700:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7701:                 } 
 7702: 
 7703:                 $first_bubble_line{$response_number} = $bubble_line;
 7704: 	        $bubble_lines_per_response{$response_number} = $lines;
 7705:                 $responsetype_per_response{$response_number} = 
 7706:                     $analysis->{$part_id.'.type'};
 7707: 	        $response_number++;
 7708: 
 7709: 	        $bubble_line +=  $lines;
 7710: 	        $total_lines +=  $lines;
 7711: 	    }
 7712:         }
 7713:     }
 7714:     &Apache::lonnet::delenv('scantron.');
 7715: 
 7716:     &save_bubble_lines();
 7717:     $env{'form.scantron_maxbubble'} =
 7718: 	$total_lines;
 7719:     return $env{'form.scantron_maxbubble'};
 7720: }
 7721: 
 7722: sub scantron_validate_missingbubbles {
 7723:     my ($r,$currentphase) = @_;
 7724:     #get student info
 7725:     my $classlist=&Apache::loncoursedata::get_classlist();
 7726:     my %idmap=&username_to_idmap($classlist);
 7727: 
 7728:     #get scantron line setup
 7729:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7730:     my ($scanlines,$scan_data)=&scantron_getfile();
 7731:     my $nav_error;
 7732:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7733:     if ($nav_error) {
 7734:         return(1,$currentphase);
 7735:     }
 7736:     if (!$max_bubble) { $max_bubble=2**31; }
 7737:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7738: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7739: 	if ($line=~/^[\s\cz]*$/) { next; }
 7740: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7741: 						 $scan_data);
 7742: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7743: 	my @to_correct;
 7744: 	
 7745: 	# Probably here's where the error is...
 7746: 
 7747: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7748:             my $lastbubble;
 7749:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7750:                my $question = $1;
 7751:                my $subquestion = $2;
 7752:                if (!defined($first_bubble_line{$question -1})) { next; }
 7753:                my $first = $first_bubble_line{$question-1};
 7754:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7755:                my $subcount = 1;
 7756:                while ($subcount<$subquestion) {
 7757:                    $first += $subans[$subcount-1];
 7758:                    $subcount ++;
 7759:                }
 7760:                my $count = $subans[$subquestion-1];
 7761:                $lastbubble = $first + $count;
 7762:             } else {
 7763:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7764:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7765:             }
 7766:             if ($lastbubble > $max_bubble) { next; }
 7767: 	    push(@to_correct,$missing);
 7768: 	}
 7769: 	if (@to_correct) {
 7770: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7771: 				     $line,'missingbubble',\@to_correct);
 7772: 	    return (1,$currentphase);
 7773: 	}
 7774: 
 7775:     }
 7776:     return (0,$currentphase+1);
 7777: }
 7778: 
 7779: 
 7780: sub scantron_process_students {
 7781:     my ($r) = @_;
 7782: 
 7783:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7784:     my ($symb)=&get_symb($r);
 7785:     if (!$symb) {
 7786: 	return '';
 7787:     }
 7788:     my $default_form_data=&defaultFormData($symb);
 7789: 
 7790:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7791:     my ($scanlines,$scan_data)=&scantron_getfile();
 7792:     my $classlist=&Apache::loncoursedata::get_classlist();
 7793:     my %idmap=&username_to_idmap($classlist);
 7794:     my $navmap=Apache::lonnavmaps::navmap->new();
 7795:     unless (ref($navmap)) {
 7796:         $r->print(&navmap_errormsg());
 7797:         return '';
 7798:     }  
 7799:     my $map=$navmap->getResourceByUrl($sequence);
 7800:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7801:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7802:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7803:                             \%grader_randomlists_by_symb);
 7804:     my $resource_error;
 7805:     foreach my $resource (@resources) {
 7806:         my $ressymb;
 7807:         if (ref($resource)) {
 7808:             $ressymb = $resource->symb();
 7809:         } else {
 7810:             $resource_error = 1;
 7811:             last;
 7812:         }
 7813:         my ($analysis,$parts) =
 7814:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7815:                                       $env{'user.name'},$env{'user.domain'},1);
 7816:         $grader_partids_by_symb{$ressymb} = $parts;
 7817:         if (ref($analysis) eq 'HASH') {
 7818:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7819:                 $grader_randomlists_by_symb{$ressymb} = 
 7820:                     $analysis->{'parts_withrandomlist'};
 7821:             }
 7822:         }
 7823:     }
 7824:     if ($resource_error) {
 7825:         $r->print(&navmap_errormsg());
 7826:         return '';
 7827:     }
 7828: 
 7829:     my ($uname,$udom);
 7830:     my $result= <<SCANTRONFORM;
 7831: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7832:   <input type="hidden" name="command" value="scantron_configphase" />
 7833:   $default_form_data
 7834: SCANTRONFORM
 7835:     $r->print($result);
 7836: 
 7837:     my @delayqueue;
 7838:     my (%completedstudents,%scandata);
 7839:     
 7840:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7841:     my $count=&get_todo_count($scanlines,$scan_data);
 7842:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7843:  				    'Bubblesheet Progress',$count,
 7844: 				    'inline',undef,'scantronupload');
 7845:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7846: 					  'Processing first student');
 7847:     $r->print('<br />');
 7848:     my $start=&Time::HiRes::time();
 7849:     my $i=-1;
 7850:     my $started;
 7851: 
 7852:     my $nav_error;
 7853:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7854:     if ($nav_error) {
 7855:         $r->print(&navmap_errormsg());
 7856:         return '';
 7857:     }
 7858: 
 7859:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7860:     # the user and return.
 7861: 
 7862:     if ($ssi_error) {
 7863: 	$r->print("</form>");
 7864: 	&ssi_print_error($r);
 7865: 	$r->print(&show_grading_menu_form($symb));
 7866:         &Apache::lonnet::remove_lock($lock);
 7867: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7868:     }
 7869: 
 7870:     my %lettdig = &letter_to_digits();
 7871:     my $numletts = scalar(keys(%lettdig));
 7872: 
 7873:     while ($i<$scanlines->{'count'}) {
 7874:  	($uname,$udom)=('','');
 7875:  	$i++;
 7876:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7877:  	if ($line=~/^[\s\cz]*$/) { next; }
 7878: 	if ($started) {
 7879: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7880: 						     'last student');
 7881: 	}
 7882: 	$started=1;
 7883:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7884:  						 $scan_data);
 7885:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7886:  					      \%idmap,$i)) {
 7887:   	    &scantron_add_delay(\@delayqueue,$line,
 7888:  				'Unable to find a student that matches',1);
 7889:  	    next;
 7890:   	}
 7891:  	if (exists $completedstudents{$uname}) {
 7892:  	    &scantron_add_delay(\@delayqueue,$line,
 7893:  				'Student '.$uname.' has multiple sheets',2);
 7894:  	    next;
 7895:  	}
 7896:   	($uname,$udom)=split(/:/,$uname);
 7897: 
 7898:         my (%partids_by_symb,$res_error);
 7899:         foreach my $resource (@resources) {
 7900:             my $ressymb;
 7901:             if (ref($resource)) {
 7902:                 $ressymb = $resource->symb();
 7903:             } else {
 7904:                 $res_error = 1;
 7905:                 last;
 7906:             }
 7907:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7908:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7909:                 my ($analysis,$parts) =
 7910:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7911:                 $partids_by_symb{$ressymb} = $parts;
 7912:             } else {
 7913:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7914:             }
 7915:         }
 7916: 
 7917:         if ($res_error) {
 7918:             &scantron_add_delay(\@delayqueue,$line,
 7919:                                 'An error occurred while grading student '.$uname,2);
 7920:             next;
 7921:         }
 7922: 
 7923: 	&Apache::lonxml::clear_problem_counter();
 7924:   	&Apache::lonnet::appenv($scan_record);
 7925: 
 7926: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7927: 	    &scantron_putfile($scanlines,$scan_data);
 7928: 	}
 7929: 	
 7930:         my $scancode;
 7931:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7932:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7933:             $scancode = $scan_record->{'scantron.CODE'};
 7934:         } else {
 7935:             $scancode = '';
 7936:         }
 7937: 
 7938:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7939:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7940:             $ssi_error = 0; # So end of handler error message does not trigger.
 7941:             $r->print("</form>");
 7942:             &ssi_print_error($r);
 7943:             $r->print(&show_grading_menu_form($symb));
 7944:             &Apache::lonnet::remove_lock($lock);
 7945:             return '';      # Why return ''?  Beats me.
 7946:         }
 7947: 
 7948: 	$completedstudents{$uname}={'line'=>$line};
 7949:         if ($env{'form.verifyrecord'}) {
 7950:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7951:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7952:             chomp($studentdata);
 7953:             $studentdata =~ s/\r$//;
 7954:             my $studentrecord = '';
 7955:             my $counter = -1;
 7956:             foreach my $resource (@resources) {
 7957:                 my $ressymb = $resource->symb();
 7958:                 ($counter,my $recording) =
 7959:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7960:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7961:                                              \%scantron_config,\%lettdig,$numletts);
 7962:                 $studentrecord .= $recording;
 7963:             }
 7964:             if ($studentrecord ne $studentdata) {
 7965:                 &Apache::lonxml::clear_problem_counter();
 7966:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7967:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7968:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7969:                     $r->print("</form>");
 7970:                     &ssi_print_error($r);
 7971:                     $r->print(&show_grading_menu_form($symb));
 7972:                     &Apache::lonnet::remove_lock($lock);
 7973:                     delete($completedstudents{$uname});
 7974:                     return '';
 7975:                 }
 7976:                 $counter = -1;
 7977:                 $studentrecord = '';
 7978:                 foreach my $resource (@resources) {
 7979:                     my $ressymb = $resource->symb();
 7980:                     ($counter,my $recording) =
 7981:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7982:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7983:                                                  \%scantron_config,\%lettdig,$numletts);
 7984:                     $studentrecord .= $recording;
 7985:                 }
 7986:                 if ($studentrecord ne $studentdata) {
 7987:                     $r->print('<p><span class="LC_warning">');
 7988:                     if ($scancode eq '') {
 7989:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 7990:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7991:                     } else {
 7992:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7993:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7994:                     }
 7995:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7996:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7997:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7998:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7999:                               &Apache::loncommon::start_data_table_row().
 8000:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8001:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 8002:                               &Apache::loncommon::end_data_table_row().
 8003:                               &Apache::loncommon::start_data_table_row().
 8004:                               '<td>'.&mt('Stored submissions').'</td>'.
 8005:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 8006:                               &Apache::loncommon::end_data_table_row().
 8007:                               &Apache::loncommon::end_data_table().'</p>');
 8008:                 } else {
 8009:                     $r->print('<br /><span class="LC_warning">'.
 8010:                              &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 />'.
 8011:                              &mt("As a consequence, this user's submission history records two tries.").
 8012:                                  '</span><br />');
 8013:                 }
 8014:             }
 8015:         }
 8016:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8017:     } continue {
 8018: 	&Apache::lonxml::clear_problem_counter();
 8019: 	&Apache::lonnet::delenv('scantron.');
 8020:     }
 8021:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8022:     &Apache::lonnet::remove_lock($lock);
 8023: #    my $lasttime = &Time::HiRes::time()-$start;
 8024: #    $r->print("<p>took $lasttime</p>");
 8025: 
 8026:     $r->print("</form>");
 8027:     $r->print(&show_grading_menu_form($symb));
 8028:     return '';
 8029: }
 8030: 
 8031: sub graders_resources_pass {
 8032:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 8033:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8034:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8035:         foreach my $resource (@{$resources}) {
 8036:             my $ressymb = $resource->symb();
 8037:             my ($analysis,$parts) =
 8038:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8039:                                           $env{'user.name'},$env{'user.domain'},1);
 8040:             $grader_partids_by_symb->{$ressymb} = $parts;
 8041:             if (ref($analysis) eq 'HASH') {
 8042:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8043:                     $grader_randomlists_by_symb->{$ressymb} =
 8044:                         $analysis->{'parts_withrandomlist'};
 8045:                 }
 8046:             }
 8047:         }
 8048:     }
 8049:     return;
 8050: }
 8051: 
 8052: sub grade_student_bubbles {
 8053:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 8054:     if (ref($resources) eq 'ARRAY') {
 8055:         my $count = 0;
 8056:         foreach my $resource (@{$resources}) {
 8057:             my $ressymb = $resource->symb();
 8058:             my %form = ('submitted'      => 'scantron',
 8059:                         'grade_target'   => 'grade',
 8060:                         'grade_username' => $uname,
 8061:                         'grade_domain'   => $udom,
 8062:                         'grade_courseid' => $env{'request.course.id'},
 8063:                         'grade_symb'     => $ressymb,
 8064:                         'CODE'           => $scancode
 8065:                        );
 8066:             if (ref($parts) eq 'HASH') {
 8067:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8068:                     foreach my $part (@{$parts->{$ressymb}}) {
 8069:                         $form{'scantron_questnum_start.'.$part} =
 8070:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 8071:                         $count++;
 8072:                     }
 8073:                 }
 8074:             }
 8075:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8076:             return 'ssi_error' if ($ssi_error);
 8077:             last if (&Apache::loncommon::connection_aborted($r));
 8078:         }
 8079:     }
 8080:     return;
 8081: }
 8082: 
 8083: sub scantron_upload_scantron_data {
 8084:     my ($r)=@_;
 8085:     my $dom = $env{'request.role.domain'};
 8086:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8087:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8088:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8089: 							  'domainid',
 8090: 							  'coursename',$dom);
 8091:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8092:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8093:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8094:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8095:     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.");
 8096:     $r->print('
 8097: <script type="text/javascript" language="javascript">
 8098:     function checkUpload(formname) {
 8099: 	if (formname.upfile.value == "") {
 8100: 	    alert("'.$nofile_alert.'");
 8101: 	    return false;
 8102: 	}
 8103:         if (formname.courseid.value == "") {
 8104:             alert("'.$nocourseid_alert.'");
 8105:             return false;
 8106:         }
 8107: 	formname.submit();
 8108:     }
 8109: 
 8110:     function ToSyllabus() {
 8111:         var cdom = '."'$dom'".';
 8112:         var cnum = document.rules.courseid.value;
 8113:         if (cdom == "" || cdom == null) {
 8114:             return;
 8115:         }
 8116:         if (cnum == "" || cnum == null) {
 8117:            return;
 8118:         }
 8119:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8120:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8121:         return;
 8122:     }
 8123: 
 8124: </script>
 8125: 
 8126: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8127: 
 8128: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8129: '.$default_form_data.
 8130:   &Apache::lonhtmlcommon::start_pick_box().
 8131:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8132:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8133:   &Apache::lonhtmlcommon::row_closure().
 8134:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8135:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8136:   &Apache::lonhtmlcommon::row_closure().
 8137:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8138:   '<input name="domainid" type="hidden" />'.$domdesc.
 8139:   &Apache::lonhtmlcommon::row_closure().
 8140:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8141:   '<input type="file" name="upfile" size="50" />'.
 8142:   &Apache::lonhtmlcommon::row_closure(1).
 8143:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8144: 
 8145: <input name="command" value="scantronupload_save" type="hidden" />
 8146: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8147: </form>
 8148: ');
 8149:     return '';
 8150: }
 8151: 
 8152: 
 8153: sub scantron_upload_scantron_data_save {
 8154:     my($r)=@_;
 8155:     my ($symb)=&get_symb($r,1);
 8156:     my $doanotherupload=
 8157: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8158: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8159: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8160: 	'</form>'."\n";
 8161:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8162: 	!&Apache::lonnet::allowed('usc',
 8163: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8164: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8165: 	if ($symb) {
 8166: 	    $r->print(&show_grading_menu_form($symb));
 8167: 	} else {
 8168: 	    $r->print($doanotherupload);
 8169: 	}
 8170: 	return '';
 8171:     }
 8172:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8173:     my $uploadedfile;
 8174:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8175:     if (length($env{'form.upfile'}) < 2) {
 8176:         $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>'));
 8177:     } else {
 8178:         my $result = 
 8179:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8180:                                             $env{'form.courseid'},$env{'form.domainid'});
 8181: 	if ($result =~ m{^/uploaded/}) {
 8182: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8183:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8184: 			  '<span class="LC_filename">'.$result.'</span>'));
 8185:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8186:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8187:                                                        $env{'form.courseid'},$uploadedfile));
 8188: 	} else {
 8189: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8190:                           '<span class="LC_error">','</span>',$result,
 8191: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8192: 	}
 8193:     }
 8194:     if ($symb) {
 8195: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8196:     } else {
 8197: 	$r->print($doanotherupload);
 8198:     }
 8199:     return '';
 8200: }
 8201: 
 8202: sub validate_uploaded_scantron_file {
 8203:     my ($cdom,$cname,$fname) = @_;
 8204:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8205:     my @lines;
 8206:     if ($scanlines ne '-1') {
 8207:         @lines=split("\n",$scanlines,-1);
 8208:     }
 8209:     my $output;
 8210:     if (@lines) {
 8211:         my (%counts,$max_match_format);
 8212:         my ($max_match_count,$max_match_pct) = (0,0);
 8213:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8214:         my %idmap = &username_to_idmap($classlist);
 8215:         foreach my $key (keys(%idmap)) {
 8216:             my $lckey = lc($key);
 8217:             $idmap{$lckey} = $idmap{$key};
 8218:         }
 8219:         my %unique_formats;
 8220:         my @formatlines = &get_scantronformat_file();
 8221:         foreach my $line (@formatlines) {
 8222:             chomp($line);
 8223:             my @config = split(/:/,$line);
 8224:             my $idstart = $config[5];
 8225:             my $idlength = $config[6];
 8226:             if (($idstart ne '') && ($idlength > 0)) {
 8227:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8228:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8229:                 } else {
 8230:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8231:                 }
 8232:             }
 8233:         }
 8234:         foreach my $key (keys(%unique_formats)) {
 8235:             my ($idstart,$idlength) = split(':',$key);
 8236:             %{$counts{$key}} = (
 8237:                                'found'   => 0,
 8238:                                'total'   => 0,
 8239:                               );
 8240:             foreach my $line (@lines) {
 8241:                 next if ($line =~ /^#/);
 8242:                 next if ($line =~ /^[\s\cz]*$/);
 8243:                 my $id = substr($line,$idstart-1,$idlength);
 8244:                 $id = lc($id);
 8245:                 if (exists($idmap{$id})) {
 8246:                     $counts{$key}{'found'} ++;
 8247:                 }
 8248:                 $counts{$key}{'total'} ++;
 8249:             }
 8250:             if ($counts{$key}{'total'}) {
 8251:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8252:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8253:                     $max_match_pct = $percent_match;
 8254:                     $max_match_format = $key;
 8255:                     $max_match_count = $counts{$key}{'total'};
 8256:                 }
 8257:             }
 8258:         }
 8259:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8260:             my $format_descs;
 8261:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8262:             for (my $i=0; $i<$numwithformat; $i++) {
 8263:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8264:                 if ($i<$numwithformat-2) {
 8265:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8266:                 } elsif ($i==$numwithformat-2) {
 8267:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8268:                 } elsif ($i==$numwithformat-1) {
 8269:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8270:                 }
 8271:             }
 8272:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8273:             $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).
 8274:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8275:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8276:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8277:                                   '<i>'.$cdom.'</i>').'</li>'.
 8278:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8279:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8280:                        '</ul>';
 8281:         }
 8282:     } else {
 8283:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8284:     }
 8285:     return $output;
 8286: }
 8287: 
 8288: sub valid_file {
 8289:     my ($requested_file)=@_;
 8290:     foreach my $filename (sort(&scantron_filenames())) {
 8291: 	if ($requested_file eq $filename) { return 1; }
 8292:     }
 8293:     return 0;
 8294: }
 8295: 
 8296: sub scantron_download_scantron_data {
 8297:     my ($r)=@_;
 8298:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8299:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8300:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8301:     my $file=$env{'form.scantron_selectfile'};
 8302:     if (! &valid_file($file)) {
 8303: 	$r->print('
 8304: 	<p>
 8305: 	    '.&mt('The requested file name was invalid.').'
 8306:         </p>
 8307: ');
 8308: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8309: 	return;
 8310:     }
 8311:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8312:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8313:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8314:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8315:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8316:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8317:     $r->print('
 8318:     <p>
 8319: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8320: 	      '<a href="'.$orig.'">','</a>').'
 8321:     </p>
 8322:     <p>
 8323: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8324: 	      '<a href="'.$corrected.'">','</a>').'
 8325:     </p>
 8326:     <p>
 8327: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8328: 	      '<a href="'.$skipped.'">','</a>').'
 8329:     </p>
 8330: ');
 8331:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8332:     return '';
 8333: }
 8334: 
 8335: sub checkscantron_results {
 8336:     my ($r) = @_;
 8337:     my ($symb)=&get_symb($r);
 8338:     if (!$symb) {return '';}
 8339:     my $grading_menu_button=&show_grading_menu_form($symb);
 8340:     my $cid = $env{'request.course.id'};
 8341:     my %lettdig = &letter_to_digits();
 8342:     my $numletts = scalar(keys(%lettdig));
 8343:     my $cnum = $env{'course.'.$cid.'.num'};
 8344:     my $cdom = $env{'course.'.$cid.'.domain'};
 8345:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8346:     my %record;
 8347:     my %scantron_config =
 8348:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8349:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8350:     my $classlist=&Apache::loncoursedata::get_classlist();
 8351:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8352:     my $navmap=Apache::lonnavmaps::navmap->new();
 8353:     unless (ref($navmap)) {
 8354:         $r->print(&navmap_errormsg());
 8355:         return '';
 8356:     }
 8357:     my $map=$navmap->getResourceByUrl($sequence);
 8358:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8359:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8360:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8361: 
 8362:     my ($uname,$udom);
 8363:     my (%scandata,%lastname,%bylast);
 8364:     $r->print('
 8365: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8366: 
 8367:     my @delayqueue;
 8368:     my %completedstudents;
 8369: 
 8370:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8371:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8372:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8373:                                     'inline',undef,'checkscantron');
 8374:     my ($username,$domain,$started);
 8375:     my $nav_error;
 8376:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8377:     if ($nav_error) {
 8378:         $r->print(&navmap_errormsg());
 8379:         return '';
 8380:     }
 8381: 
 8382:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8383:                                           'Processing first student');
 8384:     my $start=&Time::HiRes::time();
 8385:     my $i=-1;
 8386: 
 8387:     while ($i<$scanlines->{'count'}) {
 8388:         ($username,$domain,$uname)=('','','');
 8389:         $i++;
 8390:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8391:         if ($line=~/^[\s\cz]*$/) { next; }
 8392:         if ($started) {
 8393:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8394:                                                      'last student');
 8395:         }
 8396:         $started=1;
 8397:         my $scan_record=
 8398:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8399:                                                      $scan_data);
 8400:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8401:                                                               \%idmap,$i)) {
 8402:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8403:                                 'Unable to find a student that matches',1);
 8404:             next;
 8405:         }
 8406:         if (exists $completedstudents{$uname}) {
 8407:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8408:                                 'Student '.$uname.' has multiple sheets',2);
 8409:             next;
 8410:         }
 8411:         my $pid = $scan_record->{'scantron.ID'};
 8412:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8413:         push(@{$bylast{$lastname{$pid}}},$pid);
 8414:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8415:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8416:         chomp($scandata{$pid});
 8417:         $scandata{$pid} =~ s/\r$//;
 8418:         ($username,$domain)=split(/:/,$uname);
 8419:         my $counter = -1;
 8420:         foreach my $resource (@resources) {
 8421:             my $parts;
 8422:             my $ressymb = $resource->symb();
 8423:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8424:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8425:                 (my $analysis,$parts) =
 8426:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8427:             } else {
 8428:                 $parts = $grader_partids_by_symb{$ressymb};
 8429:             }
 8430:             ($counter,my $recording) =
 8431:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8432:                                          $scandata{$pid},$parts,
 8433:                                          \%scantron_config,\%lettdig,$numletts);
 8434:             $record{$pid} .= $recording;
 8435:         }
 8436:     }
 8437:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8438:     $r->print('<br />');
 8439:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8440:     $passed = 0;
 8441:     $failed = 0;
 8442:     $numstudents = 0;
 8443:     foreach my $last (sort(keys(%bylast))) {
 8444:         if (ref($bylast{$last}) eq 'ARRAY') {
 8445:             foreach my $pid (sort(@{$bylast{$last}})) {
 8446:                 my $showscandata = $scandata{$pid};
 8447:                 my $showrecord = $record{$pid};
 8448:                 $showscandata =~ s/\s/&nbsp;/g;
 8449:                 $showrecord =~ s/\s/&nbsp;/g;
 8450:                 if ($scandata{$pid} eq $record{$pid}) {
 8451:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8452:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8453: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8454: '</tr>'."\n".
 8455: '<tr class="'.$css_class.'">'."\n".
 8456: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8457:                     $passed ++;
 8458:                 } else {
 8459:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8460:                     $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".
 8461: '</tr>'."\n".
 8462: '<tr class="'.$css_class.'">'."\n".
 8463: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8464: '</tr>'."\n";
 8465:                     $failed ++;
 8466:                 }
 8467:                 $numstudents ++;
 8468:             }
 8469:         }
 8470:     }
 8471:     $r->print('<p>'.
 8472:               &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).',
 8473:                   '<b>',
 8474:                   $numstudents,
 8475:                   '</b>',
 8476:                   $env{'form.scantron_maxbubble'}).
 8477:               '</p>'
 8478:     );
 8479:     $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>');
 8480:     if ($passed) {
 8481:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8482:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8483:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8484:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8485:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8486:                  $okstudents."\n".
 8487:                  &Apache::loncommon::end_data_table().'<br />');
 8488:     }
 8489:     if ($failed) {
 8490:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8491:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8492:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8493:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8494:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8495:                  $badstudents."\n".
 8496:                  &Apache::loncommon::end_data_table()).'<br />'.
 8497:                  &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.');  
 8498:     }
 8499:     $r->print('</form><br />'.$grading_menu_button);
 8500:     return;
 8501: }
 8502: 
 8503: sub verify_scantron_grading {
 8504:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8505:         $scantron_config,$lettdig,$numletts) = @_;
 8506:     my ($record,%expected,%startpos);
 8507:     return ($counter,$record) if (!ref($resource));
 8508:     return ($counter,$record) if (!$resource->is_problem());
 8509:     my $symb = $resource->symb();
 8510:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8511:     foreach my $part_id (@{$partids}) {
 8512:         $counter ++;
 8513:         $expected{$part_id} = 0;
 8514:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8515:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8516:             foreach my $item (@sub_lines) {
 8517:                 $expected{$part_id} += $item;
 8518:             }
 8519:         } else {
 8520:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8521:         }
 8522:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8523:     }
 8524:     if ($symb) {
 8525:         my %recorded;
 8526:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8527:         if ($returnhash{'version'}) {
 8528:             my %lasthash=();
 8529:             my $version;
 8530:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8531:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8532:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8533:                 }
 8534:             }
 8535:             foreach my $key (keys(%lasthash)) {
 8536:                 if ($key =~ /\.scantron$/) {
 8537:                     my $value = &unescape($lasthash{$key});
 8538:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8539:                     if ($value eq '') {
 8540:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8541:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8542:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8543:                             }
 8544:                         }
 8545:                     } else {
 8546:                         my @tocheck;
 8547:                         my @items = split(//,$value);
 8548:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8549:                             ($scantron_config->{'Qon'} eq 'number')) {
 8550:                             if (@items < $expected{$part_id}) {
 8551:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8552:                                 my @singles = split(//,$fragment);
 8553:                                 foreach my $pos (@singles) {
 8554:                                     if ($pos eq ' ') {
 8555:                                         push(@tocheck,$pos);
 8556:                                     } else {
 8557:                                         my $next = shift(@items);
 8558:                                         push(@tocheck,$next);
 8559:                                     }
 8560:                                 }
 8561:                             } else {
 8562:                                 @tocheck = @items;
 8563:                             }
 8564:                             foreach my $letter (@tocheck) {
 8565:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8566:                                     if ($letter !~ /^[A-J]$/) {
 8567:                                         $letter = $scantron_config->{'Qoff'};
 8568:                                     }
 8569:                                     $recorded{$part_id} .= $letter;
 8570:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8571:                                     my $digit;
 8572:                                     if ($letter !~ /^[A-J]$/) {
 8573:                                         $digit = $scantron_config->{'Qoff'};
 8574:                                     } else {
 8575:                                         $digit = $lettdig->{$letter};
 8576:                                     }
 8577:                                     $recorded{$part_id} .= $digit;
 8578:                                 }
 8579:                             }
 8580:                         } else {
 8581:                             @tocheck = @items;
 8582:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8583:                                 my $curr_sub = shift(@tocheck);
 8584:                                 my $digit;
 8585:                                 if ($curr_sub =~ /^[A-J]$/) {
 8586:                                     $digit = $lettdig->{$curr_sub}-1;
 8587:                                 }
 8588:                                 if ($curr_sub eq 'J') {
 8589:                                     $digit += scalar($numletts);
 8590:                                 }
 8591:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8592:                                     if ($j == $digit) {
 8593:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8594:                                     } else {
 8595:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8596:                                     }
 8597:                                 }
 8598:                             }
 8599:                         }
 8600:                     }
 8601:                 }
 8602:             }
 8603:         }
 8604:         foreach my $part_id (@{$partids}) {
 8605:             if ($recorded{$part_id} eq '') {
 8606:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8607:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8608:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8609:                     }
 8610:                 }
 8611:             }
 8612:             $record .= $recorded{$part_id};
 8613:         }
 8614:     }
 8615:     return ($counter,$record);
 8616: }
 8617: 
 8618: sub letter_to_digits { 
 8619:     my %lettdig = (
 8620:                     A => 1,
 8621:                     B => 2,
 8622:                     C => 3,
 8623:                     D => 4,
 8624:                     E => 5,
 8625:                     F => 6,
 8626:                     G => 7,
 8627:                     H => 8,
 8628:                     I => 9,
 8629:                     J => 0,
 8630:                   );
 8631:     return %lettdig;
 8632: }
 8633: 
 8634: 
 8635: #-------- end of section for handling grading scantron forms -------
 8636: #
 8637: #-------------------------------------------------------------------
 8638: 
 8639: #-------------------------- Menu interface -------------------------
 8640: #
 8641: #--- Show a Grading Menu button - Calls the next routine ---
 8642: sub show_grading_menu_form {
 8643:     my ($symb)=@_;
 8644:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8645: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8646: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8647: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8648: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8649: 	'</form>'."\n";
 8650:     return $result;
 8651: }
 8652: 
 8653: # -- Retrieve choices for grading form
 8654: sub savedState {
 8655:     my %savedState = ();
 8656:     if ($env{'form.saveState'}) {
 8657: 	foreach (split(/:/,$env{'form.saveState'})) {
 8658: 	    my ($key,$value) = split(/=/,$_,2);
 8659: 	    $savedState{$key} = $value;
 8660: 	}
 8661:     }
 8662:     return \%savedState;
 8663: }
 8664: 
 8665: sub grading_menu {
 8666:     my ($request) = @_;
 8667:     my ($symb)=&get_symb($request);
 8668:     if (!$symb) {return '';}
 8669:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8670:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8671: 
 8672:     $request->print($table);
 8673:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8674:                   'handgrade'=>$hdgrade,
 8675:                   'probTitle'=>$probTitle,
 8676:                   'command'=>'submit_options',
 8677:                   'saveState'=>"",
 8678:                   'gradingMenu'=>1,
 8679:                   'showgrading'=>"yes");
 8680:     
 8681:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8682:     
 8683:     $fields{'command'} = 'csvform';
 8684:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8685:     
 8686:     $fields{'command'} = 'processclicker';
 8687:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8688:     
 8689:     $fields{'command'} = 'scantron_selectphase';
 8690:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8691:     
 8692:     my @menu = ({	categorytitle=>'Course Grading',
 8693:             items =>[
 8694:                         {	linktext => 'Manual Grading/View Submissions',
 8695:                     		url => $url1,
 8696:                     		permission => 'F',
 8697:                     		icon => 'edit-find-replace.png',
 8698:                     		linktitle => 'Start the process of hand grading submissions.'
 8699:                         },
 8700:                 	    {	linktext => 'Upload Scores',
 8701:                     		url => $url2,
 8702:                     		permission => 'F',
 8703:                     		icon => 'uploadscores.png',
 8704:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8705:                 	    },
 8706:                 	    {	linktext => 'Process Clicker',
 8707:                     		url => $url3,
 8708:                     		permission => 'F',
 8709:                     		icon => 'addClickerInfoFile.png',
 8710:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8711:                 	    },
 8712:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8713:                     		url => $url4,
 8714:                     		permission => 'F',
 8715:                     		icon => 'stat.png',
 8716:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 8717:                 	    }
 8718:                     ]
 8719:             });
 8720: 
 8721:     #$fields{'command'} = 'verify';
 8722:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8723:     #
 8724:     # Create the menu
 8725:     my $Str;
 8726:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8727:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8728:     $Str .= '<input type="hidden" name="command" value="" />'.
 8729:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8730: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8731: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8732: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8733: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8734: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8735: 
 8736:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8737:     #$menudata->{'jscript'}
 8738:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8739:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8740:         ' /> '.
 8741:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8742:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8743: 
 8744:     $Str .="</form>\n";
 8745:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8746:     $request->print(<<GRADINGMENUJS);
 8747: <script type="text/javascript" language="javascript">
 8748:     function checkChoice(formname,val,cmdx) {
 8749: 	if (val <= 2) {
 8750: 	    var cmd = radioSelection(formname.radioChoice);
 8751: 	    var cmdsave = cmd;
 8752: 	} else {
 8753: 	    cmd = cmdx;
 8754: 	    cmdsave = 'submission';
 8755: 	}
 8756: 	formname.command.value = cmd;
 8757: 	if (val < 5) formname.submit();
 8758: 	if (val == 5) {
 8759: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8760: 	        return false;
 8761: 	    } else {
 8762: 	        formname.submit();
 8763: 	    }
 8764: 	}
 8765:     }
 8766: 
 8767:     function checkReceiptNo(formname,nospace) {
 8768: 	var receiptNo = formname.receipt.value;
 8769: 	var checkOpt = false;
 8770: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8771: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8772: 	if (checkOpt) {
 8773: 	    alert("$receiptalert");
 8774: 	    formname.receipt.value = "";
 8775: 	    formname.receipt.focus();
 8776: 	    return false;
 8777: 	}
 8778: 	return true;
 8779:     }
 8780: </script>
 8781: GRADINGMENUJS
 8782:     &commonJSfunctions($request);
 8783:     return $Str;    
 8784: }
 8785: 
 8786: 
 8787: #--- Displays the submissions first page -------
 8788: sub submit_options {
 8789:     my ($request) = @_;
 8790:     my ($symb)=&get_symb($request);
 8791:     if (!$symb) {return '';}
 8792:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8793: 
 8794:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8795:     $request->print(<<GRADINGMENUJS);
 8796: <script type="text/javascript" language="javascript">
 8797:     function checkChoice(formname,val,cmdx) {
 8798: 	if (val <= 2) {
 8799: 	    var cmd = radioSelection(formname.radioChoice);
 8800: 	    var cmdsave = cmd;
 8801: 	} else {
 8802: 	    cmd = cmdx;
 8803: 	    cmdsave = 'submission';
 8804: 	}
 8805: 	formname.command.value = cmd;
 8806: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8807: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8808: 	if (val < 5) formname.submit();
 8809: 	if (val == 5) {
 8810: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8811: 	    formname.submit();
 8812: 	}
 8813: 	if (val < 7) formname.submit();
 8814:     }
 8815: 
 8816:     function checkReceiptNo(formname,nospace) {
 8817: 	var receiptNo = formname.receipt.value;
 8818: 	var checkOpt = false;
 8819: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8820: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8821: 	if (checkOpt) {
 8822: 	    alert("$receiptalert");
 8823: 	    formname.receipt.value = "";
 8824: 	    formname.receipt.focus();
 8825: 	    return false;
 8826: 	}
 8827: 	return true;
 8828:     }
 8829: </script>
 8830: GRADINGMENUJS
 8831:     &commonJSfunctions($request);
 8832:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8833:     my $result;
 8834:     my (undef,$sections) = &getclasslist('all','0');
 8835:     my $savedState = &savedState();
 8836:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8837:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8838:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8839:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8840: 
 8841:     # Preselect sections
 8842:     my $selsec="";
 8843:     if (ref($sections)) {
 8844:         foreach my $section (sort(@$sections)) {
 8845:             $selsec.='<option value="'.$section.'" '.
 8846:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8847:         }
 8848:     }
 8849: 
 8850:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8851: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8852: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8853: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8854: 	'<input type="hidden" name="command"     value="" />'."\n".
 8855: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8856: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8857: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8858: 
 8859:     $result.='
 8860: <h2>
 8861:   '.&mt('Grade Current Resource').'
 8862: </h2>
 8863: <div>
 8864:   '.$table.'
 8865: </div>
 8866: 
 8867: <div class="LC_columnSection">
 8868:   
 8869:     <fieldset>
 8870:       <legend>
 8871:        '.&mt('Sections').'
 8872:       </legend>
 8873:       <select name="section" multiple="multiple" size="5">'."\n";
 8874:     $result.= $selsec;
 8875:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8876:     $result.='
 8877:     </fieldset>
 8878:   
 8879:     <fieldset>
 8880:       <legend>
 8881:         '.&mt('Groups').'
 8882:       </legend>
 8883:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8884:     </fieldset>
 8885:   
 8886:     <fieldset>
 8887:       <legend>
 8888:         '.&mt('Access Status').'
 8889:       </legend>
 8890:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8891:     </fieldset>
 8892:   
 8893:     <fieldset>
 8894:       <legend>
 8895:         '.&mt('Submission Status').'
 8896:       </legend>
 8897:       <select name="submitonly" size="5">
 8898: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8899: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8900: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8901: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8902:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8903:       </select>
 8904:     </fieldset>
 8905:   
 8906: </div>
 8907: 
 8908: <br />
 8909:           <div>
 8910:             <div>
 8911:               <label>
 8912:                 <input type="radio" name="radioChoice" value="submission" '.
 8913:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8914:              &mt('Select individual students to grade and view submissions.').'
 8915: 	      </label> 
 8916:             </div>
 8917:             <div>
 8918: 	      <label>
 8919:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8920:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8921:                     &mt('Grade all selected students in a grading table.').'
 8922:               </label>
 8923:             </div>
 8924:             <div>
 8925: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8926:             </div>
 8927:           </div>
 8928: 
 8929: 
 8930:         <h2>
 8931:          '.&mt('Grade Complete Folder for One Student').'
 8932:         </h2>
 8933:         <div>
 8934:             <div>
 8935:               <label>
 8936:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8937: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8938:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8939:               </label>
 8940:             </div>
 8941:             <div>
 8942: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8943:             </div>
 8944:         </div>
 8945:   </form>';
 8946:     $result .= &show_grading_menu_form($symb);
 8947:     return $result;
 8948: }
 8949: 
 8950: sub reset_perm {
 8951:     undef(%perm);
 8952: }
 8953: 
 8954: sub init_perm {
 8955:     &reset_perm();
 8956:     foreach my $test_perm ('vgr','mgr','opa') {
 8957: 
 8958: 	my $scope = $env{'request.course.id'};
 8959: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8960: 
 8961: 	    $scope .= '/'.$env{'request.course.sec'};
 8962: 	    if ( $perm{$test_perm}=
 8963: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8964: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8965: 	    } else {
 8966: 		delete($perm{$test_perm});
 8967: 	    }
 8968: 	}
 8969:     }
 8970: }
 8971: 
 8972: sub init_old_essays {
 8973:     my ($symb,$apath,$adom,$aname) = @_;
 8974:     if ($symb ne '') {
 8975:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 8976:         if (keys(%essays) > 0) {
 8977:             $old_essays{$symb} = \%essays;
 8978:         }
 8979:     }
 8980:     return;
 8981: }
 8982: 
 8983: sub reset_old_essays {
 8984:     undef(%old_essays);
 8985: }
 8986: 
 8987: sub gather_clicker_ids {
 8988:     my %clicker_ids;
 8989: 
 8990:     my $classlist = &Apache::loncoursedata::get_classlist();
 8991: 
 8992:     # Set up a couple variables.
 8993:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8994:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8995:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8996: 
 8997:     foreach my $student (keys(%$classlist)) {
 8998:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8999:         my $username = $classlist->{$student}->[$username_idx];
 9000:         my $domain   = $classlist->{$student}->[$domain_idx];
 9001:         my $clickers =
 9002: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9003:         foreach my $id (split(/\,/,$clickers)) {
 9004:             $id=~s/^[\#0]+//;
 9005:             $id=~s/[\-\:]//g;
 9006:             if (exists($clicker_ids{$id})) {
 9007: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9008:             } else {
 9009: 		$clicker_ids{$id}=$username.':'.$domain;
 9010:             }
 9011:         }
 9012:     }
 9013:     return %clicker_ids;
 9014: }
 9015: 
 9016: sub gather_adv_clicker_ids {
 9017:     my %clicker_ids;
 9018:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9019:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9020:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9021:     foreach my $element (sort(keys(%coursepersonnel))) {
 9022:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9023:             my ($puname,$pudom)=split(/\:/,$person);
 9024:             my $clickers =
 9025: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9026:             foreach my $id (split(/\,/,$clickers)) {
 9027: 		$id=~s/^[\#0]+//;
 9028:                 $id=~s/[\-\:]//g;
 9029: 		if (exists($clicker_ids{$id})) {
 9030: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9031: 		} else {
 9032: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9033: 		}
 9034:             }
 9035:         }
 9036:     }
 9037:     return %clicker_ids;
 9038: }
 9039: 
 9040: sub clicker_grading_parameters {
 9041:     return ('gradingmechanism' => 'scalar',
 9042:             'upfiletype' => 'scalar',
 9043:             'specificid' => 'scalar',
 9044:             'pcorrect' => 'scalar',
 9045:             'pincorrect' => 'scalar');
 9046: }
 9047: 
 9048: sub process_clicker {
 9049:     my ($r)=@_;
 9050:     my ($symb)=&get_symb($r);
 9051:     if (!$symb) {return '';}
 9052:     my $result=&checkforfile_js();
 9053:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9054:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9055:     $result.=$table;
 9056:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9057:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9058:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9059:         '</b></td></tr>'."\n";
 9060:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 9061: # Attempt to restore parameters from last session, set defaults if not present
 9062:     my %Saveable_Parameters=&clicker_grading_parameters();
 9063:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9064:                                                  \%Saveable_Parameters);
 9065:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9066:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9067:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9068:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9069: 
 9070:     my %checked;
 9071:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9072:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9073:           $checked{$gradingmechanism}=' checked="checked"';
 9074:        }
 9075:     }
 9076: 
 9077:     my $upload=&mt("Upload File");
 9078:     my $type=&mt("Type");
 9079:     my $attendance=&mt("Award points just for participation");
 9080:     my $personnel=&mt("Correctness determined from response by course personnel");
 9081:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9082:     my $given=&mt("Correctness determined from given list of answers").' '.
 9083:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9084:     my $pcorrect=&mt("Percentage points for correct solution");
 9085:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9086:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9087:                                                    {'iclicker' => 'i>clicker',
 9088:                                                     'interwrite' => 'interwrite PRS'});
 9089:     $symb = &Apache::lonenc::check_encrypt($symb);
 9090:     $result.=<<ENDUPFORM;
 9091: <script type="text/javascript">
 9092: function sanitycheck() {
 9093: // Accept only integer percentages
 9094:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9095:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9096: // Find out grading choice
 9097:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9098:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9099:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9100:       }
 9101:    }
 9102: // By default, new choice equals user selection
 9103:    newgradingchoice=gradingchoice;
 9104: // Not good to give more points for false answers than correct ones
 9105:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9106:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9107:    }
 9108: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9109:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9110:       document.forms.gradesupload.pcorrect.value=100;
 9111:       document.forms.gradesupload.pincorrect.value=100;
 9112:    }
 9113: // If the values are different, cannot be attendance only
 9114:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9115:        (gradingchoice=='attendance')) {
 9116:        newgradingchoice='personnel';
 9117:    }
 9118: // Change grading choice to new one
 9119:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9120:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9121:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9122:       } else {
 9123:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9124:       }
 9125:    }
 9126: // Remember the old state
 9127:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9128: }
 9129: </script>
 9130: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9131: <input type="hidden" name="symb" value="$symb" />
 9132: <input type="hidden" name="command" value="processclickerfile" />
 9133: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9134: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9135: <input type="file" name="upfile" size="50" />
 9136: <br /><label>$type: $selectform</label>
 9137: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9138: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9139: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9140: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9141: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9142: <br />&nbsp;&nbsp;&nbsp;
 9143: <input type="text" name="givenanswer" size="50" />
 9144: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9145: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9146: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9147: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9148: </form>
 9149: ENDUPFORM
 9150:     $result.='</td></tr></table>'."\n".
 9151:              '</td></tr></table><br /><br />'."\n";
 9152:     $result.=&show_grading_menu_form($symb);
 9153:     return $result;
 9154: }
 9155: 
 9156: sub process_clicker_file {
 9157:     my ($r)=@_;
 9158:     my ($symb)=&get_symb($r);
 9159:     if (!$symb) {return '';}
 9160: 
 9161:     my %Saveable_Parameters=&clicker_grading_parameters();
 9162:     &Apache::loncommon::store_course_settings('grades_clicker',
 9163:                                               \%Saveable_Parameters);
 9164: 
 9165:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9166:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9167: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9168: 	return $result.&show_grading_menu_form($symb);
 9169:     }
 9170:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9171:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9172:         return $result.&show_grading_menu_form($symb);
 9173:     }
 9174:     my $foundgiven=0;
 9175:     if ($env{'form.gradingmechanism'} eq 'given') {
 9176:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9177:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9178:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9179:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9180:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9181:         $foundgiven=$#answers+1;
 9182:     }
 9183:     my %clicker_ids=&gather_clicker_ids();
 9184:     my %correct_ids;
 9185:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9186: 	%correct_ids=&gather_adv_clicker_ids();
 9187:     }
 9188:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9189: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9190: 	   $correct_id=~tr/a-z/A-Z/;
 9191: 	   $correct_id=~s/\s//gs;
 9192: 	   $correct_id=~s/^[\#0]+//;
 9193:            $correct_id=~s/[\-\:]//g;
 9194:            if ($correct_id) {
 9195: 	      $correct_ids{$correct_id}='specified';
 9196:            }
 9197:         }
 9198:     }
 9199:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9200: 	$result.=&mt('Score based on attendance only');
 9201:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9202:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9203:     } else {
 9204: 	my $number=0;
 9205: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9206: 	foreach my $id (sort(keys(%correct_ids))) {
 9207: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9208: 	    if ($correct_ids{$id} eq 'specified') {
 9209: 		$result.=&mt('specified');
 9210: 	    } else {
 9211: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9212: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9213: 	    }
 9214: 	    $number++;
 9215: 	}
 9216:         $result.="</p>\n";
 9217: 	if ($number==0) {
 9218: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9219: 	    return $result.&show_grading_menu_form($symb);
 9220: 	}
 9221:     }
 9222:     if (length($env{'form.upfile'}) < 2) {
 9223:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9224: 		     '<span class="LC_error">',
 9225: 		     '</span>',
 9226: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9227:         return $result.&show_grading_menu_form($symb);
 9228:     }
 9229: 
 9230: # Were able to get all the info needed, now analyze the file
 9231: 
 9232:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9233:     $symb = &Apache::lonenc::check_encrypt($symb);
 9234:     my $heading=&mt('Scanning clicker file');
 9235:     $result.=(<<ENDHEADER);
 9236: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9237: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9238: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
 9239: <form method="post" action="/adm/grades" name="clickeranalysis">
 9240: <input type="hidden" name="symb" value="$symb" />
 9241: <input type="hidden" name="command" value="assignclickergrades" />
 9242: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9243: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9244: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9245: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9246: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9247: ENDHEADER
 9248:     if ($env{'form.gradingmechanism'} eq 'given') {
 9249:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9250:     } 
 9251:     my %responses;
 9252:     my @questiontitles;
 9253:     my $errormsg='';
 9254:     my $number=0;
 9255:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9256: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9257:     }
 9258:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9259:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9260:     }
 9261:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9262:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9263:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9264:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9265:              '<br />';
 9266:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9267:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9268:        return $result.&show_grading_menu_form($symb);
 9269:     } 
 9270: # Remember Question Titles
 9271: # FIXME: Possibly need delimiter other than ":"
 9272:     for (my $i=0;$i<$number;$i++) {
 9273:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9274:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9275:     }
 9276:     my $correct_count=0;
 9277:     my $student_count=0;
 9278:     my $unknown_count=0;
 9279: # Match answers with usernames
 9280: # FIXME: Possibly need delimiter other than ":"
 9281:     foreach my $id (keys(%responses)) {
 9282:        if ($correct_ids{$id}) {
 9283:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9284:           $correct_count++;
 9285:        } elsif ($clicker_ids{$id}) {
 9286:           if ($clicker_ids{$id}=~/\,/) {
 9287: # More than one user with the same clicker!
 9288:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9289:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9290:                            "<select name='multi".$id."'>";
 9291:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9292:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9293:              }
 9294:              $result.='</select>';
 9295:              $unknown_count++;
 9296:           } else {
 9297: # Good: found one and only one user with the right clicker
 9298:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9299:              $student_count++;
 9300:           }
 9301:        } else {
 9302:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9303:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9304:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9305:                    "\n".&mt("Domain").": ".
 9306:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9307:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9308:           $unknown_count++;
 9309:        }
 9310:     }
 9311:     $result.='<hr />'.
 9312:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9313:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9314:        if ($correct_count==0) {
 9315:           $errormsg.="Found no correct answers answers for grading!";
 9316:        } elsif ($correct_count>1) {
 9317:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9318:        }
 9319:     }
 9320:     if ($number<1) {
 9321:        $errormsg.="Found no questions.";
 9322:     }
 9323:     if ($errormsg) {
 9324:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9325:     } else {
 9326:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9327:     }
 9328:     $result.='</form></td></tr></table>'."\n".
 9329:              '</td></tr></table><br /><br />'."\n";
 9330:     return $result.&show_grading_menu_form($symb);
 9331: }
 9332: 
 9333: sub iclicker_eval {
 9334:     my ($questiontitles,$responses)=@_;
 9335:     my $number=0;
 9336:     my $errormsg='';
 9337:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9338:         my %components=&Apache::loncommon::record_sep($line);
 9339:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9340: 	if ($entries[0] eq 'Question') {
 9341: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9342: 		$$questiontitles[$number]=$entries[$i];
 9343: 		$number++;
 9344: 	    }
 9345: 	}
 9346: 	if ($entries[0]=~/^\#/) {
 9347: 	    my $id=$entries[0];
 9348: 	    my @idresponses;
 9349: 	    $id=~s/^[\#0]+//;
 9350: 	    for (my $i=0;$i<$number;$i++) {
 9351: 		my $idx=3+$i*6;
 9352:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9353: 		push(@idresponses,$entries[$idx]);
 9354: 	    }
 9355: 	    $$responses{$id}=join(',',@idresponses);
 9356: 	}
 9357:     }
 9358:     return ($errormsg,$number);
 9359: }
 9360: 
 9361: sub interwrite_eval {
 9362:     my ($questiontitles,$responses)=@_;
 9363:     my $number=0;
 9364:     my $errormsg='';
 9365:     my $skipline=1;
 9366:     my $questionnumber=0;
 9367:     my %idresponses=();
 9368:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9369:         my %components=&Apache::loncommon::record_sep($line);
 9370:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9371:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9372:         if ($entries[1] eq 'Response') { $skipline=1; }
 9373:         next if $skipline;
 9374:         if ($entries[0]!=$questionnumber) {
 9375:            $questionnumber=$entries[0];
 9376:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9377:            $number++;
 9378:         }
 9379:         my $id=$entries[4];
 9380:         $id=~s/^[\#0]+//;
 9381:         $id=~s/^v\d*\://i;
 9382:         $id=~s/[\-\:]//g;
 9383:         $idresponses{$id}[$number]=$entries[6];
 9384:     }
 9385:     foreach my $id (keys(%idresponses)) {
 9386:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9387:        $$responses{$id}=~s/^\s*\,//;
 9388:     }
 9389:     return ($errormsg,$number);
 9390: }
 9391: 
 9392: sub assign_clicker_grades {
 9393:     my ($r)=@_;
 9394:     my ($symb)=&get_symb($r);
 9395:     if (!$symb) {return '';}
 9396: # See which part we are saving to
 9397:     my $res_error;
 9398:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9399:     if ($res_error) {
 9400:         return &navmap_errormsg();
 9401:     }
 9402: # FIXME: This should probably look for the first handgradeable part
 9403:     my $part=$$partlist[0];
 9404: # Start screen output
 9405:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9406: 
 9407:     $result .= '<br />'.
 9408:                &Apache::loncommon::start_data_table().
 9409:                &Apache::loncommon::start_data_table_header_row().
 9410:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9411:                &Apache::loncommon::end_data_table_header_row().
 9412:                &Apache::loncommon::start_data_table_row().'<td>';
 9413: 
 9414: # Get correct result
 9415: # FIXME: Possibly need delimiter other than ":"
 9416:     my @correct=();
 9417:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9418:     my $number=$env{'form.number'};
 9419:     if ($gradingmechanism ne 'attendance') {
 9420:        foreach my $key (keys(%env)) {
 9421:           if ($key=~/^form\.correct\:/) {
 9422:              my @input=split(/\,/,$env{$key});
 9423:              for (my $i=0;$i<=$#input;$i++) {
 9424:                  if (($correct[$i]) && ($input[$i]) &&
 9425:                      ($correct[$i] ne $input[$i])) {
 9426:                     $result.='<br /><span class="LC_warning">'.
 9427:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9428:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9429:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9430:                     $correct[$i]=$input[$i];
 9431:                  }
 9432:              }
 9433:           }
 9434:        }
 9435:        for (my $i=0;$i<$number;$i++) {
 9436:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9437:              $result.='<br /><span class="LC_error">'.
 9438:                       &mt('No correct result given for question "[_1]"!',
 9439:                           $env{'form.question:'.$i}).'</span>';
 9440:           }
 9441:        }
 9442:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9443:     }
 9444: # Start grading
 9445:     my $pcorrect=$env{'form.pcorrect'};
 9446:     my $pincorrect=$env{'form.pincorrect'};
 9447:     my $storecount=0;
 9448:     my %users=();
 9449:     foreach my $key (keys(%env)) {
 9450:        my $user='';
 9451:        if ($key=~/^form\.student\:(.*)$/) {
 9452:           $user=$1;
 9453:        }
 9454:        if ($key=~/^form\.unknown\:(.*)$/) {
 9455:           my $id=$1;
 9456:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9457:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9458:           } elsif ($env{'form.multi'.$id}) {
 9459:              $user=$env{'form.multi'.$id};
 9460:           }
 9461:        }
 9462:        if ($user) {
 9463:           if ($users{$user}) {
 9464:              $result.='<br /><span class="LC_warning">'.
 9465:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9466:                       '</span><br />';
 9467:           }
 9468:           $users{$user}=1;
 9469:           my @answer=split(/\,/,$env{$key});
 9470:           my $sum=0;
 9471:           my $realnumber=$number;
 9472:           for (my $i=0;$i<$number;$i++) {
 9473:              if  ($correct[$i] eq '-') {
 9474:                 $realnumber--;
 9475:              } elsif ($answer[$i]) {
 9476:                 if ($gradingmechanism eq 'attendance') {
 9477:                    $sum+=$pcorrect;
 9478:                 } elsif ($correct[$i] eq '*') {
 9479:                    $sum+=$pcorrect;
 9480:                 } else {
 9481: # We actually grade if correct or not
 9482:                    my $increment=$pincorrect;
 9483: # Special case: numerical answer "0"
 9484:                    if ($correct[$i] eq '0') {
 9485:                       if ($answer[$i]=~/^[0\.]+$/) {
 9486:                          $increment=$pcorrect;
 9487:                       }
 9488: # General numerical answer, both evaluate to something non-zero
 9489:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9490:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9491:                          $increment=$pcorrect;
 9492:                       }
 9493: # Must be just alphanumeric
 9494:                    } elsif ($answer[$i] eq $correct[$i]) {
 9495:                       $increment=$pcorrect;
 9496:                    }
 9497:                    $sum+=$increment;
 9498:                 }
 9499:              }
 9500:           }
 9501:           my $ave=$sum/(100*$realnumber);
 9502: # Store
 9503:           my ($username,$domain)=split(/\:/,$user);
 9504:           my %grades=();
 9505:           $grades{"resource.$part.solved"}='correct_by_override';
 9506:           $grades{"resource.$part.awarded"}=$ave;
 9507:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9508:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9509:                                                  $env{'request.course.id'},
 9510:                                                  $domain,$username);
 9511:           if ($returncode ne 'ok') {
 9512:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9513:           } else {
 9514:              $storecount++;
 9515:           }
 9516:        }
 9517:     }
 9518: # We are done
 9519:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9520:              '</td>'.
 9521:              &Apache::loncommon::end_data_table_row().
 9522:              &Apache::loncommon::end_data_table()."<br /><br />\n";
 9523:     return $result.&show_grading_menu_form($symb);
 9524: }
 9525: 
 9526: sub navmap_errormsg {
 9527:     return '<div class="LC_error">'.
 9528:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9529:            &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>').
 9530:            '</div>';
 9531: }
 9532: 
 9533: sub handler {
 9534:     my $request=$_[0];
 9535:     &reset_caches();
 9536:     if ($request->header_only) {
 9537:         &Apache::loncommon::content_type($request,'text/html');
 9538:         $request->send_http_header;
 9539:         return OK;
 9540:     }
 9541:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9542: 
 9543:     my $symb=&get_symb($request,1);
 9544:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9545:     my $command=$commands[0];
 9546: 
 9547:     if ($#commands > 0) {
 9548: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9549:     }
 9550: 
 9551:     $ssi_error = 0;
 9552:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9553:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
 9554:                                           {'bread_crumbs' => $brcrum});
 9555:     if ($symb eq '' && $command eq '') {
 9556: 	if ($env{'user.adv'}) {
 9557:             &Apache::loncommon::content_type($request,'text/html');
 9558:             $request->send_http_header;
 9559:             $request->print($start_page);
 9560: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9561: 		($env{'form.codethree'})) {
 9562: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9563: 		    $env{'form.codethree'};
 9564: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9565: 		    &Apache::lonnet::checkin($token);
 9566: 		if ($tsymb) {
 9567: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9568: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9569: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9570: 					  ('grade_username' => $tuname,
 9571: 					   'grade_domain' => $tudom,
 9572: 					   'grade_courseid' => $tcrsid,
 9573: 					   'grade_symb' => $tsymb)));
 9574: 		    } else {
 9575: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9576: 		    }
 9577: 		} else {
 9578: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9579: 		}
 9580: 	    } else {
 9581: 		$request->print(&Apache::lonxml::tokeninputfield());
 9582: 	    }
 9583:         } elsif ($env{'request.course.id'}) {
 9584:             &init_perm(); 
 9585:             if (!%perm) {
 9586:                 $request->internal_redirect('/adm/quickgrades');
 9587:             } else {
 9588:                 &Apache::loncommon::content_type($request,'text/html');
 9589:                 $request->send_http_header;
 9590:                 $request->print($start_page);
 9591:             }
 9592:         }
 9593:     } else {
 9594:         &init_perm();
 9595:         if (!$env{'request.course.id'}) {
 9596:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
 9597:                     ($command =~ /^scantronupload/)) {
 9598:                 # Not in a course.
 9599:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
 9600:                 return HTTP_NOT_ACCEPTABLE;
 9601:             }
 9602:         } elsif (!%perm) {
 9603:             $request->internal_redirect('/adm/quickgrades');
 9604:         }
 9605:         &Apache::loncommon::content_type($request,'text/html');
 9606:         $request->send_http_header;
 9607:         $request->print($start_page);
 9608: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9609: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9610: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9611: 	    &pickStudentPage($request);
 9612: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9613: 	    &displayPage($request);
 9614: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9615: 	    &updateGradeByPage($request);
 9616: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9617: 	    &processGroup($request);
 9618: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9619: 	    $request->print(&grading_menu($request));
 9620: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9621: 	    $request->print(&submit_options($request));
 9622: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9623: 	    $request->print(&viewgrades($request));
 9624: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9625: 	    $request->print(&processHandGrade($request));
 9626: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9627: 	    $request->print(&editgrades($request));
 9628: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9629: 	    $request->print(&verifyreceipt($request));
 9630:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9631:             $request->print(&process_clicker($request));
 9632:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9633:             $request->print(&process_clicker_file($request));
 9634:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9635:             $request->print(&assign_clicker_grades($request));
 9636: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9637: 	    $request->print(&upcsvScores_form($request));
 9638: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9639: 	    $request->print(&csvupload($request));
 9640: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9641: 	    $request->print(&csvuploadmap($request));
 9642: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9643: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9644: 		$request->print(&csvuploadoptions($request));
 9645: 	    } else {
 9646: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9647: 		    $env{'form.upfile_associate'} = 'reverse';
 9648: 		} else {
 9649: 		    $env{'form.upfile_associate'} = 'forward';
 9650: 		}
 9651: 		$request->print(&csvuploadmap($request));
 9652: 	    }
 9653: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9654: 	    $request->print(&csvuploadassign($request));
 9655: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9656: 	    $request->print(&scantron_selectphase($request));
 9657:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9658:  	    $request->print(&scantron_do_warning($request));
 9659: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9660: 	    $request->print(&scantron_validate_file($request));
 9661: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9662: 	    $request->print(&scantron_process_students($request));
 9663:  	} elsif ($command eq 'scantronupload' && 
 9664:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9665: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9666:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9667:  	} elsif ($command eq 'scantronupload_save' &&
 9668:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9669: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9670:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9671:  	} elsif ($command eq 'scantron_download' &&
 9672: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9673:  	    $request->print(&scantron_download_scantron_data($request));
 9674:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9675:             $request->print(&checkscantron_results($request));     
 9676: 	} elsif ($command) {
 9677: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9678: 	}
 9679:     }
 9680:     if ($ssi_error) {
 9681: 	&ssi_print_error($request);
 9682:     }
 9683:     $request->print(&Apache::loncommon::end_page());
 9684:     &reset_caches();
 9685:     return OK;
 9686: }
 9687: 
 9688: 1;
 9689: 
 9690: __END__;
 9691: 
 9692: 
 9693: =head1 NAME
 9694: 
 9695: Apache::grades
 9696: 
 9697: =head1 SYNOPSIS
 9698: 
 9699: Handles the viewing of grades.
 9700: 
 9701: This is part of the LearningOnline Network with CAPA project
 9702: described at http://www.lon-capa.org.
 9703: 
 9704: =head1 OVERVIEW
 9705: 
 9706: Do an ssi with retries:
 9707: While I'd love to factor out this with the vesrion in lonprintout,
 9708: 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
 9709: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9710: 
 9711: At least the logic that drives this has been pulled out into loncommon.
 9712: 
 9713: 
 9714: 
 9715: ssi_with_retries - Does the server side include of a resource.
 9716:                      if the ssi call returns an error we'll retry it up to
 9717:                      the number of times requested by the caller.
 9718:                      If we still have a proble, no text is appended to the
 9719:                      output and we set some global variables.
 9720:                      to indicate to the caller an SSI error occurred.  
 9721:                      All of this is supposed to deal with the issues described
 9722:                      in LonCAPA BZ 5631 see:
 9723:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9724:                      by informing the user that this happened.
 9725: 
 9726: Parameters:
 9727:   resource   - The resource to include.  This is passed directly, without
 9728:                interpretation to lonnet::ssi.
 9729:   form       - The form hash parameters that guide the interpretation of the resource
 9730:                
 9731:   retries    - Number of retries allowed before giving up completely.
 9732: Returns:
 9733:   On success, returns the rendered resource identified by the resource parameter.
 9734: Side Effects:
 9735:   The following global variables can be set:
 9736:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9737:                               It is up to the caller to initialize this to false
 9738:                               if desired.
 9739:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9740:                               of the resource that could not be rendered by the ssi
 9741:                               call.
 9742:    ssi_error_message   - The error string fetched from the ssi response
 9743:                               in the event of an error.
 9744: 
 9745: 
 9746: =head1 HANDLER SUBROUTINE
 9747: 
 9748: ssi_with_retries()
 9749: 
 9750: =head1 SUBROUTINES
 9751: 
 9752: =over
 9753: 
 9754: =item scantron_get_correction() : 
 9755: 
 9756:    Builds the interface screen to interact with the operator to fix a
 9757:    specific error condition in a specific scanline
 9758: 
 9759:  Arguments:
 9760:     $r           - Apache request object
 9761:     $i           - number of the current scanline
 9762:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9763:     $scan_config - hash ref as returned from &get_scantron_config()
 9764:     $line        - full contents of the current scanline
 9765:     $error       - error condition, valid values are
 9766:                    'incorrectCODE', 'duplicateCODE',
 9767:                    'doublebubble', 'missingbubble',
 9768:                    'duplicateID', 'incorrectID'
 9769:     $arg         - extra information needed
 9770:        For errors:
 9771:          - duplicateID   - paper number that this studentID was seen before on
 9772:          - duplicateCODE - array ref of the paper numbers this CODE was
 9773:                            seen on before
 9774:          - incorrectCODE - current incorrect CODE 
 9775:          - doublebubble  - array ref of the bubble lines that have double
 9776:                            bubble errors
 9777:          - missingbubble - array ref of the bubble lines that have missing
 9778:                            bubble errors
 9779: 
 9780: =item  scantron_get_maxbubble() : 
 9781: 
 9782:    Arguments:
 9783:        $nav_error  - Reference to scalar which is a flag to indicate a
 9784:                       failure to retrieve a navmap object.
 9785:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9786:        calling routine should trap the error condition and display the warning
 9787:        found in &navmap_errormsg().
 9788: 
 9789:    Returns the maximum number of bubble lines that are expected to
 9790:    occur. Does this by walking the selected sequence rendering the
 9791:    resource and then checking &Apache::lonxml::get_problem_counter()
 9792:    for what the current value of the problem counter is.
 9793: 
 9794:    Caches the results to $env{'form.scantron_maxbubble'},
 9795:    $env{'form.scantron.bubble_lines.n'}, 
 9796:    $env{'form.scantron.first_bubble_line.n'} and
 9797:    $env{"form.scantron.sub_bubblelines.n"}
 9798:    which are the total number of bubble, lines, the number of bubble
 9799:    lines for response n and number of the first bubble line for response n,
 9800:    and a comma separated list of numbers of bubble lines for sub-questions
 9801:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9802: 
 9803: 
 9804: =item  scantron_validate_missingbubbles() : 
 9805: 
 9806:    Validates all scanlines in the selected file to not have any
 9807:     answers that don't have bubbles that have not been verified
 9808:     to be bubble free.
 9809: 
 9810: =item  scantron_process_students() : 
 9811: 
 9812:    Routine that does the actual grading of the bubblesheet information.
 9813: 
 9814:    The parsed scanline hash is added to %env 
 9815: 
 9816:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9817:    foreach resource , with the form data of
 9818: 
 9819: 	'submitted'     =>'scantron' 
 9820: 	'grade_target'  =>'grade',
 9821: 	'grade_username'=> username of student
 9822: 	'grade_domain'  => domain of student
 9823: 	'grade_courseid'=> of course
 9824: 	'grade_symb'    => symb of resource to grade
 9825: 
 9826:     This triggers a grading pass. The problem grading code takes care
 9827:     of converting the bubbled letter information (now in %env) into a
 9828:     valid submission.
 9829: 
 9830: =item  scantron_upload_scantron_data() :
 9831: 
 9832:     Creates the screen for adding a new bubblesheet data file to a course.
 9833: 
 9834: =item  scantron_upload_scantron_data_save() : 
 9835: 
 9836:    Adds a provided bubble information data file to the course if user
 9837:    has the correct privileges to do so. 
 9838: 
 9839: =item  valid_file() :
 9840: 
 9841:    Validates that the requested bubble data file exists in the course.
 9842: 
 9843: =item  scantron_download_scantron_data() : 
 9844: 
 9845:    Shows a list of the three internal files (original, corrected,
 9846:    skipped) for a specific bubblesheet data file that exists in the
 9847:    course.
 9848: 
 9849: =item  scantron_validate_ID() : 
 9850: 
 9851:    Validates all scanlines in the selected file to not have any
 9852:    invalid or underspecified student/employee IDs
 9853: 
 9854: =item navmap_errormsg() :
 9855: 
 9856:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9857:    Should be called whenever the request to instantiate a navmap object fails.  
 9858: 
 9859: =back
 9860: 
 9861: =cut

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