File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.740: download - view: text, annotated - select for diffs
Fri May 19 19:25:05 2017 UTC (6 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Facilitate work of localization phrasechecker script.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.740 2017/05/19 19:25:05 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::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: my %old_essays=();
   58: 
   59: #  These variables are used to recover from ssi errors
   60: 
   61: my $ssi_retries = 5;
   62: my $ssi_error;
   63: my $ssi_error_resource;
   64: my $ssi_error_message;
   65: 
   66: 
   67: sub ssi_with_retries {
   68:     my ($resource, $retries, %form) = @_;
   69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   70:     if ($response->is_error) {
   71: 	$ssi_error          = 1;
   72: 	$ssi_error_resource = $resource;
   73: 	$ssi_error_message  = $response->code . " " . $response->message;
   74:     }
   75: 
   76:     return $content;
   77: 
   78: }
   79: #
   80: #  Prodcuces an ssi retry failure error message to the user:
   81: #
   82: 
   83: sub ssi_print_error {
   84:     my ($r) = @_;
   85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   86:     $r->print('
   87: <br />
   88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   89: <p>
   90: '.&mt('Unable to retrieve a resource from a server:').'<br />
   91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   92: '.&mt('Error:').' '.$ssi_error_message.'
   93: </p>
   94: <p>'.
   95: &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 />'.
   96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   97: '</p>');
   98:     return;
   99: }
  100: 
  101: #
  102: # --- Retrieve the parts from the metadata file.---
  103: # Returns an array of everything that the resources stores away
  104: #
  105: 
  106: sub getpartlist {
  107:     my ($symb,$errorref) = @_;
  108: 
  109:     my $navmap   = Apache::lonnavmaps::navmap->new();
  110:     unless (ref($navmap)) {
  111:         if (ref($errorref)) { 
  112:             $$errorref = 'navmap';
  113:             return;
  114:         }
  115:     }
  116:     my $res      = $navmap->getBySymb($symb);
  117:     my $partlist = $res->parts();
  118:     my $url      = $res->src();
  119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  120: 
  121:     my @stores;
  122:     foreach my $part (@{ $partlist }) {
  123: 	foreach my $key (@metakeys) {
  124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  125: 	}
  126:     }
  127:     return @stores;
  128: }
  129: 
  130: #--- Format fullname, username:domain if different for display
  131: #--- Use anywhere where the student names are listed
  132: sub nameUserString {
  133:     my ($type,$fullname,$uname,$udom) = @_;
  134:     if ($type eq 'header') {
  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  136:     } else {
  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  139:     }
  140: }
  141: 
  142: #--- Get the partlist and the response type for a given problem. ---
  143: #--- Indicate if a response type is coded handgraded or not. ---
  144: #--- Sets response_error pointer to "1" if navmaps object broken ---
  145: sub response_type {
  146:     my ($symb,$response_error) = @_;
  147: 
  148:     my $navmap = Apache::lonnavmaps::navmap->new();
  149:     unless (ref($navmap)) {
  150:         if (ref($response_error)) {
  151:             $$response_error = 1;
  152:         }
  153:         return;
  154:     }
  155:     my $res = $navmap->getBySymb($symb);
  156:     unless (ref($res)) {
  157:         $$response_error = 1;
  158:         return;
  159:     }
  160:     my $partlist = $res->parts();
  161:     my %vPart = 
  162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  163:     my (%response_types,%handgrade);
  164:     foreach my $part (@{ $partlist }) {
  165: 	next if (%vPart && !exists($vPart{$part}));
  166: 
  167: 	my @types = $res->responseType($part);
  168: 	my @ids = $res->responseIds($part);
  169: 	for (my $i=0; $i < scalar(@ids); $i++) {
  170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  171: 	    $handgrade{$part.'_'.$ids[$i]} = 
  172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  173: 				     '.handgrade',$symb);
  174: 	}
  175:     }
  176:     return ($partlist,\%handgrade,\%response_types);
  177: }
  178: 
  179: sub flatten_responseType {
  180:     my ($responseType) = @_;
  181:     my @part_response_id =
  182: 	map { 
  183: 	    my $part = $_;
  184: 	    map {
  185: 		[$part,$_]
  186: 		} sort(keys(%{ $responseType->{$part} }));
  187: 	} sort(keys(%$responseType));
  188:     return @part_response_id;
  189: }
  190: 
  191: sub get_display_part {
  192:     my ($partID,$symb)=@_;
  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  194:     if (defined($display) and $display ne '') {
  195:         $display.= ' (<span class="LC_internal_info">'
  196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  197:     } else {
  198: 	$display=$partID;
  199:     }
  200:     return $display;
  201: }
  202: 
  203: sub reset_caches {
  204:     &reset_analyze_cache();
  205:     &reset_perm();
  206:     &reset_old_essays();
  207: }
  208: 
  209: {
  210:     my %analyze_cache;
  211:     my %analyze_cache_formkeys;
  212: 
  213:     sub reset_analyze_cache {
  214: 	undef(%analyze_cache);
  215:         undef(%analyze_cache_formkeys);
  216:     }
  217: 
  218:     sub get_analyze {
  219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  220: 	my $key = "$symb\0$uname\0$udom";
  221:         if ($type eq 'randomizetry') {
  222:             if ($trial ne '') {
  223:                 $key .= "\0".$trial;
  224:             }
  225:         }
  226: 	if (exists($analyze_cache{$key})) {
  227:             my $getupdate = 0;
  228:             if (ref($add_to_hash) eq 'HASH') {
  229:                 foreach my $item (keys(%{$add_to_hash})) {
  230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  232:                             $getupdate = 1;
  233:                             last;
  234:                         }
  235:                     } else {
  236:                         $getupdate = 1;
  237:                     }
  238:                 }
  239:             }
  240:             if (!$getupdate) {
  241:                 return $analyze_cache{$key};
  242:             }
  243:         }
  244: 
  245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  246: 	$url=&Apache::lonnet::clutter($url);
  247:         my %form = ('grade_target'      => 'analyze',
  248:                     'grade_domain'      => $udom,
  249:                     'grade_symb'        => $symb,
  250:                     'grade_courseid'    =>  $env{'request.course.id'},
  251:                     'grade_username'    => $uname,
  252:                     'grade_noincrement' => $no_increment);
  253:         if ($bubbles_per_row ne '') {
  254:             $form{'bubbles_per_row'} = $bubbles_per_row;
  255:         }
  256:         if ($type eq 'randomizetry') {
  257:             $form{'grade_questiontype'} = $type;
  258:             if ($rndseed ne '') {
  259:                 $form{'grade_rndseed'} = $rndseed;
  260:             }
  261:         }
  262:         if (ref($add_to_hash)) {
  263:             %form = (%form,%{$add_to_hash});
  264:         }
  265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  268:         if (ref($add_to_hash) eq 'HASH') {
  269:             $analyze_cache_formkeys{$key} = $add_to_hash;
  270:         } else {
  271:             $analyze_cache_formkeys{$key} = {};
  272:         }
  273: 	return $analyze_cache{$key} = \%analyze;
  274:     }
  275: 
  276:     sub get_order {
  277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  279: 	return $analyze->{"$partid.$respid.shown"};
  280:     }
  281: 
  282:     sub get_radiobutton_correct_foil {
  283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  286:         if (ref($foils) eq 'ARRAY') {
  287: 	    foreach my $foil (@{$foils}) {
  288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  289: 		    return $foil;
  290: 	        }
  291: 	    }
  292: 	}
  293:     }
  294: 
  295:     sub scantron_partids_tograde {
  296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  297:         my (%analysis,@parts);
  298:         if (ref($resource)) {
  299:             my $symb = $resource->symb();
  300:             my $add_to_form;
  301:             if ($check_for_randomlist) {
  302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  303:             }
  304:             my $analyze = 
  305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  306:                              undef,undef,undef,$bubbles_per_row);
  307:             if (ref($analyze) eq 'HASH') {
  308:                 %analysis = %{$analyze};
  309:             }
  310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  311:                 foreach my $part (@{$analysis{'parts'}}) {
  312:                     my ($id,$respid) = split(/\./,$part);
  313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  314:                         push(@parts,$part);
  315:                     }
  316:                 }
  317:             }
  318:         }
  319:         return (\%analysis,\@parts);
  320:     }
  321: 
  322: }
  323: 
  324: #--- Clean response type for display
  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
  326: #        response types only.
  327: sub cleanRecord {
  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  330:     my $grayFont = '<span class="LC_internal_info">';
  331:     if ($response =~ /^(option|rank)$/) {
  332: 	my %answer=&Apache::lonnet::str2hash($answer);
  333:         my @answer = %answer;
  334:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  335: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  336: 	my ($toprow,$bottomrow);
  337: 	foreach my $foil (@$order) {
  338: 	    if ($grading{$foil} == 1) {
  339: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  340: 	    } else {
  341: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  342: 	    }
  343: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  344: 	}
  345: 	return '<blockquote><table border="1">'.
  346: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  348: 	    $bottomrow.'</tr></table></blockquote>';
  349:     } elsif ($response eq 'match') {
  350: 	my %answer=&Apache::lonnet::str2hash($answer);
  351:         my @answer = %answer;
  352:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  353: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  354: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  355: 	my ($toprow,$middlerow,$bottomrow);
  356: 	foreach my $foil (@$order) {
  357: 	    my $item=shift(@items);
  358: 	    if ($grading{$foil} == 1) {
  359: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  360: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  361: 	    } else {
  362: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  363: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  364: 	    }
  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  366: 	}
  367: 	return '<blockquote><table border="1">'.
  368: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  369: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  370: 	    $middlerow.'</tr>'.
  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  372: 	    $bottomrow.'</tr></table></blockquote>';
  373:     } elsif ($response eq 'radiobutton') {
  374: 	my %answer=&Apache::lonnet::str2hash($answer);
  375:         my @answer = %answer;
  376:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  377: 	my ($toprow,$bottomrow);
  378: 	my $correct = 
  379: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  380: 	foreach my $foil (@$order) {
  381: 	    if (exists($answer{$foil})) {
  382: 		if ($foil eq $correct) {
  383: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  384: 		} else {
  385: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  386: 		}
  387: 	    } else {
  388: 		$toprow.='<td>'.&mt('false').'</td>';
  389: 	    }
  390: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  391: 	}
  392: 	return '<blockquote><table border="1">'.
  393: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  395: 	    $bottomrow.'</tr></table></blockquote>';
  396:     } elsif ($response eq 'essay') {
  397: 	if (! exists ($env{'form.'.$symb})) {
  398: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  399: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  400: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  401: 
  402: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  403: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  404: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  405: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  406: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  407: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  408: 	}
  409: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  410: 
  411:     } elsif ( $response eq 'organic') {
  412:         my $result=&mt('Smile representation: [_1]',
  413:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  414: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  415: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  416: 	return $result;
  417:     } elsif ( $response eq 'Task') {
  418: 	if ( $answer eq 'SUBMITTED') {
  419: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  420: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  421: 	    return $result;
  422: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  423: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  424: 			       keys(%{$record}));
  425: 	    return join('<br />',($version,@matches));
  426: 			       
  427: 			       
  428: 	} else {
  429: 	    my $result =
  430: 		'<p>'
  431: 		.&mt('Overall result: [_1]',
  432: 		     $record->{$version."resource.$respid.$partid.status"})
  433: 		.'</p>';
  434: 	    
  435: 	    $result .= '<ul>';
  436: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  437: 			     keys(%{$record}));
  438: 	    foreach my $grade (sort(@grade)) {
  439: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  440: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  441: 				     $dim, $record->{$grade}).
  442: 			  '</li>';
  443: 	    }
  444: 	    $result.='</ul>';
  445: 	    return $result;
  446: 	}
  447:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  448:         # Respect multiple input fields, see Bug #5409
  449: 	$answer = 
  450: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  451: 							      $answer);
  452: 	return $answer;
  453:     }
  454:     return &HTML::Entities::encode($answer, '"<>&');
  455: }
  456: 
  457: #-- A couple of common js functions
  458: sub commonJSfunctions {
  459:     my $request = shift;
  460:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  461:     function radioSelection(radioButton) {
  462: 	var selection=null;
  463: 	if (radioButton.length > 1) {
  464: 	    for (var i=0; i<radioButton.length; i++) {
  465: 		if (radioButton[i].checked) {
  466: 		    return radioButton[i].value;
  467: 		}
  468: 	    }
  469: 	} else {
  470: 	    if (radioButton.checked) return radioButton.value;
  471: 	}
  472: 	return selection;
  473:     }
  474: 
  475:     function pullDownSelection(selectOne) {
  476: 	var selection="";
  477: 	if (selectOne.length > 1) {
  478: 	    for (var i=0; i<selectOne.length; i++) {
  479: 		if (selectOne[i].selected) {
  480: 		    return selectOne[i].value;
  481: 		}
  482: 	    }
  483: 	} else {
  484:             // only one value it must be the selected one
  485: 	    return selectOne.value;
  486: 	}
  487:     }
  488: COMMONJSFUNCTIONS
  489: }
  490: 
  491: #--- Dumps the class list with usernames,list of sections,
  492: #--- section, ids and fullnames for each user.
  493: sub getclasslist {
  494:     my ($getsec,$filterlist,$getgroup) = @_;
  495:     my @getsec;
  496:     my @getgroup;
  497:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  498:     if (!ref($getsec)) {
  499: 	if ($getsec ne '' && $getsec ne 'all') {
  500: 	    @getsec=($getsec);
  501: 	}
  502:     } else {
  503: 	@getsec=@{$getsec};
  504:     }
  505:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  506:     if (!ref($getgroup)) {
  507: 	if ($getgroup ne '' && $getgroup ne 'all') {
  508: 	    @getgroup=($getgroup);
  509: 	}
  510:     } else {
  511: 	@getgroup=@{$getgroup};
  512:     }
  513:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  514: 
  515:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  516:     # Bail out if we were unable to get the classlist
  517:     return if (! defined($classlist));
  518:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  519:     #
  520:     my %sections;
  521:     my %fullnames;
  522:     foreach my $student (keys(%$classlist)) {
  523:         my $end      = 
  524:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  525:         my $start    = 
  526:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  527:         my $id       = 
  528:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  529:         my $section  = 
  530:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  531:         my $fullname = 
  532:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  533:         my $status   = 
  534:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  535:         my $group   = 
  536:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  537: 	# filter students according to status selected
  538: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  539: 	    if (!($stu_status =~ $status)) {
  540: 		delete($classlist->{$student});
  541: 		next;
  542: 	    }
  543: 	}
  544: 	# filter students according to groups selected
  545: 	my @stu_groups = split(/,/,$group);
  546: 	if (@getgroup) {
  547: 	    my $exclude = 1;
  548: 	    foreach my $grp (@getgroup) {
  549: 	        foreach my $stu_group (@stu_groups) {
  550: 	            if ($stu_group eq $grp) {
  551: 	                $exclude = 0;
  552:     	            } 
  553: 	        }
  554:     	        if (($grp eq 'none') && !$group) {
  555:         	        $exclude = 0;
  556:         	}
  557: 	    }
  558: 	    if ($exclude) {
  559: 	        delete($classlist->{$student});
  560: 	    }
  561: 	}
  562: 	$section = ($section ne '' ? $section : 'none');
  563: 	if (&canview($section)) {
  564: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  565: 		$sections{$section}++;
  566: 		if ($classlist->{$student}) {
  567: 		    $fullnames{$student}=$fullname;
  568: 		}
  569: 	    } else {
  570: 		delete($classlist->{$student});
  571: 	    }
  572: 	} else {
  573: 	    delete($classlist->{$student});
  574: 	}
  575:     }
  576:     my %seen = ();
  577:     my @sections = sort(keys(%sections));
  578:     return ($classlist,\@sections,\%fullnames);
  579: }
  580: 
  581: sub canmodify {
  582:     my ($sec)=@_;
  583:     if ($perm{'mgr'}) {
  584: 	if (!defined($perm{'mgr_section'})) {
  585: 	    # can modify whole class
  586: 	    return 1;
  587: 	} else {
  588: 	    if ($sec eq $perm{'mgr_section'}) {
  589: 		#can modify the requested section
  590: 		return 1;
  591: 	    } else {
  592: 		# can't modify the request section
  593: 		return 0;
  594: 	    }
  595: 	}
  596:     }
  597:     #can't modify
  598:     return 0;
  599: }
  600: 
  601: sub canview {
  602:     my ($sec)=@_;
  603:     if ($perm{'vgr'}) {
  604: 	if (!defined($perm{'vgr_section'})) {
  605: 	    # can modify whole class
  606: 	    return 1;
  607: 	} else {
  608: 	    if ($sec eq $perm{'vgr_section'}) {
  609: 		#can modify the requested section
  610: 		return 1;
  611: 	    } else {
  612: 		# can't modify the request section
  613: 		return 0;
  614: 	    }
  615: 	}
  616:     }
  617:     #can't modify
  618:     return 0;
  619: }
  620: 
  621: #--- Retrieve the grade status of a student for all the parts
  622: sub student_gradeStatus {
  623:     my ($symb,$udom,$uname,$partlist) = @_;
  624:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  625:     my %partstatus = ();
  626:     foreach (@$partlist) {
  627: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  628: 	$status              = 'nothing' if ($status eq '');
  629: 	$partstatus{$_}      = $status;
  630: 	my $subkey           = "resource.$_.submitted_by";
  631: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  632:     }
  633:     return %partstatus;
  634: }
  635: 
  636: # hidden form and javascript that calls the form
  637: # Use by verifyscript and viewgrades
  638: # Shows a student's view of problem and submission
  639: sub jscriptNform {
  640:     my ($symb) = @_;
  641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  642:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  643: 	'    function viewOneStudent(user,domain) {'."\n".
  644: 	'	document.onestudent.student.value = user;'."\n".
  645: 	'	document.onestudent.userdom.value = domain;'."\n".
  646: 	'	document.onestudent.submit();'."\n".
  647: 	'    }'."\n".
  648: 	"\n");
  649:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  650: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  651: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  652: 	'<input type="hidden" name="command" value="submission" />'."\n".
  653: 	'<input type="hidden" name="student" value="" />'."\n".
  654: 	'<input type="hidden" name="userdom" value="" />'."\n".
  655: 	'</form>'."\n";
  656:     return $jscript;
  657: }
  658: 
  659: 
  660: 
  661: # Given the score (as a number [0-1] and the weight) what is the final
  662: # point value? This function will round to the nearest tenth, third,
  663: # or quarter if one of those is within the tolerance of .00001.
  664: sub compute_points {
  665:     my ($score, $weight) = @_;
  666:     
  667:     my $tolerance = .00001;
  668:     my $points = $score * $weight;
  669: 
  670:     # Check for nearness to 1/x.
  671:     my $check_for_nearness = sub {
  672:         my ($factor) = @_;
  673:         my $num = ($points * $factor) + $tolerance;
  674:         my $floored_num = floor($num);
  675:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  676:             return $floored_num / $factor;
  677:         }
  678:         return $points;
  679:     };
  680: 
  681:     $points = $check_for_nearness->(10);
  682:     $points = $check_for_nearness->(3);
  683:     $points = $check_for_nearness->(4);
  684:     
  685:     return $points;
  686: }
  687: 
  688: #------------------ End of general use routines --------------------
  689: 
  690: #
  691: # Find most similar essay
  692: #
  693: 
  694: sub most_similar {
  695:     my ($uname,$udom,$symb,$uessay)=@_;
  696: 
  697:     unless ($symb) { return ''; }
  698: 
  699:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  700: 
  701: # ignore spaces and punctuation
  702: 
  703:     $uessay=~s/\W+/ /gs;
  704: 
  705: # ignore empty submissions (occuring when only files are sent)
  706: 
  707:     unless ($uessay=~/\w+/s) { return ''; }
  708: 
  709: # these will be returned. Do not care if not at least 50 percent similar
  710:     my $limit=0.6;
  711:     my $sname='';
  712:     my $sdom='';
  713:     my $scrsid='';
  714:     my $sessay='';
  715: # go through all essays ...
  716:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  717: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  718: # ... except the same student
  719:         next if (($tname eq $uname) && ($tdom eq $udom));
  720: 	my $tessay=$old_essays{$symb}{$tkey};
  721: 	$tessay=~s/\W+/ /gs;
  722: # String similarity gives up if not even limit
  723: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  724: # Found one
  725: 	if ($tsimilar>$limit) {
  726: 	    $limit=$tsimilar;
  727: 	    $sname=$tname;
  728: 	    $sdom=$tdom;
  729: 	    $scrsid=$tcrsid;
  730: 	    $sessay=$old_essays{$symb}{$tkey};
  731: 	}
  732:     }
  733:     if ($limit>0.6) {
  734:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  735:     } else {
  736:        return ('','','','',0);
  737:     }
  738: }
  739: 
  740: #-------------------------------------------------------------------
  741: 
  742: #------------------------------------ Receipt Verification Routines
  743: #
  744: 
  745: sub initialverifyreceipt {
  746:    my ($request,$symb) = @_;
  747:    &commonJSfunctions($request);
  748:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  749:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  750:         '-<input type="text" name="receipt" size="4" />'.
  751:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  752:         '<input type="hidden" name="command" value="verify" />'.
  753:         "</form>\n";
  754: }
  755: 
  756: #--- Check whether a receipt number is valid.---
  757: sub verifyreceipt {
  758:     my ($request,$symb)  = @_;
  759: 
  760:     my $courseid = $env{'request.course.id'};
  761:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  762: 	$env{'form.receipt'};
  763:     $receipt     =~ s/[^\-\d]//g;
  764: 
  765:     my $title.=
  766: 	'<h3><span class="LC_info">'.
  767: 	&mt('Verifying Receipt Number [_1]',$receipt).
  768: 	'</span></h3>'."\n";
  769: 
  770:     my ($string,$contents,$matches) = ('','',0);
  771:     my (undef,undef,$fullname) = &getclasslist('all','0');
  772:     
  773:     my $receiptparts=0;
  774:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  775: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  776:     my $parts=['0'];
  777:     if ($receiptparts) {
  778:         my $res_error; 
  779:         ($parts)=&response_type($symb,\$res_error);
  780:         if ($res_error) {
  781:             return &navmap_errormsg();
  782:         } 
  783:     }
  784:     
  785:     my $header = 
  786: 	&Apache::loncommon::start_data_table().
  787: 	&Apache::loncommon::start_data_table_header_row().
  788: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  789: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  790: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  791:     if ($receiptparts) {
  792: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  793:     }
  794:     $header.=
  795: 	&Apache::loncommon::end_data_table_header_row();
  796: 
  797:     foreach (sort 
  798: 	     {
  799: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  800: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  801: 		 }
  802: 		 return $a cmp $b;
  803: 	     } (keys(%$fullname))) {
  804: 	my ($uname,$udom)=split(/\:/);
  805: 	foreach my $part (@$parts) {
  806: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  807: 		$contents.=
  808: 		    &Apache::loncommon::start_data_table_row().
  809: 		    '<td>&nbsp;'."\n".
  810: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  811: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  812: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  813: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  814: 		if ($receiptparts) {
  815: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  816: 		}
  817: 		$contents.= 
  818: 		    &Apache::loncommon::end_data_table_row()."\n";
  819: 		
  820: 		$matches++;
  821: 	    }
  822: 	}
  823:     }
  824:     if ($matches == 0) {
  825:         $string = $title
  826:                  .'<p class="LC_warning">'
  827:                  .&mt('No match found for the above receipt number.')
  828:                  .'</p>';
  829:     } else {
  830: 	$string = &jscriptNform($symb).$title.
  831: 	    '<p>'.
  832: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  833: 	    '</p>'.
  834: 	    $header.
  835: 	    $contents.
  836: 	    &Apache::loncommon::end_data_table()."\n";
  837:     }
  838:     return $string;
  839: }
  840: 
  841: #--- This is called by a number of programs.
  842: #--- Called from the Grading Menu - View/Grade an individual student
  843: #--- Also called directly when one clicks on the subm button 
  844: #    on the problem page.
  845: sub listStudents {
  846:     my ($request,$symb,$submitonly) = @_;
  847: 
  848:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  849:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  850:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  851:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  852:     unless ($submitonly) {
  853:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  854:     }
  855: 
  856:     my $result='';
  857:     my $res_error;
  858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  859: 
  860:     my %js_lt = &Apache::lonlocal::texthash (
  861: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  862: 		'single'   => 'Please select the student before clicking on the Next button.',
  863: 	     );
  864:     &js_escape(\%js_lt);
  865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  866:     function checkSelect(checkBox) {
  867: 	var ctr=0;
  868: 	var sense="";
  869: 	if (checkBox.length > 1) {
  870: 	    for (var i=0; i<checkBox.length; i++) {
  871: 		if (checkBox[i].checked) {
  872: 		    ctr++;
  873: 		}
  874: 	    }
  875: 	    sense = '$js_lt{'multiple'}';
  876: 	} else {
  877: 	    if (checkBox.checked) {
  878: 		ctr = 1;
  879: 	    }
  880: 	    sense = '$js_lt{'single'}';
  881: 	}
  882: 	if (ctr == 0) {
  883: 	    alert(sense);
  884: 	    return false;
  885: 	}
  886: 	document.gradesub.submit();
  887:     }
  888: 
  889:     function reLoadList(formname) {
  890: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  891: 	formname.command.value = 'submission';
  892: 	formname.submit();
  893:     }
  894: LISTJAVASCRIPT
  895: 
  896:     &commonJSfunctions($request);
  897:     $request->print($result);
  898: 
  899:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  900: 	"\n";
  901: 	
  902:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  903:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  904:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  905:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  906:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  907:                   .&Apache::lonhtmlcommon::row_closure();
  908:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  909:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  910:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  911:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  912:                   .&Apache::lonhtmlcommon::row_closure();
  913: 
  914:     my $submission_options;
  915:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  916:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  917:     $env{'form.Status'} = $saveStatus;
  918:     $submission_options.=
  919:         '<span class="LC_nobreak">'.
  920:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  921:         &mt('last submission').' </label></span>'."\n".
  922:         '<span class="LC_nobreak">'.
  923:         '<label><input type="radio" name="lastSub" value="last" /> '.
  924:         &mt('last submission with details').' </label></span>'."\n".
  925:         '<span class="LC_nobreak">'.
  926:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  927:         &mt('all submissions').'</label></span>'."\n".
  928:         '<span class="LC_nobreak">'.
  929:         '<label><input type="radio" name="lastSub" value="all" /> '.
  930:         &mt('all submissions with details').'</label></span>';
  931:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
  932:                   .$submission_options
  933:                   .&Apache::lonhtmlcommon::row_closure();
  934: 
  935:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  936:                   .'<select name="increment">'
  937:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  938:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  939:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  940:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  941:                   .'</select>'
  942:                   .&Apache::lonhtmlcommon::row_closure();
  943: 
  944:     $gradeTable .= 
  945:         &build_section_inputs().
  946: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  947: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  948: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  949: 
  950:     if (exists($env{'form.Status'})) {
  951: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  952:     } else {
  953:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  954:                       .&Apache::lonhtmlcommon::StatusOptions(
  955:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  956:                       .&Apache::lonhtmlcommon::row_closure();
  957:     }
  958: 
  959:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  960:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  961:                   .&Apache::lonhtmlcommon::row_closure(1)
  962:                   .&Apache::lonhtmlcommon::end_pick_box();
  963: 
  964:     $gradeTable .= '<p>'
  965:                   .&mt("To view/grade/regrade 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"
  966:                   .'<input type="hidden" name="command" value="processGroup" />'
  967:                   .'</p>';
  968: 
  969: # checkall buttons
  970:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  971:     $gradeTable.='<input type="button" '."\n".
  972:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  973:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  974:     $gradeTable.=&check_buttons();
  975:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  976:     $gradeTable.= &Apache::loncommon::start_data_table().
  977: 	&Apache::loncommon::start_data_table_header_row();
  978:     my $loop = 0;
  979:     while ($loop < 2) {
  980: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  981: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  982: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
  983: 	    foreach my $part (sort(@$partlist)) {
  984: 		my $display_part=
  985: 		    &get_display_part((split(/_/,$part))[0],$symb);
  986: 		$gradeTable.=
  987: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  988: 	    }
  989: 	} elsif ($submitonly eq 'queued') {
  990: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  991: 	}
  992: 	$loop++;
  993: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  994:     }
  995:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  996: 
  997:     my $ctr = 0;
  998:     foreach my $student (sort 
  999: 			 {
 1000: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1001: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1002: 			     }
 1003: 			     return $a cmp $b;
 1004: 			 }
 1005: 			 (keys(%$fullname))) {
 1006: 	my ($uname,$udom) = split(/:/,$student);
 1007: 
 1008: 	my %status = ();
 1009: 
 1010: 	if ($submitonly eq 'queued') {
 1011: 	    my %queue_status = 
 1012: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1013: 							$udom,$uname);
 1014: 	    next if (!defined($queue_status{'gradingqueue'}));
 1015: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1016: 	}
 1017: 
 1018: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1019: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1020: 	    my $submitted = 0;
 1021: 	    my $graded = 0;
 1022: 	    my $incorrect = 0;
 1023: 	    foreach (keys(%status)) {
 1024: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1025: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1026: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1027: 		
 1028: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1029: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1030: 		    $submitted = 0;
 1031: 		    my ($part)=split(/\./,$partid);
 1032: 		    $gradeTable.='<input type="hidden" name="'.
 1033: 			$student.':'.$part.':submitted_by" value="'.
 1034: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1035: 		}
 1036: 	    }
 1037: 	    
 1038: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1039: 				     $submitonly eq 'incorrect' ||
 1040: 				     $submitonly eq 'graded'));
 1041: 	    next if (!$graded && ($submitonly eq 'graded'));
 1042: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1043: 	}
 1044: 
 1045: 	$ctr++;
 1046: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1047:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1048: 	if ( $perm{'vgr'} eq 'F' ) {
 1049: 	    if ($ctr%2 ==1) {
 1050: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1051: 	    }
 1052: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1053:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1054:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1055: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1056: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1057: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1058: 
 1059: 	    if ($submitonly ne 'all') {
 1060: 		foreach (sort(keys(%status))) {
 1061: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1062: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1063: 		}
 1064: 	    }
 1065: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1066: 	    if ($ctr%2 ==0) {
 1067: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1068: 	    }
 1069: 	}
 1070:     }
 1071:     if ($ctr%2 ==1) {
 1072: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1073: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1074: 		foreach (@$partlist) {
 1075: 		    $gradeTable.='<td>&nbsp;</td>';
 1076: 		}
 1077: 	    } elsif ($submitonly eq 'queued') {
 1078: 		$gradeTable.='<td>&nbsp;</td>';
 1079: 	    }
 1080: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1081:     }
 1082: 
 1083:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1084:         '<input type="button" '.
 1085:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1086:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1087:     if ($ctr == 0) {
 1088: 	my $num_students=(scalar(keys(%$fullname)));
 1089: 	if ($num_students eq 0) {
 1090: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1091: 	} else {
 1092: 	    my $submissions='submissions';
 1093: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1094: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1095: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1096: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1097: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1098: 		    $num_students).
 1099: 		'</span><br />';
 1100: 	}
 1101:     } elsif ($ctr == 1) {
 1102: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1103:     }
 1104:     $request->print($gradeTable);
 1105:     return '';
 1106: }
 1107: 
 1108: #---- Called from the listStudents routine
 1109: 
 1110: sub check_script {
 1111:     my ($form, $type)=@_;
 1112:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1113:     function checkall() {
 1114:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1115:             ele = document.forms.'.$form.'.elements[i];
 1116:             if (ele.name == "'.$type.'") {
 1117:             document.forms.'.$form.'.elements[i].checked=true;
 1118:                                        }
 1119:         }
 1120:     }
 1121: 
 1122:     function checksec() {
 1123:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1124:             ele = document.forms.'.$form.'.elements[i];
 1125:            string = document.forms.'.$form.'.chksec.value;
 1126:            if
 1127:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1128:               document.forms.'.$form.'.elements[i].checked=true;
 1129:             }
 1130:         }
 1131:     }
 1132: 
 1133: 
 1134:     function uncheckall() {
 1135:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1136:             ele = document.forms.'.$form.'.elements[i];
 1137:             if (ele.name == "'.$type.'") {
 1138:             document.forms.'.$form.'.elements[i].checked=false;
 1139:                                        }
 1140:         }
 1141:     }
 1142: 
 1143: '."\n");
 1144:     return $chkallscript;
 1145: }
 1146: 
 1147: sub check_buttons {
 1148:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1149:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1150:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1151:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1152:     return $buttons;
 1153: }
 1154: 
 1155: #     Displays the submissions for one student or a group of students
 1156: sub processGroup {
 1157:     my ($request,$symb)  = @_;
 1158:     my $ctr        = 0;
 1159:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1160:     my $total      = scalar(@stuchecked)-1;
 1161: 
 1162:     foreach my $student (@stuchecked) {
 1163: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1164: 	$env{'form.student'}        = $uname;
 1165: 	$env{'form.userdom'}        = $udom;
 1166: 	$env{'form.fullname'}       = $fullname;
 1167: 	&submission($request,$ctr,$total,$symb);
 1168: 	$ctr++;
 1169:     }
 1170:     return '';
 1171: }
 1172: 
 1173: #------------------------------------------------------------------------------------
 1174: #
 1175: #-------------------------- Next few routines handles grading by student, essentially
 1176: #                           handles essay response type problem/part
 1177: #
 1178: #--- Javascript to handle the submission page functionality ---
 1179: sub sub_page_js {
 1180:     my $request = shift;
 1181:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1182:     &js_escape(\$alertmsg);
 1183:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1184:     function updateRadio(formname,id,weight) {
 1185: 	var gradeBox = formname["GD_BOX"+id];
 1186: 	var radioButton = formname["RADVAL"+id];
 1187: 	var oldpts = formname["oldpts"+id].value;
 1188: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1189: 	gradeBox.value = pts;
 1190: 	var resetbox = false;
 1191: 	if (isNaN(pts) || pts < 0) {
 1192: 	    alert("$alertmsg"+pts);
 1193: 	    for (var i=0; i<radioButton.length; i++) {
 1194: 		if (radioButton[i].checked) {
 1195: 		    gradeBox.value = i;
 1196: 		    resetbox = true;
 1197: 		}
 1198: 	    }
 1199: 	    if (!resetbox) {
 1200: 		formtextbox.value = "";
 1201: 	    }
 1202: 	    return;
 1203: 	}
 1204: 
 1205: 	if (pts > weight) {
 1206: 	    var resp = confirm("You entered a value ("+pts+
 1207: 			       ") greater than the weight for the part. Accept?");
 1208: 	    if (resp == false) {
 1209: 		gradeBox.value = oldpts;
 1210: 		return;
 1211: 	    }
 1212: 	}
 1213: 
 1214: 	for (var i=0; i<radioButton.length; i++) {
 1215: 	    radioButton[i].checked=false;
 1216: 	    if (pts == i && pts != "") {
 1217: 		radioButton[i].checked=true;
 1218: 	    }
 1219: 	}
 1220: 	updateSelect(formname,id);
 1221: 	formname["stores"+id].value = "0";
 1222:     }
 1223: 
 1224:     function writeBox(formname,id,pts) {
 1225: 	var gradeBox = formname["GD_BOX"+id];
 1226: 	if (checkSolved(formname,id) == 'update') {
 1227: 	    gradeBox.value = pts;
 1228: 	} else {
 1229: 	    var oldpts = formname["oldpts"+id].value;
 1230: 	    gradeBox.value = oldpts;
 1231: 	    var radioButton = formname["RADVAL"+id];
 1232: 	    for (var i=0; i<radioButton.length; i++) {
 1233: 		radioButton[i].checked=false;
 1234: 		if (i == oldpts) {
 1235: 		    radioButton[i].checked=true;
 1236: 		}
 1237: 	    }
 1238: 	}
 1239: 	formname["stores"+id].value = "0";
 1240: 	updateSelect(formname,id);
 1241: 	return;
 1242:     }
 1243: 
 1244:     function clearRadBox(formname,id) {
 1245: 	if (checkSolved(formname,id) == 'noupdate') {
 1246: 	    updateSelect(formname,id);
 1247: 	    return;
 1248: 	}
 1249: 	gradeSelect = formname["GD_SEL"+id];
 1250: 	for (var i=0; i<gradeSelect.length; i++) {
 1251: 	    if (gradeSelect[i].selected) {
 1252: 		var selectx=i;
 1253: 	    }
 1254: 	}
 1255: 	var stores = formname["stores"+id];
 1256: 	if (selectx == stores.value) { return };
 1257: 	var gradeBox = formname["GD_BOX"+id];
 1258: 	gradeBox.value = "";
 1259: 	var radioButton = formname["RADVAL"+id];
 1260: 	for (var i=0; i<radioButton.length; i++) {
 1261: 	    radioButton[i].checked=false;
 1262: 	}
 1263: 	stores.value = selectx;
 1264:     }
 1265: 
 1266:     function checkSolved(formname,id) {
 1267: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1268: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1269: 	    if (!reply) {return "noupdate";}
 1270: 	    formname.overRideScore.value = 'yes';
 1271: 	}
 1272: 	return "update";
 1273:     }
 1274: 
 1275:     function updateSelect(formname,id) {
 1276: 	formname["GD_SEL"+id][0].selected = true;
 1277: 	return;
 1278:     }
 1279: 
 1280: //=========== Check that a point is assigned for all the parts  ============
 1281:     function checksubmit(formname,val,total,parttot) {
 1282: 	formname.gradeOpt.value = val;
 1283: 	if (val == "Save & Next") {
 1284: 	    for (i=0;i<=total;i++) {
 1285: 		for (j=0;j<parttot;j++) {
 1286: 		    var partid = formname["partid"+i+"_"+j].value;
 1287: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1288: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1289: 			if (points == "") {
 1290: 			    var name = formname["name"+i].value;
 1291: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1292: 			    var resp = confirm("You did not assign a score for "+studentID+
 1293: 					       ", part "+partid+". Continue?");
 1294: 			    if (resp == false) {
 1295: 				formname["GD_BOX"+i+"_"+partid].focus();
 1296: 				return false;
 1297: 			    }
 1298: 			}
 1299: 		    }
 1300: 		}
 1301: 	    }
 1302: 	}
 1303: 	formname.submit();
 1304:     }
 1305: 
 1306: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1307:     function checkSubmitPage(formname,total) {
 1308: 	noscore = new Array(100);
 1309: 	var ptr = 0;
 1310: 	for (i=1;i<total;i++) {
 1311: 	    var partid = formname["q_"+i].value;
 1312: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1313: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1314: 		var status = formname["solved"+i+"_"+partid].value;
 1315: 		if (points == "" && status != "correct_by_student") {
 1316: 		    noscore[ptr] = i;
 1317: 		    ptr++;
 1318: 		}
 1319: 	    }
 1320: 	}
 1321: 	if (ptr != 0) {
 1322: 	    var sense = ptr == 1 ? ": " : "s: ";
 1323: 	    var prolist = "";
 1324: 	    if (ptr == 1) {
 1325: 		prolist = noscore[0];
 1326: 	    } else {
 1327: 		var i = 0;
 1328: 		while (i < ptr-1) {
 1329: 		    prolist += noscore[i]+", ";
 1330: 		    i++;
 1331: 		}
 1332: 		prolist += "and "+noscore[i];
 1333: 	    }
 1334: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1335: 	    if (resp == false) {
 1336: 		return false;
 1337: 	    }
 1338: 	}
 1339: 
 1340: 	formname.submit();
 1341:     }
 1342: SUBJAVASCRIPT
 1343: }
 1344: 
 1345: #--- javascript for essay type problem --
 1346: sub sub_page_kw_js {
 1347:     my $request = shift;
 1348:     my $iconpath = $request->dir_config('lonIconsURL');
 1349:     &commonJSfunctions($request);
 1350: 
 1351:     my $inner_js_msg_central= (<<INNERJS);
 1352: <script type="text/javascript">
 1353:     function checkInput() {
 1354:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1355:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1356:       var usrctr = document.msgcenter.usrctr.value;
 1357:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1358:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1359: 
 1360:       var msgchk = "";
 1361:       if (document.msgcenter.subchk.checked) {
 1362:          msgchk = "msgsub,";
 1363:       }
 1364:       var includemsg = 0;
 1365:       for (var i=1; i<=nmsg; i++) {
 1366:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1367:           var frmmsg = document.msgcenter["msg"+i];
 1368:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1369:           var showflg = opener.document.SCORE["shownOnce"+i];
 1370:           showflg.value = "1";
 1371:           var chkbox = document.msgcenter["msgn"+i];
 1372:           if (chkbox.checked) {
 1373:              msgchk += "savemsg"+i+",";
 1374:              includemsg = 1;
 1375:           }
 1376:       }
 1377:       if (document.msgcenter.newmsgchk.checked) {
 1378:          msgchk += "newmsg"+usrctr;
 1379:          includemsg = 1;
 1380:       }
 1381:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1382:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1383:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1384:       includemsg.value = msgchk;
 1385: 
 1386:       self.close()
 1387: 
 1388:     }
 1389: </script>
 1390: INNERJS
 1391: 
 1392:     my $inner_js_highlight_central= (<<INNERJS);
 1393: <script type="text/javascript">
 1394:     function updateChoice(flag) {
 1395:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1396:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1397:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1398:       opener.document.SCORE.refresh.value = "on";
 1399:       if (opener.document.SCORE.keywords.value!=""){
 1400:          opener.document.SCORE.submit();
 1401:       }
 1402:       self.close()
 1403:     }
 1404: </script>
 1405: INNERJS
 1406: 
 1407:     my $start_page_msg_central = 
 1408:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1409: 				       {'js_ready'  => 1,
 1410: 					'only_body' => 1,
 1411: 					'bgcolor'   =>'#FFFFFF',});
 1412:     my $end_page_msg_central = 
 1413: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1414: 
 1415: 
 1416:     my $start_page_highlight_central = 
 1417:         &Apache::loncommon::start_page('Highlight Central',
 1418: 				       $inner_js_highlight_central,
 1419: 				       {'js_ready'  => 1,
 1420: 					'only_body' => 1,
 1421: 					'bgcolor'   =>'#FFFFFF',});
 1422:     my $end_page_highlight_central = 
 1423: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1424: 
 1425:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1426:     $docopen=~s/^document\.//;
 1427:     my %js_lt = &Apache::lonlocal::texthash(
 1428:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1429:                 plse => 'Please select a word or group of words from document and then click this link.',
 1430:                 adds => 'Add selection to keyword list? Edit if desired.',
 1431:                 col1 => 'red',
 1432:                 col2 => 'green',
 1433:                 col3 => 'blue',
 1434:                 siz1 => 'normal',
 1435:                 siz2 => '+1',
 1436:                 siz3 => '+2',
 1437:                 sty1 => 'normal',
 1438:                 sty2 => 'italic',
 1439:                 sty3 => 'bold',
 1440:              );
 1441:     my %html_js_lt = &Apache::lonlocal::texthash(
 1442:                 comp => 'Compose Message for: ',
 1443:                 incl => 'Include',
 1444:                 type => 'Type',
 1445:                 subj => 'Subject',
 1446:                 mesa => 'Message',
 1447:                 new  => 'New',
 1448:                 save => 'Save',
 1449:                 canc => 'Cancel',
 1450:                 kehi => 'Keyword Highlight Options',
 1451:                 txtc => 'Text Color',
 1452:                 font => 'Font Size',
 1453:                 fnst => 'Font Style',
 1454:              );
 1455:     &js_escape(\%js_lt);
 1456:     &html_escape(\%html_js_lt);
 1457:     &js_escape(\%html_js_lt);
 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1459: 
 1460: //===================== Show list of keywords ====================
 1461:   function keywords(formname) {
 1462:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1463:     if (nret==null) return;
 1464:     formname.keywords.value = nret;
 1465: 
 1466:     if (formname.keywords.value != "") {
 1467: 	formname.refresh.value = "on";
 1468: 	formname.submit();
 1469:     }
 1470:     return;
 1471:   }
 1472: 
 1473: //===================== Script to view submitted by ==================
 1474:   function viewSubmitter(submitter) {
 1475:     document.SCORE.refresh.value = "on";
 1476:     document.SCORE.NCT.value = "1";
 1477:     document.SCORE.unamedom0.value = submitter;
 1478:     document.SCORE.submit();
 1479:     return;
 1480:   }
 1481: 
 1482: //===================== Script to add keyword(s) ==================
 1483:   function getSel() {
 1484:     if (document.getSelection) txt = document.getSelection();
 1485:     else if (document.selection) txt = document.selection.createRange().text;
 1486:     else return;
 1487:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1488:     if (cleantxt=="") {
 1489: 	alert("$js_lt{'plse'}");
 1490: 	return;
 1491:     }
 1492:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1493:     if (nret==null) return;
 1494:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1495:     if (document.SCORE.keywords.value != "") {
 1496: 	document.SCORE.refresh.value = "on";
 1497: 	document.SCORE.submit();
 1498:     }
 1499:     return;
 1500:   }
 1501: 
 1502: //====================== Script for composing message ==============
 1503:    // preload images
 1504:    img1 = new Image();
 1505:    img1.src = "$iconpath/mailbkgrd.gif";
 1506:    img2 = new Image();
 1507:    img2.src = "$iconpath/mailto.gif";
 1508: 
 1509:   function msgCenter(msgform,usrctr,fullname) {
 1510:     var Nmsg  = msgform.savemsgN.value;
 1511:     savedMsgHeader(Nmsg,usrctr,fullname);
 1512:     var subject = msgform.msgsub.value;
 1513:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1514:     re = /msgsub/;
 1515:     var shwsel = "";
 1516:     if (re.test(msgchk)) { shwsel = "checked" }
 1517:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1518:     displaySubject(checkEntities(subject),shwsel);
 1519:     for (var i=1; i<=Nmsg; i++) {
 1520: 	var testmsg = "savemsg"+i+",";
 1521: 	re = new RegExp(testmsg,"g");
 1522: 	shwsel = "";
 1523: 	if (re.test(msgchk)) { shwsel = "checked" }
 1524: 	var message = document.SCORE["savemsg"+i].value;
 1525: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1526: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1527: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1528:     }
 1529:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1530:     shwsel = "";
 1531:     re = /newmsg/;
 1532:     if (re.test(msgchk)) { shwsel = "checked" }
 1533:     newMsg(newmsg,shwsel);
 1534:     msgTail(); 
 1535:     return;
 1536:   }
 1537: 
 1538:   function checkEntities(strx) {
 1539:     if (strx.length == 0) return strx;
 1540:     var orgStr = ["&", "<", ">", '"']; 
 1541:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1542:     var counter = 0;
 1543:     while (counter < 4) {
 1544: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1545: 	counter++;
 1546:     }
 1547:     return strx;
 1548:   }
 1549: 
 1550:   function strReplace(strx, orgStr, newStr) {
 1551:     return strx.split(orgStr).join(newStr);
 1552:   }
 1553: 
 1554:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1555:     var height = 70*Nmsg+250;
 1556:     if (height > 600) {
 1557: 	height = 600;
 1558:     }
 1559:     var xpos = (screen.width-600)/2;
 1560:     xpos = (xpos < 0) ? '0' : xpos;
 1561:     var ypos = (screen.height-height)/2-30;
 1562:     ypos = (ypos < 0) ? '0' : ypos;
 1563: 
 1564:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1565:     pWin.focus();
 1566:     pDoc = pWin.document;
 1567:     pDoc.$docopen;
 1568:     pDoc.write('$start_page_msg_central');
 1569: 
 1570:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1571:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1572:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1573: 
 1574:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1575:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1576: }
 1577:     function displaySubject(msg,shwsel) {
 1578:     pDoc = pWin.document;
 1579:     pDoc.write("<tr>");
 1580:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1581:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1582:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1583: }
 1584: 
 1585:   function displaySavedMsg(ctr,msg,shwsel) {
 1586:     pDoc = pWin.document;
 1587:     pDoc.write("<tr>");
 1588:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1589:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1590:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1591: }
 1592: 
 1593:   function newMsg(newmsg,shwsel) {
 1594:     pDoc = pWin.document;
 1595:     pDoc.write("<tr>");
 1596:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1597:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1598:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1599: }
 1600: 
 1601:   function msgTail() {
 1602:     pDoc = pWin.document;
 1603:     //pDoc.write("<\\/table>");
 1604:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1605:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1606:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1607:     pDoc.write("<\\/form>");
 1608:     pDoc.write('$end_page_msg_central');
 1609:     pDoc.close();
 1610: }
 1611: 
 1612: //====================== Script for keyword highlight options ==============
 1613:   function kwhighlight() {
 1614:     var kwclr    = document.SCORE.kwclr.value;
 1615:     var kwsize   = document.SCORE.kwsize.value;
 1616:     var kwstyle  = document.SCORE.kwstyle.value;
 1617:     var redsel = "";
 1618:     var grnsel = "";
 1619:     var blusel = "";
 1620:     var txtcol1 = "$js_lt{'col1'}";
 1621:     var txtcol2 = "$js_lt{'col2'}";
 1622:     var txtcol3 = "$js_lt{'col3'}";
 1623:     var txtsiz1 = "$js_lt{'siz1'}";
 1624:     var txtsiz2 = "$js_lt{'siz2'}";
 1625:     var txtsiz3 = "$js_lt{'siz3'}";
 1626:     var txtsty1 = "$js_lt{'sty1'}";
 1627:     var txtsty2 = "$js_lt{'sty2'}";
 1628:     var txtsty3 = "$js_lt{'sty3'}";
 1629:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1630:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1631:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1632:     var sznsel = "";
 1633:     var sz1sel = "";
 1634:     var sz2sel = "";
 1635:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1636:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1637:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1638:     var synsel = "";
 1639:     var syisel = "";
 1640:     var sybsel = "";
 1641:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1642:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1643:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1644:     highlightCentral();
 1645:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1646:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1647:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1648:     highlightend();
 1649:     return;
 1650:   }
 1651: 
 1652:   function highlightCentral() {
 1653: //    if (window.hwdWin) window.hwdWin.close();
 1654:     var xpos = (screen.width-400)/2;
 1655:     xpos = (xpos < 0) ? '0' : xpos;
 1656:     var ypos = (screen.height-330)/2-30;
 1657:     ypos = (ypos < 0) ? '0' : ypos;
 1658: 
 1659:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1660:     hwdWin.focus();
 1661:     var hDoc = hwdWin.document;
 1662:     hDoc.$docopen;
 1663:     hDoc.write('$start_page_highlight_central');
 1664:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1665:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1666: 
 1667:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1668:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1669:   }
 1670: 
 1671:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1672:     var hDoc = hwdWin.document;
 1673:     hDoc.write("<tr>");
 1674:     hDoc.write("<td align=\\"left\\">");
 1675:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1676:     hDoc.write("<td align=\\"left\\">");
 1677:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1678:     hDoc.write("<td align=\\"left\\">");
 1679:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1680:     hDoc.write("<\\/tr>");
 1681:   }
 1682: 
 1683:   function highlightend() { 
 1684:     var hDoc = hwdWin.document;
 1685:     hDoc.write("<\\/table><br \\/>");
 1686:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1687:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1688:     hDoc.write("<\\/form>");
 1689:     hDoc.write('$end_page_highlight_central');
 1690:     hDoc.close();
 1691:   }
 1692: 
 1693: SUBJAVASCRIPT
 1694: }
 1695: 
 1696: sub get_increment {
 1697:     my $increment = $env{'form.increment'};
 1698:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1699:         $increment != .1) {
 1700:         $increment = 1;
 1701:     }
 1702:     return $increment;
 1703: }
 1704: 
 1705: sub gradeBox_start {
 1706:     return (
 1707:         &Apache::loncommon::start_data_table()
 1708:        .&Apache::loncommon::start_data_table_header_row()
 1709:        .'<th>'.&mt('Part').'</th>'
 1710:        .'<th>'.&mt('Points').'</th>'
 1711:        .'<th>&nbsp;</th>'
 1712:        .'<th>'.&mt('Assign Grade').'</th>'
 1713:        .'<th>'.&mt('Weight').'</th>'
 1714:        .'<th>'.&mt('Grade Status').'</th>'
 1715:        .&Apache::loncommon::end_data_table_header_row()
 1716:     );
 1717: }
 1718: 
 1719: sub gradeBox_end {
 1720:     return (
 1721:         &Apache::loncommon::end_data_table()
 1722:     );
 1723: }
 1724: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1725: sub gradeBox {
 1726:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1727:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1728: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1729:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1730:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1731:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1732:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1733:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1734: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1735:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1736:     my $display_part= &get_display_part($partid,$symb);
 1737:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1738: 				       [$partid]);
 1739:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1740:     if ($last_resets{$partid}) {
 1741:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1742:     }
 1743:     my $result=&Apache::loncommon::start_data_table_row();
 1744:     my $ctr = 0;
 1745:     my $thisweight = 0;
 1746:     my $increment = &get_increment();
 1747: 
 1748:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1749:     while ($thisweight<=$wgt) {
 1750: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1751:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1752: 	    $thisweight.')" value="'.$thisweight.'" '.
 1753: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1754: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1755:         $thisweight += $increment;
 1756: 	$ctr++;
 1757:     }
 1758:     $radio.='</tr></table>';
 1759: 
 1760:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1761: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1762: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1763: 	$wgt.')" /></td>'."\n";
 1764:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1765: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1766: 	' </td>'."\n";
 1767:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1768: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1769:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1770: 	$line.='<option></option>'.
 1771: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1772:     } else {
 1773: 	$line.='<option selected="selected"></option>'.
 1774: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1775:     }
 1776:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1777: 
 1778: 
 1779:     $result .= 
 1780: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1781:     $result.=&Apache::loncommon::end_data_table_row();
 1782:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1783:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1784: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1785: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1786: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1787:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1788:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1789:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1790:         $aggtries.'" />'."\n";
 1791:     my $res_error;
 1792:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1793:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1794:     if ($res_error) {
 1795:         return &navmap_errormsg();
 1796:     }
 1797:     return $result;
 1798: }
 1799: 
 1800: sub handback_box {
 1801:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1802:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1803:     my (@respids);
 1804:     my @part_response_id = &flatten_responseType($responseType);
 1805:     foreach my $part_response_id (@part_response_id) {
 1806:     	my ($part,$resp) = @{ $part_response_id };
 1807:         if ($part eq $partid) {
 1808:             push(@respids,$resp);
 1809:         }
 1810:     }
 1811:     my $result;
 1812:     foreach my $respid (@respids) {
 1813: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1814: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1815: 	next if (!@$files);
 1816: 	my $file_counter = 0;
 1817: 	foreach my $file (@$files) {
 1818: 	    if ($file =~ /\/portfolio\//) {
 1819:                 $file_counter++;
 1820:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1821:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1822:     	        $file_disp = "$name.$ext";
 1823:     	        $file = $file_path.$file_disp;
 1824:     	        $result.=&mt('Return commented version of [_1] to student.',
 1825:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1826:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1827:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1828: 	    }
 1829: 	}
 1830:         if ($file_counter) {
 1831:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1832:                        '<span class="LC_info">'.
 1833:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1834:         }
 1835:     }
 1836:     return $result;    
 1837: }
 1838: 
 1839: sub show_problem {
 1840:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1841:     my $rendered;
 1842:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1843:     &Apache::lonxml::remember_problem_counter();
 1844:     if ($mode eq 'both' or $mode eq 'text') {
 1845: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1846: 						       $env{'request.course.id'},
 1847: 						       undef,\%form);
 1848:     }
 1849:     if ($removeform) {
 1850: 	$rendered=~s|<form(.*?)>||g;
 1851: 	$rendered=~s|</form>||g;
 1852: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1853:     }
 1854:     my $companswer;
 1855:     if ($mode eq 'both' or $mode eq 'answer') {
 1856: 	&Apache::lonxml::restore_problem_counter();
 1857: 	$companswer=
 1858: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1859: 						    $env{'request.course.id'},
 1860: 						    %form);
 1861:     }
 1862:     if ($removeform) {
 1863: 	$companswer=~s|<form(.*?)>||g;
 1864: 	$companswer=~s|</form>||g;
 1865: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1866:     }
 1867:     my $renderheading = &mt('View of the problem');
 1868:     my $answerheading = &mt('Correct answer');
 1869:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1870:         my $stu_fullname = $env{'form.fullname'};
 1871:         if ($stu_fullname eq '') {
 1872:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1873:         }
 1874:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1875:         if ($forwhom ne '') {
 1876:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1877:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1878:         }
 1879:     }
 1880:     $rendered=
 1881:         '<div class="LC_Box">'
 1882:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1883:        .$rendered
 1884:        .'</div>';
 1885:     $companswer=
 1886:         '<div class="LC_Box">'
 1887:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1888:        .$companswer
 1889:        .'</div>';
 1890:     my $result;
 1891:     if ($mode eq 'both') {
 1892:         $result=$rendered.$companswer;
 1893:     } elsif ($mode eq 'text') {
 1894:         $result=$rendered;
 1895:     } elsif ($mode eq 'answer') {
 1896:         $result=$companswer;
 1897:     }
 1898:     return $result;
 1899: }
 1900: 
 1901: sub files_exist {
 1902:     my ($r, $symb) = @_;
 1903:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1904: 
 1905:     foreach my $student (@students) {
 1906:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1907:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1908: 					      $udom,$uname);
 1909:         my ($string,$timestamp)= &get_last_submission(\%record);
 1910:         foreach my $submission (@$string) {
 1911:             my ($partid,$respid) =
 1912: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1913:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1914: 					   \%record);
 1915:             return 1 if (@$files);
 1916:         }
 1917:     }
 1918:     return 0;
 1919: }
 1920: 
 1921: sub download_all_link {
 1922:     my ($r,$symb) = @_;
 1923:     unless (&files_exist($r, $symb)) {
 1924:        $r->print(&mt('There are currently no submitted documents.'));
 1925:        return;
 1926:     }
 1927: 
 1928:     my $all_students = 
 1929: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1930: 
 1931:     my $parts =
 1932: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1933: 
 1934:     my $identifier = &Apache::loncommon::get_cgi_id();
 1935:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1936:                              'cgi.'.$identifier.'.symb' => $symb,
 1937:                              'cgi.'.$identifier.'.parts' => $parts,});
 1938:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1939: 	      &mt('Download All Submitted Documents').'</a>');
 1940:     return;
 1941: }
 1942: 
 1943: sub submit_download_link {
 1944:     my ($request,$symb) = @_;
 1945:     if (!$symb) { return ''; }
 1946: #FIXME: Figure out which type of problem this is and provide appropriate download
 1947:     &download_all_link($request,$symb);
 1948: }
 1949: 
 1950: sub build_section_inputs {
 1951:     my $section_inputs;
 1952:     if ($env{'form.section'} eq '') {
 1953:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1954:     } else {
 1955:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1956:         foreach my $section (@sections) {
 1957:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1958:         }
 1959:     }
 1960:     return $section_inputs;
 1961: }
 1962: 
 1963: # --------------------------- show submissions of a student, option to grade 
 1964: sub submission {
 1965:     my ($request,$counter,$total,$symb) = @_;
 1966:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1967:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1968:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1969:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1970: 
 1971:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1972:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1973: 
 1974:     if (!&canview($usec)) {
 1975:         $request->print(
 1976:             '<span class="LC_warning">'.
 1977:             &mt('Unable to view requested student.').
 1978:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 1979:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 1980:             '</span>');
 1981: 	return;
 1982:     }
 1983: 
 1984:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1985:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1986:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1987:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1988:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1989: 	'" src="'.$request->dir_config('lonIconsURL').
 1990: 	'/check.gif" height="16" border="0" />';
 1991: 
 1992:     # header info
 1993:     if ($counter == 0) {
 1994: 	&sub_page_js($request);
 1995: 	&sub_page_kw_js($request);
 1996: 
 1997: 	# option to display problem, only once else it cause problems 
 1998:         # with the form later since the problem has a form.
 1999: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2000: 	    my $mode;
 2001: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2002: 		$mode='both';
 2003: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2004: 		$mode='text';
 2005: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2006: 		$mode='answer';
 2007: 	    }
 2008: 	    &Apache::lonxml::clear_problem_counter();
 2009: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2010: 	}
 2011: 
 2012: 	# kwclr is the only variable that is guaranteed not to be blank 
 2013:         # if this subroutine has been called once.
 2014: 	my %keyhash = ();
 2015: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2016:         if (1) {
 2017: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2018: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2019: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2020: 
 2021: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2022: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2023: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2024: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2025: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2026: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2027: 		$keyhash{$symb.'_subject'} : $probtitle;
 2028: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2029: 	}
 2030: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2031: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2032: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2033: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2034: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2035: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2036: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2037: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2038: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2039: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2040: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2041: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2042: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2043: 			&build_section_inputs().
 2044: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2045: 			'<input type="hidden" name="NCT"'.
 2046: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2047: #	if ($env{'form.handgrade'} eq 'yes') {
 2048:         if (1) {
 2049: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2050: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2051: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2052: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2053: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2054: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2055: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2056: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2057: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2058: 	    }
 2059: 	}
 2060: 	
 2061: 	my ($cts,$prnmsg) = (1,'');
 2062: 	while ($cts <= $env{'form.savemsgN'}) {
 2063: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2064: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2065: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2066: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2067: 		'" />'."\n".
 2068: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2069: 	    $cts++;
 2070: 	}
 2071: 	$request->print($prnmsg);
 2072: 
 2073: #	if ($env{'form.handgrade'} eq 'yes') {
 2074:         if (1) {
 2075: 
 2076:             my %lt = &Apache::lonlocal::texthash(
 2077:                           keyh => 'Keyword Highlighting for Essays',
 2078:                           keyw => 'Keyword Options',
 2079:                           list => 'List',
 2080:                           past => 'Paste Selection to List',
 2081:                           high => 'Highlight Attribute',
 2082:                      );    
 2083: #
 2084: # Print out the keyword options line
 2085: #
 2086: 	    $request->print(
 2087:                 '<div class="LC_columnSection">'
 2088:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2089:                .&Apache::lonhtmlcommon::funclist_from_array(
 2090:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2091:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2092:  class="page">'.$lt{'past'}.'</a>',
 2093:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2094:                     {legend => $lt{'keyw'}})
 2095:                .'</fieldset></div>'
 2096:             );
 2097: 
 2098: #
 2099: # Load the other essays for similarity check
 2100: #
 2101:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2102: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2103: 	    $apath=&escape($apath);
 2104: 	    $apath=~s/\W/\_/gs;
 2105:             &init_old_essays($symb,$apath,$adom,$aname);
 2106:         }
 2107:     }
 2108: 
 2109: # This is where output for one specific student would start
 2110:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2111:     $request->print(
 2112:         "\n\n"
 2113:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2114:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2115:        ."\n"
 2116:     );
 2117: 
 2118:     # Show additional functions if allowed
 2119:     if ($perm{'vgr'}) {
 2120:         $request->print(
 2121:             &Apache::loncommon::track_student_link(
 2122:                 'View recent activity',
 2123:                 $uname,$udom,'check')
 2124:            .' '
 2125:         );
 2126:     }
 2127:     if ($perm{'opa'}) {
 2128:         $request->print(
 2129:             &Apache::loncommon::pprmlink(
 2130:                 &mt('Set/Change parameters'),
 2131:                 $uname,$udom,$symb,'check'));
 2132:     }
 2133: 
 2134:     # Show Problem
 2135:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2136: 	my $mode;
 2137: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2138: 	    $mode='both';
 2139: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2140: 	    $mode='text';
 2141: 	} elsif ($env{'form.vAns'} eq 'all') {
 2142: 	    $mode='answer';
 2143: 	}
 2144: 	&Apache::lonxml::clear_problem_counter();
 2145: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2146:     }
 2147: 
 2148:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2149:     my $res_error;
 2150:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2151:     if ($res_error) {
 2152:         $request->print(&navmap_errormsg());
 2153:         return;
 2154:     }
 2155: 
 2156:     # Display student info
 2157:     $request->print(($counter == 0 ? '' : '<br />'));
 2158: 
 2159:     my $result='<div class="LC_Box">'
 2160:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2161:     $result.='<input type="hidden" name="name'.$counter.
 2162:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2163: #    if ($env{'form.handgrade'} eq 'no') {
 2164:     if (1) {
 2165:         $result.='<p class="LC_info">'
 2166:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2167:                 ."</p>\n";
 2168:     }
 2169: 
 2170:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2171:     my $fullname;
 2172:     my $col_fullnames = [];
 2173: #    if ($env{'form.handgrade'} eq 'yes') {
 2174:     if (1) {
 2175: 	(my $sub_result,$fullname,$col_fullnames)=
 2176: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2177: 				 $counter);
 2178: 	$result.=$sub_result;
 2179:     }
 2180:     $request->print($result."\n");
 2181:     
 2182:     # print student answer/submission
 2183:     # Options are (1) Handgraded submission only
 2184:     #             (2) Last submission, includes submission that is not handgraded 
 2185:     #                  (for multi-response type part)
 2186:     #             (3) Last submission plus the parts info
 2187:     #             (4) The whole record for this student
 2188:     
 2189:     my ($string,$timestamp)= &get_last_submission(\%record);
 2190: 	
 2191:     my $lastsubonly;
 2192: 
 2193:     if ($$timestamp eq '') {
 2194:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2195:     } else {
 2196:         $lastsubonly =
 2197:             '<div class="LC_grade_submissions_body">'
 2198:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2199: 
 2200: 	my %seenparts;
 2201: 	my @part_response_id = &flatten_responseType($responseType);
 2202: 	foreach my $part (@part_response_id) {
 2203: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2204: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2205: 
 2206: 	    my ($partid,$respid) = @{ $part };
 2207: 	    my $display_part=&get_display_part($partid,$symb);
 2208: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2209: 		if (exists($seenparts{$partid})) { next; }
 2210: 		$seenparts{$partid}=1;
 2211:                 $request->print(
 2212:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2213:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2214:                                '<a href="javascript:viewSubmitter(\''.
 2215:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2216:                                '\');" target="_self">'.
 2217:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2218:                     '<br />');
 2219: 		next;
 2220: 		}
 2221: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2222: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2223:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2224:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2225:                     ' <span class="LC_internal_info">'.
 2226:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2227:                     '</span>&nbsp; &nbsp;'.
 2228: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2229: 		next;
 2230: 	    }
 2231: 	    foreach my $submission (@$string) {
 2232: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2233: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2234: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2235: 		# Similarity check
 2236:                 my $similar='';
 2237:                 my ($type,$trial,$rndseed);
 2238:                 if ($hide eq 'rand') {
 2239:                     $type = 'randomizetry';
 2240:                     $trial = $record{"resource.$partid.tries"};
 2241:                     $rndseed = $record{"resource.$partid.rndseed"};
 2242:                 }
 2243: 	        if ($env{'form.checkPlag'}) {
 2244:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2245: 		        &most_similar($uname,$udom,$symb,$subval);
 2246: 		    if ($osim) {
 2247: 			$osim=int($osim*100.0);
 2248: 			my %old_course_desc = 
 2249: 			    &Apache::lonnet::coursedescription($ocrsid,
 2250: 							{'one_time' => 1});
 2251: 
 2252:                         if ($hide eq 'anon') {
 2253:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2254:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2255:                         } else {
 2256: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2257: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2258: 				    $osim,
 2259: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2260: 				        $old_course_desc{'description'},
 2261: 				        $old_course_desc{'num'},
 2262: 				        $old_course_desc{'domain'}).
 2263: 				    '</span></h3><blockquote><i>'.
 2264: 				    &keywords_highlight($oessay).
 2265: 				    '</i></blockquote><hr />';
 2266:                         }
 2267: 	            }
 2268: 		}
 2269: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2270:                                      undef,$type,$trial,$rndseed);
 2271:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2272: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2273: 		    my $display_part=&get_display_part($partid,$symb);
 2274:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2275:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2276:                         ' <span class="LC_internal_info">'.
 2277:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2278:                         '</span>&nbsp; &nbsp;';
 2279: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2280:                         
 2281: 		    if (@$files) {
 2282:                         if ($hide eq 'anon') {
 2283:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2284:                         } else {
 2285:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2286:                                         .'<br /><span class="LC_warning">';
 2287:                             if(@$files == 1) {
 2288:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2289:                             } else {
 2290:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2291:                             }
 2292:                             $lastsubonly .= '</span>';                         
 2293:                             foreach my $file (@$files) {
 2294:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2295:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2296:                             }
 2297:                         }
 2298: 			$lastsubonly.='<br />';
 2299:                     }
 2300:                     if ($hide eq 'anon') {
 2301:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2302:                     } else {
 2303:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2304:                         if ($draft) {
 2305:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2306:                         }
 2307:                         $subval =
 2308: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2309: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2310:                         if ($responsetype eq 'essay') {
 2311:                             $subval =~ s{\n}{<br />}g;
 2312:                         }
 2313:                         $lastsubonly.=$subval."\n";
 2314:                     }
 2315: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2316: 		    $lastsubonly.='</div>';
 2317: 		}
 2318:             }
 2319: 	}
 2320: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2321:     }
 2322:     $request->print($lastsubonly);
 2323:     if ($env{'form.lastSub'} eq 'datesub') {
 2324:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2325: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2326:   
 2327:     } 
 2328:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2329:         my $identifier = (&canmodify($usec)? $counter : '');
 2330:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2331: 								 $env{'request.course.id'},
 2332: 								 $last,'.submission',
 2333: 								 'Apache::grades::keywords_highlight',
 2334:                                                                  $usec,$identifier));
 2335:     }
 2336:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2337: 	.$udom.'" />'."\n");
 2338:     # return if view submission with no grading option
 2339:     if (!&canmodify($usec)) {
 2340: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2341: 	return;
 2342:     } else {
 2343: 	$request->print('</div>'."\n");
 2344:     }
 2345: 
 2346:     # essay grading message center
 2347: #    if ($env{'form.handgrade'} eq 'yes') {
 2348:     if (1) {
 2349: 	my $result='<div class="LC_grade_message_center">';
 2350:     
 2351: 	$result.='<div class="LC_grade_message_center_header">'.
 2352: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2353: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2354: 	my $msgfor = $givenn.' '.$lastname;
 2355: 	if (scalar(@$col_fullnames) > 0) {
 2356: 	    my $lastone = pop(@$col_fullnames);
 2357: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2358: 	}
 2359: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2360: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2361: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2362: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2363: 	    ',\''.$msgfor.'\');" target="_self">'.
 2364: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2365: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2366: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2367: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2368: 	    '<br />&nbsp;('.
 2369: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2370: 	$result.='</div></div>';
 2371: 	$request->print($result);
 2372:     }
 2373: 
 2374:     my %seen = ();
 2375:     my @partlist;
 2376:     my @gradePartRespid;
 2377:     my @part_response_id = &flatten_responseType($responseType);
 2378:     $request->print(
 2379:         '<div class="LC_Box">'
 2380:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2381:     );
 2382:     $request->print(&gradeBox_start());
 2383:     foreach my $part_response_id (@part_response_id) {
 2384:     	my ($partid,$respid) = @{ $part_response_id };
 2385: 	my $part_resp = join('_',@{ $part_response_id });
 2386: 	next if ($seen{$partid} > 0);
 2387: 	$seen{$partid}++;
 2388: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2389: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2390: 	push(@partlist,$partid);
 2391: 	push(@gradePartRespid,$partid.'.'.$respid);
 2392: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2393:     }
 2394:     $request->print(&gradeBox_end()); # </div>
 2395:     $request->print('</div>');
 2396: 
 2397:     $request->print('<div class="LC_grade_info_links">');
 2398:     $request->print('</div>');
 2399: 
 2400:     $result='<input type="hidden" name="partlist'.$counter.
 2401: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2402:     $result.='<input type="hidden" name="gradePartRespid'.
 2403: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2404:     my $ctr = 0;
 2405:     while ($ctr < scalar(@partlist)) {
 2406: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2407: 	    $partlist[$ctr].'" />'."\n";
 2408: 	$ctr++;
 2409:     }
 2410:     $request->print($result.''."\n");
 2411: 
 2412: # Done with printing info for one student
 2413: 
 2414:     $request->print('</div>');#LC_grade_show_user
 2415: 
 2416: 
 2417:     # print end of form
 2418:     if ($counter == $total) {
 2419:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2420: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2421: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2422: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2423: 	my $ntstu ='<select name="NTSTU">'.
 2424: 	    '<option>1</option><option>2</option>'.
 2425: 	    '<option>3</option><option>5</option>'.
 2426: 	    '<option>7</option><option>10</option></select>'."\n";
 2427: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2428: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2429:         $endform.=&mt('[_1]student(s)',$ntstu);
 2430: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2431: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2432: 	    '<input type="button" value="'.&mt('Next').'" '.
 2433: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2434:         $endform.='<span class="LC_warning">'.
 2435:                   &mt('(Next and Previous (student) do not save the scores.)').
 2436:                   '</span>'."\n" ;
 2437:         $endform.="<input type='hidden' value='".&get_increment().
 2438:             "' name='increment' />";
 2439: 	$endform.='</td></tr></table></form>';
 2440: 	$request->print($endform);
 2441:     }
 2442:     return '';
 2443: }
 2444: 
 2445: sub check_collaborators {
 2446:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2447:     my ($result,@col_fullnames);
 2448:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2449:     foreach my $part (keys(%$handgrade)) {
 2450: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2451: 					'.maxcollaborators',
 2452: 					$symb,$udom,$uname);
 2453: 	next if ($ncol <= 0);
 2454: 	$part =~ s/\_/\./g;
 2455: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2456: 	my (@good_collaborators, @bad_collaborators);
 2457: 	foreach my $possible_collaborator
 2458: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2459: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2460: 	    next if ($possible_collaborator eq '');
 2461: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2462: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2463: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2464: 	    # Doing this grep allows 'fuzzy' specification
 2465: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2466: 			       keys(%$classlist));
 2467: 	    if (! scalar(@matches)) {
 2468: 		push(@bad_collaborators, $possible_collaborator);
 2469: 	    } else {
 2470: 		push(@good_collaborators, @matches);
 2471: 	    }
 2472: 	}
 2473: 	if (scalar(@good_collaborators) != 0) {
 2474: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2475: 	    foreach my $name (@good_collaborators) {
 2476: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2477: 		push(@col_fullnames, $givenn.' '.$lastname);
 2478: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2479: 	    }
 2480: 	    $result.='</ol><br />'."\n";
 2481: 	    my ($part)=split(/\./,$part);
 2482: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2483: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2484: 		"\n";
 2485: 	}
 2486: 	if (scalar(@bad_collaborators) > 0) {
 2487: 	    $result.='<div class="LC_warning">';
 2488: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2489: 	    $result .= '</div>';
 2490: 	}         
 2491: 	if (scalar(@bad_collaborators > $ncol)) {
 2492: 	    $result .= '<div class="LC_warning">';
 2493: 	    $result .= &mt('This student has submitted too many '.
 2494: 		'collaborators.  Maximum is [_1].',$ncol);
 2495: 	    $result .= '</div>';
 2496: 	}
 2497:     }
 2498:     return ($result,$fullname,\@col_fullnames);
 2499: }
 2500: 
 2501: #--- Retrieve the last submission for all the parts
 2502: sub get_last_submission {
 2503:     my ($returnhash)=@_;
 2504:     my (@string,$timestamp,%lasthidden);
 2505:     if ($$returnhash{'version'}) {
 2506: 	my %lasthash=();
 2507: 	my ($version);
 2508: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2509: 	    foreach my $key (sort(split(/\:/,
 2510: 					$$returnhash{$version.':keys'}))) {
 2511: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2512: 		$timestamp = 
 2513: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2514: 	    }
 2515: 	}
 2516:         my (%typeparts,%randombytry);
 2517:         my $showsurv = 
 2518:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2519:         foreach my $key (sort(keys(%lasthash))) {
 2520:             if ($key =~ /\.type$/) {
 2521:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2522:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2523:                     ($lasthash{$key} eq 'randomizetry')) {
 2524:                     my ($ign,@parts) = split(/\./,$key);
 2525:                     pop(@parts);
 2526:                     my $id = join('.',@parts);
 2527:                     if ($lasthash{$key} eq 'randomizetry') {
 2528:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2529:                     } else {
 2530:                         unless ($showsurv) {
 2531:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2532:                         }
 2533:                     }
 2534:                     delete($lasthash{$key});
 2535:                 }
 2536:             }
 2537:         }
 2538:         my @hidden = keys(%typeparts);
 2539:         my @randomize = keys(%randombytry);
 2540: 	foreach my $key (keys(%lasthash)) {
 2541: 	    next if ($key !~ /\.submission$/);
 2542:             my $hide;
 2543:             if (@hidden) {
 2544:                 foreach my $id (@hidden) {
 2545:                     if ($key =~ /^\Q$id\E/) {
 2546:                         $hide = 'anon';
 2547:                         last;
 2548:                     }
 2549:                 }
 2550:             }
 2551:             unless ($hide) {
 2552:                 if (@randomize) {
 2553:                     foreach my $id (@randomize) {
 2554:                         if ($key =~ /^\Q$id\E/) {
 2555:                             $hide = 'rand';
 2556:                             last;
 2557:                         }
 2558:                     }
 2559:                 }
 2560:             }
 2561: 	    my ($partid,$foo) = split(/submission$/,$key);
 2562: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2563:             push(@string, join(':', $key, $hide, $draft, (
 2564:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2565:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2566: 	}
 2567:     }
 2568:     if (!@string) {
 2569: 	$string[0] =
 2570: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2571:     }
 2572:     return (\@string,\$timestamp);
 2573: }
 2574: 
 2575: #--- High light keywords, with style choosen by user.
 2576: sub keywords_highlight {
 2577:     my $string    = shift;
 2578:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2579:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2580:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2581:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2582:     foreach my $keyword (@keylist) {
 2583: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2584:     }
 2585:     return $string;
 2586: }
 2587: 
 2588: # For Tasks provide a mechanism to display previous version for one specific student
 2589: 
 2590: sub show_previous_task_version {
 2591:     my ($request,$symb) = @_;
 2592:     if ($symb eq '') {
 2593:         $request->print(
 2594:             '<span class="LC_error">'.
 2595:             &mt('Unable to handle ambiguous references.').
 2596:             '</span>');
 2597:         return '';
 2598:     }
 2599:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2600:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2601:     if (!&canview($usec)) {
 2602:         $request->print(
 2603:             '<span class="LC_warning">'.
 2604:             &mt('Unable to view previous version for requested student.').
 2605:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2606:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2607:             '</span>');
 2608:         return;
 2609:     }
 2610:     my $mode = 'both';
 2611:     my $isTask = ($symb =~/\.task$/);
 2612:     if ($isTask) {
 2613:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2614:             if ($env{'form.fullname'} eq '') {
 2615:                 $env{'form.fullname'} =
 2616:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2617:             }
 2618:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2619:             $request->print("\n\n".
 2620:                             '<div class="LC_grade_show_user">'.
 2621:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2622:                             '</h2>'."\n");
 2623:             &Apache::lonxml::clear_problem_counter();
 2624:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2625:                             {'previousversion' => $env{'form.previousversion'} }));
 2626:             $request->print("\n</div>");
 2627:         }
 2628:     }
 2629:     return;
 2630: }
 2631: 
 2632: sub choose_task_version_form {
 2633:     my ($symb,$uname,$udom,$nomenu) = @_;
 2634:     my $isTask = ($symb =~/\.task$/);
 2635:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2636:     if ($isTask) {
 2637:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2638:                                               $udom,$uname);
 2639:         if (($record{'resource.0.version'} eq '') ||
 2640:             ($record{'resource.0.version'} < 2)) {
 2641:             return ($record{'resource.0.version'},
 2642:                     $record{'resource.0.version'},$result,$js);
 2643:         } else {
 2644:             $current = $record{'resource.0.version'};
 2645:         }
 2646:         if ($env{'form.previousversion'}) {
 2647:             $displayed = $env{'form.previousversion'};
 2648:             $rowtitle = &mt('Choose another version:')
 2649:         } else {
 2650:             $displayed = $current;
 2651:             $rowtitle = &mt('Show earlier version:');
 2652:         }
 2653:         $result = '<div class="LC_left_float">';
 2654:         my $list;
 2655:         my $numversions = 0;
 2656:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2657:             if ($i == $current) {
 2658:                 if (!$env{'form.previousversion'} || $nomenu) {
 2659:                     next;
 2660:                 } else {
 2661:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2662:                     $numversions ++;
 2663:                 }
 2664:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2665:                 unless ($i == $env{'form.previousversion'}) {
 2666:                     $numversions ++;
 2667:                 }
 2668:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2669:             }
 2670:         }
 2671:         if ($numversions) {
 2672:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2673:             $result .=
 2674:                 '<form name="getprev" method="post" action=""'.
 2675:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2676:                 &Apache::loncommon::start_data_table().
 2677:                 &Apache::loncommon::start_data_table_row().
 2678:                 '<th align="left">'.$rowtitle.'</th>'.
 2679:                 '<td><select name="version">'.
 2680:                 '<option>'.&mt('Select').'</option>'.
 2681:                 $list.
 2682:                 '</select></td>'.
 2683:                 &Apache::loncommon::end_data_table_row();
 2684:             unless ($nomenu) {
 2685:                 $result .= &Apache::loncommon::start_data_table_row().
 2686:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2687:                 '<td><span class="LC_nobreak">'.
 2688:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2689:                 &mt('Yes').'</label>'.
 2690:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2691:                 '</span></td>'.
 2692:                 &Apache::loncommon::end_data_table_row();
 2693:             }
 2694:             $result .=
 2695:                 &Apache::loncommon::start_data_table_row().
 2696:                 '<th align="left">&nbsp;</th>'.
 2697:                 '<td>'.
 2698:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2699:                 '</td>'.
 2700:                 &Apache::loncommon::end_data_table_row().
 2701:                 &Apache::loncommon::end_data_table().
 2702:                 '</form>';
 2703:             $js = &previous_display_javascript($nomenu,$current);
 2704:         } elsif ($displayed && $nomenu) {
 2705:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2706:         } else {
 2707:             $result .= &mt('No previous versions to show for this student');
 2708:         }
 2709:         $result .= '</div>';
 2710:     }
 2711:     return ($current,$displayed,$result,$js);
 2712: }
 2713: 
 2714: sub previous_display_javascript {
 2715:     my ($nomenu,$current) = @_;
 2716:     my $js = <<"JSONE";
 2717: <script type="text/javascript">
 2718: // <![CDATA[
 2719: function previousVersion(uname,udom,symb) {
 2720:     var current = '$current';
 2721:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2722:     var prevstr = new RegExp("^\\\\d+\$");
 2723:     if (!prevstr.test(version)) {
 2724:         return false;
 2725:     }
 2726:     var url = '';
 2727:     if (version == current) {
 2728:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2729:     } else {
 2730:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2731:     }
 2732: JSONE
 2733:     if ($nomenu) {
 2734:         $js .= <<"JSTWO";
 2735:     document.location.href = url;
 2736: JSTWO
 2737:     } else {
 2738:         $js .= <<"JSTHREE";
 2739:     var newwin = 0;
 2740:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2741:         if (document.getprev.prevwin[i].checked == true) {
 2742:             newwin = document.getprev.prevwin[i].value;
 2743:         }
 2744:     }
 2745:     if (newwin == 1) {
 2746:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2747:         url = url+'&inhibitmenu=yes';
 2748:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2749:             previousWin = window.open(url,'',options,1);
 2750:         } else {
 2751:             previousWin.location.href = url;
 2752:         }
 2753:         previousWin.focus();
 2754:         return false;
 2755:     } else {
 2756:         document.location.href = url;
 2757:         return false;
 2758:     }
 2759: JSTHREE
 2760:     }
 2761:     $js .= <<"ENDJS";
 2762:     return false;
 2763: }
 2764: // ]]>
 2765: </script>
 2766: ENDJS
 2767: 
 2768: }
 2769: 
 2770: #--- Called from submission routine
 2771: sub processHandGrade {
 2772:     my ($request,$symb) = @_;
 2773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2774:     my $button = $env{'form.gradeOpt'};
 2775:     my $ngrade = $env{'form.NCT'};
 2776:     my $ntstu  = $env{'form.NTSTU'};
 2777:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2778:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2779: 
 2780:     if ($button eq 'Save & Next') {
 2781: 	my $ctr = 0;
 2782: 	while ($ctr < $ngrade) {
 2783: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2784: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2785:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2786: 	    if ($errorflag eq 'no_score') {
 2787: 		$ctr++;
 2788: 		next;
 2789: 	    }
 2790: 	    if ($errorflag eq 'not_allowed') {
 2791: 		$request->print(
 2792:                     '<span class="LC_error">'
 2793:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2794:                    .'</span>');
 2795: 		$ctr++;
 2796: 		next;
 2797: 	    }
 2798:             if ($numhidden) {
 2799:                 $request->print(
 2800:                     '<span class="LC_info">'
 2801:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2802:                    .'</span><br />');
 2803:             }
 2804: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2805: 	    my ($subject,$message,$msgstatus) = ('','','');
 2806: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2807:             my ($feedurl,$showsymb) =
 2808: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2809: 	    my $messagetail;
 2810: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2811: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2812: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2813: 		$subject.=' ['.$restitle.']';
 2814: 		my (@msgnum) = split(/,/,$includemsg);
 2815: 		foreach (@msgnum) {
 2816: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2817: 		}
 2818: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2819: 		if ($env{'form.withgrades'.$ctr}) {
 2820: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2821: 		    $messagetail = " for <a href=\"".
 2822: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2823: 		}
 2824: 		$msgstatus = 
 2825:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2826: 						     $message.$messagetail,
 2827:                                                      undef,$feedurl,undef,
 2828:                                                      undef,undef,$showsymb,
 2829:                                                      $restitle);
 2830: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2831: 				$msgstatus.'<br />');
 2832: 	    }
 2833: 	    if ($env{'form.collaborator'.$ctr}) {
 2834: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2835: 		foreach my $collabstr (@collabstrs) {
 2836: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2837: 		    foreach my $collaborator (@collaborators) {
 2838: 			my ($errorflag,$pts,$wgt) = 
 2839: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2840: 					   $env{'form.unamedom'.$ctr},$part);
 2841: 			if ($errorflag eq 'not_allowed') {
 2842: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2843: 			    next;
 2844: 			} elsif ($message ne '') {
 2845: 			    my ($baseurl,$showsymb) = 
 2846: 				&get_feedurl_and_symb($symb,$collaborator,
 2847: 						      $udom);
 2848: 			    if ($env{'form.withgrades'.$ctr}) {
 2849: 				$messagetail = " for <a href=\"".
 2850:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2851: 			    }
 2852: 			    $msgstatus = 
 2853: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2854: 			}
 2855: 		    }
 2856: 		}
 2857: 	    }
 2858: 	    $ctr++;
 2859: 	}
 2860:     }
 2861: 
 2862: #    if ($env{'form.handgrade'} eq 'yes') {
 2863:     if (1) {
 2864: 	# Keywords sorted in alphabatical order
 2865: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2866: 	my %keyhash = ();
 2867: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2868: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2869: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2870: 	$env{'form.keywords'} = join(' ',@keywords);
 2871: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2872: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2873: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2874: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2875: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2876: 
 2877: 	# message center - Order of message gets changed. Blank line is eliminated.
 2878: 	# New messages are saved in env for the next student.
 2879: 	# All messages are saved in nohist_handgrade.db
 2880: 	my ($ctr,$idx) = (1,1);
 2881: 	while ($ctr <= $env{'form.savemsgN'}) {
 2882: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2883: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2884: 		$idx++;
 2885: 	    }
 2886: 	    $ctr++;
 2887: 	}
 2888: 	$ctr = 0;
 2889: 	while ($ctr < $ngrade) {
 2890: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2891: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2892: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2893: 		$idx++;
 2894: 	    }
 2895: 	    $ctr++;
 2896: 	}
 2897: 	$env{'form.savemsgN'} = --$idx;
 2898: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2899: 	my $putresult = &Apache::lonnet::put
 2900: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2901:     }
 2902:     # Called by Save & Refresh from Highlight Attribute Window
 2903:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2904:     if ($env{'form.refresh'} eq 'on') {
 2905: 	my ($ctr,$total) = (0,0);
 2906: 	while ($ctr < $ngrade) {
 2907: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2908: 	    $ctr++;
 2909: 	}
 2910: 	$env{'form.NTSTU'}=$ngrade;
 2911: 	$ctr = 0;
 2912: 	while ($ctr < $total) {
 2913: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2914: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2915: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2916: 	    &submission($request,$ctr,$total-1,$symb);
 2917: 	    $ctr++;
 2918: 	}
 2919: 	return '';
 2920:     }
 2921: 
 2922:     # Get the next/previous one or group of students
 2923:     my $firststu = $env{'form.unamedom0'};
 2924:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2925:     my $ctr = 2;
 2926:     while ($laststu eq '') {
 2927: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2928: 	$ctr++;
 2929: 	$laststu = $firststu if ($ctr > $ngrade);
 2930:     }
 2931: 
 2932:     my (@parsedlist,@nextlist);
 2933:     my ($nextflg) = 0;
 2934:     foreach my $item (sort 
 2935: 	     {
 2936: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2937: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2938: 		 }
 2939: 		 return $a cmp $b;
 2940: 	     } (keys(%$fullname))) {
 2941: # FIXME: this is fishy, looks like the button label
 2942: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2943: 	    push(@parsedlist,$item);
 2944: 	}
 2945: 	$nextflg = 1 if ($item eq $laststu);
 2946: 	if ($button eq 'Previous') {
 2947: 	    last if ($item eq $firststu);
 2948: 	    push(@parsedlist,$item);
 2949: 	}
 2950:     }
 2951:     $ctr = 0;
 2952: # FIXME: this is fishy, looks like the button label
 2953:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2954:     my $res_error;
 2955:     my ($partlist) = &response_type($symb,\$res_error);
 2956:     if ($res_error) {
 2957:         $request->print(&navmap_errormsg());
 2958:         return;
 2959:     }
 2960:     foreach my $student (@parsedlist) {
 2961: 	my $submitonly=$env{'form.submitonly'};
 2962: 	my ($uname,$udom) = split(/:/,$student);
 2963: 	
 2964: 	if ($submitonly eq 'queued') {
 2965: 	    my %queue_status = 
 2966: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2967: 							$udom,$uname);
 2968: 	    next if (!defined($queue_status{'gradingqueue'}));
 2969: 	}
 2970: 
 2971: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2972: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2973: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2974: 	    my $submitted = 0;
 2975: 	    my $ungraded = 0;
 2976: 	    my $incorrect = 0;
 2977: 	    foreach my $item (keys(%status)) {
 2978: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2979: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2980: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2981: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2982: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2983: 		    $submitted = 0;
 2984: 		}
 2985: 	    }
 2986: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2987: 				     $submitonly eq 'incorrect' ||
 2988: 				     $submitonly eq 'graded'));
 2989: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2990: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2991: 	}
 2992: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2993: 	last if ($ctr == $ntstu);
 2994: 	$ctr++;
 2995:     }
 2996: 
 2997:     $ctr = 0;
 2998:     my $total = scalar(@nextlist)-1;
 2999: 
 3000:     foreach (sort(@nextlist)) {
 3001: 	my ($uname,$udom,$submitter) = split(/:/);
 3002: 	$env{'form.student'}  = $uname;
 3003: 	$env{'form.userdom'}  = $udom;
 3004: 	$env{'form.fullname'} = $$fullname{$_};
 3005: 	&submission($request,$ctr,$total,$symb);
 3006: 	$ctr++;
 3007:     }
 3008:     if ($total < 0) {
 3009: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3010: 	$request->print($the_end);
 3011:     }
 3012:     return '';
 3013: }
 3014: 
 3015: #---- Save the score and award for each student, if changed
 3016: sub saveHandGrade {
 3017:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3018:     my @version_parts;
 3019:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3020: 					   $env{'request.course.id'});
 3021:     if (!&canmodify($usec)) { return('not_allowed'); }
 3022:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3023:     my @parts_graded;
 3024:     my %newrecord  = ();
 3025:     my ($pts,$wgt,$totchg) = ('','',0);
 3026:     my %aggregate = ();
 3027:     my $aggregateflag = 0;
 3028:     if ($env{'form.HIDE'.$newflg}) {
 3029:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3030:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3031:         $totchg += $numchgs;
 3032:     }
 3033:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3034:     foreach my $new_part (@parts) {
 3035: 	#collaborator ($submi may vary for different parts
 3036: 	if ($submitter && $new_part ne $part) { next; }
 3037: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3038: 	if ($dropMenu eq 'excused') {
 3039: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3040: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3041: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3042: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3043: 		}
 3044: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3045: 	    }
 3046: 	} elsif ($dropMenu eq 'reset status'
 3047: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3048: 	    foreach my $key (keys(%record)) {
 3049: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3050: 	    }
 3051: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3052: 		"$env{'user.name'}:$env{'user.domain'}";
 3053:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3054: 
 3055:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3056: 					       [$new_part]);
 3057:             my $aggtries =$totaltries;
 3058:             if ($last_resets{$new_part}) {
 3059:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3060: 					   $new_part);
 3061:             }
 3062: 
 3063:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3064:             if ($aggtries > 0) {
 3065:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3066:                 $aggregateflag = 1;
 3067:             }
 3068: 	} elsif ($dropMenu eq '') {
 3069: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3070: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3071: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3072: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3073: 		next;
 3074: 	    }
 3075: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3076: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3077: 	    my $partial= $pts/$wgt;
 3078: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3079: 		#do not update score for part if not changed.
 3080:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3081: 		next;
 3082: 	    } else {
 3083: 	        push(@parts_graded,$new_part);
 3084: 	    }
 3085: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3086: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3087: 	    }
 3088: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3089: 	    if ($partial == 0) {
 3090: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3091: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3092: 		}
 3093: 	    } else {
 3094: 		if ($record{$reckey} ne 'correct_by_override') {
 3095: 		    $newrecord{$reckey} = 'correct_by_override';
 3096: 		}
 3097: 	    }	    
 3098: 	    if ($submitter && 
 3099: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3100: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3101: 	    }
 3102: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3103: 		"$env{'user.name'}:$env{'user.domain'}";
 3104: 	}
 3105: 	# unless problem has been graded, set flag to version the submitted files
 3106: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3107: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3108: 	        $dropMenu eq 'reset status')
 3109: 	   {
 3110: 	    push(@version_parts,$new_part);
 3111: 	}
 3112:     }
 3113:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3114:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3115: 
 3116:     if (%newrecord) {
 3117:         if (@version_parts) {
 3118:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3119:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3120: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3121: 	    foreach my $new_part (@version_parts) {
 3122: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3123: 				$new_part,\%newrecord);
 3124: 	    }
 3125:         }
 3126: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3127: 				$env{'request.course.id'},$domain,$stuname);
 3128: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3129: 				     $cdom,$cnum,$domain,$stuname);
 3130:     }
 3131:     if ($aggregateflag) {
 3132:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3133: 			      $cdom,$cnum);
 3134:     }
 3135:     return ('',$pts,$wgt,$totchg);
 3136: }
 3137: 
 3138: sub makehidden {
 3139:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3140:     return unless (ref($record) eq 'HASH');
 3141:     my %modified;
 3142:     my $numchanged = 0;
 3143:     if (exists($record->{$version.':keys'})) {
 3144:         my $partsregexp = $parts;
 3145:         $partsregexp =~ s/,/|/g;
 3146:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3147:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3148:                  my $item = $1;
 3149:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3150:                      $modified{$key} = $record->{$version.':'.$key};
 3151:                  }
 3152:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3153:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3154:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3155:                 $modified{$key} = $record->{$version.':'.$key};
 3156:             }
 3157:         }
 3158:         if (keys(%modified)) {
 3159:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3160:                                           $domain,$stuname,$tolog) eq 'ok') {
 3161:                 $numchanged ++;
 3162:             }
 3163:         }
 3164:     }
 3165:     return $numchanged;
 3166: }
 3167: 
 3168: sub check_and_remove_from_queue {
 3169:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3170:     my @ungraded_parts;
 3171:     foreach my $part (@{$parts}) {
 3172: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3173: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3174: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3175: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3176: 		) {
 3177: 	    push(@ungraded_parts, $part);
 3178: 	}
 3179:     }
 3180:     if ( !@ungraded_parts ) {
 3181: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3182: 					       $cnum,$domain,$stuname);
 3183:     }
 3184: }
 3185: 
 3186: sub handback_files {
 3187:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3188:     my $portfolio_root = '/userfiles/portfolio';
 3189:     my $res_error;
 3190:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3191:     if ($res_error) {
 3192:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3193:         return;
 3194:     }
 3195:     my @handedback;
 3196:     my $file_msg;
 3197:     my @part_response_id = &flatten_responseType($responseType);
 3198:     foreach my $part_response_id (@part_response_id) {
 3199:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3200: 	my $part_resp = join('_',@{ $part_response_id });
 3201:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3202:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3203:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3204:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3205:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3206:                     my ($directory,$answer_file) = 
 3207:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3208:                     my ($answer_name,$answer_ver,$answer_ext) =
 3209: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3210: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3211:                     my $getpropath = 1;
 3212:                     my ($dir_list,$listerror) = 
 3213:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3214:                                                  $domain,$stuname,$getpropath);
 3215: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3216:                     # fix filename
 3217:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3218:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3219:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3220:             	                                $save_file_name);
 3221:                     if ($result !~ m|^/uploaded/|) {
 3222:                         $request->print('<br /><span class="LC_error">'.
 3223:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3224:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3225:                                         '</span>');
 3226:                     } else {
 3227:                         # mark the file as read only
 3228:                         push(@handedback,$save_file_name);
 3229: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3230: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3231: 			}
 3232:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3233: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3234:                     }
 3235:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3236:                 }
 3237:             }
 3238:         }
 3239:     }
 3240:     if (@handedback > 0) {
 3241:         $request->print('<br />');
 3242:         my @what = ($symb,$env{'request.course.id'},'handback');
 3243:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3244:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3245:         my ($subject,$message);
 3246:         if (scalar(@handedback) == 1) {
 3247:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3248:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3249:         } else {
 3250:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3251:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3252:         }
 3253:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3254:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3255:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3256:         my ($feedurl,$showsymb) =
 3257:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3258:         my $restitle = &Apache::lonnet::gettitle($symb);
 3259:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3260:         my $msgstatus =
 3261:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3262:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3263:                  $restitle);
 3264:         if ($msgstatus) {
 3265:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3266:         }
 3267:     }
 3268:     return;
 3269: }
 3270: 
 3271: sub get_feedurl_and_symb {
 3272:     my ($symb,$uname,$udom) = @_;
 3273:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3274:     $url = &Apache::lonnet::clutter($url);
 3275:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3276: 					$symb,$udom,$uname);
 3277:     if ($encrypturl =~ /^yes$/i) {
 3278: 	&Apache::lonenc::encrypted(\$url,1);
 3279: 	&Apache::lonenc::encrypted(\$symb,1);
 3280:     }
 3281:     return ($url,$symb);
 3282: }
 3283: 
 3284: sub get_submitted_files {
 3285:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3286:     my @files;
 3287:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3288:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3289:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3290:     	    push(@files,$file_url.$file);
 3291:         }
 3292:     }
 3293:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3294:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3295:     }
 3296:     return (\@files);
 3297: }
 3298: 
 3299: # ----------- Provides number of tries since last reset.
 3300: sub get_num_tries {
 3301:     my ($record,$last_reset,$part) = @_;
 3302:     my $timestamp = '';
 3303:     my $num_tries = 0;
 3304:     if ($$record{'version'}) {
 3305:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3306:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3307:                 $timestamp = $$record{$version.':timestamp'};
 3308:                 if ($timestamp > $last_reset) {
 3309:                     $num_tries ++;
 3310:                 } else {
 3311:                     last;
 3312:                 }
 3313:             }
 3314:         }
 3315:     }
 3316:     return $num_tries;
 3317: }
 3318: 
 3319: # ----------- Determine decrements required in aggregate totals 
 3320: sub decrement_aggs {
 3321:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3322:     my %decrement = (
 3323:                         attempts => 0,
 3324:                         users => 0,
 3325:                         correct => 0
 3326:                     );
 3327:     $decrement{'attempts'} = $aggtries;
 3328:     if ($solvedstatus =~ /^correct/) {
 3329:         $decrement{'correct'} = 1;
 3330:     }
 3331:     if ($aggtries == $totaltries) {
 3332:         $decrement{'users'} = 1;
 3333:     }
 3334:     foreach my $type (keys(%decrement)) {
 3335:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3336:     }
 3337:     return;
 3338: }
 3339: 
 3340: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3341: sub get_last_resets {
 3342:     my ($symb,$courseid,$partids) =@_;
 3343:     my %last_resets;
 3344:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3345:     my $cname = $env{'course.'.$courseid.'.num'};
 3346:     my @keys;
 3347:     foreach my $part (@{$partids}) {
 3348: 	push(@keys,"$symb\0$part\0resettime");
 3349:     }
 3350:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3351: 				     $cdom,$cname);
 3352:     foreach my $part (@{$partids}) {
 3353: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3354:     }
 3355:     return %last_resets;
 3356: }
 3357: 
 3358: # ----------- Handles creating versions for portfolio files as answers
 3359: sub version_portfiles {
 3360:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3361:     my $version_parts = join('|',@$v_flag);
 3362:     my @returned_keys;
 3363:     my $parts = join('|', @$parts_graded);
 3364:     foreach my $key (keys(%$record)) {
 3365:         my $new_portfiles;
 3366:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3367:             my @versioned_portfiles;
 3368:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3369:             if (@portfiles) {
 3370:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3371:                                                       \@versioned_portfiles);
 3372:             }
 3373:             $$record{$key} = join(',',@versioned_portfiles);
 3374:             push(@returned_keys,$key);
 3375:         }
 3376:     } 
 3377:     return (@returned_keys);   
 3378: }
 3379: 
 3380: #--------------------------------------------------------------------------------------
 3381: #
 3382: #-------------------------- Next few routines handles grading by section or whole class
 3383: #
 3384: #--- Javascript to handle grading by section or whole class
 3385: sub viewgrades_js {
 3386:     my ($request) = shift;
 3387: 
 3388:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3389:     &js_escape(\$alertmsg);
 3390:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3391:    function writePoint(partid,weight,point) {
 3392: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3393: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3394: 	if (point == "textval") {
 3395: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3396: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3397: 		alert("$alertmsg"+parseFloat(point));
 3398: 		var resetbox = false;
 3399: 		for (var i=0; i<radioButton.length; i++) {
 3400: 		    if (radioButton[i].checked) {
 3401: 			textbox.value = i;
 3402: 			resetbox = true;
 3403: 		    }
 3404: 		}
 3405: 		if (!resetbox) {
 3406: 		    textbox.value = "";
 3407: 		}
 3408: 		return;
 3409: 	    }
 3410: 	    if (parseFloat(point) > parseFloat(weight)) {
 3411: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3412: 				   ") greater than the weight for the part. Accept?");
 3413: 		if (resp == false) {
 3414: 		    textbox.value = "";
 3415: 		    return;
 3416: 		}
 3417: 	    }
 3418: 	    for (var i=0; i<radioButton.length; i++) {
 3419: 		radioButton[i].checked=false;
 3420: 		if (parseFloat(point) == i) {
 3421: 		    radioButton[i].checked=true;
 3422: 		}
 3423: 	    }
 3424: 
 3425: 	} else {
 3426: 	    textbox.value = parseFloat(point);
 3427: 	}
 3428: 	for (i=0;i<document.classgrade.total.value;i++) {
 3429: 	    var user = document.classgrade["ctr"+i].value;
 3430: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3431: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3432: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3433: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3434: 	    if (saveval != "correct") {
 3435: 		scorename.value = point;
 3436: 		if (selname[0].selected != true) {
 3437: 		    selname[0].selected = true;
 3438: 		}
 3439: 	    }
 3440: 	}
 3441: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3442:     }
 3443: 
 3444:     function writeRadText(partid,weight) {
 3445: 	var selval   = document.classgrade["SELVAL_"+partid];
 3446: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3447:         var override = document.classgrade["FORCE_"+partid].checked;
 3448: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3449: 	if (selval[1].selected || selval[2].selected) {
 3450: 	    for (var i=0; i<radioButton.length; i++) {
 3451: 		radioButton[i].checked=false;
 3452: 
 3453: 	    }
 3454: 	    textbox.value = "";
 3455: 
 3456: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3457: 		var user = document.classgrade["ctr"+i].value;
 3458: 		user = user.replace(new RegExp(':', 'g'),"_");
 3459: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3460: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3461: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3462: 		if ((saveval != "correct") || override) {
 3463: 		    scorename.value = "";
 3464: 		    if (selval[1].selected) {
 3465: 			selname[1].selected = true;
 3466: 		    } else {
 3467: 			selname[2].selected = true;
 3468: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3469: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3470: 		    }
 3471: 		}
 3472: 	    }
 3473: 	} else {
 3474: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3475: 		var user = document.classgrade["ctr"+i].value;
 3476: 		user = user.replace(new RegExp(':', 'g'),"_");
 3477: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3478: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3479: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3480: 		if ((saveval != "correct") || override) {
 3481: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3482: 		    selname[0].selected = true;
 3483: 		}
 3484: 	    }
 3485: 	}	    
 3486:     }
 3487: 
 3488:     function changeSelect(partid,user) {
 3489: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3490: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3491: 	var point  = textbox.value;
 3492: 	var weight = document.classgrade["weight_"+partid].value;
 3493: 
 3494: 	if (isNaN(point) || parseFloat(point) < 0) {
 3495: 	    alert("$alertmsg"+parseFloat(point));
 3496: 	    textbox.value = "";
 3497: 	    return;
 3498: 	}
 3499: 	if (parseFloat(point) > parseFloat(weight)) {
 3500: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3501: 			       ") greater than the weight of the part. Accept?");
 3502: 	    if (resp == false) {
 3503: 		textbox.value = "";
 3504: 		return;
 3505: 	    }
 3506: 	}
 3507: 	selval[0].selected = true;
 3508:     }
 3509: 
 3510:     function changeOneScore(partid,user) {
 3511: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3512: 	if (selval[1].selected || selval[2].selected) {
 3513: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3514: 	    if (selval[2].selected) {
 3515: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3516: 	    }
 3517:         }
 3518:     }
 3519: 
 3520:     function resetEntry(numpart) {
 3521: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3522: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3523: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3524: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3525: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3526: 	    for (var i=0; i<radioButton.length; i++) {
 3527: 		radioButton[i].checked=false;
 3528: 
 3529: 	    }
 3530: 	    textbox.value = "";
 3531: 	    selval[0].selected = true;
 3532: 
 3533: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3534: 		var user = document.classgrade["ctr"+i].value;
 3535: 		user = user.replace(new RegExp(':', 'g'),"_");
 3536: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3537: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3538: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3539: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3540: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3541: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3542: 		if (saveselval == "excused") {
 3543: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3544: 		} else {
 3545: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3546: 		}
 3547: 	    }
 3548: 	}
 3549:     }
 3550: 
 3551: VIEWJAVASCRIPT
 3552: }
 3553: 
 3554: #--- show scores for a section or whole class w/ option to change/update a score
 3555: sub viewgrades {
 3556:     my ($request,$symb) = @_;
 3557:     &viewgrades_js($request);
 3558: 
 3559:     #need to make sure we have the correct data for later EXT calls, 
 3560:     #thus invalidate the cache
 3561:     &Apache::lonnet::devalidatecourseresdata(
 3562:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3563:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3564:     &Apache::lonnet::clear_EXT_cache_status();
 3565: 
 3566:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3567: 
 3568:     #view individual student submission form - called using Javascript viewOneStudent
 3569:     $result.=&jscriptNform($symb);
 3570: 
 3571:     #beginning of class grading form
 3572:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3573:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3574: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3575: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3576: 	&build_section_inputs().
 3577: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3578: 
 3579:     #retrieve selected groups
 3580:     my (@groups,$group_display);
 3581:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3582:     if (grep(/^all$/,@groups)) {
 3583:         @groups = ('all');
 3584:     } elsif (grep(/^none$/,@groups)) {
 3585:         @groups = ('none');
 3586:     } elsif (@groups > 0) {
 3587:         $group_display = join(', ',@groups);
 3588:     }
 3589: 
 3590:     my ($common_header,$specific_header,@sections,$section_display);
 3591:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3592:     if (grep(/^all$/,@sections)) {
 3593:         @sections = ('all');
 3594:         if ($group_display) {
 3595:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3596:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3597:         } elsif (grep(/^none$/,@groups)) {
 3598:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3599:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3600:         } else {
 3601: 	    $common_header = &mt('Assign Common Grade to Class');
 3602:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3603:         }
 3604:     } elsif (grep(/^none$/,@sections)) {
 3605:         @sections = ('none');
 3606:         if ($group_display) {
 3607:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3608:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3609:         } elsif (grep(/^none$/,@groups)) {
 3610:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3611:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3612:         } else {
 3613:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3614: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3615:         }
 3616:     } else {
 3617:         $section_display = join (", ",@sections);
 3618:         if ($group_display) {
 3619:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3620:                                  $section_display,$group_display);
 3621:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3622:                                    $section_display,$group_display);
 3623:         } elsif (grep(/^none$/,@groups)) {
 3624:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3625:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3626:         } else {
 3627:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3628: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3629:         }
 3630:     }
 3631:     my %submit_types = &substatus_options();
 3632:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3633: 
 3634:     if ($env{'form.submitonly'} eq 'all') {
 3635:         $result.= '<h3>'.$common_header.'</h3>';
 3636:     } else {
 3637:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3638:     }
 3639:     $result .= &Apache::loncommon::start_data_table();
 3640:     #radio buttons/text box for assigning points for a section or class.
 3641:     #handles different parts of a problem
 3642:     my $res_error;
 3643:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3644:     if ($res_error) {
 3645:         return &navmap_errormsg();
 3646:     }
 3647:     my %weight = ();
 3648:     my $ctsparts = 0;
 3649:     my %seen = ();
 3650:     my @part_response_id = &flatten_responseType($responseType);
 3651:     foreach my $part_response_id (@part_response_id) {
 3652:     	my ($partid,$respid) = @{ $part_response_id };
 3653: 	my $part_resp = join('_',@{ $part_response_id });
 3654: 	next if $seen{$partid};
 3655: 	$seen{$partid}++;
 3656: 	my $handgrade=$$handgrade{$part_resp};
 3657: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3658: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3659: 
 3660: 	my $display_part=&get_display_part($partid,$symb);
 3661: 	my $radio.='<table border="0"><tr>';  
 3662: 	my $ctr = 0;
 3663: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3664: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3665: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3666: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3667: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3668: 	    $ctr++;
 3669: 	}
 3670: 	$radio.='</tr></table>';
 3671: 	my $line = '<input type="text" name="TEXTVAL_'.
 3672: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3673: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3674: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3675:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3676:             '<select name="SELVAL_'.$partid.'" '.
 3677:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3678:                 $weight{$partid}.')"> '.
 3679: 	    '<option selected="selected"> </option>'.
 3680: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3681: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3682: 	    '</select></td>'.
 3683:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3684: 	$line.='<input type="hidden" name="partid_'.
 3685: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3686: 	$line.='<input type="hidden" name="weight_'.
 3687: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3688: 
 3689: 	$result.=
 3690: 	    &Apache::loncommon::start_data_table_row()."\n".
 3691: 	    '<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>'.
 3692: 	    &Apache::loncommon::end_data_table_row()."\n";
 3693: 	$ctsparts++;
 3694:     }
 3695:     $result.=&Apache::loncommon::end_data_table()."\n".
 3696: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3697:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3698: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3699: 
 3700:     #table listing all the students in a section/class
 3701:     #header of table
 3702:     if ($env{'form.submitonly'} eq 'all') {
 3703:         $result.= '<h3>'.$specific_header.'</h3>';
 3704:     } else {
 3705:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3706:     }
 3707:     $result.= &Apache::loncommon::start_data_table().
 3708: 	      &Apache::loncommon::start_data_table_header_row().
 3709: 	      '<th>'.&mt('No.').'</th>'.
 3710: 	      '<th>'.&nameUserString('header')."</th>\n";
 3711:     my $partserror;
 3712:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3713:     if ($partserror) {
 3714:         return &navmap_errormsg();
 3715:     }
 3716:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3717:     my @partids = ();
 3718:     foreach my $part (@parts) {
 3719: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3720:         my $narrowtext = &mt('Tries');
 3721: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3722: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3723: 	my ($partid) = &split_part_type($part);
 3724:         push(@partids,$partid);
 3725: #
 3726: # FIXME: Looks like $display looks at English text
 3727: #
 3728: 	my $display_part=&get_display_part($partid,$symb);
 3729: 	if ($display =~ /^Partial Credit Factor/) {
 3730: 	    $result.='<th>'.
 3731: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3732: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3733: 	    next;
 3734: 	    
 3735: 	} else {
 3736: 	    if ($display =~ /Problem Status/) {
 3737: 		my $grade_status_mt = &mt('Grade Status');
 3738: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3739: 	    }
 3740: 	    my $part_mt = &mt('Part:');
 3741: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3742: 	}
 3743: 
 3744: 	$result.='<th>'.$display.'</th>'."\n";
 3745:     }
 3746:     $result.=&Apache::loncommon::end_data_table_header_row();
 3747: 
 3748:     my %last_resets = 
 3749: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3750: 
 3751:     #get info for each student
 3752:     #list all the students - with points and grade status
 3753:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3754:     my $ctr = 0;
 3755:     foreach (sort 
 3756: 	     {
 3757: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3758: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3759: 		 }
 3760: 		 return $a cmp $b;
 3761: 	     } (keys(%$fullname))) {
 3762: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3763: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 3764:     }
 3765:     $result.=&Apache::loncommon::end_data_table();
 3766:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3767:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3768: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3769:     if ($ctr == 0) {
 3770:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3771:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3772:                 '<span class="LC_warning">';
 3773:         if ($env{'form.submitonly'} eq 'all') {
 3774:             if (grep(/^all$/,@sections)) {
 3775:                 if (grep(/^all$/,@groups)) {
 3776:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3777:                                    $stu_status);
 3778:                 } elsif (grep(/^none$/,@groups)) {
 3779:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 3780:                                    $stu_status); 
 3781:                 } else {
 3782:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3783:                                    $group_display,$stu_status);
 3784:                 }
 3785:             } elsif (grep(/^none$/,@sections)) {
 3786:                 if (grep(/^all$/,@groups)) {
 3787:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 3788:                                    $stu_status);
 3789:                 } elsif (grep(/^none$/,@groups)) {
 3790:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 3791:                                    $stu_status);
 3792:                 } else {
 3793:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3794:                                    $group_display,$stu_status);
 3795:                 }
 3796:             } else {
 3797:                 if (grep(/^all$/,@groups)) {
 3798:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3799:                                    $section_display,$stu_status);
 3800:                 } elsif (grep(/^none$/,@groups)) {
 3801:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 3802:                                    $section_display,$stu_status);
 3803:                 } else {
 3804:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 3805:                                    $section_display,$group_display,$stu_status);
 3806:                 }
 3807:             }
 3808:         } else {
 3809:             if (grep(/^all$/,@sections)) {
 3810:                 if (grep(/^all$/,@groups)) {
 3811:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3812:                                    $stu_status,$submission_status);
 3813:                 } elsif (grep(/^none$/,@groups)) {
 3814:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3815:                                    $stu_status,$submission_status);
 3816:                 } else {
 3817:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3818:                                    $group_display,$stu_status,$submission_status);
 3819:                 }
 3820:             } elsif (grep(/^none$/,@sections)) {
 3821:                 if (grep(/^all$/,@groups)) {
 3822:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3823:                                    $stu_status,$submission_status);
 3824:                 } elsif (grep(/^none$/,@groups)) {
 3825:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3826:                                    $stu_status,$submission_status);
 3827:                 } else {
 3828:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3829:                                    $group_display,$stu_status,$submission_status);
 3830:                 }
 3831:             } else {
 3832:                 if (grep(/^all$/,@groups)) {
 3833: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3834: 	                           $section_display,$stu_status,$submission_status);
 3835:                 } elsif (grep(/^none$/,@groups)) {
 3836:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 3837:                                    $section_display,$stu_status,$submission_status);
 3838:                 } else {
 3839:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
 3840:                                    $section_display,$group_display,$stu_status,$submission_status);
 3841:                 }
 3842:             }
 3843:         }
 3844: 	$result .= '</span><br />';
 3845:     }
 3846:     return $result;
 3847: }
 3848: 
 3849: #--- call by previous routine to display each student who satisfies submission filter. 
 3850: sub viewstudentgrade {
 3851:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3852:     my ($uname,$udom) = split(/:/,$student);
 3853:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3854:     my $submitonly = $env{'form.submitonly'};
 3855:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 3856:         my %partstatus = ();
 3857:         if (ref($parts) eq 'ARRAY') {
 3858:             foreach my $apart (@{$parts}) {
 3859:                 my ($part,$type) = &split_part_type($apart);
 3860:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 3861:                 $status = 'nothing' if ($status eq '');
 3862:                 $partstatus{$part}      = $status;
 3863:                 my $subkey = "resource.$part.submitted_by";
 3864:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 3865:             }
 3866:             my $submitted = 0;
 3867:             my $graded = 0;
 3868:             my $incorrect = 0;
 3869:             foreach my $key (keys(%partstatus)) {
 3870:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 3871:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 3872:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 3873: 
 3874:                 my $partid = (split(/\./,$key))[1];
 3875:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 3876:                     $submitted = 0;
 3877:                 }
 3878:             }
 3879:             return if (!$submitted && ($submitonly eq 'yes' ||
 3880:                                        $submitonly eq 'incorrect' ||
 3881:                                        $submitonly eq 'graded'));
 3882:             return if (!$graded && ($submitonly eq 'graded'));
 3883:             return if (!$incorrect && $submitonly eq 'incorrect');
 3884:         }
 3885:     }
 3886:     if ($submitonly eq 'queued') {
 3887:         my ($cdom,$cnum) = split(/_/,$courseid);
 3888:         my %queue_status =
 3889:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3890:                                                     $udom,$uname);
 3891:         return if (!defined($queue_status{'gradingqueue'}));
 3892:     }
 3893:     $$ctr++;
 3894:     my %aggregates = ();
 3895:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3896: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 3897: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 3898: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3899: 	'\');" target="_self">'.$fullname.'</a> '.
 3900: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3901:     $student=~s/:/_/; # colon doen't work in javascript for names
 3902:     foreach my $apart (@$parts) {
 3903: 	my ($part,$type) = &split_part_type($apart);
 3904: 	my $score=$record{"resource.$part.$type"};
 3905:         $result.='<td align="center">';
 3906:         my ($aggtries,$totaltries);
 3907:         unless (exists($aggregates{$part})) {
 3908: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3909: 	    $aggtries = $totaltries;
 3910:             if ($$last_resets{$part}) {  
 3911:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3912: 					   $part);
 3913:             }
 3914:             $result.='<input type="hidden" name="'.
 3915:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3916:             $result.='<input type="hidden" name="'.
 3917:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3918:             $aggregates{$part} = 1;
 3919:         }
 3920: 	if ($type eq 'awarded') {
 3921: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3922: 	    $result.='<input type="hidden" name="'.
 3923: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3924: 	    $result.='<input type="text" name="'.
 3925: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3926:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3927: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3928: 	} elsif ($type eq 'solved') {
 3929: 	    my ($status,$foo)=split(/_/,$score,2);
 3930: 	    $status = 'nothing' if ($status eq '');
 3931: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3932: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3933: 	    $result.='&nbsp;<select name="'.
 3934: 		'GD_'.$student.'_'.$part.'_solved" '.
 3935:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3936: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3937: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3938: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3939: 	    $result.="</select>&nbsp;</td>\n";
 3940: 	} else {
 3941: 	    $result.='<input type="hidden" name="'.
 3942: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3943: 		    "\n";
 3944: 	    $result.='<input type="text" name="'.
 3945: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3946: 		'value="'.$score.'" size="4" /></td>'."\n";
 3947: 	}
 3948:     }
 3949:     $result.=&Apache::loncommon::end_data_table_row();
 3950:     return $result;
 3951: }
 3952: 
 3953: #--- change scores for all the students in a section/class
 3954: #    record does not get update if unchanged
 3955: sub editgrades {
 3956:     my ($request,$symb) = @_;
 3957: 
 3958:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3959:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3960:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3961: 
 3962:     my $result= &Apache::loncommon::start_data_table().
 3963: 	&Apache::loncommon::start_data_table_header_row().
 3964: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3965: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3966:     my %scoreptr = (
 3967: 		    'correct'  =>'correct_by_override',
 3968: 		    'incorrect'=>'incorrect_by_override',
 3969: 		    'excused'  =>'excused',
 3970: 		    'ungraded' =>'ungraded_attempted',
 3971:                     'credited' =>'credit_attempted',
 3972: 		    'nothing'  => '',
 3973: 		    );
 3974:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3975: 
 3976:     my (@partid);
 3977:     my %weight = ();
 3978:     my %columns = ();
 3979:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3980: 
 3981:     my $partserror;
 3982:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3983:     if ($partserror) {
 3984:         return &navmap_errormsg();
 3985:     }
 3986:     my $header;
 3987:     while ($ctr < $env{'form.totalparts'}) {
 3988: 	my $partid = $env{'form.partid_'.$ctr};
 3989: 	push(@partid,$partid);
 3990: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3991: 	$ctr++;
 3992:     }
 3993:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3994:     foreach my $partid (@partid) {
 3995: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3996: 	    '<th align="center">'.&mt('New Score').'</th>';
 3997: 	$columns{$partid}=2;
 3998: 	foreach my $stores (@parts) {
 3999: 	    my ($part,$type) = &split_part_type($stores);
 4000: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4001: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4002: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4003: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4004:             my $narrowtext = &mt('Tries');
 4005: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4006: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4007: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4008: 	    $columns{$partid}+=2;
 4009: 	}
 4010:     }
 4011:     foreach my $partid (@partid) {
 4012: 	my $display_part=&get_display_part($partid,$symb);
 4013: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4014: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4015: 	    '</th>';
 4016: 
 4017:     }
 4018:     $result .= &Apache::loncommon::end_data_table_header_row().
 4019: 	&Apache::loncommon::start_data_table_header_row().
 4020: 	$header.
 4021: 	&Apache::loncommon::end_data_table_header_row();
 4022:     my @noupdate;
 4023:     my ($updateCtr,$noupdateCtr) = (1,1);
 4024:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4025: 	my $line;
 4026: 	my $user = $env{'form.ctr'.$i};
 4027: 	my ($uname,$udom)=split(/:/,$user);
 4028: 	my %newrecord;
 4029: 	my $updateflag = 0;
 4030: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4031: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4032: 	if (!&canmodify($usec)) {
 4033: 	    my $numcols=scalar(@partid)*4+2;
 4034: 	    push(@noupdate,
 4035: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 4036: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 4037: 	    next;
 4038: 	}
 4039:         my %aggregate = ();
 4040:         my $aggregateflag = 0;
 4041: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4042: 	foreach (@partid) {
 4043: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4044: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4045: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4046: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4047: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4048: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4049: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4050: 	    my $score;
 4051: 	    if ($partial eq '') {
 4052: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4053: 	    } elsif ($partial > 0) {
 4054: 		$score = 'correct_by_override';
 4055: 	    } elsif ($partial == 0) {
 4056: 		$score = 'incorrect_by_override';
 4057: 	    }
 4058: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4059: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4060: 
 4061: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4062: 		"$env{'user.name'}:$env{'user.domain'}";
 4063: 	    if ($dropMenu eq 'reset status' &&
 4064: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4065: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4066: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4067: 		$newrecord{'resource.'.$_.'.award'} = '';
 4068: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4069: 		$updateflag = 1;
 4070:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4071:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4072:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4073:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4074:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4075:                     $aggregateflag = 1;
 4076:                 }
 4077: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4078: 		$updateflag = 1;
 4079: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4080: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4081: 		$rec_update++;
 4082: 	    }
 4083: 
 4084: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4085: 		'<td align="center">'.$awarded.
 4086: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4087: 
 4088: 
 4089: 	    my $partid=$_;
 4090: 	    foreach my $stores (@parts) {
 4091: 		my ($part,$type) = &split_part_type($stores);
 4092: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4093: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4094: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4095: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4096: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4097: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4098: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4099: 		    $updateflag=1;
 4100: 		}
 4101: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4102: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4103: 	    }
 4104: 	}
 4105: 	$line.="\n";
 4106: 
 4107: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4108: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4109: 
 4110: 	if ($updateflag) {
 4111: 	    $count++;
 4112: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4113: 				    $udom,$uname);
 4114: 
 4115: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4116: 					      $cnum,$udom,$uname)) {
 4117: 		# need to figure out if should be in queue.
 4118: 		my %record =  
 4119: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4120: 					     $udom,$uname);
 4121: 		my $all_graded = 1;
 4122: 		my $none_graded = 1;
 4123: 		foreach my $part (@parts) {
 4124: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4125: 			$all_graded = 0;
 4126: 		    } else {
 4127: 			$none_graded = 0;
 4128: 		    }
 4129: 		}
 4130: 
 4131: 		if ($all_graded || $none_graded) {
 4132: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4133: 							   $symb,$cdom,$cnum,
 4134: 							   $udom,$uname);
 4135: 		}
 4136: 	    }
 4137: 
 4138: 	    $result.=&Apache::loncommon::start_data_table_row().
 4139: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4140: 		&Apache::loncommon::end_data_table_row();
 4141: 	    $updateCtr++;
 4142: 	} else {
 4143: 	    push(@noupdate,
 4144: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4145: 	    $noupdateCtr++;
 4146: 	}
 4147:         if ($aggregateflag) {
 4148:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4149: 				  $cdom,$cnum);
 4150:         }
 4151:     }
 4152:     if (@noupdate) {
 4153: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 4154: 	my $numcols=scalar(@partid)*4+2;
 4155: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4156: 	    '<td align="center" colspan="'.$numcols.'">'.
 4157: 	    &mt('No Changes Occurred For the Students Below').
 4158: 	    '</td>'.
 4159: 	    &Apache::loncommon::end_data_table_row();
 4160: 	foreach my $line (@noupdate) {
 4161: 	    $result.=
 4162: 		&Apache::loncommon::start_data_table_row().
 4163: 		$line.
 4164: 		&Apache::loncommon::end_data_table_row();
 4165: 	}
 4166:     }
 4167:     $result .= &Apache::loncommon::end_data_table();
 4168:     my $msg = '<p><b>'.
 4169: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4170: 	    $rec_update,$count).'</b><br />'.
 4171: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4172: 	'</b></p>';
 4173:     return $title.$msg.$result;
 4174: }
 4175: 
 4176: sub split_part_type {
 4177:     my ($partstr) = @_;
 4178:     my ($temp,@allparts)=split(/_/,$partstr);
 4179:     my $type=pop(@allparts);
 4180:     my $part=join('_',@allparts);
 4181:     return ($part,$type);
 4182: }
 4183: 
 4184: #------------- end of section for handling grading by section/class ---------
 4185: #
 4186: #----------------------------------------------------------------------------
 4187: 
 4188: 
 4189: #----------------------------------------------------------------------------
 4190: #
 4191: #-------------------------- Next few routines handles grading by csv upload
 4192: #
 4193: #--- Javascript to handle csv upload
 4194: sub csvupload_javascript_reverse_associate {
 4195:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4196:     my $error2=&mt('You need to specify at least one grading field');
 4197:   &js_escape(\$error1);
 4198:   &js_escape(\$error2);
 4199:   return(<<ENDPICK);
 4200:   function verify(vf) {
 4201:     var foundsomething=0;
 4202:     var founduname=0;
 4203:     var foundID=0;
 4204:     for (i=0;i<=vf.nfields.value;i++) {
 4205:       tw=eval('vf.f'+i+'.selectedIndex');
 4206:       if (i==0 && tw!=0) { foundID=1; }
 4207:       if (i==1 && tw!=0) { founduname=1; }
 4208:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4209:     }
 4210:     if (founduname==0 && foundID==0) {
 4211: 	alert('$error1');
 4212: 	return;
 4213:     }
 4214:     if (foundsomething==0) {
 4215: 	alert('$error2');
 4216: 	return;
 4217:     }
 4218:     vf.submit();
 4219:   }
 4220:   function flip(vf,tf) {
 4221:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4222:     var i;
 4223:     for (i=0;i<=vf.nfields.value;i++) {
 4224:       //can not pick the same destination field for both name and domain
 4225:       if (((i ==0)||(i ==1)) && 
 4226:           ((tf==0)||(tf==1)) && 
 4227:           (i!=tf) &&
 4228:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4229:         eval('vf.f'+i+'.selectedIndex=0;')
 4230:       }
 4231:     }
 4232:   }
 4233: ENDPICK
 4234: }
 4235: 
 4236: sub csvupload_javascript_forward_associate {
 4237:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4238:     my $error2=&mt('You need to specify at least one grading field');
 4239:   &js_escape(\$error1);
 4240:   &js_escape(\$error2);
 4241:   return(<<ENDPICK);
 4242:   function verify(vf) {
 4243:     var foundsomething=0;
 4244:     var founduname=0;
 4245:     var foundID=0;
 4246:     for (i=0;i<=vf.nfields.value;i++) {
 4247:       tw=eval('vf.f'+i+'.selectedIndex');
 4248:       if (tw==1) { foundID=1; }
 4249:       if (tw==2) { founduname=1; }
 4250:       if (tw>3) { foundsomething=1; }
 4251:     }
 4252:     if (founduname==0 && foundID==0) {
 4253: 	alert('$error1');
 4254: 	return;
 4255:     }
 4256:     if (foundsomething==0) {
 4257: 	alert('$error2');
 4258: 	return;
 4259:     }
 4260:     vf.submit();
 4261:   }
 4262:   function flip(vf,tf) {
 4263:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4264:     var i;
 4265:     //can not pick the same destination field twice
 4266:     for (i=0;i<=vf.nfields.value;i++) {
 4267:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4268:         eval('vf.f'+i+'.selectedIndex=0;')
 4269:       }
 4270:     }
 4271:   }
 4272: ENDPICK
 4273: }
 4274: 
 4275: sub csvuploadmap_header {
 4276:     my ($request,$symb,$datatoken,$distotal)= @_;
 4277:     my $javascript;
 4278:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4279: 	$javascript=&csvupload_javascript_reverse_associate();
 4280:     } else {
 4281: 	$javascript=&csvupload_javascript_forward_associate();
 4282:     }
 4283: 
 4284:     $symb = &Apache::lonenc::check_encrypt($symb);
 4285:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4286:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4287:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4288:     my $reverse=&mt("Reverse Association");
 4289:     $request->print(<<ENDPICK);
 4290: <br />
 4291: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4292: <input type="hidden" name="associate"  value="" />
 4293: <input type="hidden" name="phase"      value="three" />
 4294: <input type="hidden" name="datatoken"  value="$datatoken" />
 4295: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4296: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4297: <input type="hidden" name="upfile_associate" 
 4298:                                        value="$env{'form.upfile_associate'}" />
 4299: <input type="hidden" name="symb"       value="$symb" />
 4300: <input type="hidden" name="command"    value="csvuploadoptions" />
 4301: <hr />
 4302: ENDPICK
 4303:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4304:     return '';
 4305: 
 4306: }
 4307: 
 4308: sub csvupload_fields {
 4309:     my ($symb,$errorref) = @_;
 4310:     my (@parts) = &getpartlist($symb,$errorref);
 4311:     if (ref($errorref)) {
 4312:         if ($$errorref) {
 4313:             return;
 4314:         }
 4315:     }
 4316: 
 4317:     my @fields=(['ID','Student/Employee ID'],
 4318:                 ['clicker','Clicker ID'],
 4319: 		['username','Student Username'],
 4320: 		['domain','Student Domain']);
 4321:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4322:     foreach my $part (sort(@parts)) {
 4323: 	my @datum;
 4324: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4325: 	my $name=$part;
 4326: 	if  (!$display) { $display = $name; }
 4327: 	@datum=($name,$display);
 4328: 	if ($name=~/^stores_(.*)_awarded/) {
 4329: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4330: 	}
 4331: 	push(@fields,\@datum);
 4332:     }
 4333:     return (@fields);
 4334: }
 4335: 
 4336: sub csvuploadmap_footer {
 4337:     my ($request,$i,$keyfields) =@_;
 4338:     my $buttontext = &mt('Assign Grades');
 4339:     $request->print(<<ENDPICK);
 4340: </table>
 4341: <input type="hidden" name="nfields" value="$i" />
 4342: <input type="hidden" name="keyfields" value="$keyfields" />
 4343: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4344: </form>
 4345: ENDPICK
 4346: }
 4347: 
 4348: sub checkforfile_js {
 4349:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4350:     &js_escape(\$alertmsg);
 4351:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4352:     function checkUpload(formname) {
 4353: 	if (formname.upfile.value == "") {
 4354: 	    alert("$alertmsg");
 4355: 	    return false;
 4356: 	}
 4357: 	formname.submit();
 4358:     }
 4359: CSVFORMJS
 4360:     return $result;
 4361: }
 4362: 
 4363: sub upcsvScores_form {
 4364:     my ($request,$symb) = @_;
 4365:     if (!$symb) {return '';}
 4366:     my $result=&checkforfile_js();
 4367:     $result.=&Apache::loncommon::start_data_table().
 4368:              &Apache::loncommon::start_data_table_header_row().
 4369:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4370:              &Apache::loncommon::end_data_table_header_row().
 4371:              &Apache::loncommon::start_data_table_row().'<td>';
 4372:     my $upload=&mt("Upload Scores");
 4373:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4374:     my $ignore=&mt('Ignore First Line');
 4375:     $symb = &Apache::lonenc::check_encrypt($symb);
 4376:     $result.=<<ENDUPFORM;
 4377: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4378: <input type="hidden" name="symb" value="$symb" />
 4379: <input type="hidden" name="command" value="csvuploadmap" />
 4380: $upfile_select
 4381: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4382: </form>
 4383: ENDUPFORM
 4384:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4385:                            &mt("How do I create a CSV file from a spreadsheet")).
 4386:              '</td>'.
 4387:             &Apache::loncommon::end_data_table_row().
 4388:             &Apache::loncommon::end_data_table();
 4389:     return $result;
 4390: }
 4391: 
 4392: 
 4393: sub csvuploadmap {
 4394:     my ($request,$symb)= @_;
 4395:     if (!$symb) {return '';}
 4396: 
 4397:     my $datatoken;
 4398:     if (!$env{'form.datatoken'}) {
 4399: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4400:     } else {
 4401: 	$datatoken=$env{'form.datatoken'};
 4402: 	&Apache::loncommon::load_tmp_file($request);
 4403:     }
 4404:     my @records=&Apache::loncommon::upfile_record_sep();
 4405:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4406:     my ($i,$keyfields);
 4407:     if (@records) {
 4408:         my $fieldserror;
 4409: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4410:         if ($fieldserror) {
 4411:             $request->print(&navmap_errormsg());
 4412:             return;
 4413:         }
 4414: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4415: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4416: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4417: 							  \@fields);
 4418: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4419: 	    chop($keyfields);
 4420: 	} else {
 4421: 	    unshift(@fields,['none','']);
 4422: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4423: 							    \@fields);
 4424:             foreach my $rec (@records) {
 4425:                 my %temp = &Apache::loncommon::record_sep($rec);
 4426:                 if (%temp) {
 4427:                     $keyfields=join(',',sort(keys(%temp)));
 4428:                     last;
 4429:                 }
 4430:             }
 4431: 	}
 4432:     }
 4433:     &csvuploadmap_footer($request,$i,$keyfields);
 4434: 
 4435:     return '';
 4436: }
 4437: 
 4438: sub csvuploadoptions {
 4439:     my ($request,$symb)= @_;
 4440:     my $overwrite=&mt('Overwrite any existing score');
 4441:     $request->print(<<ENDPICK);
 4442: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4443: <input type="hidden" name="command"    value="csvuploadassign" />
 4444: <p>
 4445: <label>
 4446:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4447:    $overwrite
 4448: </label>
 4449: </p>
 4450: ENDPICK
 4451:     my %fields=&get_fields();
 4452:     if (!defined($fields{'domain'})) {
 4453: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4454: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4455:     }
 4456:     foreach my $key (sort(keys(%env))) {
 4457: 	if ($key !~ /^form\.(.*)$/) { next; }
 4458: 	my $cleankey=$1;
 4459: 	if ($cleankey eq 'command') { next; }
 4460: 	$request->print('<input type="hidden" name="'.$cleankey.
 4461: 			'"  value="'.$env{$key}.'" />'."\n");
 4462:     }
 4463:     # FIXME do a check for any duplicated user ids...
 4464:     # FIXME do a check for any invalid user ids?...
 4465:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4466: <hr /></form>'."\n");
 4467:     return '';
 4468: }
 4469: 
 4470: sub get_fields {
 4471:     my %fields;
 4472:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4473:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4474: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4475: 	    if ($env{'form.f'.$i} ne 'none') {
 4476: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4477: 	    }
 4478: 	} else {
 4479: 	    if ($env{'form.f'.$i} ne 'none') {
 4480: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4481: 	    }
 4482: 	}
 4483:     }
 4484:     return %fields;
 4485: }
 4486: 
 4487: sub csvuploadassign {
 4488:     my ($request,$symb)= @_;
 4489:     if (!$symb) {return '';}
 4490:     my $error_msg = '';
 4491:     &Apache::loncommon::load_tmp_file($request);
 4492:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4493:     my %fields=&get_fields();
 4494:     my $courseid=$env{'request.course.id'};
 4495:     my ($classlist) = &getclasslist('all',0);
 4496:     my @notallowed;
 4497:     my @skipped;
 4498:     my @warnings;
 4499:     my $countdone=0;
 4500:     foreach my $grade (@gradedata) {
 4501: 	my %entries=&Apache::loncommon::record_sep($grade);
 4502: 	my $domain;
 4503: 	if ($entries{$fields{'domain'}}) {
 4504: 	    $domain=$entries{$fields{'domain'}};
 4505: 	} else {
 4506: 	    $domain=$env{'form.default_domain'};
 4507: 	}
 4508: 	$domain=~s/\s//g;
 4509: 	my $username=$entries{$fields{'username'}};
 4510: 	$username=~s/\s//g;
 4511: 	if (!$username) {
 4512: 	    my $id=$entries{$fields{'ID'}};
 4513: 	    $id=~s/\s//g;
 4514:             if ($id ne '') {
 4515: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4516: 	        $username=$ids{$id};
 4517:             } else {
 4518:                 if ($entries{$fields{'clicker'}}) {
 4519:                     my $clicker = $entries{$fields{'clicker'}};
 4520:                     $clicker=~s/\s//g;
 4521:                     if ($clicker ne '') {
 4522:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4523:                         if ($clickers{$clicker} ne '') {  
 4524:                             my $match = 0;
 4525:                             my @inclass;
 4526:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4527:                                 if (exists($$classlist{"$poss:$domain"})) {
 4528:                                     $username = $poss;
 4529:                                     push(@inclass,$poss);
 4530:                                     $match ++;
 4531:                                     
 4532:                                 }
 4533:                             }
 4534:                             if ($match > 1) {
 4535:                                 undef($username); 
 4536:                                 $request->print('<p class="LC_warning">'.
 4537:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4538:                                                 $clicker,join(', ',@inclass)).'</p>');
 4539:                             }
 4540:                         }
 4541:                     }
 4542:                 }
 4543:             }
 4544: 	}
 4545: 	if (!exists($$classlist{"$username:$domain"})) {
 4546: 	    my $id=$entries{$fields{'ID'}};
 4547: 	    $id=~s/\s//g;
 4548:             my $clicker = $entries{$fields{'clicker'}};
 4549:             $clicker=~s/\s//g;
 4550:             if ($clicker) {
 4551:                 push(@skipped,"$clicker:$domain");
 4552: 	    } elsif ($id) {
 4553: 		push(@skipped,"$id:$domain");
 4554: 	    } else {
 4555: 		push(@skipped,"$username:$domain");
 4556: 	    }
 4557: 	    next;
 4558: 	}
 4559: 	my $usec=$classlist->{"$username:$domain"}[5];
 4560: 	if (!&canmodify($usec)) {
 4561: 	    push(@notallowed,"$username:$domain");
 4562: 	    next;
 4563: 	}
 4564: 	my %points;
 4565: 	my %grades;
 4566: 	foreach my $dest (keys(%fields)) {
 4567: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4568: 		$dest eq 'domain') { next; }
 4569: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4570: 	    if ($dest=~/stores_(.*)_points/) {
 4571: 		my $part=$1;
 4572: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4573: 					      $symb,$domain,$username);
 4574:                 if ($wgt) {
 4575:                     $entries{$fields{$dest}}=~s/\s//g;
 4576:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4577:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4578:                                           : 'correct_by_override';
 4579:                     if ($pcr>1) {
 4580:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4581:                     }
 4582:                     $grades{"resource.$part.awarded"}=$pcr;
 4583:                     $grades{"resource.$part.solved"}=$award;
 4584:                     $points{$part}=1;
 4585:                 } else {
 4586:                     $error_msg = "<br />" .
 4587:                         &mt("Some point values were assigned"
 4588:                             ." for problems with a weight "
 4589:                             ."of zero. These values were "
 4590:                             ."ignored.");
 4591:                 }
 4592: 	    } else {
 4593: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4594: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4595: 		my $store_key=$dest;
 4596: 		$store_key=~s/^stores/resource/;
 4597: 		$store_key=~s/_/\./g;
 4598: 		$grades{$store_key}=$entries{$fields{$dest}};
 4599: 	    }
 4600: 	}
 4601: 	if (! %grades) { 
 4602:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4603:         } else {
 4604: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4605: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4606: 					   $env{'request.course.id'},
 4607: 					   $domain,$username);
 4608: 	   if ($result eq 'ok') {
 4609: # Successfully stored
 4610: 	      $request->print('.');
 4611: # Remove from grading queue
 4612:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4613:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4614:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4615:                                              $domain,$username);
 4616:               $countdone++;
 4617:            } else {
 4618: 	      $request->print("<p><span class=\"LC_error\">".
 4619:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4620:                                   "$username:$domain",$result)."</span></p>");
 4621: 	   }
 4622: 	   $request->rflush();
 4623:         }
 4624:     }
 4625:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4626:     if (@warnings) {
 4627:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4628:         $request->print(join(', ',@warnings));
 4629:     }
 4630:     if (@skipped) {
 4631: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4632:         $request->print(join(', ',@skipped));
 4633:     }
 4634:     if (@notallowed) {
 4635: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4636: 	$request->print(join(', ',@notallowed));
 4637:     }
 4638:     $request->print("<br />\n");
 4639:     return $error_msg;
 4640: }
 4641: #------------- end of section for handling csv file upload ---------
 4642: #
 4643: #-------------------------------------------------------------------
 4644: #
 4645: #-------------- Next few routines handle grading by page/sequence
 4646: #
 4647: #--- Select a page/sequence and a student to grade
 4648: sub pickStudentPage {
 4649:     my ($request,$symb) = @_;
 4650: 
 4651:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4652:     &js_escape(\$alertmsg);
 4653:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4654: 
 4655: function checkPickOne(formname) {
 4656:     if (radioSelection(formname.student) == null) {
 4657: 	alert("$alertmsg");
 4658: 	return;
 4659:     }
 4660:     ptr = pullDownSelection(formname.selectpage);
 4661:     formname.page.value = formname["page"+ptr].value;
 4662:     formname.title.value = formname["title"+ptr].value;
 4663:     formname.submit();
 4664: }
 4665: 
 4666: LISTJAVASCRIPT
 4667:     &commonJSfunctions($request);
 4668: 
 4669:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4670:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4671:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4672: 
 4673:     my $result='<h3><span class="LC_info">&nbsp;'.
 4674: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4675: 
 4676:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4677:     my $map_error;
 4678:     my ($titles,$symbx) = &getSymbMap($map_error);
 4679:     if ($map_error) {
 4680:         $request->print(&navmap_errormsg());
 4681:         return; 
 4682:     }
 4683:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4684: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4685: #    my $type=($curpage =~ /\.(page|sequence)/);
 4686: 
 4687:     # Collection of hidden fields
 4688:     my $ctr=0;
 4689:     foreach (@$titles) {
 4690:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4691:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4692:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4693:         $ctr++;
 4694:     }
 4695:     $result.='<input type="hidden" name="page" />'."\n".
 4696:         '<input type="hidden" name="title" />'."\n";
 4697: 
 4698:     $result.=&build_section_inputs();
 4699:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4700:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4701: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4702: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4703: 
 4704:     # Show grading options
 4705:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4706:     my $select = '<select name="selectpage">'."\n";
 4707:     $ctr=0;
 4708:     foreach (@$titles) {
 4709: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4710: 	$select.='<option value="'.$ctr.'"'.
 4711: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4712: 	    '>'.$showtitle.'</option>'."\n";
 4713: 	$ctr++;
 4714:     }
 4715:     $select.= '</select>';
 4716: 
 4717:     $result.=
 4718:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4719:        .$select
 4720:        .&Apache::lonhtmlcommon::row_closure();
 4721: 
 4722:     $result.=
 4723:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4724:        .'<label><input type="radio" name="vProb" value="no"'
 4725:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4726:        .'<label><input type="radio" name="vProb" value="yes" />'
 4727:            .&mt('yes').'</label>'."\n"
 4728:        .&Apache::lonhtmlcommon::row_closure();
 4729: 
 4730:     $result.=
 4731:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4732:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4733:            .&mt('none').' </label>'."\n"
 4734:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4735:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4736:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4737:            .&mt('all submissions with details').' </label>'
 4738:        .&Apache::lonhtmlcommon::row_closure();
 4739:     
 4740:     $result.=
 4741:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4742:        .'<input type="text" name="CODE" value="" />'
 4743:        .&Apache::lonhtmlcommon::row_closure(1)
 4744:        .&Apache::lonhtmlcommon::end_pick_box();
 4745: 
 4746:     # Show list of students to select for grading
 4747:     $result.='<br /><input type="button" '.
 4748:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4749: 
 4750:     $request->print($result);
 4751: 
 4752:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4753: 	&Apache::loncommon::start_data_table().
 4754: 	&Apache::loncommon::start_data_table_header_row().
 4755: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4756: 	'<th>'.&nameUserString('header').'</th>'.
 4757: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4758: 	'<th>'.&nameUserString('header').'</th>'.
 4759: 	&Apache::loncommon::end_data_table_header_row();
 4760:  
 4761:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4762:     my $ptr = 1;
 4763:     foreach my $student (sort 
 4764: 			 {
 4765: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4766: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4767: 			     }
 4768: 			     return $a cmp $b;
 4769: 			 } (keys(%$fullname))) {
 4770: 	my ($uname,$udom) = split(/:/,$student);
 4771: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4772:                                   : '</td>');
 4773: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4774: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4775: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4776: 	$studentTable.=
 4777: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4778:                          : '');
 4779: 	$ptr++;
 4780:     }
 4781:     if ($ptr%2 == 0) {
 4782: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4783: 	    &Apache::loncommon::end_data_table_row();
 4784:     }
 4785:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4786:     $studentTable.='<input type="button" '.
 4787:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4788: 
 4789:     $request->print($studentTable);
 4790: 
 4791:     return '';
 4792: }
 4793: 
 4794: sub getSymbMap {
 4795:     my ($map_error) = @_;
 4796:     my $navmap = Apache::lonnavmaps::navmap->new();
 4797:     unless (ref($navmap)) {
 4798:         if (ref($map_error)) {
 4799:             $$map_error = 'navmap';
 4800:         }
 4801:         return;
 4802:     }
 4803:     my %symbx = ();
 4804:     my @titles = ();
 4805:     my $minder = 0;
 4806: 
 4807:     # Gather every sequence that has problems.
 4808:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4809: 					       1,0,1);
 4810:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4811: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4812: 	    my $title = $minder.'.'.
 4813: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4814: 	    push(@titles, $title); # minder in case two titles are identical
 4815: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4816: 	    $minder++;
 4817: 	}
 4818:     }
 4819:     return \@titles,\%symbx;
 4820: }
 4821: 
 4822: #
 4823: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4824: sub displayPage {
 4825:     my ($request,$symb) = @_;
 4826:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4827:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4828:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4829:     my $pageTitle = $env{'form.page'};
 4830:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4831:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4832:     my $usec=$classlist->{$env{'form.student'}}[5];
 4833: 
 4834:     #need to make sure we have the correct data for later EXT calls, 
 4835:     #thus invalidate the cache
 4836:     &Apache::lonnet::devalidatecourseresdata(
 4837:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4838:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4839:     &Apache::lonnet::clear_EXT_cache_status();
 4840: 
 4841:     if (!&canview($usec)) {
 4842:         $request->print(
 4843:             '<span class="LC_warning">'.
 4844:             &mt('Unable to view requested student. ([_1])',
 4845:                     $env{'form.student'}).
 4846:             '</span>');
 4847:         return;
 4848:     }
 4849:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4850:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4851: 	'</h3>'."\n";
 4852:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4853:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4854: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4855:     } else {
 4856: 	delete($env{'form.CODE'});
 4857:     }
 4858:     &sub_page_js($request);
 4859:     $request->print($result);
 4860: 
 4861:     my $navmap = Apache::lonnavmaps::navmap->new();
 4862:     unless (ref($navmap)) {
 4863:         $request->print(&navmap_errormsg());
 4864:         return;
 4865:     }
 4866:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4867:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4868:     if (!$map) {
 4869: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4870: 	return; 
 4871:     }
 4872:     my $iterator = $navmap->getIterator($map->map_start(),
 4873: 					$map->map_finish());
 4874: 
 4875:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4876: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4877: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4878: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4879: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4880: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4881: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4882: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4883: 
 4884:     if (defined($env{'form.CODE'})) {
 4885: 	$studentTable.=
 4886: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4887:     }
 4888:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4889: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4890: 
 4891:     $studentTable.='&nbsp;<span class="LC_info">'.
 4892:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4893:         '</span>'."\n".
 4894: 	&Apache::loncommon::start_data_table().
 4895: 	&Apache::loncommon::start_data_table_header_row().
 4896: 	'<th>'.&mt('Prob.').'</th>'.
 4897: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4898: 	&Apache::loncommon::end_data_table_header_row();
 4899: 
 4900:     &Apache::lonxml::clear_problem_counter();
 4901:     my ($depth,$question,$prob) = (1,1,1);
 4902:     $iterator->next(); # skip the first BEGIN_MAP
 4903:     my $curRes = $iterator->next(); # for "current resource"
 4904:     while ($depth > 0) {
 4905:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4906:         if($curRes == $iterator->END_MAP) { $depth--; }
 4907: 
 4908:         if (ref($curRes) && $curRes->is_problem()) {
 4909: 	    my $parts = $curRes->parts();
 4910:             my $title = $curRes->compTitle();
 4911: 	    my $symbx = $curRes->symb();
 4912: 	    $studentTable.=
 4913: 		&Apache::loncommon::start_data_table_row().
 4914: 		'<td align="center" valign="top" >'.$prob.
 4915: 		(scalar(@{$parts}) == 1 ? '' 
 4916: 		                        : '<br />('.&mt('[_1]parts',
 4917: 							scalar(@{$parts}).'&nbsp;').')'
 4918: 		 ).
 4919: 		 '</td>';
 4920: 	    $studentTable.='<td valign="top">';
 4921: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4922: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4923: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4924: 					     undef,'both',\%form);
 4925: 	    } else {
 4926: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4927: 		$companswer =~ s|<form(.*?)>||g;
 4928: 		$companswer =~ s|</form>||g;
 4929: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4930: #		    $companswer =~ s/$1/ /ms;
 4931: #		    $request->print('match='.$1."<br />\n");
 4932: #		}
 4933: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4934: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4935: 	    }
 4936: 
 4937: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4938: 
 4939: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4940: 		if ($record{'version'} eq '') {
 4941: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4942: 		} else {
 4943: 		    my %responseType = ();
 4944: 		    foreach my $partid (@{$parts}) {
 4945: 			my @responseIds =$curRes->responseIds($partid);
 4946: 			my @responseType =$curRes->responseType($partid);
 4947: 			my %responseIds;
 4948: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4949: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4950: 			}
 4951: 			$responseType{$partid} = \%responseIds;
 4952: 		    }
 4953: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4954: 
 4955: 		}
 4956: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4957: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4958:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 4959: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4960: 									$env{'request.course.id'},
 4961: 									'','.submission',undef,
 4962:                                                                         $usec,$identifier);
 4963:  
 4964: 	    }
 4965: 	    if (&canmodify($usec)) {
 4966:             $studentTable.=&gradeBox_start();
 4967: 		foreach my $partid (@{$parts}) {
 4968: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4969: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4970: 		    $question++;
 4971: 		}
 4972:             $studentTable.=&gradeBox_end();
 4973: 		$prob++;
 4974: 	    }
 4975: 	    $studentTable.='</td></tr>';
 4976: 
 4977: 	}
 4978:         $curRes = $iterator->next();
 4979:     }
 4980: 
 4981:     $studentTable.=
 4982:         '</table>'."\n".
 4983:         '<input type="button" value="'.&mt('Save').'" '.
 4984:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4985:         '</form>'."\n";
 4986:     $request->print($studentTable);
 4987: 
 4988:     return '';
 4989: }
 4990: 
 4991: sub displaySubByDates {
 4992:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4993:     my $isCODE=0;
 4994:     my $isTask = ($symb =~/\.task$/);
 4995:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4996:     my $studentTable=&Apache::loncommon::start_data_table().
 4997: 	&Apache::loncommon::start_data_table_header_row().
 4998: 	'<th>'.&mt('Date/Time').'</th>'.
 4999: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5000:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5001: 	'<th>'.&mt('Submission').'</th>'.
 5002: 	'<th>'.&mt('Status').'</th>'.
 5003: 	&Apache::loncommon::end_data_table_header_row();
 5004:     my ($version);
 5005:     my %mark;
 5006:     my %orders;
 5007:     $mark{'correct_by_student'} = $checkIcon;
 5008:     if (!exists($$record{'1:timestamp'})) {
 5009: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5010:     }
 5011: 
 5012:     my $interaction;
 5013:     my $no_increment = 1;
 5014:     my (%lastrndseed,%lasttype);
 5015:     for ($version=1;$version<=$$record{'version'};$version++) {
 5016: 	my $timestamp = 
 5017: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5018: 	if (exists($$record{$version.':resource.0.version'})) {
 5019: 	    $interaction = $$record{$version.':resource.0.version'};
 5020: 	}
 5021:         if ($isTask && $env{'form.previousversion'}) {
 5022:             next unless ($interaction == $env{'form.previousversion'});
 5023:         }
 5024: 	my $where = ($isTask ? "$version:resource.$interaction"
 5025: 		             : "$version:resource");
 5026: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5027: 	    '<td>'.$timestamp.'</td>';
 5028: 	if ($isCODE) {
 5029: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5030: 	}
 5031:         if ($isTask) {
 5032:             $studentTable.='<td>'.$interaction.'</td>';
 5033:         }
 5034: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5035: 	my @displaySub = ();
 5036: 	foreach my $partid (@{$parts}) {
 5037:             my ($hidden,$type);
 5038:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5039:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5040:                 $hidden = 1;
 5041:             }
 5042: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5043: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5044: 	    
 5045: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5046: 	    my $display_part=&get_display_part($partid,$symb);
 5047: 	    foreach my $matchKey (@matchKey) {
 5048: 		if (exists($$record{$version.':'.$matchKey}) &&
 5049: 		    $$record{$version.':'.$matchKey} ne '') {
 5050:                     
 5051: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5052: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5053:                     $displaySub[0].='<span class="LC_nobreak">';
 5054:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5055:                                    .' <span class="LC_internal_info">'
 5056:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5057:                                    .'</span>'
 5058:                                    .' <b>';
 5059:                     if ($hidden) {
 5060:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5061:                     } else {
 5062:                         my ($trial,$rndseed,$newvariation);
 5063:                         if ($type eq 'randomizetry') {
 5064:                             $trial = $$record{"$where.$partid.tries"};
 5065:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5066:                         }
 5067: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5068: 			    $displaySub[0].=&mt('Trial not counted');
 5069: 		        } else {
 5070: 			    $displaySub[0].=&mt('Trial: [_1]',
 5071: 					    $$record{"$where.$partid.tries"});
 5072:                             if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5073:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5074:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5075:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5076:                                 }
 5077:                             }
 5078:                             $lastrndseed{$partid} = $rndseed;
 5079:                             $lasttype{$partid} = $type;
 5080: 		        }
 5081: 		        my $responseType=($isTask ? 'Task'
 5082:                                               : $responseType->{$partid}->{$responseId});
 5083: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5084: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5085: 			    $orders{$partid}->{$responseId}=
 5086: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5087:                                            $no_increment,$type,$trial,$rndseed);
 5088: 		        }
 5089: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5090: 		        $displaySub[0].='&nbsp; '.
 5091: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5092:                     }
 5093: 		}
 5094: 	    }
 5095: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5096: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5097: 				    $$record{"$where.$partid.checkedin"},
 5098: 				    $$record{"$where.$partid.checkedin.slot"}).
 5099: 					'<br />';
 5100: 	    }
 5101: 	    if (exists $$record{"$where.$partid.award"}) {
 5102: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5103: 		    lc($$record{"$where.$partid.award"}).' '.
 5104: 		    $mark{$$record{"$where.$partid.solved"}}.
 5105: 		    '<br />';
 5106: 	    }
 5107: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5108: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5109: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5110: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5111: 		$displaySub[2].=
 5112: 		    $$record{"$version:resource.$partid.regrader"}.
 5113: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5114: 	    }
 5115: 	}
 5116: 	# needed because old essay regrader has not parts info
 5117: 	if (exists $$record{"$version:resource.regrader"}) {
 5118: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5119: 	}
 5120: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5121: 	if ($displaySub[2]) {
 5122: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5123: 	}
 5124: 	$studentTable.='&nbsp;</td>'.
 5125: 	    &Apache::loncommon::end_data_table_row();
 5126:     }
 5127:     $studentTable.=&Apache::loncommon::end_data_table();
 5128:     return $studentTable;
 5129: }
 5130: 
 5131: sub updateGradeByPage {
 5132:     my ($request,$symb) = @_;
 5133: 
 5134:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5135:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5136:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5137:     my $pageTitle = $env{'form.page'};
 5138:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5139:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5140:     my $usec=$classlist->{$env{'form.student'}}[5];
 5141:     if (!&canmodify($usec)) {
 5142: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5143: 	return;
 5144:     }
 5145:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5146:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5147: 	'</h3>'."\n";
 5148: 
 5149:     $request->print($result);
 5150: 
 5151: 
 5152:     my $navmap = Apache::lonnavmaps::navmap->new();
 5153:     unless (ref($navmap)) {
 5154:         $request->print(&navmap_errormsg());
 5155:         return;
 5156:     }
 5157:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5158:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5159:     if (!$map) {
 5160: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5161: 	return; 
 5162:     }
 5163:     my $iterator = $navmap->getIterator($map->map_start(),
 5164: 					$map->map_finish());
 5165: 
 5166:     my $studentTable=
 5167: 	&Apache::loncommon::start_data_table().
 5168: 	&Apache::loncommon::start_data_table_header_row().
 5169: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5170: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5171: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5172: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5173: 	&Apache::loncommon::end_data_table_header_row();
 5174: 
 5175:     $iterator->next(); # skip the first BEGIN_MAP
 5176:     my $curRes = $iterator->next(); # for "current resource"
 5177:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5178:     while ($depth > 0) {
 5179:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5180:         if($curRes == $iterator->END_MAP) { $depth--; }
 5181: 
 5182:         if (ref($curRes) && $curRes->is_problem()) {
 5183: 	    my $parts = $curRes->parts();
 5184:             my $title = $curRes->compTitle();
 5185: 	    my $symbx = $curRes->symb();
 5186: 	    $studentTable.=
 5187: 		&Apache::loncommon::start_data_table_row().
 5188: 		'<td align="center" valign="top" >'.$prob.
 5189: 		(scalar(@{$parts}) == 1 ? '' 
 5190:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5191: 		.')').'</td>';
 5192: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5193: 
 5194: 	    my %newrecord=();
 5195: 	    my @displayPts=();
 5196:             my %aggregate = ();
 5197:             my $aggregateflag = 0;
 5198:             if ($env{'form.HIDE'.$prob}) {
 5199:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5200:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5201:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5202:                 $hideflag += $numchgs;
 5203:             }
 5204: 	    foreach my $partid (@{$parts}) {
 5205: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5206: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5207: 
 5208: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5209: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5210: 		my $partial = $newpts/$wgt;
 5211: 		my $score;
 5212: 		if ($partial > 0) {
 5213: 		    $score = 'correct_by_override';
 5214: 		} elsif ($newpts ne '') { #empty is taken as 0
 5215: 		    $score = 'incorrect_by_override';
 5216: 		}
 5217: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5218: 		if ($dropMenu eq 'excused') {
 5219: 		    $partial = '';
 5220: 		    $score = 'excused';
 5221: 		} elsif ($dropMenu eq 'reset status'
 5222: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5223: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5224: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5225: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5226: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5227: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5228: 		    $changeflag++;
 5229: 		    $newpts = '';
 5230:                     
 5231:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5232:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5233:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5234:                     if ($aggtries > 0) {
 5235:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5236:                         $aggregateflag = 1;
 5237:                     }
 5238: 		}
 5239: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5240: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5241: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5242: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5243: 		    '&nbsp;<br />';
 5244: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5245: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5246: 		    '&nbsp;<br />';
 5247: 		$question++;
 5248: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5249: 
 5250: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5251: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5252: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5253: 		    if (scalar(keys(%newrecord)) > 0);
 5254: 
 5255: 		$changeflag++;
 5256: 	    }
 5257: 	    if (scalar(keys(%newrecord)) > 0) {
 5258: 		my %record = 
 5259: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5260: 					     $udom,$uname);
 5261: 
 5262: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5263: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5264: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5265: 		    $newrecord{'resource.CODE'} = '';
 5266: 		}
 5267: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5268: 					$udom,$uname);
 5269: 		%record = &Apache::lonnet::restore($symbx,
 5270: 						   $env{'request.course.id'},
 5271: 						   $udom,$uname);
 5272: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5273: 					     $cdom,$cnum,$udom,$uname);
 5274: 	    }
 5275: 	    
 5276:             if ($aggregateflag) {
 5277:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5278:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5279:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5280:             }
 5281: 
 5282: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5283: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5284: 		&Apache::loncommon::end_data_table_row();
 5285: 
 5286: 	    $prob++;
 5287: 	}
 5288:         $curRes = $iterator->next();
 5289:     }
 5290: 
 5291:     $studentTable.=&Apache::loncommon::end_data_table();
 5292:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5293: 		  &mt('The scores were changed for [quant,_1,problem].',
 5294: 		  $changeflag).'<br />');
 5295:     my $hidemsg=($hideflag == 0 ? '' :
 5296:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5297:                      $hideflag).'<br />');
 5298:     $request->print($hidemsg.$grademsg.$studentTable);
 5299: 
 5300:     return '';
 5301: }
 5302: 
 5303: #-------- end of section for handling grading by page/sequence ---------
 5304: #
 5305: #-------------------------------------------------------------------
 5306: 
 5307: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5308: #
 5309: #------ start of section for handling grading by page/sequence ---------
 5310: 
 5311: =pod
 5312: 
 5313: =head1 Bubble sheet grading routines
 5314: 
 5315:   For this documentation:
 5316: 
 5317:    'scanline' refers to the full line of characters
 5318:    from the file that we are parsing that represents one entire sheet
 5319: 
 5320:    'bubble line' refers to the data
 5321:    representing the line of bubbles that are on the physical bubblesheet
 5322: 
 5323: 
 5324: The overall process is that a scanned in bubblesheet data is uploaded
 5325: into a course. When a user wants to grade, they select a
 5326: sequence/folder of resources, a file of bubblesheet info, and pick
 5327: one of the predefined configurations for what each scanline looks
 5328: like.
 5329: 
 5330: Next each scanline is checked for any errors of either 'missing
 5331: bubbles' (it's an error because it may have been mis-scanned
 5332: because too light bubbling), 'double bubble' (each bubble line should
 5333: have no more than one letter picked), invalid or duplicated CODE,
 5334: invalid student/employee ID
 5335: 
 5336: If the CODE option is used that determines the randomization of the
 5337: homework problems, either way the student/employee ID is looked up into a
 5338: username:domain.
 5339: 
 5340: During the validation phase the instructor can choose to skip scanlines. 
 5341: 
 5342: After the validation phase, there are now 3 bubblesheet files
 5343: 
 5344:   scantron_original_filename (unmodified original file)
 5345:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5346:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5347: 
 5348: Also there is a separate hash nohist_scantrondata that contains extra
 5349: correction information that isn't representable in the bubblesheet
 5350: file (see &scantron_getfile() for more information)
 5351: 
 5352: After all scanlines are either valid, marked as valid or skipped, then
 5353: foreach line foreach problem in the picked sequence, an ssi request is
 5354: made that simulates a user submitting their selected letter(s) against
 5355: the homework problem.
 5356: 
 5357: =over 4
 5358: 
 5359: 
 5360: 
 5361: =item defaultFormData
 5362: 
 5363:   Returns html hidden inputs used to hold context/default values.
 5364: 
 5365:  Arguments:
 5366:   $symb - $symb of the current resource 
 5367: 
 5368: =cut
 5369: 
 5370: sub defaultFormData {
 5371:     my ($symb)=@_;
 5372:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5373: }
 5374: 
 5375: 
 5376: =pod 
 5377: 
 5378: =item getSequenceDropDown
 5379: 
 5380:    Return html dropdown of possible sequences to grade
 5381:  
 5382:  Arguments:
 5383:    $symb - $symb of the current resource
 5384:    $map_error - ref to scalar which will container error if
 5385:                 $navmap object is unavailable in &getSymbMap().
 5386: 
 5387: =cut
 5388: 
 5389: sub getSequenceDropDown {
 5390:     my ($symb,$map_error)=@_;
 5391:     my $result='<select name="selectpage">'."\n";
 5392:     my ($titles,$symbx) = &getSymbMap($map_error);
 5393:     if (ref($map_error)) {
 5394:         return if ($$map_error);
 5395:     }
 5396:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5397:     my $ctr=0;
 5398:     foreach (@$titles) {
 5399: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5400: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5401: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5402: 	    '>'.$showtitle.'</option>'."\n";
 5403: 	$ctr++;
 5404:     }
 5405:     $result.= '</select>';
 5406:     return $result;
 5407: }
 5408: 
 5409: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5410:                                    # key is zero-based index - 0, 1, 2 ...
 5411: 
 5412: my %first_bubble_line;             # First bubble line no. for each bubble.
 5413: 
 5414: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5415:                                    # matchresponse or rankresponse, where 
 5416:                                    # an individual response can have multiple 
 5417:                                    # lines
 5418: 
 5419: my %responsetype_per_response;     # responsetype for each response
 5420: 
 5421: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5422:                                    # numbered response. Needed when randomorder
 5423:                                    # or randompick are in use. Key is ID, value 
 5424:                                    # is response number.
 5425: 
 5426: # Save and restore the bubble lines array to the form env.
 5427: 
 5428: 
 5429: sub save_bubble_lines {
 5430:     foreach my $line (keys(%bubble_lines_per_response)) {
 5431: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5432: 	$env{"form.scantron.first_bubble_line.$line"} =
 5433: 	    $first_bubble_line{$line};
 5434:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5435:             $subdivided_bubble_lines{$line};
 5436:         $env{"form.scantron.responsetype.$line"} =
 5437:             $responsetype_per_response{$line};
 5438:     }
 5439:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5440:         my $line = $masterseq_id_responsenum{$resid};
 5441:         $env{"form.scantron.residpart.$line"} = $resid;
 5442:     }
 5443: }
 5444: 
 5445: 
 5446: sub restore_bubble_lines {
 5447:     my $line = 0;
 5448:     %bubble_lines_per_response = ();
 5449:     %masterseq_id_responsenum = ();
 5450:     while ($env{"form.scantron.bubblelines.$line"}) {
 5451: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5452: 	$bubble_lines_per_response{$line} = $value;
 5453: 	$first_bubble_line{$line}  =
 5454: 	    $env{"form.scantron.first_bubble_line.$line"};
 5455:         $subdivided_bubble_lines{$line} =
 5456:             $env{"form.scantron.sub_bubblelines.$line"};
 5457:         $responsetype_per_response{$line} =
 5458:             $env{"form.scantron.responsetype.$line"};
 5459:         my $id = $env{"form.scantron.residpart.$line"};
 5460:         $masterseq_id_responsenum{$id} = $line;
 5461: 	$line++;
 5462:     }
 5463: }
 5464: 
 5465: =pod 
 5466: 
 5467: =item scantron_filenames
 5468: 
 5469:    Returns a list of the scantron files in the current course 
 5470: 
 5471: =cut
 5472: 
 5473: sub scantron_filenames {
 5474:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5475:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5476:     my $getpropath = 1;
 5477:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5478:                                                         $cname,$getpropath);
 5479:     my @possiblenames;
 5480:     if (ref($dirlist) eq 'ARRAY') {
 5481:         foreach my $filename (sort(@{$dirlist})) {
 5482: 	    ($filename)=split(/&/,$filename);
 5483: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5484: 	    $filename=~s/^scantron_orig_//;
 5485: 	    push(@possiblenames,$filename);
 5486:         }
 5487:     }
 5488:     return @possiblenames;
 5489: }
 5490: 
 5491: =pod 
 5492: 
 5493: =item scantron_uploads
 5494: 
 5495:    Returns  html drop-down list of scantron files in current course.
 5496: 
 5497:  Arguments:
 5498:    $file2grade - filename to set as selected in the dropdown
 5499: 
 5500: =cut
 5501: 
 5502: sub scantron_uploads {
 5503:     my ($file2grade) = @_;
 5504:     my $result=	'<select name="scantron_selectfile">';
 5505:     $result.="<option></option>";
 5506:     foreach my $filename (sort(&scantron_filenames())) {
 5507: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5508:     }
 5509:     $result.="</select>";
 5510:     return $result;
 5511: }
 5512: 
 5513: =pod 
 5514: 
 5515: =item scantron_scantab
 5516: 
 5517:   Returns html drop down of the scantron formats in the scantronformat.tab
 5518:   file.
 5519: 
 5520: =cut
 5521: 
 5522: sub scantron_scantab {
 5523:     my $result='<select name="scantron_format">'."\n";
 5524:     $result.='<option></option>'."\n";
 5525:     my @lines = &get_scantronformat_file();
 5526:     if (@lines > 0) {
 5527:         foreach my $line (@lines) {
 5528:             next if (($line =~ /^\#/) || ($line eq ''));
 5529: 	    my ($name,$descrip)=split(/:/,$line);
 5530: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5531:         }
 5532:     }
 5533:     $result.='</select>'."\n";
 5534:     return $result;
 5535: }
 5536: 
 5537: =pod
 5538: 
 5539: =item get_scantronformat_file
 5540: 
 5541:   Returns an array containing lines from the scantron format file for
 5542:   the domain of the course.
 5543: 
 5544:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5545:   lines are from this file.
 5546: 
 5547:   Otherwise, if a default.tab has been published in RES space by the 
 5548:   domainconfig user, lines are from this file.
 5549: 
 5550:   Otherwise, fall back to getting lines from the legacy file on the
 5551:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5552: 
 5553: =cut
 5554: 
 5555: sub get_scantronformat_file {
 5556:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5557:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5558:     my $gottab = 0;
 5559:     my @lines;
 5560:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5561:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5562:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5563:             if ($formatfile ne '-1') {
 5564:                 @lines = split("\n",$formatfile,-1);
 5565:                 $gottab = 1;
 5566:             }
 5567:         }
 5568:     }
 5569:     if (!$gottab) {
 5570:         my $confname = $cdom.'-domainconfig';
 5571:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5572:         my $formatfile =  &Apache::lonnet::getfile($default);
 5573:         if ($formatfile ne '-1') {
 5574:             @lines = split("\n",$formatfile,-1);
 5575:             $gottab = 1;
 5576:         }
 5577:     }
 5578:     if (!$gottab) {
 5579:         my @domains = &Apache::lonnet::current_machine_domains();
 5580:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5581:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5582:             @lines = <$fh>;
 5583:             close($fh);
 5584:         } else {
 5585:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5586:             @lines = <$fh>;
 5587:             close($fh);
 5588:         }
 5589:     }
 5590:     return @lines;
 5591: }
 5592: 
 5593: =pod 
 5594: 
 5595: =item scantron_CODElist
 5596: 
 5597:   Returns html drop down of the saved CODE lists from current course,
 5598:   generated from earlier printings.
 5599: 
 5600: =cut
 5601: 
 5602: sub scantron_CODElist {
 5603:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5604:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5605:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5606:     my $namechoice='<option></option>';
 5607:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5608: 	if ($name =~ /^error: 2 /) { next; }
 5609: 	if ($name =~ /^type\0/) { next; }
 5610: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5611:     }
 5612:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5613:     return $namechoice;
 5614: }
 5615: 
 5616: =pod 
 5617: 
 5618: =item scantron_CODEunique
 5619: 
 5620:   Returns the html for "Each CODE to be used once" radio.
 5621: 
 5622: =cut
 5623: 
 5624: sub scantron_CODEunique {
 5625:     my $result='<span class="LC_nobreak">
 5626:                  <label><input type="radio" name="scantron_CODEunique"
 5627:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5628:                 </span>
 5629:                 <span class="LC_nobreak">
 5630:                  <label><input type="radio" name="scantron_CODEunique"
 5631:                         value="no" />'.&mt('No').' </label>
 5632:                 </span>';
 5633:     return $result;
 5634: }
 5635: 
 5636: =pod 
 5637: 
 5638: =item scantron_selectphase
 5639: 
 5640:   Generates the initial screen to start the bubblesheet process.
 5641:   Allows for - starting a grading run.
 5642:              - downloading existing scan data (original, corrected
 5643:                                                 or skipped info)
 5644: 
 5645:              - uploading new scan data
 5646: 
 5647:  Arguments:
 5648:   $r          - The Apache request object
 5649:   $file2grade - name of the file that contain the scanned data to score
 5650: 
 5651: =cut
 5652: 
 5653: sub scantron_selectphase {
 5654:     my ($r,$file2grade,$symb) = @_;
 5655:     if (!$symb) {return '';}
 5656:     my $map_error;
 5657:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5658:     if ($map_error) {
 5659:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5660:         return;
 5661:     }
 5662:     my $default_form_data=&defaultFormData($symb);
 5663:     my $file_selector=&scantron_uploads($file2grade);
 5664:     my $format_selector=&scantron_scantab();
 5665:     my $CODE_selector=&scantron_CODElist();
 5666:     my $CODE_unique=&scantron_CODEunique();
 5667:     my $result;
 5668: 
 5669:     $ssi_error = 0;
 5670: 
 5671:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5672:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5673: 
 5674: 	# Chunk of form to prompt for a scantron file upload.
 5675: 
 5676:         $r->print('
 5677:     <br />
 5678:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5679:        '.&Apache::loncommon::start_data_table_header_row().'
 5680:             <th>
 5681:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5682:             </th>
 5683:        '.&Apache::loncommon::end_data_table_header_row().'
 5684:        '.&Apache::loncommon::start_data_table_row().'
 5685:             <td>
 5686: ');
 5687:     my $default_form_data=&defaultFormData($symb);
 5688:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5689:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5690:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5691:     &js_escape(\$alertmsg);
 5692:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5693:     function checkUpload(formname) {
 5694: 	if (formname.upfile.value == "") {
 5695: 	    alert("'.$alertmsg.'");
 5696: 	    return false;
 5697: 	}
 5698: 	formname.submit();
 5699:     }'));
 5700:     $r->print('
 5701:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5702:                 '.$default_form_data.'
 5703:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5704:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5705:                 <input name="command" value="scantronupload_save" type="hidden" />
 5706:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5707:                 <br />
 5708:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5709:               </form>
 5710: ');
 5711: 
 5712:         $r->print('
 5713:             </td>
 5714:        '.&Apache::loncommon::end_data_table_row().'
 5715:        '.&Apache::loncommon::end_data_table().'
 5716: ');
 5717:     }
 5718: 
 5719:     # Chunk of form to prompt for a file to grade and how:
 5720: 
 5721:     $result.= '
 5722:     <br />
 5723:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5724:     <input type="hidden" name="command" value="scantron_warning" />
 5725:     '.$default_form_data.'
 5726:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5727:        '.&Apache::loncommon::start_data_table_header_row().'
 5728:             <th colspan="2">
 5729:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5730:             </th>
 5731:        '.&Apache::loncommon::end_data_table_header_row().'
 5732:        '.&Apache::loncommon::start_data_table_row().'
 5733:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5734:        '.&Apache::loncommon::end_data_table_row().'
 5735:        '.&Apache::loncommon::start_data_table_row().'
 5736:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5737:        '.&Apache::loncommon::end_data_table_row().'
 5738:        '.&Apache::loncommon::start_data_table_row().'
 5739:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5740:        '.&Apache::loncommon::end_data_table_row().'
 5741:        '.&Apache::loncommon::start_data_table_row().'
 5742:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5743:        '.&Apache::loncommon::end_data_table_row().'
 5744:        '.&Apache::loncommon::start_data_table_row().'
 5745:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5746:        '.&Apache::loncommon::end_data_table_row().'
 5747:        '.&Apache::loncommon::start_data_table_row().'
 5748: 	    <td> '.&mt('Options:').' </td>
 5749:             <td>
 5750: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5751:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5752:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5753: 	    </td>
 5754:        '.&Apache::loncommon::end_data_table_row().'
 5755:        '.&Apache::loncommon::start_data_table_row().'
 5756:             <td colspan="2">
 5757:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5758:             </td>
 5759:        '.&Apache::loncommon::end_data_table_row().'
 5760:     '.&Apache::loncommon::end_data_table().'
 5761:     </form>
 5762: ';
 5763:    
 5764:     $r->print($result);
 5765: 
 5766: 
 5767: 
 5768:     # Chunk of the form that prompts to view a scoring office file,
 5769:     # corrected file, skipped records in a file.
 5770: 
 5771:     $r->print('
 5772:    <br />
 5773:    <form action="/adm/grades" name="scantron_download">
 5774:      '.$default_form_data.'
 5775:      <input type="hidden" name="command" value="scantron_download" />
 5776:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5777:        '.&Apache::loncommon::start_data_table_header_row().'
 5778:               <th>
 5779:                 &nbsp;'.&mt('Download a scoring office file').'
 5780:               </th>
 5781:        '.&Apache::loncommon::end_data_table_header_row().'
 5782:        '.&Apache::loncommon::start_data_table_row().'
 5783:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5784:                 <br />
 5785:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5786:        '.&Apache::loncommon::end_data_table_row().'
 5787:      '.&Apache::loncommon::end_data_table().'
 5788:    </form>
 5789:    <br />
 5790: ');
 5791: 
 5792:     &Apache::lonpickcode::code_list($r,2);
 5793: 
 5794:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5795:              $default_form_data."\n".
 5796:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5797:              &Apache::loncommon::start_data_table_header_row()."\n".
 5798:              '<th colspan="2">
 5799:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5800:              '</th>'."\n".
 5801:               &Apache::loncommon::end_data_table_header_row()."\n".
 5802:               &Apache::loncommon::start_data_table_row()."\n".
 5803:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5804:               '<td> '.$sequence_selector.' </td>'.
 5805:               &Apache::loncommon::end_data_table_row()."\n".
 5806:               &Apache::loncommon::start_data_table_row()."\n".
 5807:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5808:               '<td> '.$file_selector.' </td>'."\n".
 5809:               &Apache::loncommon::end_data_table_row()."\n".
 5810:               &Apache::loncommon::start_data_table_row()."\n".
 5811:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5812:               '<td> '.$format_selector.' </td>'."\n".
 5813:               &Apache::loncommon::end_data_table_row()."\n".
 5814:               &Apache::loncommon::start_data_table_row()."\n".
 5815:               '<td> '.&mt('Options').' </td>'."\n".
 5816:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5817:               &Apache::loncommon::end_data_table_row()."\n".
 5818:               &Apache::loncommon::start_data_table_row()."\n".
 5819:               '<td colspan="2">'."\n".
 5820:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5821:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5822:               '</td>'."\n".
 5823:               &Apache::loncommon::end_data_table_row()."\n".
 5824:               &Apache::loncommon::end_data_table()."\n".
 5825:               '</form><br />');
 5826:     return;
 5827: }
 5828: 
 5829: =pod
 5830: 
 5831: =item get_scantron_config
 5832: 
 5833:    Parse and return the bubblesheet configuration line selected as a
 5834:    hash of configuration file fields.
 5835: 
 5836:  Arguments:
 5837:     which - the name of the configuration to parse from the file.
 5838: 
 5839: 
 5840:  Returns:
 5841:             If the named configuration is not in the file, an empty
 5842:             hash is returned.
 5843:     a hash with the fields
 5844:       name         - internal name for the this configuration setup
 5845:       description  - text to display to operator that describes this config
 5846:       CODElocation - if 0 or the string 'none'
 5847:                           - no CODE exists for this config
 5848:                      if -1 || the string 'letter'
 5849:                           - a CODE exists for this config and is
 5850:                             a string of letters
 5851:                      Unsupported value (but planned for future support)
 5852:                           if a positive integer
 5853:                                - The CODE exists as the first n items from
 5854:                                  the question section of the form
 5855:                           if the string 'number'
 5856:                                - The CODE exists for this config and is
 5857:                                  a string of numbers
 5858:       CODEstart   - (only matter if a CODE exists) column in the line where
 5859:                      the CODE starts
 5860:       CODElength  - length of the CODE
 5861:       IDstart     - column where the student/employee ID starts
 5862:       IDlength    - length of the student/employee ID info
 5863:       Qstart      - column where the information from the bubbled
 5864:                     'questions' start
 5865:       Qlength     - number of columns comprising a single bubble line from
 5866:                     the sheet. (usually either 1 or 10)
 5867:       Qon         - either a single character representing the character used
 5868:                     to signal a bubble was chosen in the positional setup, or
 5869:                     the string 'letter' if the letter of the chosen bubble is
 5870:                     in the final, or 'number' if a number representing the
 5871:                     chosen bubble is in the file (1->A 0->J)
 5872:       Qoff        - the character used to represent that a bubble was
 5873:                     left blank
 5874:       PaperID     - if the scanning process generates a unique number for each
 5875:                     sheet scanned the column that this ID number starts in
 5876:       PaperIDlength - number of columns that comprise the unique ID number
 5877:                       for the sheet of paper
 5878:       FirstName   - column that the first name starts in
 5879:       FirstNameLength - number of columns that the first name spans
 5880:  
 5881:       LastName    - column that the last name starts in
 5882:       LastNameLength - number of columns that the last name spans
 5883:       BubblesPerRow - number of bubbles available in each row used to 
 5884:                       bubble an answer. (If not specified, 10 assumed).
 5885: 
 5886: =cut
 5887: 
 5888: sub get_scantron_config {
 5889:     my ($which) = @_;
 5890:     my @lines = &get_scantronformat_file();
 5891:     my %config;
 5892:     #FIXME probably should move to XML it has already gotten a bit much now
 5893:     foreach my $line (@lines) {
 5894: 	my ($name,$descrip)=split(/:/,$line);
 5895: 	if ($name ne $which ) { next; }
 5896: 	chomp($line);
 5897: 	my @config=split(/:/,$line);
 5898: 	$config{'name'}=$config[0];
 5899: 	$config{'description'}=$config[1];
 5900: 	$config{'CODElocation'}=$config[2];
 5901: 	$config{'CODEstart'}=$config[3];
 5902: 	$config{'CODElength'}=$config[4];
 5903: 	$config{'IDstart'}=$config[5];
 5904: 	$config{'IDlength'}=$config[6];
 5905: 	$config{'Qstart'}=$config[7];
 5906:  	$config{'Qlength'}=$config[8];
 5907: 	$config{'Qoff'}=$config[9];
 5908: 	$config{'Qon'}=$config[10];
 5909: 	$config{'PaperID'}=$config[11];
 5910: 	$config{'PaperIDlength'}=$config[12];
 5911: 	$config{'FirstName'}=$config[13];
 5912: 	$config{'FirstNamelength'}=$config[14];
 5913: 	$config{'LastName'}=$config[15];
 5914: 	$config{'LastNamelength'}=$config[16];
 5915:         $config{'BubblesPerRow'}=$config[17];
 5916: 	last;
 5917:     }
 5918:     return %config;
 5919: }
 5920: 
 5921: =pod 
 5922: 
 5923: =item username_to_idmap
 5924: 
 5925:     creates a hash keyed by student/employee ID with values of the corresponding
 5926:     student username:domain. If a single ID occurs for more than one student,
 5927:     the status of the student is checked, and if Active, the value in the hash
 5928:     will be set to the Active student.
 5929: 
 5930:   Arguments:
 5931: 
 5932:     $classlist - reference to the class list hash. This is a hash
 5933:                  keyed by student name:domain  whose elements are references
 5934:                  to arrays containing various chunks of information
 5935:                  about the student. (See loncoursedata for more info).
 5936: 
 5937:   Returns
 5938:     %idmap - the constructed hash
 5939: 
 5940: =cut
 5941: 
 5942: sub username_to_idmap {
 5943:     my ($classlist)= @_;
 5944:     my %idmap;
 5945:     foreach my $student (keys(%$classlist)) {
 5946:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 5947:         unless ($id eq '') {
 5948:             if (!exists($idmap{$id})) {
 5949:                 $idmap{$id} = $student;
 5950:             } else {
 5951:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 5952:                 if ($status eq 'Active') {
 5953:                     $idmap{$id} = $student;
 5954:                 }
 5955:             }
 5956:         }
 5957:     }
 5958:     return %idmap;
 5959: }
 5960: 
 5961: =pod
 5962: 
 5963: =item scantron_fixup_scanline
 5964: 
 5965:    Process a requested correction to a scanline.
 5966: 
 5967:   Arguments:
 5968:     $scantron_config   - hash from &get_scantron_config()
 5969:     $scan_data         - hash of correction information 
 5970:                           (see &scantron_getfile())
 5971:     $line              - existing scanline
 5972:     $whichline         - line number of the passed in scanline
 5973:     $field             - type of change to process 
 5974:                          (either 
 5975:                           'ID'     -> correct the student/employee ID
 5976:                           'CODE'   -> correct the CODE
 5977:                           'answer' -> fixup the submitted answers)
 5978:     
 5979:    $args               - hash of additional info,
 5980:                           - 'ID' 
 5981:                                'newid' -> studentID to use in replacement
 5982:                                           of existing one
 5983:                           - 'CODE' 
 5984:                                'CODE_ignore_dup' - set to true if duplicates
 5985:                                                    should be ignored.
 5986: 	                       'CODE' - is new code or 'use_unfound'
 5987:                                         if the existing unfound code should
 5988:                                         be used as is
 5989:                           - 'answer'
 5990:                                'response' - new answer or 'none' if blank
 5991:                                'question' - the bubble line to change
 5992:                                'questionnum' - the question identifier,
 5993:                                                may include subquestion. 
 5994: 
 5995:   Returns:
 5996:     $line - the modified scanline
 5997: 
 5998:   Side effects: 
 5999:     $scan_data - may be updated
 6000: 
 6001: =cut
 6002: 
 6003: 
 6004: sub scantron_fixup_scanline {
 6005:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6006:     if ($field eq 'ID') {
 6007: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6008: 	    return ($line,1,'New value too large');
 6009: 	}
 6010: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6011: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6012: 				     $args->{'newid'});
 6013: 	}
 6014: 	substr($line,$$scantron_config{'IDstart'}-1,
 6015: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6016: 	if ($args->{'newid'}=~/^\s*$/) {
 6017: 	    &scan_data($scan_data,"$whichline.user",
 6018: 		       $args->{'username'}.':'.$args->{'domain'});
 6019: 	}
 6020:     } elsif ($field eq 'CODE') {
 6021: 	if ($args->{'CODE_ignore_dup'}) {
 6022: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6023: 	}
 6024: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6025: 	if ($args->{'CODE'} ne 'use_unfound') {
 6026: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6027: 		return ($line,1,'New CODE value too large');
 6028: 	    }
 6029: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6030: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6031: 	    }
 6032: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6033: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6034: 	}
 6035:     } elsif ($field eq 'answer') {
 6036: 	my $length=$scantron_config->{'Qlength'};
 6037: 	my $off=$scantron_config->{'Qoff'};
 6038: 	my $on=$scantron_config->{'Qon'};
 6039: 	my $answer=${off}x$length;
 6040: 	if ($args->{'response'} eq 'none') {
 6041: 	    &scan_data($scan_data,
 6042: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6043: 	} else {
 6044: 	    if ($on eq 'letter') {
 6045: 		my @alphabet=('A'..'Z');
 6046: 		$answer=$alphabet[$args->{'response'}];
 6047: 	    } elsif ($on eq 'number') {
 6048: 		$answer=$args->{'response'}+1;
 6049: 		if ($answer == 10) { $answer = '0'; }
 6050: 	    } else {
 6051: 		substr($answer,$args->{'response'},1)=$on;
 6052: 	    }
 6053: 	    &scan_data($scan_data,
 6054: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6055: 	}
 6056: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6057: 	substr($line,$where-1,$length)=$answer;
 6058:     }
 6059:     return $line;
 6060: }
 6061: 
 6062: =pod
 6063: 
 6064: =item scan_data
 6065: 
 6066:     Edit or look up  an item in the scan_data hash.
 6067: 
 6068:   Arguments:
 6069:     $scan_data  - The hash (see scantron_getfile)
 6070:     $key        - shorthand of the key to edit (actual key is
 6071:                   scantronfilename_key).
 6072:     $data        - New value of the hash entry.
 6073:     $delete      - If true, the entry is removed from the hash.
 6074: 
 6075:   Returns:
 6076:     The new value of the hash table field (undefined if deleted).
 6077: 
 6078: =cut
 6079: 
 6080: 
 6081: sub scan_data {
 6082:     my ($scan_data,$key,$value,$delete)=@_;
 6083:     my $filename=$env{'form.scantron_selectfile'};
 6084:     if (defined($value)) {
 6085: 	$scan_data->{$filename.'_'.$key} = $value;
 6086:     }
 6087:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6088:     return $scan_data->{$filename.'_'.$key};
 6089: }
 6090: 
 6091: # ----- These first few routines are general use routines.----
 6092: 
 6093: # Return the number of occurences of a pattern in a string.
 6094: 
 6095: sub occurence_count {
 6096:     my ($string, $pattern) = @_;
 6097: 
 6098:     my @matches = ($string =~ /$pattern/g);
 6099: 
 6100:     return scalar(@matches);
 6101: }
 6102: 
 6103: 
 6104: # Take a string known to have digits and convert all the
 6105: # digits into letters in the range J,A..I.
 6106: 
 6107: sub digits_to_letters {
 6108:     my ($input) = @_;
 6109: 
 6110:     my @alphabet = ('J', 'A'..'I');
 6111: 
 6112:     my @input    = split(//, $input);
 6113:     my $output ='';
 6114:     for (my $i = 0; $i < scalar(@input); $i++) {
 6115: 	if ($input[$i] =~ /\d/) {
 6116: 	    $output .= $alphabet[$input[$i]];
 6117: 	} else {
 6118: 	    $output .= $input[$i];
 6119: 	}
 6120:     }
 6121:     return $output;
 6122: }
 6123: 
 6124: =pod 
 6125: 
 6126: =item scantron_parse_scanline
 6127: 
 6128:   Decodes a scanline from the selected bubblesheet file
 6129: 
 6130:  Arguments:
 6131:     line             - The text of the bubblesheet file line to process
 6132:     whichline        - Line number
 6133:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6134:     scan_data        - Hash of extra information about the scanline
 6135:                        (see scantron_getfile for more information)
 6136:     just_header      - True if should not process question answers but only
 6137:                        the stuff to the left of the answers.
 6138:     randomorder      - True if randomorder in use
 6139:     randompick       - True if randompick in use
 6140:     sequence         - Exam folder URL
 6141:     master_seq       - Ref to array containing symbs in exam folder
 6142:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6143:                        (corresponding values are resource objects)
 6144:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6145:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6146:                        are refs to an array of resource objects, ordered
 6147:                        according to order used for CODE, when randomorder
 6148:                        and or randompick are in use.
 6149:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6150:                        for current line to question number used for same question
 6151:                         in "Master Sequence" (as seen by Course Coordinator).
 6152:     startline        - Ref to hash where key is question number (0 is first)
 6153:                        and value is number of first bubble line for current 
 6154:                        student or code-based randompick and/or randomorder.
 6155:     totalref         - Ref of scalar used to score total number of bubble
 6156:                        lines needed for responses in a scan line (used when
 6157:                        randompick in use. 
 6158:     
 6159:  Returns:
 6160:    Hash containing the result of parsing the scanline
 6161: 
 6162:    Keys are all proceeded by the string 'scantron.'
 6163: 
 6164:        CODE    - the CODE in use for this scanline
 6165:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6166:                  by the operator
 6167:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6168:                             CODEs were selected, but the usage has been
 6169:                             forced by the operator
 6170:        ID  - student/employee ID
 6171:        PaperID - if used, the ID number printed on the sheet when the 
 6172:                  paper was scanned
 6173:        FirstName - first name from the sheet
 6174:        LastName  - last name from the sheet
 6175: 
 6176:      if just_header was not true these key may also exist
 6177: 
 6178:        missingerror - a list of bubble ranges that are considered to be answers
 6179:                       to a single question that don't have any bubbles filled in.
 6180:                       Of the form questionnumber:firstbubblenumber:count.
 6181:        doubleerror  - a list of bubble ranges that are considered to be answers
 6182:                       to a single question that have more than one bubble filled in.
 6183:                       Of the form questionnumber::firstbubblenumber:count
 6184:    
 6185:                 In the above, count is the number of bubble responses in the
 6186:                 input line needed to represent the possible answers to the question.
 6187:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6188:                 per line would have count = 2.
 6189: 
 6190:        maxquest     - the number of the last bubble line that was parsed
 6191: 
 6192:        (<number> starts at 1)
 6193:        <number>.answer - zero or more letters representing the selected
 6194:                          letters from the scanline for the bubble line 
 6195:                          <number>.
 6196:                          if blank there was either no bubble or there where
 6197:                          multiple bubbles, (consult the keys missingerror and
 6198:                          doubleerror if this is an error condition)
 6199: 
 6200: =cut
 6201: 
 6202: sub scantron_parse_scanline {
 6203:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6204:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6205:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6206: 
 6207:     my %record;
 6208:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6209:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6210: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6211: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6212: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6213: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6214: 	    $record{'scantron.CODE'}=substr($data,
 6215: 					    $$scantron_config{'CODEstart'}-1,
 6216: 					    $$scantron_config{'CODElength'});
 6217: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6218: 		$record{'scantron.useCODE'}=1;
 6219: 	    }
 6220: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6221: 		$record{'scantron.CODE_ignore_dup'}=1;
 6222: 	    }
 6223: 	} else {
 6224: 	    #FIXME interpret first N questions
 6225: 	}
 6226:     }
 6227:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6228: 				  $$scantron_config{'IDlength'});
 6229:     $record{'scantron.PaperID'}=
 6230: 	substr($data,$$scantron_config{'PaperID'}-1,
 6231: 	       $$scantron_config{'PaperIDlength'});
 6232:     $record{'scantron.FirstName'}=
 6233: 	substr($data,$$scantron_config{'FirstName'}-1,
 6234: 	       $$scantron_config{'FirstNamelength'});
 6235:     $record{'scantron.LastName'}=
 6236: 	substr($data,$$scantron_config{'LastName'}-1,
 6237: 	       $$scantron_config{'LastNamelength'});
 6238:     if ($just_header) { return \%record; }
 6239: 
 6240:     my @alphabet=('A'..'Z');
 6241:     my $questnum=0;
 6242:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6243: 
 6244:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6245:     if ($randompick || $randomorder) {
 6246:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6247:                                          $master_seq,$symb_to_resource,
 6248:                                          $partids_by_symb,$orderedforcode,
 6249:                                          $respnumlookup,$startline);
 6250:         if ($total) {
 6251:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6252:         }
 6253:         if (ref($totalref)) {
 6254:             $$totalref = $total;
 6255:         }
 6256:     }
 6257:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6258:     chomp($questions);		# Get rid of any trailing \n.
 6259:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6260:     while (length($questions)) {
 6261:         my $answers_needed;
 6262:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6263:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6264:         } else {
 6265: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6266:         }
 6267:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6268:                              || 1;
 6269:         $questnum++;
 6270:         my $quest_id = $questnum;
 6271:         my $currentquest = substr($questions,0,$answer_length);
 6272:         $questions       = substr($questions,$answer_length);
 6273:         if (length($currentquest) < $answer_length) { next; }
 6274: 
 6275:         my $subdivided;
 6276:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6277:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6278:         } else {
 6279:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6280:         }
 6281:         if ($subdivided =~ /,/) {
 6282:             my $subquestnum = 1;
 6283:             my $subquestions = $currentquest;
 6284:             my @subanswers_needed = split(/,/,$subdivided);
 6285:             foreach my $subans (@subanswers_needed) {
 6286:                 my $subans_length =
 6287:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6288:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6289:                 $subquestions   = substr($subquestions,$subans_length);
 6290:                 $quest_id = "$questnum.$subquestnum";
 6291:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6292:                     ($$scantron_config{'Qon'} eq 'number')) {
 6293:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6294:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6295:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6296:                         $randomorder,$randompick,$respnumlookup);
 6297:                 } else {
 6298:                     $ansnum = &scantron_validator_positional($ansnum,
 6299:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6300:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6301:                         $randomorder,$randompick,$respnumlookup);
 6302:                 }
 6303:                 $subquestnum ++;
 6304:             }
 6305:         } else {
 6306:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6307:                 ($$scantron_config{'Qon'} eq 'number')) {
 6308:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6309:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6310:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6311:                     $randomorder,$randompick,$respnumlookup);
 6312:             } else {
 6313:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6314:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6315:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6316:                     $randomorder,$randompick,$respnumlookup);
 6317:             }
 6318:         }
 6319:     }
 6320:     $record{'scantron.maxquest'}=$questnum;
 6321:     return \%record;
 6322: }
 6323: 
 6324: sub get_master_seq {
 6325:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6326:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6327:                    (ref($symb_to_resource) eq 'HASH'));
 6328:     my $resource_error;
 6329:     foreach my $resource (@{$resources}) {
 6330:         my $ressymb;
 6331:         if (ref($resource)) {
 6332:             $ressymb = $resource->symb();
 6333:             push(@{$master_seq},$ressymb);
 6334:             $symb_to_resource->{$ressymb} = $resource;
 6335:         } else {
 6336:             $resource_error = 1;
 6337:             last;
 6338:         }
 6339:     }
 6340:     return $resource_error;
 6341: }
 6342: 
 6343: sub get_respnum_lookups {
 6344:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6345:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6346:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6347:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6348:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6349:                    (ref($startline) eq 'HASH'));
 6350:     my ($user,$scancode);
 6351:     if ((exists($record->{'scantron.CODE'})) &&
 6352:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6353:         $scancode = $record->{'scantron.CODE'};
 6354:     } else {
 6355:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6356:     }
 6357:     my @mapresources =
 6358:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6359:                      $orderedforcode);
 6360:     my $total = 0;
 6361:     my $count = 0;
 6362:     foreach my $resource (@mapresources) {
 6363:         my $id = $resource->id();
 6364:         my $symb = $resource->symb();
 6365:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6366:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6367:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6368:                 if ($respnum ne '') {
 6369:                     $respnumlookup->{$count} = $respnum;
 6370:                     $startline->{$count} = $total;
 6371:                     $total += $bubble_lines_per_response{$respnum};
 6372:                     $count ++;
 6373:                 }
 6374:             }
 6375:         }
 6376:     }
 6377:     return $total;
 6378: }
 6379: 
 6380: sub scantron_validator_lettnum {
 6381:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6382:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6383:         $randompick,$respnumlookup) = @_;
 6384: 
 6385:     # Qon 'letter' implies for each slot in currquest we have:
 6386:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6387:     #    about anything else (esp. a value of Qoff) for missing
 6388:     #    bubbles.
 6389:     #
 6390:     # Qon 'number' implies each slot gives a digit that indexes the
 6391:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6392:     #    and * or ? for double bubbles on a single line.
 6393:     #
 6394: 
 6395:     my $matchon;
 6396:     if ($$scantron_config{'Qon'} eq 'letter') {
 6397:         $matchon = '[A-Z]';
 6398:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6399:         $matchon = '\d';
 6400:     }
 6401:     my $occurrences = 0;
 6402:     my $responsenum = $questnum-1;
 6403:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6404:        $responsenum = $respnumlookup->{$questnum-1} 
 6405:     }
 6406:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6407:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6408:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6409:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6410:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6411:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6412:         my @singlelines = split('',$currquest);
 6413:         foreach my $entry (@singlelines) {
 6414:             $occurrences = &occurence_count($entry,$matchon);
 6415:             if ($occurrences > 1) {
 6416:                 last;
 6417:             }
 6418:         }
 6419:     } else {
 6420:         $occurrences = &occurence_count($currquest,$matchon); 
 6421:     }
 6422:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6423:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6424:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6425:             my $bubble = substr($currquest,$ans,1);
 6426:             if ($bubble =~ /$matchon/ ) {
 6427:                 if ($$scantron_config{'Qon'} eq 'number') {
 6428:                     if ($bubble == 0) {
 6429:                         $bubble = 10; 
 6430:                     }
 6431:                     $record->{"scantron.$ansnum.answer"} = 
 6432:                         $alphabet->[$bubble-1];
 6433:                 } else {
 6434:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6435:                 }
 6436:             } else {
 6437:                 $record->{"scantron.$ansnum.answer"}='';
 6438:             }
 6439:             $ansnum++;
 6440:         }
 6441:     } elsif (!defined($currquest)
 6442:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6443:             || (&occurence_count($currquest,$matchon) == 0)) {
 6444:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6445:             $record->{"scantron.$ansnum.answer"}='';
 6446:             $ansnum++;
 6447:         }
 6448:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6449:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6450:         }
 6451:     } else {
 6452:         if ($$scantron_config{'Qon'} eq 'number') {
 6453:             $currquest = &digits_to_letters($currquest);            
 6454:         }
 6455:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6456:             my $bubble = substr($currquest,$ans,1);
 6457:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6458:             $ansnum++;
 6459:         }
 6460:     }
 6461:     return $ansnum;
 6462: }
 6463: 
 6464: sub scantron_validator_positional {
 6465:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6466:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6467:         $randomorder,$randompick,$respnumlookup) = @_;
 6468: 
 6469:     # Otherwise there's a positional notation;
 6470:     # each bubble line requires Qlength items, and there are filled in
 6471:     # bubbles for each case where there 'Qon' characters.
 6472:     #
 6473: 
 6474:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6475: 
 6476:     # If the split only gives us one element.. the full length of the
 6477:     # answer string, no bubbles are filled in:
 6478: 
 6479:     if ($answers_needed eq '') {
 6480:         return;
 6481:     }
 6482: 
 6483:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6484:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6485:             $record->{"scantron.$ansnum.answer"}='';
 6486:             $ansnum++;
 6487:         }
 6488:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6489:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6490:         }
 6491:     } elsif (scalar(@array) == 2) {
 6492:         my $location = length($array[0]);
 6493:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6494:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6495:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6496:             if ($ans eq $line_num) {
 6497:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6498:             } else {
 6499:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6500:             }
 6501:             $ansnum++;
 6502:          }
 6503:     } else {
 6504:         #  If there's more than one instance of a bubble character
 6505:         #  That's a double bubble; with positional notation we can
 6506:         #  record all the bubbles filled in as well as the
 6507:         #  fact this response consists of multiple bubbles.
 6508:         #
 6509:         my $responsenum = $questnum-1;
 6510:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6511:             $responsenum = $respnumlookup->{$questnum-1}
 6512:         }
 6513:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6514:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6515:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6516:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6517:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6518:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6519:             my $doubleerror = 0;
 6520:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6521:                    (!$doubleerror)) {
 6522:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6523:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6524:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6525:                if (length(@currarray) > 2) {
 6526:                    $doubleerror = 1;
 6527:                } 
 6528:             }
 6529:             if ($doubleerror) {
 6530:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6531:             }
 6532:         } else {
 6533:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6534:         }
 6535:         my $item = $ansnum;
 6536:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6537:             $record->{"scantron.$item.answer"} = '';
 6538:             $item ++;
 6539:         }
 6540: 
 6541:         my @ans=@array;
 6542:         my $i=0;
 6543:         my $increment = 0;
 6544:         while ($#ans) {
 6545:             $i+=length($ans[0]) + $increment;
 6546:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6547:             my $bubble = $i%$$scantron_config{'Qlength'};
 6548:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6549:             shift(@ans);
 6550:             $increment = 1;
 6551:         }
 6552:         $ansnum += $answers_needed;
 6553:     }
 6554:     return $ansnum;
 6555: }
 6556: 
 6557: =pod
 6558: 
 6559: =item scantron_add_delay
 6560: 
 6561:    Adds an error message that occurred during the grading phase to a
 6562:    queue of messages to be shown after grading pass is complete
 6563: 
 6564:  Arguments:
 6565:    $delayqueue  - arrary ref of hash ref of error messages
 6566:    $scanline    - the scanline that caused the error
 6567:    $errormesage - the error message
 6568:    $errorcode   - a numeric code for the error
 6569: 
 6570:  Side Effects:
 6571:    updates the $delayqueue to have a new hash ref of the error
 6572: 
 6573: =cut
 6574: 
 6575: sub scantron_add_delay {
 6576:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6577:     push(@$delayqueue,
 6578: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6579: 	  'ecode' => $errorcode }
 6580: 	 );
 6581: }
 6582: 
 6583: =pod
 6584: 
 6585: =item scantron_find_student
 6586: 
 6587:    Finds the username for the current scanline
 6588: 
 6589:   Arguments:
 6590:    $scantron_record - hash result from scantron_parse_scanline
 6591:    $scan_data       - hash of correction information 
 6592:                       (see &scantron_getfile() form more information)
 6593:    $idmap           - hash from &username_to_idmap()
 6594:    $line            - number of current scanline
 6595:  
 6596:   Returns:
 6597:    Either 'username:domain' or undef if unknown
 6598: 
 6599: =cut
 6600: 
 6601: sub scantron_find_student {
 6602:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6603:     my $scanID=$$scantron_record{'scantron.ID'};
 6604:     if ($scanID =~ /^\s*$/) {
 6605:  	return &scan_data($scan_data,"$line.user");
 6606:     }
 6607:     foreach my $id (keys(%$idmap)) {
 6608:  	if (lc($id) eq lc($scanID)) {
 6609:  	    return $$idmap{$id};
 6610:  	}
 6611:     }
 6612:     return undef;
 6613: }
 6614: 
 6615: =pod
 6616: 
 6617: =item scantron_filter
 6618: 
 6619:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6620:    hidden resources was selected
 6621: 
 6622: =cut
 6623: 
 6624: sub scantron_filter {
 6625:     my ($curres)=@_;
 6626: 
 6627:     if (ref($curres) && $curres->is_problem()) {
 6628: 	# if the user has asked to not have either hidden
 6629: 	# or 'randomout' controlled resources to be graded
 6630: 	# don't include them
 6631: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6632: 	    && $curres->randomout) {
 6633: 	    return 0;
 6634: 	}
 6635: 	return 1;
 6636:     }
 6637:     return 0;
 6638: }
 6639: 
 6640: =pod
 6641: 
 6642: =item scantron_process_corrections
 6643: 
 6644:    Gets correction information out of submitted form data and corrects
 6645:    the scanline
 6646: 
 6647: =cut
 6648: 
 6649: sub scantron_process_corrections {
 6650:     my ($r) = @_;
 6651:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6652:     my ($scanlines,$scan_data)=&scantron_getfile();
 6653:     my $classlist=&Apache::loncoursedata::get_classlist();
 6654:     my $which=$env{'form.scantron_line'};
 6655:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6656:     my ($skip,$err,$errmsg);
 6657:     if ($env{'form.scantron_skip_record'}) {
 6658: 	$skip=1;
 6659:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6660: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6661: 	    $env{'form.scantron_domain'};
 6662: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6663: 	($line,$err,$errmsg)=
 6664: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6665: 				     'ID',{'newid'=>$newid,
 6666: 				    'username'=>$env{'form.scantron_username'},
 6667: 				    'domain'=>$env{'form.scantron_domain'}});
 6668:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6669: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6670: 	my $newCODE;
 6671: 	my %args;
 6672: 	if      ($resolution eq 'use_unfound') {
 6673: 	    $newCODE='use_unfound';
 6674: 	} elsif ($resolution eq 'use_found') {
 6675: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6676: 	} elsif ($resolution eq 'use_typed') {
 6677: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6678: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6679: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6680: 	}
 6681: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6682: 	    $args{'CODE_ignore_dup'}=1;
 6683: 	}
 6684: 	$args{'CODE'}=$newCODE;
 6685: 	($line,$err,$errmsg)=
 6686: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6687: 				     'CODE',\%args);
 6688:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6689: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6690: 	    ($line,$err,$errmsg)=
 6691: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6692: 					 $which,'answer',
 6693: 					 { 'question'=>$question,
 6694: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6695:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6696: 	    if ($err) { last; }
 6697: 	}
 6698:     }
 6699:     if ($err) {
 6700:         $r->print(
 6701:             '<p class="LC_error">'
 6702:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6703:                 $errmsg)
 6704:            .'</p>');
 6705:     } else {
 6706: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6707: 	&scantron_putfile($scanlines,$scan_data);
 6708:     }
 6709: }
 6710: 
 6711: =pod
 6712: 
 6713: =item reset_skipping_status
 6714: 
 6715:    Forgets the current set of remember skipped scanlines (and thus
 6716:    reverts back to considering all lines in the
 6717:    scantron_skipped_<filename> file)
 6718: 
 6719: =cut
 6720: 
 6721: sub reset_skipping_status {
 6722:     my ($scanlines,$scan_data)=&scantron_getfile();
 6723:     &scan_data($scan_data,'remember_skipping',undef,1);
 6724:     &scantron_putfile(undef,$scan_data);
 6725: }
 6726: 
 6727: =pod
 6728: 
 6729: =item start_skipping
 6730: 
 6731:    Marks a scanline to be skipped. 
 6732: 
 6733: =cut
 6734: 
 6735: sub start_skipping {
 6736:     my ($scan_data,$i)=@_;
 6737:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6738:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6739: 	$remembered{$i}=2;
 6740:     } else {
 6741: 	$remembered{$i}=1;
 6742:     }
 6743:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6744: }
 6745: 
 6746: =pod
 6747: 
 6748: =item should_be_skipped
 6749: 
 6750:    Checks whether a scanline should be skipped.
 6751: 
 6752: =cut
 6753: 
 6754: sub should_be_skipped {
 6755:     my ($scanlines,$scan_data,$i)=@_;
 6756:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6757: 	# not redoing old skips
 6758: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6759: 	return 0;
 6760:     }
 6761:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6762: 
 6763:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6764: 	return 0;
 6765:     }
 6766:     return 1;
 6767: }
 6768: 
 6769: =pod
 6770: 
 6771: =item remember_current_skipped
 6772: 
 6773:    Discovers what scanlines are in the scantron_skipped_<filename>
 6774:    file and remembers them into scan_data for later use.
 6775: 
 6776: =cut
 6777: 
 6778: sub remember_current_skipped {
 6779:     my ($scanlines,$scan_data)=&scantron_getfile();
 6780:     my %to_remember;
 6781:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6782: 	if ($scanlines->{'skipped'}[$i]) {
 6783: 	    $to_remember{$i}=1;
 6784: 	}
 6785:     }
 6786: 
 6787:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6788:     &scantron_putfile(undef,$scan_data);
 6789: }
 6790: 
 6791: =pod
 6792: 
 6793: =item check_for_error
 6794: 
 6795:     Checks if there was an error when attempting to remove a specific
 6796:     scantron_.. bubblesheet data file. Prints out an error if
 6797:     something went wrong.
 6798: 
 6799: =cut
 6800: 
 6801: sub check_for_error {
 6802:     my ($r,$result)=@_;
 6803:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6804: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6805:     }
 6806: }
 6807: 
 6808: =pod
 6809: 
 6810: =item scantron_warning_screen
 6811: 
 6812:    Interstitial screen to make sure the operator has selected the
 6813:    correct options before we start the validation phase.
 6814: 
 6815: =cut
 6816: 
 6817: sub scantron_warning_screen {
 6818:     my ($button_text,$symb)=@_;
 6819:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6820:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6821:     my $CODElist;
 6822:     if ($scantron_config{'CODElocation'} &&
 6823: 	$scantron_config{'CODEstart'} &&
 6824: 	$scantron_config{'CODElength'}) {
 6825: 	$CODElist=$env{'form.scantron_CODElist'};
 6826: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 6827: 	$CODElist=
 6828: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6829: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6830:     }
 6831:     my $lastbubblepoints;
 6832:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6833:         $lastbubblepoints =
 6834:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6835:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6836:     }
 6837:     return ('
 6838: <p>
 6839: <span class="LC_warning">
 6840: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 6841: </p>
 6842: <table>
 6843: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6844: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6845: '.$CODElist.$lastbubblepoints.'
 6846: </table>
 6847: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 6848: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
 6849: 
 6850: <br />
 6851: ');
 6852: }
 6853: 
 6854: =pod
 6855: 
 6856: =item scantron_do_warning
 6857: 
 6858:    Check if the operator has picked something for all required
 6859:    fields. Error out if something is missing.
 6860: 
 6861: =cut
 6862: 
 6863: sub scantron_do_warning {
 6864:     my ($r,$symb)=@_;
 6865:     if (!$symb) {return '';}
 6866:     my $default_form_data=&defaultFormData($symb);
 6867:     $r->print(&scantron_form_start().$default_form_data);
 6868:     if ( $env{'form.selectpage'} eq '' ||
 6869: 	 $env{'form.scantron_selectfile'} eq '' ||
 6870: 	 $env{'form.scantron_format'} eq '' ) {
 6871: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6872: 	if ( $env{'form.selectpage'} eq '') {
 6873: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6874: 	} 
 6875: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6876: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6877: 	} 
 6878: 	if ( $env{'form.scantron_format'} eq '') {
 6879: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6880: 	} 
 6881:     } else {
 6882: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6883:         my $bubbledbyhand=&hand_bubble_option();
 6884: 	$r->print('
 6885: '.$warning.$bubbledbyhand.'
 6886: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6887: <input type="hidden" name="command" value="scantron_validate" />
 6888: ');
 6889:     }
 6890:     $r->print("</form><br />");
 6891:     return '';
 6892: }
 6893: 
 6894: =pod
 6895: 
 6896: =item scantron_form_start
 6897: 
 6898:     html hidden input for remembering all selected grading options
 6899: 
 6900: =cut
 6901: 
 6902: sub scantron_form_start {
 6903:     my ($max_bubble)=@_;
 6904:     my $result= <<SCANTRONFORM;
 6905: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6906:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6907:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6908:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6909:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6910:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6911:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6912:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6913:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6914:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6915: SCANTRONFORM
 6916: 
 6917:   my $line = 0;
 6918:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6919:        my $chunk =
 6920: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6921:        $chunk .=
 6922: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6923:        $chunk .= 
 6924:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6925:        $chunk .=
 6926:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6927:        $chunk .=
 6928:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 6929:        $result .= $chunk;
 6930:        $line++;
 6931:     }
 6932:     return $result;
 6933: }
 6934: 
 6935: =pod
 6936: 
 6937: =item scantron_validate_file
 6938: 
 6939:     Dispatch routine for doing validation of a bubblesheet data file.
 6940: 
 6941:     Also processes any necessary information resets that need to
 6942:     occur before validation begins (ignore previous corrections,
 6943:     restarting the skipped records processing)
 6944: 
 6945: =cut
 6946: 
 6947: sub scantron_validate_file {
 6948:     my ($r,$symb) = @_;
 6949:     if (!$symb) {return '';}
 6950:     my $default_form_data=&defaultFormData($symb);
 6951:     
 6952:     # do the detection of only doing skipped records first before we delete
 6953:     # them when doing the corrections reset
 6954:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6955: 	&reset_skipping_status();
 6956:     }
 6957:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6958: 	&remember_current_skipped();
 6959: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6960:     }
 6961: 
 6962:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6963: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6964: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6965: 	&check_for_error($r,&scantron_remove_scan_data());
 6966: 	$env{'form.scantron_options_ignore'}='done';
 6967:     }
 6968: 
 6969:     if ($env{'form.scantron_corrections'}) {
 6970: 	&scantron_process_corrections($r);
 6971:     }
 6972:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6973:     #get the student pick code ready
 6974:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6975:     my $nav_error;
 6976:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6977:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6978:     if ($nav_error) {
 6979:         $r->print(&navmap_errormsg());
 6980:         return '';
 6981:     }
 6982:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6983:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6984:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6985:     }
 6986:     $r->print($result);
 6987:     
 6988:     my @validate_phases=( 'sequence',
 6989: 			  'ID',
 6990: 			  'CODE',
 6991: 			  'doublebubble',
 6992: 			  'missingbubbles');
 6993:     if (!$env{'form.validatepass'}) {
 6994: 	$env{'form.validatepass'} = 0;
 6995:     }
 6996:     my $currentphase=$env{'form.validatepass'};
 6997: 
 6998: 
 6999:     my $stop=0;
 7000:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7001: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7002: 	$r->rflush();
 7003:      
 7004: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7005: 	{
 7006: 	    no strict 'refs';
 7007: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7008: 	}
 7009:     }
 7010:     if (!$stop) {
 7011: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7012: 	$r->print(&mt('Validation process complete.').'<br />'.
 7013:                   $warning.
 7014:                   &mt('Perform verification for each student after storage of submissions?').
 7015:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7016:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7017:                   ('&nbsp;'x3).'<label>'.
 7018:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7019:                   '</label></span><br />'.
 7020:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7021:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7022:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7023:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7024:     } else {
 7025: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7026: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7027:     }
 7028:     if ($stop) {
 7029: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7030: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7031: 	    $r->print(' '.&mt('this error').' <br />');
 7032: 
 7033: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
 7034: 	} else {
 7035:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7036: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7037:             } else {
 7038:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7039:             }
 7040: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7041: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7042: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7043: 	}
 7044:     }
 7045:     $r->print(" </form><br />");
 7046:     return '';
 7047: }
 7048: 
 7049: 
 7050: =pod
 7051: 
 7052: =item scantron_remove_file
 7053: 
 7054:    Removes the requested bubblesheet data file, makes sure that
 7055:    scantron_original_<filename> is never removed
 7056: 
 7057: 
 7058: =cut
 7059: 
 7060: sub scantron_remove_file {
 7061:     my ($which)=@_;
 7062:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7063:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7064:     my $file='scantron_';
 7065:     if ($which eq 'corrected' || $which eq 'skipped') {
 7066: 	$file.=$which.'_';
 7067:     } else {
 7068: 	return 'refused';
 7069:     }
 7070:     $file.=$env{'form.scantron_selectfile'};
 7071:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7072: }
 7073: 
 7074: 
 7075: =pod
 7076: 
 7077: =item scantron_remove_scan_data
 7078: 
 7079:    Removes all scan_data correction for the requested bubblesheet
 7080:    data file.  (In the case that both the are doing skipped records we need
 7081:    to remember the old skipped lines for the time being so that element
 7082:    persists for a while.)
 7083: 
 7084: =cut
 7085: 
 7086: sub scantron_remove_scan_data {
 7087:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7088:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7089:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7090:     my @todelete;
 7091:     my $filename=$env{'form.scantron_selectfile'};
 7092:     foreach my $key (@keys) {
 7093: 	if ($key=~/^\Q$filename\E_/) {
 7094: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7095: 		$key=~/remember_skipping/) {
 7096: 		next;
 7097: 	    }
 7098: 	    push(@todelete,$key);
 7099: 	}
 7100:     }
 7101:     my $result;
 7102:     if (@todelete) {
 7103: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7104: 				       \@todelete,$cdom,$cname);
 7105:     } else {
 7106: 	$result = 'ok';
 7107:     }
 7108:     return $result;
 7109: }
 7110: 
 7111: 
 7112: =pod
 7113: 
 7114: =item scantron_getfile
 7115: 
 7116:     Fetches the requested bubblesheet data file (all 3 versions), and
 7117:     the scan_data hash
 7118:   
 7119:   Arguments:
 7120:     None
 7121: 
 7122:   Returns:
 7123:     2 hash references
 7124: 
 7125:      - first one has 
 7126:          orig      -
 7127:          corrected -
 7128:          skipped   -  each of which points to an array ref of the specified
 7129:                       file broken up into individual lines
 7130:          count     - number of scanlines
 7131:  
 7132:      - second is the scan_data hash possible keys are
 7133:        ($number refers to scanline numbered $number and thus the key affects
 7134:         only that scanline
 7135:         $bubline refers to the specific bubble line element and the aspects
 7136:         refers to that specific bubble line element)
 7137: 
 7138:        $number.user - username:domain to use
 7139:        $number.CODE_ignore_dup 
 7140:                     - ignore the duplicate CODE error 
 7141:        $number.useCODE
 7142:                     - use the CODE in the scanline as is
 7143:        $number.no_bubble.$bubline
 7144:                     - it is valid that there is no bubbled in bubble
 7145:                       at $number $bubline
 7146:        remember_skipping
 7147:                     - a frozen hash containing keys of $number and values
 7148:                       of either 
 7149:                         1 - we are on a 'do skipped records pass' and plan
 7150:                             on processing this line
 7151:                         2 - we are on a 'do skipped records pass' and this
 7152:                             scanline has been marked to skip yet again
 7153: 
 7154: =cut
 7155: 
 7156: sub scantron_getfile {
 7157:     #FIXME really would prefer a scantron directory
 7158:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7159:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7160:     my $lines;
 7161:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7162: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7163:     my %scanlines;
 7164:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7165:     my $temp=$scanlines{'orig'};
 7166:     $scanlines{'count'}=$#$temp;
 7167: 
 7168:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7169: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7170:     if ($lines eq '-1') {
 7171: 	$scanlines{'corrected'}=[];
 7172:     } else {
 7173: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7174:     }
 7175:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7176: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7177:     if ($lines eq '-1') {
 7178: 	$scanlines{'skipped'}=[];
 7179:     } else {
 7180: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7181:     }
 7182:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7183:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7184:     my %scan_data = @tmp;
 7185:     return (\%scanlines,\%scan_data);
 7186: }
 7187: 
 7188: =pod
 7189: 
 7190: =item lonnet_putfile
 7191: 
 7192:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7193: 
 7194:  Arguments:
 7195:    $contents - data to store
 7196:    $filename - filename to store $contents into
 7197: 
 7198:  Returns:
 7199:    result value from &Apache::lonnet::finishuserfileupload
 7200: 
 7201: =cut
 7202: 
 7203: sub lonnet_putfile {
 7204:     my ($contents,$filename)=@_;
 7205:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7206:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7207:     $env{'form.sillywaytopassafilearound'}=$contents;
 7208:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7209: 
 7210: }
 7211: 
 7212: =pod
 7213: 
 7214: =item scantron_putfile
 7215: 
 7216:     Stores the current version of the bubblesheet data files, and the
 7217:     scan_data hash. (Does not modify the original version only the
 7218:     corrected and skipped versions.
 7219: 
 7220:  Arguments:
 7221:     $scanlines - hash ref that looks like the first return value from
 7222:                  &scantron_getfile()
 7223:     $scan_data - hash ref that looks like the second return value from
 7224:                  &scantron_getfile()
 7225: 
 7226: =cut
 7227: 
 7228: sub scantron_putfile {
 7229:     my ($scanlines,$scan_data) = @_;
 7230:     #FIXME really would prefer a scantron directory
 7231:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7232:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7233:     if ($scanlines) {
 7234: 	my $prefix='scantron_';
 7235: # no need to update orig, shouldn't change
 7236: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7237: #		    $env{'form.scantron_selectfile'});
 7238: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7239: 			$prefix.'corrected_'.
 7240: 			$env{'form.scantron_selectfile'});
 7241: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7242: 			$prefix.'skipped_'.
 7243: 			$env{'form.scantron_selectfile'});
 7244:     }
 7245:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7246: }
 7247: 
 7248: =pod
 7249: 
 7250: =item scantron_get_line
 7251: 
 7252:    Returns the correct version of the scanline
 7253: 
 7254:  Arguments:
 7255:     $scanlines - hash ref that looks like the first return value from
 7256:                  &scantron_getfile()
 7257:     $scan_data - hash ref that looks like the second return value from
 7258:                  &scantron_getfile()
 7259:     $i         - number of the requested line (starts at 0)
 7260: 
 7261:  Returns:
 7262:    A scanline, (either the original or the corrected one if it
 7263:    exists), or undef if the requested scanline should be
 7264:    skipped. (Either because it's an skipped scanline, or it's an
 7265:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7266:    pass.
 7267: 
 7268: =cut
 7269: 
 7270: sub scantron_get_line {
 7271:     my ($scanlines,$scan_data,$i)=@_;
 7272:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7273:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7274:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7275:     return $scanlines->{'orig'}[$i]; 
 7276: }
 7277: 
 7278: =pod
 7279: 
 7280: =item scantron_todo_count
 7281: 
 7282:     Counts the number of scanlines that need processing.
 7283: 
 7284:  Arguments:
 7285:     $scanlines - hash ref that looks like the first return value from
 7286:                  &scantron_getfile()
 7287:     $scan_data - hash ref that looks like the second return value from
 7288:                  &scantron_getfile()
 7289: 
 7290:  Returns:
 7291:     $count - number of scanlines to process
 7292: 
 7293: =cut
 7294: 
 7295: sub get_todo_count {
 7296:     my ($scanlines,$scan_data)=@_;
 7297:     my $count=0;
 7298:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7299: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7300: 	if ($line=~/^[\s\cz]*$/) { next; }
 7301: 	$count++;
 7302:     }
 7303:     return $count;
 7304: }
 7305: 
 7306: =pod
 7307: 
 7308: =item scantron_put_line
 7309: 
 7310:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7311:     data file.
 7312: 
 7313:  Arguments:
 7314:     $scanlines - hash ref that looks like the first return value from
 7315:                  &scantron_getfile()
 7316:     $scan_data - hash ref that looks like the second return value from
 7317:                  &scantron_getfile()
 7318:     $i         - line number to update
 7319:     $newline   - contents of the updated scanline
 7320:     $skip      - if true make the line for skipping and update the
 7321:                  'skipped' file
 7322: 
 7323: =cut
 7324: 
 7325: sub scantron_put_line {
 7326:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7327:     if ($skip) {
 7328: 	$scanlines->{'skipped'}[$i]=$newline;
 7329: 	&start_skipping($scan_data,$i);
 7330: 	return;
 7331:     }
 7332:     $scanlines->{'corrected'}[$i]=$newline;
 7333: }
 7334: 
 7335: =pod
 7336: 
 7337: =item scantron_clear_skip
 7338: 
 7339:    Remove a line from the 'skipped' file
 7340: 
 7341:  Arguments:
 7342:     $scanlines - hash ref that looks like the first return value from
 7343:                  &scantron_getfile()
 7344:     $scan_data - hash ref that looks like the second return value from
 7345:                  &scantron_getfile()
 7346:     $i         - line number to update
 7347: 
 7348: =cut
 7349: 
 7350: sub scantron_clear_skip {
 7351:     my ($scanlines,$scan_data,$i)=@_;
 7352:     if (exists($scanlines->{'skipped'}[$i])) {
 7353: 	undef($scanlines->{'skipped'}[$i]);
 7354: 	return 1;
 7355:     }
 7356:     return 0;
 7357: }
 7358: 
 7359: =pod
 7360: 
 7361: =item scantron_filter_not_exam
 7362: 
 7363:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7364:    filter out resources that are not marked as 'exam' mode
 7365: 
 7366: =cut
 7367: 
 7368: sub scantron_filter_not_exam {
 7369:     my ($curres)=@_;
 7370:     
 7371:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7372: 	# if the user has asked to not have either hidden
 7373: 	# or 'randomout' controlled resources to be graded
 7374: 	# don't include them
 7375: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7376: 	    && $curres->randomout) {
 7377: 	    return 0;
 7378: 	}
 7379: 	return 1;
 7380:     }
 7381:     return 0;
 7382: }
 7383: 
 7384: =pod
 7385: 
 7386: =item scantron_validate_sequence
 7387: 
 7388:     Validates the selected sequence, checking for resource that are
 7389:     not set to exam mode.
 7390: 
 7391: =cut
 7392: 
 7393: sub scantron_validate_sequence {
 7394:     my ($r,$currentphase) = @_;
 7395: 
 7396:     my $navmap=Apache::lonnavmaps::navmap->new();
 7397:     unless (ref($navmap)) {
 7398:         $r->print(&navmap_errormsg());
 7399:         return (1,$currentphase);
 7400:     }
 7401:     my (undef,undef,$sequence)=
 7402: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7403: 
 7404:     my $map=$navmap->getResourceByUrl($sequence);
 7405: 
 7406:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7407:                                     value="ignore" />');
 7408:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7409: 	my @resources=
 7410: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7411: 	if (@resources) {
 7412: 	    $r->print(
 7413:                 '<p class="LC_warning">'
 7414:                .&mt('Some resources in the sequence currently are not set to'
 7415:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7416:                    .' work correctly.')
 7417:                .'</p>'
 7418:             );
 7419: 	    return (1,$currentphase);
 7420: 	}
 7421:     }
 7422: 
 7423:     return (0,$currentphase+1);
 7424: }
 7425: 
 7426: 
 7427: 
 7428: sub scantron_validate_ID {
 7429:     my ($r,$currentphase) = @_;
 7430:     
 7431:     #get student info
 7432:     my $classlist=&Apache::loncoursedata::get_classlist();
 7433:     my %idmap=&username_to_idmap($classlist);
 7434: 
 7435:     #get scantron line setup
 7436:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7437:     my ($scanlines,$scan_data)=&scantron_getfile();
 7438: 
 7439:     my $nav_error;
 7440:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7441:     if ($nav_error) {
 7442:         $r->print(&navmap_errormsg());
 7443:         return(1,$currentphase);
 7444:     }
 7445: 
 7446:     my %found=('ids'=>{},'usernames'=>{});
 7447:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7448: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7449: 	if ($line=~/^[\s\cz]*$/) { next; }
 7450: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7451: 						 $scan_data);
 7452: 	my $id=$$scan_record{'scantron.ID'};
 7453: 	my $found;
 7454: 	foreach my $checkid (keys(%idmap)) {
 7455: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7456: 	}
 7457: 	if ($found) {
 7458: 	    my $username=$idmap{$found};
 7459: 	    if ($found{'ids'}{$found}) {
 7460: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7461: 					 $line,'duplicateID',$found);
 7462: 		return(1,$currentphase);
 7463: 	    } elsif ($found{'usernames'}{$username}) {
 7464: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7465: 					 $line,'duplicateID',$username);
 7466: 		return(1,$currentphase);
 7467: 	    }
 7468: 	    #FIXME store away line we previously saw the ID on to use above
 7469: 	    $found{'ids'}{$found}++;
 7470: 	    $found{'usernames'}{$username}++;
 7471: 	} else {
 7472: 	    if ($id =~ /^\s*$/) {
 7473: 		my $username=&scan_data($scan_data,"$i.user");
 7474: 		if (defined($username) && $found{'usernames'}{$username}) {
 7475: 		    &scantron_get_correction($r,$i,$scan_record,
 7476: 					     \%scantron_config,
 7477: 					     $line,'duplicateID',$username);
 7478: 		    return(1,$currentphase);
 7479: 		} elsif (!defined($username)) {
 7480: 		    &scantron_get_correction($r,$i,$scan_record,
 7481: 					     \%scantron_config,
 7482: 					     $line,'incorrectID');
 7483: 		    return(1,$currentphase);
 7484: 		}
 7485: 		$found{'usernames'}{$username}++;
 7486: 	    } else {
 7487: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7488: 					 $line,'incorrectID');
 7489: 		return(1,$currentphase);
 7490: 	    }
 7491: 	}
 7492:     }
 7493: 
 7494:     return (0,$currentphase+1);
 7495: }
 7496: 
 7497: 
 7498: sub scantron_get_correction {
 7499:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7500:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7501: #FIXME in the case of a duplicated ID the previous line, probably need
 7502: #to show both the current line and the previous one and allow skipping
 7503: #the previous one or the current one
 7504: 
 7505:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7506:         $r->print(
 7507:             '<p class="LC_warning">'
 7508:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7509:                 "<b>$error</b>",
 7510:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7511:            ."</p> \n");
 7512:     } else {
 7513:         $r->print(
 7514:             '<p class="LC_warning">'
 7515:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7516:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7517:            ."</p> \n");
 7518:     }
 7519:     my $message =
 7520:         '<p>'
 7521:        .&mt('The ID on the form is [_1]',
 7522:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7523:        .'<br />'
 7524:        .&mt('The name on the paper is [_1], [_2]',
 7525:             $$scan_record{'scantron.LastName'},
 7526:             $$scan_record{'scantron.FirstName'})
 7527:        .'</p>';
 7528: 
 7529:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7530:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7531:                            # Array populated for doublebubble or
 7532:     my @lines_to_correct;  # missingbubble errors to build javascript
 7533:                            # to validate radio button checking   
 7534: 
 7535:     if ($error =~ /ID$/) {
 7536: 	if ($error eq 'incorrectID') {
 7537:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7538: 		      "</p>\n");
 7539: 	} elsif ($error eq 'duplicateID') {
 7540:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7541: 	}
 7542: 	$r->print($message);
 7543: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7544: 	$r->print("\n<ul><li> ");
 7545: 	#FIXME it would be nice if this sent back the user ID and
 7546: 	#could do partial userID matches
 7547: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7548: 				       'scantron_username','scantron_domain'));
 7549: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7550: 	$r->print("\n:\n".
 7551: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7552: 
 7553: 	$r->print('</li>');
 7554:     } elsif ($error =~ /CODE$/) {
 7555: 	if ($error eq 'incorrectCODE') {
 7556: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7557: 	} elsif ($error eq 'duplicateCODE') {
 7558: 	    $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");
 7559: 	}
 7560: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7561: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7562:                  ."</p>\n");
 7563: 	$r->print($message);
 7564: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7565: 	$r->print("\n<br /> ");
 7566: 	my $i=0;
 7567: 	if ($error eq 'incorrectCODE' 
 7568: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7569: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7570: 	    if ($closest > 0) {
 7571: 		foreach my $testcode (@{$closest}) {
 7572: 		    my $checked='';
 7573: 		    if (!$i) { $checked=' checked="checked"'; }
 7574: 		    $r->print("
 7575:    <label>
 7576:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7577:        ".&mt("Use the similar CODE [_1] instead.",
 7578: 	    "<b><tt>".$testcode."</tt></b>")."
 7579:     </label>
 7580:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7581: 		    $r->print("\n<br />");
 7582: 		    $i++;
 7583: 		}
 7584: 	    }
 7585: 	}
 7586: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7587: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7588: 	    $r->print("
 7589:     <label>
 7590:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7591:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7592: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7593:     </label>");
 7594: 	    $r->print("\n<br />");
 7595: 	}
 7596: 
 7597: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7598: function change_radio(field) {
 7599:     var slct=document.scantronupload.scantron_CODE_resolution;
 7600:     var i;
 7601:     for (i=0;i<slct.length;i++) {
 7602:         if (slct[i].value==field) { slct[i].checked=true; }
 7603:     }
 7604: }
 7605: ENDSCRIPT
 7606: 	my $href="/adm/pickcode?".
 7607: 	   "form=".&escape("scantronupload").
 7608: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7609: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7610: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7611: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7612: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7613: 	    $r->print("
 7614:     <label>
 7615:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7616:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7617: 	     "<a target='_blank' href='$href'>","</a>")."
 7618:     </label> 
 7619:     ".&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\')" />'));
 7620: 	    $r->print("\n<br />");
 7621: 	}
 7622: 	$r->print("
 7623:     <label>
 7624:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7625:        ".&mt("Use [_1] as the CODE.",
 7626: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7627: 	$r->print("\n<br /><br />");
 7628:     } elsif ($error eq 'doublebubble') {
 7629: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7630: 
 7631: 	# The form field scantron_questions is acutally a list of line numbers.
 7632: 	# represented by this form so:
 7633: 
 7634: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7635:                                                 $respnumlookup,$startline);
 7636: 
 7637: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7638: 		  $line_list.'" />');
 7639: 	$r->print($message);
 7640: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7641: 	foreach my $question (@{$arg}) {
 7642: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7643:                                                    $scan_record, $error,
 7644:                                                    $randomorder,$randompick,
 7645:                                                    $respnumlookup,$startline);
 7646:             push(@lines_to_correct,@linenums);
 7647: 	}
 7648:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7649:     } elsif ($error eq 'missingbubble') {
 7650: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7651: 	$r->print($message);
 7652: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7653: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7654: 
 7655: 	# The form field scantron_questions is actually a list of line numbers not
 7656: 	# a list of question numbers. Therefore:
 7657: 	#
 7658: 
 7659: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7660:                                                 $respnumlookup,$startline);
 7661: 
 7662: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7663: 		  $line_list.'" />');
 7664: 	foreach my $question (@{$arg}) {
 7665: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7666:                                                    $scan_record, $error,
 7667:                                                    $randomorder,$randompick,
 7668:                                                    $respnumlookup,$startline);
 7669:             push(@lines_to_correct,@linenums);
 7670: 	}
 7671:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7672:     } else {
 7673: 	$r->print("\n<ul>");
 7674:     }
 7675:     $r->print("\n</li></ul>");
 7676: }
 7677: 
 7678: sub verify_bubbles_checked {
 7679:     my (@ansnums) = @_;
 7680:     my $ansnumstr = join('","',@ansnums);
 7681:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7682:     &js_escape(\$warning);
 7683:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7684: function verify_bubble_radio(form) {
 7685:     var ansnumArray = new Array ("$ansnumstr");
 7686:     var need_bubble_count = 0;
 7687:     for (var i=0; i<ansnumArray.length; i++) {
 7688:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7689:             var bubble_picked = 0; 
 7690:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7691:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7692:                     bubble_picked = 1;
 7693:                 }
 7694:             }
 7695:             if (bubble_picked == 0) {
 7696:                 need_bubble_count ++;
 7697:             }
 7698:         }
 7699:     }
 7700:     if (need_bubble_count) {
 7701:         alert("$warning");
 7702:         return;
 7703:     }
 7704:     form.submit(); 
 7705: }
 7706: ENDSCRIPT
 7707:     return $output;
 7708: }
 7709: 
 7710: =pod
 7711: 
 7712: =item  questions_to_line_list
 7713: 
 7714: Converts a list of questions into a string of comma separated
 7715: line numbers in the answer sheet used by the questions.  This is
 7716: used to fill in the scantron_questions form field.
 7717: 
 7718:   Arguments:
 7719:      questions    - Reference to an array of questions.
 7720:      randomorder  - True if randomorder in use.
 7721:      randompick   - True if randompick in use.
 7722:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7723:                      for current line to question number used for same question
 7724:                      in "Master Seqence" (as seen by Course Coordinator).
 7725:      startline    - Reference to hash where key is question number (0 is first)
 7726:                     and key is number of first bubble line for current student
 7727:                     or code-based randompick and/or randomorder.
 7728: 
 7729: =cut
 7730: 
 7731: 
 7732: sub questions_to_line_list {
 7733:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7734:     my @lines;
 7735: 
 7736:     foreach my $item (@{$questions}) {
 7737:         my $question = $item;
 7738:         my ($first,$count,$last);
 7739:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7740:             $question = $1;
 7741:             my $subquestion = $2;
 7742:             my $responsenum = $question-1;
 7743:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7744:                 $responsenum = $respnumlookup->{$question-1};
 7745:                 if (ref($startline) eq 'HASH') {
 7746:                     $first = $startline->{$question-1} + 1;
 7747:                 }
 7748:             } else {
 7749:                 $first = $first_bubble_line{$responsenum} + 1;
 7750:             }
 7751:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7752:             my $subcount = 1;
 7753:             while ($subcount<$subquestion) {
 7754:                 $first += $subans[$subcount-1];
 7755:                 $subcount ++;
 7756:             }
 7757:             $count = $subans[$subquestion-1];
 7758:         } else {
 7759:             my $responsenum = $question-1;
 7760:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7761:                 $responsenum = $respnumlookup->{$question-1};
 7762:                 if (ref($startline) eq 'HASH') {
 7763:                     $first = $startline->{$question-1} + 1;
 7764:                 }
 7765:             } else {
 7766:                 $first = $first_bubble_line{$responsenum} + 1;
 7767:             }
 7768: 	    $count   = $bubble_lines_per_response{$responsenum};
 7769:         }
 7770:         $last = $first+$count-1;
 7771:         push(@lines, ($first..$last));
 7772:     }
 7773:     return join(',', @lines);
 7774: }
 7775: 
 7776: =pod 
 7777: 
 7778: =item prompt_for_corrections
 7779: 
 7780: Prompts for a potentially multiline correction to the
 7781: user's bubbling (factors out common code from scantron_get_correction
 7782: for multi and missing bubble cases).
 7783: 
 7784:  Arguments:
 7785:    $r           - Apache request object.
 7786:    $question    - The question number to prompt for.
 7787:    $scan_config - The scantron file configuration hash.
 7788:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7789:    $error       - Type of error
 7790:    $randomorder - True if randomorder in use.
 7791:    $randompick  - True if randompick in use.
 7792:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7793:                     for current line to question number used for same question
 7794:                     in "Master Seqence" (as seen by Course Coordinator).
 7795:    $startline   - Reference to hash where key is question number (0 is first)
 7796:                   and value is number of first bubble line for current student
 7797:                   or code-based randompick and/or randomorder.
 7798: 
 7799: 
 7800:  Implicit inputs:
 7801:    %bubble_lines_per_response   - Starting line numbers for each question.
 7802:                                   Numbered from 0 (but question numbers are from
 7803:                                   1.
 7804:    %first_bubble_line           - Starting bubble line for each question.
 7805:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7806:                                   type problems render as separate sub-questions, 
 7807:                                   in exam mode. This hash contains a 
 7808:                                   comma-separated list of the lines per 
 7809:                                   sub-question.
 7810:    %responsetype_per_response   - essayresponse, formularesponse,
 7811:                                   stringresponse, imageresponse, reactionresponse,
 7812:                                   and organicresponse type problem parts can have
 7813:                                   multiple lines per response if the weight
 7814:                                   assigned exceeds 10.  In this case, only
 7815:                                   one bubble per line is permitted, but more 
 7816:                                   than one line might contain bubbles, e.g.
 7817:                                   bubbling of: line 1 - J, line 2 - J, 
 7818:                                   line 3 - B would assign 22 points.  
 7819: 
 7820: =cut
 7821: 
 7822: sub prompt_for_corrections {
 7823:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 7824:         $randompick, $respnumlookup, $startline) = @_;
 7825:     my ($current_line,$lines);
 7826:     my @linenums;
 7827:     my $questionnum = $question;
 7828:     my ($first,$responsenum);
 7829:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7830:         $question = $1;
 7831:         my $subquestion = $2;
 7832:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7833:             $responsenum = $respnumlookup->{$question-1};
 7834:             if (ref($startline) eq 'HASH') {
 7835:                 $first = $startline->{$question-1};
 7836:             }
 7837:         } else {
 7838:             $responsenum = $question-1;
 7839:             $first = $first_bubble_line{$responsenum};
 7840:         }
 7841:         $current_line = $first + 1 ;
 7842:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7843:         my $subcount = 1;
 7844:         while ($subcount<$subquestion) {
 7845:             $current_line += $subans[$subcount-1];
 7846:             $subcount ++;
 7847:         }
 7848:         $lines = $subans[$subquestion-1];
 7849:     } else {
 7850:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7851:             $responsenum = $respnumlookup->{$question-1};
 7852:             if (ref($startline) eq 'HASH') { 
 7853:                 $first = $startline->{$question-1};
 7854:             }
 7855:         } else {
 7856:             $responsenum = $question-1;
 7857:             $first = $first_bubble_line{$responsenum};
 7858:         }
 7859:         $current_line = $first + 1;
 7860:         $lines        = $bubble_lines_per_response{$responsenum};
 7861:     }
 7862:     if ($lines > 1) {
 7863:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7864:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 7865:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 7866:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 7867:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 7868:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 7869:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 7870:             $r->print(
 7871:                 &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
 7872:                .'<br /><br />'
 7873:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 7874:                .'<br />'
 7875:                .&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.')
 7876:                .'<br />'
 7877:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 7878:                .'<br /><br />'
 7879:             );
 7880:         } else {
 7881:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7882:         }
 7883:     }
 7884:     for (my $i =0; $i < $lines; $i++) {
 7885:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7886: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 7887: 	        		  $questionnum,$error,split('', $selected));
 7888:         push(@linenums,$current_line);
 7889: 	$current_line++;
 7890:     }
 7891:     if ($lines > 1) {
 7892: 	$r->print("<hr /><br />");
 7893:     }
 7894:     return @linenums;
 7895: }
 7896: 
 7897: =pod
 7898: 
 7899: =item scantron_bubble_selector
 7900:   
 7901:    Generates the html radiobuttons to correct a single bubble line
 7902:    possibly showing the existing the selected bubbles if known
 7903: 
 7904:  Arguments:
 7905:     $r           - Apache request object
 7906:     $scan_config - hash from &get_scantron_config()
 7907:     $line        - Number of the line being displayed.
 7908:     $questionnum - Question number (may include subquestion)
 7909:     $error       - Type of error.
 7910:     @selected    - Array of bubbles picked on this line.
 7911: 
 7912: =cut
 7913: 
 7914: sub scantron_bubble_selector {
 7915:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7916:     my $max=$$scan_config{'Qlength'};
 7917: 
 7918:     my $scmode=$$scan_config{'Qon'};
 7919:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7920:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7921:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7922:             $max=$$scan_config{'BubblesPerRow'};
 7923:             if (($scmode eq 'number') && ($max > 10)) {
 7924:                 $max = 10;
 7925:             } elsif (($scmode eq 'letter') && $max > 26) {
 7926:                 $max = 26;
 7927:             }
 7928:         } else {
 7929:             $max = 10;
 7930:         }
 7931:     }
 7932: 
 7933:     my @alphabet=('A'..'Z');
 7934:     $r->print(&Apache::loncommon::start_data_table().
 7935:               &Apache::loncommon::start_data_table_row());
 7936:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7937:     for (my $i=0;$i<$max+1;$i++) {
 7938: 	$r->print("\n".'<td align="center">');
 7939: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7940: 	else { $r->print('&nbsp;'); }
 7941: 	$r->print('</td>');
 7942:     }
 7943:     $r->print(&Apache::loncommon::end_data_table_row().
 7944:               &Apache::loncommon::start_data_table_row());
 7945:     for (my $i=0;$i<$max;$i++) {
 7946: 	$r->print("\n".
 7947: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7948: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7949:     }
 7950:     my $nobub_checked = ' ';
 7951:     if ($error eq 'missingbubble') {
 7952:         $nobub_checked = ' checked = "checked" ';
 7953:     }
 7954:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7955: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7956:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7957:               $line.'" value="'.$questionnum.'" /></td>');
 7958:     $r->print(&Apache::loncommon::end_data_table_row().
 7959:               &Apache::loncommon::end_data_table());
 7960: }
 7961: 
 7962: =pod
 7963: 
 7964: =item num_matches
 7965: 
 7966:    Counts the number of characters that are the same between the two arguments.
 7967: 
 7968:  Arguments:
 7969:    $orig - CODE from the scanline
 7970:    $code - CODE to match against
 7971: 
 7972:  Returns:
 7973:    $count - integer count of the number of same characters between the
 7974:             two arguments
 7975: 
 7976: =cut
 7977: 
 7978: sub num_matches {
 7979:     my ($orig,$code) = @_;
 7980:     my @code=split(//,$code);
 7981:     my @orig=split(//,$orig);
 7982:     my $same=0;
 7983:     for (my $i=0;$i<scalar(@code);$i++) {
 7984: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7985:     }
 7986:     return $same;
 7987: }
 7988: 
 7989: =pod
 7990: 
 7991: =item scantron_get_closely_matching_CODEs
 7992: 
 7993:    Cycles through all CODEs and finds the set that has the greatest
 7994:    number of same characters as the provided CODE
 7995: 
 7996:  Arguments:
 7997:    $allcodes - hash ref returned by &get_codes()
 7998:    $CODE     - CODE from the current scanline
 7999: 
 8000:  Returns:
 8001:    2 element list
 8002:     - first elements is number of how closely matching the best fit is 
 8003:       (5 means best set has 5 matching characters)
 8004:     - second element is an arrary ref containing the set of valid CODEs
 8005:       that best fit the passed in CODE
 8006: 
 8007: =cut
 8008: 
 8009: sub scantron_get_closely_matching_CODEs {
 8010:     my ($allcodes,$CODE)=@_;
 8011:     my @CODEs;
 8012:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8013: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8014:     }
 8015: 
 8016:     return ($#CODEs,$CODEs[-1]);
 8017: }
 8018: 
 8019: =pod
 8020: 
 8021: =item get_codes
 8022: 
 8023:    Builds a hash which has keys of all of the valid CODEs from the selected
 8024:    set of remembered CODEs.
 8025: 
 8026:  Arguments:
 8027:   $old_name - name of the set of remembered CODEs
 8028:   $cdom     - domain of the course
 8029:   $cnum     - internal course name
 8030: 
 8031:  Returns:
 8032:   %allcodes - keys are the valid CODEs, values are all 1
 8033: 
 8034: =cut
 8035: 
 8036: sub get_codes {
 8037:     my ($old_name, $cdom, $cnum) = @_;
 8038:     if (!$old_name) {
 8039: 	$old_name=$env{'form.scantron_CODElist'};
 8040:     }
 8041:     if (!$cdom) {
 8042: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8043:     }
 8044:     if (!$cnum) {
 8045: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8046:     }
 8047:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8048: 				    $cdom,$cnum);
 8049:     my %allcodes;
 8050:     if ($result{"type\0$old_name"} eq 'number') {
 8051: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8052:     } else {
 8053: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8054:     }
 8055:     return %allcodes;
 8056: }
 8057: 
 8058: =pod
 8059: 
 8060: =item scantron_validate_CODE
 8061: 
 8062:    Validates all scanlines in the selected file to not have any
 8063:    invalid or underspecified CODEs and that none of the codes are
 8064:    duplicated if this was requested.
 8065: 
 8066: =cut
 8067: 
 8068: sub scantron_validate_CODE {
 8069:     my ($r,$currentphase) = @_;
 8070:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8071:     if ($scantron_config{'CODElocation'} &&
 8072: 	$scantron_config{'CODEstart'} &&
 8073: 	$scantron_config{'CODElength'}) {
 8074: 	if (!defined($env{'form.scantron_CODElist'})) {
 8075: 	    &FIXME_blow_up()
 8076: 	}
 8077:     } else {
 8078: 	return (0,$currentphase+1);
 8079:     }
 8080:     
 8081:     my %usedCODEs;
 8082: 
 8083:     my %allcodes=&get_codes();
 8084: 
 8085:     my $nav_error;
 8086:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8087:     if ($nav_error) {
 8088:         $r->print(&navmap_errormsg());
 8089:         return(1,$currentphase);
 8090:     }
 8091: 
 8092:     my ($scanlines,$scan_data)=&scantron_getfile();
 8093:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8094: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8095: 	if ($line=~/^[\s\cz]*$/) { next; }
 8096: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8097: 						 $scan_data);
 8098: 	my $CODE=$$scan_record{'scantron.CODE'};
 8099: 	my $error=0;
 8100: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8101: 	    &scantron_get_correction($r,$i,$scan_record,
 8102: 				     \%scantron_config,
 8103: 				     $line,'incorrectCODE',\%allcodes);
 8104: 	    return(1,$currentphase);
 8105: 	}
 8106: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8107: 	    && !$$scan_record{'scantron.useCODE'}) {
 8108: 	    &scantron_get_correction($r,$i,$scan_record,
 8109: 				     \%scantron_config,
 8110: 				     $line,'incorrectCODE',\%allcodes);
 8111: 	    return(1,$currentphase);
 8112: 	}
 8113: 	if (exists($usedCODEs{$CODE}) 
 8114: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8115: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8116: 	    &scantron_get_correction($r,$i,$scan_record,
 8117: 				     \%scantron_config,
 8118: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8119: 	    return(1,$currentphase);
 8120: 	}
 8121: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8122:     }
 8123:     return (0,$currentphase+1);
 8124: }
 8125: 
 8126: =pod
 8127: 
 8128: =item scantron_validate_doublebubble
 8129: 
 8130:    Validates all scanlines in the selected file to not have any
 8131:    bubble lines with multiple bubbles marked.
 8132: 
 8133: =cut
 8134: 
 8135: sub scantron_validate_doublebubble {
 8136:     my ($r,$currentphase) = @_;
 8137:     #get student info
 8138:     my $classlist=&Apache::loncoursedata::get_classlist();
 8139:     my %idmap=&username_to_idmap($classlist);
 8140:     my (undef,undef,$sequence)=
 8141:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8142: 
 8143:     #get scantron line setup
 8144:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8145:     my ($scanlines,$scan_data)=&scantron_getfile();
 8146: 
 8147:     my $navmap = Apache::lonnavmaps::navmap->new();
 8148:     unless (ref($navmap)) {
 8149:         $r->print(&navmap_errormsg());
 8150:         return(1,$currentphase);
 8151:     }
 8152:     my $map=$navmap->getResourceByUrl($sequence);
 8153:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8154:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8155:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8156:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8157: 
 8158:     my $nav_error;
 8159:     if (ref($map)) {
 8160:         $randomorder = $map->randomorder();
 8161:         $randompick = $map->randompick();
 8162:         if ($randomorder || $randompick) {
 8163:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8164:             if ($nav_error) {
 8165:                 $r->print(&navmap_errormsg());
 8166:                 return(1,$currentphase);
 8167:             }
 8168:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8169:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8170:         }
 8171:     } else {
 8172:         $r->print(&navmap_errormsg());
 8173:         return(1,$currentphase);
 8174:     }
 8175: 
 8176:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8177:     if ($nav_error) {
 8178:         $r->print(&navmap_errormsg());
 8179:         return(1,$currentphase);
 8180:     }
 8181: 
 8182:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8183: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8184: 	if ($line=~/^[\s\cz]*$/) { next; }
 8185: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8186: 						 $scan_data,undef,\%idmap,$randomorder,
 8187:                                                  $randompick,$sequence,\@master_seq,
 8188:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8189:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8190: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8191: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8192: 				 'doublebubble',
 8193: 				 $$scan_record{'scantron.doubleerror'},
 8194:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8195:     	return (1,$currentphase);
 8196:     }
 8197:     return (0,$currentphase+1);
 8198: }
 8199: 
 8200: 
 8201: sub scantron_get_maxbubble {
 8202:     my ($nav_error,$scantron_config) = @_;
 8203:     if (defined($env{'form.scantron_maxbubble'}) &&
 8204: 	$env{'form.scantron_maxbubble'}) {
 8205: 	&restore_bubble_lines();
 8206: 	return $env{'form.scantron_maxbubble'};
 8207:     }
 8208: 
 8209:     my (undef, undef, $sequence) =
 8210: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8211: 
 8212:     my $navmap=Apache::lonnavmaps::navmap->new();
 8213:     unless (ref($navmap)) {
 8214:         if (ref($nav_error)) {
 8215:             $$nav_error = 1;
 8216:         }
 8217:         return;
 8218:     }
 8219:     my $map=$navmap->getResourceByUrl($sequence);
 8220:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8221:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8222: 
 8223:     &Apache::lonxml::clear_problem_counter();
 8224: 
 8225:     my $uname       = $env{'user.name'};
 8226:     my $udom        = $env{'user.domain'};
 8227:     my $cid         = $env{'request.course.id'};
 8228:     my $total_lines = 0;
 8229:     %bubble_lines_per_response = ();
 8230:     %first_bubble_line         = ();
 8231:     %subdivided_bubble_lines   = ();
 8232:     %responsetype_per_response = ();
 8233:     %masterseq_id_responsenum  = ();
 8234: 
 8235:     my $response_number = 0;
 8236:     my $bubble_line     = 0;
 8237:     foreach my $resource (@resources) {
 8238:         my $resid = $resource->id(); 
 8239:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8240:                                                           $udom,undef,$bubbles_per_row);
 8241:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8242: 	    foreach my $part_id (@{$parts}) {
 8243:                 my $lines;
 8244: 
 8245: 	        # TODO - make this a persistent hash not an array.
 8246: 
 8247:                 # optionresponse, matchresponse and rankresponse type items 
 8248:                 # render as separate sub-questions in exam mode.
 8249:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8250:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8251:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8252:                     my ($numbub,$numshown);
 8253:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8254:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8255:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8256:                         }
 8257:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8258:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8259:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8260:                         }
 8261:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8262:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8263:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8264:                         }
 8265:                     }
 8266:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8267:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8268:                     }
 8269:                     my $bubbles_per_row =
 8270:                         &bubblesheet_bubbles_per_row($scantron_config);
 8271:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8272:                     if (($numbub % $bubbles_per_row) != 0) {
 8273:                         $inner_bubble_lines++;
 8274:                     }
 8275:                     for (my $i=0; $i<$numshown; $i++) {
 8276:                         $subdivided_bubble_lines{$response_number} .= 
 8277:                             $inner_bubble_lines.',';
 8278:                     }
 8279:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8280:                     $lines = $numshown * $inner_bubble_lines;
 8281:                 } else {
 8282:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8283:                 }
 8284: 
 8285:                 $first_bubble_line{$response_number} = $bubble_line;
 8286: 	        $bubble_lines_per_response{$response_number} = $lines;
 8287:                 $responsetype_per_response{$response_number} = 
 8288:                     $analysis->{$part_id.'.type'};
 8289:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8290: 	        $response_number++;
 8291: 
 8292: 	        $bubble_line +=  $lines;
 8293: 	        $total_lines +=  $lines;
 8294: 	    }
 8295:         }
 8296:     }
 8297:     &Apache::lonnet::delenv('scantron.');
 8298: 
 8299:     &save_bubble_lines();
 8300:     $env{'form.scantron_maxbubble'} =
 8301: 	$total_lines;
 8302:     return $env{'form.scantron_maxbubble'};
 8303: }
 8304: 
 8305: sub bubblesheet_bubbles_per_row {
 8306:     my ($scantron_config) = @_;
 8307:     my $bubbles_per_row;
 8308:     if (ref($scantron_config) eq 'HASH') {
 8309:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8310:     }
 8311:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8312:         $bubbles_per_row = 10;
 8313:     }
 8314:     return $bubbles_per_row;
 8315: }
 8316: 
 8317: sub scantron_validate_missingbubbles {
 8318:     my ($r,$currentphase) = @_;
 8319:     #get student info
 8320:     my $classlist=&Apache::loncoursedata::get_classlist();
 8321:     my %idmap=&username_to_idmap($classlist);
 8322:     my (undef,undef,$sequence)=
 8323:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8324: 
 8325:     #get scantron line setup
 8326:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8327:     my ($scanlines,$scan_data)=&scantron_getfile();
 8328: 
 8329:     my $navmap = Apache::lonnavmaps::navmap->new();
 8330:     unless (ref($navmap)) {
 8331:         $r->print(&navmap_errormsg());
 8332:         return(1,$currentphase);
 8333:     }
 8334: 
 8335:     my $map=$navmap->getResourceByUrl($sequence);
 8336:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8337:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8338:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8339:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8340: 
 8341:     my $nav_error;
 8342:     if (ref($map)) {
 8343:         $randomorder = $map->randomorder();
 8344:         $randompick = $map->randompick();
 8345:         if ($randomorder || $randompick) {
 8346:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8347:             if ($nav_error) {
 8348:                 $r->print(&navmap_errormsg());
 8349:                 return(1,$currentphase);
 8350:             }
 8351:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8352:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8353:         }
 8354:     } else {
 8355:         $r->print(&navmap_errormsg());
 8356:         return(1,$currentphase);
 8357:     }
 8358: 
 8359: 
 8360:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8361:     if ($nav_error) {
 8362:         $r->print(&navmap_errormsg());
 8363:         return(1,$currentphase);
 8364:     }
 8365: 
 8366:     if (!$max_bubble) { $max_bubble=2**31; }
 8367:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8368: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8369: 	if ($line=~/^[\s\cz]*$/) { next; }
 8370: 	my $scan_record =
 8371:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8372: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8373:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8374:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8375: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8376: 	my @to_correct;
 8377: 	
 8378: 	# Probably here's where the error is...
 8379: 
 8380: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8381:             my $lastbubble;
 8382:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8383:                my $question = $1;
 8384:                my $subquestion = $2;
 8385:                my ($first,$responsenum);
 8386:                if ($randomorder || $randompick) {
 8387:                    $responsenum = $respnumlookup{$question-1};
 8388:                    $first = $startline{$question-1};
 8389:                } else {
 8390:                    $responsenum = $question-1; 
 8391:                    $first = $first_bubble_line{$responsenum};
 8392:                }
 8393:                if (!defined($first)) { next; }
 8394:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8395:                my $subcount = 1;
 8396:                while ($subcount<$subquestion) {
 8397:                    $first += $subans[$subcount-1];
 8398:                    $subcount ++;
 8399:                }
 8400:                my $count = $subans[$subquestion-1];
 8401:                $lastbubble = $first + $count;
 8402:             } else {
 8403:                my ($first,$responsenum);
 8404:                if ($randomorder || $randompick) {
 8405:                    $responsenum = $respnumlookup{$missing-1};
 8406:                    $first = $startline{$missing-1};
 8407:                } else {
 8408:                    $responsenum = $missing-1;
 8409:                    $first = $first_bubble_line{$responsenum};
 8410:                }
 8411:                if (!defined($first)) { next; }
 8412:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8413:             }
 8414:             if ($lastbubble > $max_bubble) { next; }
 8415: 	    push(@to_correct,$missing);
 8416: 	}
 8417: 	if (@to_correct) {
 8418: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8419: 				     $line,'missingbubble',\@to_correct,
 8420:                                      $randomorder,$randompick,\%respnumlookup,
 8421:                                      \%startline);
 8422: 	    return (1,$currentphase);
 8423: 	}
 8424: 
 8425:     }
 8426:     return (0,$currentphase+1);
 8427: }
 8428: 
 8429: sub hand_bubble_option {
 8430:     my (undef, undef, $sequence) =
 8431:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8432:     return if ($sequence eq '');
 8433:     my $navmap = Apache::lonnavmaps::navmap->new();
 8434:     unless (ref($navmap)) {
 8435:         return;
 8436:     }
 8437:     my $needs_hand_bubbles;
 8438:     my $map=$navmap->getResourceByUrl($sequence);
 8439:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8440:     foreach my $res (@resources) {
 8441:         if (ref($res)) {
 8442:             if ($res->is_problem()) {
 8443:                 my $partlist = $res->parts();
 8444:                 foreach my $part (@{ $partlist }) {
 8445:                     my @types = $res->responseType($part);
 8446:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8447:                         $needs_hand_bubbles = 1;
 8448:                         last;
 8449:                     }
 8450:                 }
 8451:             }
 8452:         }
 8453:     }
 8454:     if ($needs_hand_bubbles) {
 8455:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8456:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8457:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8458:                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
 8459:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
 8460:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8461:     }
 8462:     return;
 8463: }
 8464: 
 8465: sub scantron_process_students {
 8466:     my ($r,$symb) = @_;
 8467: 
 8468:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8469:     if (!$symb) {
 8470: 	return '';
 8471:     }
 8472:     my $default_form_data=&defaultFormData($symb);
 8473: 
 8474:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8475:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8476:     my ($scanlines,$scan_data)=&scantron_getfile();
 8477:     my $classlist=&Apache::loncoursedata::get_classlist();
 8478:     my %idmap=&username_to_idmap($classlist);
 8479:     my $navmap=Apache::lonnavmaps::navmap->new();
 8480:     unless (ref($navmap)) {
 8481:         $r->print(&navmap_errormsg());
 8482:         return '';
 8483:     }
 8484:     my $map=$navmap->getResourceByUrl($sequence);
 8485:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8486:         %grader_randomlists_by_symb);
 8487:     if (ref($map)) {
 8488:         $randomorder = $map->randomorder();
 8489:         $randompick = $map->randompick();
 8490:     } else {
 8491:         $r->print(&navmap_errormsg());
 8492:         return '';
 8493:     }
 8494:     my $nav_error;
 8495:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8496:     if ($randomorder || $randompick) {
 8497:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8498:         if ($nav_error) {
 8499:             $r->print(&navmap_errormsg());
 8500:             return '';
 8501:         }
 8502:     }
 8503:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8504:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8505: 
 8506:     my ($uname,$udom);
 8507:     my $result= <<SCANTRONFORM;
 8508: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8509:   <input type="hidden" name="command" value="scantron_configphase" />
 8510:   $default_form_data
 8511: SCANTRONFORM
 8512:     $r->print($result);
 8513: 
 8514:     my @delayqueue;
 8515:     my (%completedstudents,%scandata);
 8516:     
 8517:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8518:     my $count=&get_todo_count($scanlines,$scan_data);
 8519:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8520:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8521:     $r->print('<br />');
 8522:     my $start=&Time::HiRes::time();
 8523:     my $i=-1;
 8524:     my $started;
 8525: 
 8526:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8527:     if ($nav_error) {
 8528:         $r->print(&navmap_errormsg());
 8529:         return '';
 8530:     }
 8531: 
 8532:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8533:     # the user and return.
 8534: 
 8535:     if ($ssi_error) {
 8536: 	$r->print("</form>");
 8537: 	&ssi_print_error($r);
 8538:         &Apache::lonnet::remove_lock($lock);
 8539: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8540:     }
 8541: 
 8542:     my %lettdig = &letter_to_digits();
 8543:     my $numletts = scalar(keys(%lettdig));
 8544:     my %orderedforcode;
 8545: 
 8546:     while ($i<$scanlines->{'count'}) {
 8547:  	($uname,$udom)=('','');
 8548:  	$i++;
 8549:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8550:  	if ($line=~/^[\s\cz]*$/) { next; }
 8551: 	if ($started) {
 8552: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8553: 	}
 8554: 	$started=1;
 8555:         my %respnumlookup = ();
 8556:         my %startline = ();
 8557:         my $total;
 8558:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8559:                                                  $scan_data,undef,\%idmap,$randomorder,
 8560:                                                  $randompick,$sequence,\@master_seq,
 8561:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8562:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8563:                                                  \$total);
 8564:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8565:  					      \%idmap,$i)) {
 8566:   	    &scantron_add_delay(\@delayqueue,$line,
 8567:  				'Unable to find a student that matches',1);
 8568:  	    next;
 8569:   	}
 8570:  	if (exists $completedstudents{$uname}) {
 8571:  	    &scantron_add_delay(\@delayqueue,$line,
 8572:  				'Student '.$uname.' has multiple sheets',2);
 8573:  	    next;
 8574:  	}
 8575:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8576:         my $user = $uname.':'.$usec;
 8577:   	($uname,$udom)=split(/:/,$uname);
 8578: 
 8579:         my $scancode;
 8580:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8581:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8582:             $scancode = $scan_record->{'scantron.CODE'};
 8583:         } else {
 8584:             $scancode = '';
 8585:         }
 8586: 
 8587:         my @mapresources = @resources;
 8588:         if ($randomorder || $randompick) {
 8589:             @mapresources = 
 8590:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8591:                              \%orderedforcode);
 8592:         }
 8593:         my (%partids_by_symb,$res_error);
 8594:         foreach my $resource (@mapresources) {
 8595:             my $ressymb;
 8596:             if (ref($resource)) {
 8597:                 $ressymb = $resource->symb();
 8598:             } else {
 8599:                 $res_error = 1;
 8600:                 last;
 8601:             }
 8602:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8603:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8604:                 my ($analysis,$parts) =
 8605:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8606:                                               $uname,$udom,undef,$bubbles_per_row);
 8607:                 $partids_by_symb{$ressymb} = $parts;
 8608:             } else {
 8609:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8610:             }
 8611:         }
 8612: 
 8613:         if ($res_error) {
 8614:             &scantron_add_delay(\@delayqueue,$line,
 8615:                                 'An error occurred while grading student '.$uname,2);
 8616:             next;
 8617:         }
 8618: 
 8619: 	&Apache::lonxml::clear_problem_counter();
 8620:   	&Apache::lonnet::appenv($scan_record);
 8621: 
 8622: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8623: 	    &scantron_putfile($scanlines,$scan_data);
 8624: 	}
 8625: 	
 8626:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8627:                                    \@mapresources,\%partids_by_symb,
 8628:                                    $bubbles_per_row,$randomorder,$randompick,
 8629:                                    \%respnumlookup,\%startline) 
 8630:             eq 'ssi_error') {
 8631:             $ssi_error = 0; # So end of handler error message does not trigger.
 8632:             $r->print("</form>");
 8633:             &ssi_print_error($r);
 8634:             &Apache::lonnet::remove_lock($lock);
 8635:             return '';      # Why return ''?  Beats me.
 8636:         }
 8637: 
 8638:         if (($scancode) && ($randomorder || $randompick)) {
 8639:             my $parmresult =
 8640:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8641:                                                        '0_examcode',2,$scancode,
 8642:                                                        'string_examcode',$uname,
 8643:                                                        $udom);
 8644:         }
 8645: 	$completedstudents{$uname}={'line'=>$line};
 8646:         if ($env{'form.verifyrecord'}) {
 8647:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8648:             if ($randompick) {
 8649:                 if ($total) {
 8650:                     $lastpos = $total*$scantron_config{'Qlength'};
 8651:                 }
 8652:             }
 8653: 
 8654:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8655:             chomp($studentdata);
 8656:             $studentdata =~ s/\r$//;
 8657:             my $studentrecord = '';
 8658:             my $counter = -1;
 8659:             foreach my $resource (@mapresources) {
 8660:                 my $ressymb = $resource->symb();
 8661:                 ($counter,my $recording) =
 8662:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8663:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8664:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8665:                                              $randompick,\%respnumlookup,\%startline);
 8666:                 $studentrecord .= $recording;
 8667:             }
 8668:             if ($studentrecord ne $studentdata) {
 8669:                 &Apache::lonxml::clear_problem_counter();
 8670:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8671:                                            \@mapresources,\%partids_by_symb,
 8672:                                            $bubbles_per_row,$randomorder,$randompick,
 8673:                                            \%respnumlookup,\%startline) 
 8674:                     eq 'ssi_error') {
 8675:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8676:                     $r->print("</form>");
 8677:                     &ssi_print_error($r);
 8678:                     &Apache::lonnet::remove_lock($lock);
 8679:                     delete($completedstudents{$uname});
 8680:                     return '';
 8681:                 }
 8682:                 $counter = -1;
 8683:                 $studentrecord = '';
 8684:                 foreach my $resource (@mapresources) {
 8685:                     my $ressymb = $resource->symb();
 8686:                     ($counter,my $recording) =
 8687:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8688:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8689:                                                  \%scantron_config,\%lettdig,$numletts,
 8690:                                                  $randomorder,$randompick,\%respnumlookup,
 8691:                                                  \%startline);
 8692:                     $studentrecord .= $recording;
 8693:                 }
 8694:                 if ($studentrecord ne $studentdata) {
 8695:                     $r->print('<p><span class="LC_warning">');
 8696:                     if ($scancode eq '') {
 8697:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8698:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8699:                     } else {
 8700:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8701:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8702:                     }
 8703:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8704:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8705:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8706:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8707:                               &Apache::loncommon::start_data_table_row().
 8708:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8709:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8710:                               &Apache::loncommon::end_data_table_row().
 8711:                               &Apache::loncommon::start_data_table_row().
 8712:                               '<td>'.&mt('Stored submissions').'</td>'.
 8713:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8714:                               &Apache::loncommon::end_data_table_row().
 8715:                               &Apache::loncommon::end_data_table().'</p>');
 8716:                 } else {
 8717:                     $r->print('<br /><span class="LC_warning">'.
 8718:                              &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 />'.
 8719:                              &mt("As a consequence, this user's submission history records two tries.").
 8720:                                  '</span><br />');
 8721:                 }
 8722:             }
 8723:         }
 8724:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8725:     } continue {
 8726: 	&Apache::lonxml::clear_problem_counter();
 8727: 	&Apache::lonnet::delenv('scantron.');
 8728:     }
 8729:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8730:     &Apache::lonnet::remove_lock($lock);
 8731: #    my $lasttime = &Time::HiRes::time()-$start;
 8732: #    $r->print("<p>took $lasttime</p>");
 8733: 
 8734:     $r->print("</form>");
 8735:     return '';
 8736: }
 8737: 
 8738: sub graders_resources_pass {
 8739:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8740:         $bubbles_per_row) = @_;
 8741:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8742:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8743:         foreach my $resource (@{$resources}) {
 8744:             my $ressymb = $resource->symb();
 8745:             my ($analysis,$parts) =
 8746:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8747:                                           $env{'user.name'},$env{'user.domain'},
 8748:                                           1,$bubbles_per_row);
 8749:             $grader_partids_by_symb->{$ressymb} = $parts;
 8750:             if (ref($analysis) eq 'HASH') {
 8751:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8752:                     $grader_randomlists_by_symb->{$ressymb} =
 8753:                         $analysis->{'parts_withrandomlist'};
 8754:                 }
 8755:             }
 8756:         }
 8757:     }
 8758:     return;
 8759: }
 8760: 
 8761: =pod
 8762: 
 8763: =item users_order
 8764: 
 8765:   Returns array of resources in current map, ordered based on either CODE,
 8766:   if this is a CODEd exam, or based on student's identity if this is a 
 8767:   "NAMEd" exam.
 8768: 
 8769:   Should be used when randomorder and/or randompick applied when the 
 8770:   corresponding exam was printed, prior to students completing bubblesheets 
 8771:   for the version of the exam the student received.
 8772: 
 8773: =cut
 8774: 
 8775: sub users_order  {
 8776:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8777:     my @mapresources;
 8778:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8779:         return @mapresources;
 8780:     }
 8781:     if ($scancode) {
 8782:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8783:             @mapresources = @{$orderedforcode->{$scancode}};
 8784:         } else {
 8785:             $env{'form.CODE'} = $scancode;
 8786:             my $actual_seq =
 8787:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8788:                                                                $master_seq,
 8789:                                                                $user,$scancode,1);
 8790:             if (ref($actual_seq) eq 'ARRAY') {
 8791:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8792:                 if (ref($orderedforcode) eq 'HASH') {
 8793:                     if (@mapresources > 0) { 
 8794:                         $orderedforcode->{$scancode} = \@mapresources;
 8795:                     }
 8796:                 }
 8797:             }
 8798:             delete($env{'form.CODE'});
 8799:         }
 8800:     } else {
 8801:         my $actual_seq =
 8802:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8803:                                                            $master_seq,
 8804:                                                            $user,undef,1);
 8805:         if (ref($actual_seq) eq 'ARRAY') {
 8806:             @mapresources = 
 8807:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 8808:         }
 8809:     }
 8810:     return @mapresources;
 8811: }
 8812: 
 8813: sub grade_student_bubbles {
 8814:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 8815:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 8816:     my $uselookup = 0;
 8817:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 8818:         (ref($startline) eq 'HASH')) {
 8819:         $uselookup = 1;
 8820:     }
 8821: 
 8822:     if (ref($resources) eq 'ARRAY') {
 8823:         my $count = 0;
 8824:         foreach my $resource (@{$resources}) {
 8825:             my $ressymb = $resource->symb();
 8826:             my %form = ('submitted'      => 'scantron',
 8827:                         'grade_target'   => 'grade',
 8828:                         'grade_username' => $uname,
 8829:                         'grade_domain'   => $udom,
 8830:                         'grade_courseid' => $env{'request.course.id'},
 8831:                         'grade_symb'     => $ressymb,
 8832:                         'CODE'           => $scancode
 8833:                        );
 8834:             if ($bubbles_per_row ne '') {
 8835:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8836:             }
 8837:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8838:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8839:             }
 8840:             if (ref($parts) eq 'HASH') {
 8841:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8842:                     foreach my $part (@{$parts->{$ressymb}}) {
 8843:                         if ($uselookup) {
 8844:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 8845:                         } else {
 8846:                             $form{'scantron_questnum_start.'.$part} =
 8847:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 8848:                         }
 8849:                         $count++;
 8850:                     }
 8851:                 }
 8852:             }
 8853:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8854:             return 'ssi_error' if ($ssi_error);
 8855:             last if (&Apache::loncommon::connection_aborted($r));
 8856:         }
 8857:     }
 8858:     return;
 8859: }
 8860: 
 8861: sub scantron_upload_scantron_data {
 8862:     my ($r,$symb)=@_;
 8863:     my $dom = $env{'request.role.domain'};
 8864:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8865:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8866:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8867: 							  'domainid',
 8868: 							  'coursename',$dom);
 8869:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8870:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8871:     my $default_form_data=&defaultFormData($symb);
 8872:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8873:     &js_escape(\$nofile_alert);
 8874:     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.");
 8875:     &js_escape(\$nocourseid_alert);
 8876:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8877:     function checkUpload(formname) {
 8878: 	if (formname.upfile.value == "") {
 8879: 	    alert("'.$nofile_alert.'");
 8880: 	    return false;
 8881: 	}
 8882:         if (formname.courseid.value == "") {
 8883:             alert("'.$nocourseid_alert.'");
 8884:             return false;
 8885:         }
 8886: 	formname.submit();
 8887:     }
 8888: 
 8889:     function ToSyllabus() {
 8890:         var cdom = '."'$dom'".';
 8891:         var cnum = document.rules.courseid.value;
 8892:         if (cdom == "" || cdom == null) {
 8893:             return;
 8894:         }
 8895:         if (cnum == "" || cnum == null) {
 8896:            return;
 8897:         }
 8898:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8899:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8900:         return;
 8901:     }
 8902: 
 8903: '));
 8904:     $r->print('
 8905: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8906: 
 8907: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8908: '.$default_form_data.
 8909:   &Apache::lonhtmlcommon::start_pick_box().
 8910:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8911:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8912:   &Apache::lonhtmlcommon::row_closure().
 8913:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8914:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8915:   &Apache::lonhtmlcommon::row_closure().
 8916:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8917:   '<input name="domainid" type="hidden" />'.$domdesc.
 8918:   &Apache::lonhtmlcommon::row_closure().
 8919:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8920:   '<input type="file" name="upfile" size="50" />'.
 8921:   &Apache::lonhtmlcommon::row_closure(1).
 8922:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8923: 
 8924: <input name="command" value="scantronupload_save" type="hidden" />
 8925: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8926: </form>
 8927: ');
 8928:     return '';
 8929: }
 8930: 
 8931: 
 8932: sub scantron_upload_scantron_data_save {
 8933:     my($r,$symb)=@_;
 8934:     my $doanotherupload=
 8935: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8936: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8937: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8938: 	'</form>'."\n";
 8939:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8940: 	!&Apache::lonnet::allowed('usc',
 8941: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8942: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8943: 	unless ($symb) {
 8944: 	    $r->print($doanotherupload);
 8945: 	}
 8946: 	return '';
 8947:     }
 8948:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8949:     my $uploadedfile;
 8950:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 8951:     if (length($env{'form.upfile'}) < 2) {
 8952:         $r->print(
 8953:             &Apache::lonhtmlcommon::confirm_success(
 8954:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 8955:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 8956:     } else {
 8957:         my $result = 
 8958:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8959:                                             $env{'form.courseid'},$env{'form.domainid'});
 8960:         if ($result =~ m{^/uploaded/}) {
 8961:             $r->print(
 8962:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 8963:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 8964:                         (length($env{'form.upfile'})-1),
 8965:                         '<span class="LC_filename">'.$result.'</span>'));
 8966:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8967:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8968:                                                        $env{'form.courseid'},$uploadedfile));
 8969:         } else {
 8970:             $r->print(
 8971:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 8972:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 8973:                           $result,
 8974: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8975: 	}
 8976:     }
 8977:     if ($symb) {
 8978: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8979:     } else {
 8980: 	$r->print($doanotherupload);
 8981:     }
 8982:     return '';
 8983: }
 8984: 
 8985: sub validate_uploaded_scantron_file {
 8986:     my ($cdom,$cname,$fname) = @_;
 8987:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8988:     my @lines;
 8989:     if ($scanlines ne '-1') {
 8990:         @lines=split("\n",$scanlines,-1);
 8991:     }
 8992:     my $output;
 8993:     if (@lines) {
 8994:         my (%counts,$max_match_format);
 8995:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 8996:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8997:         my %idmap = &username_to_idmap($classlist);
 8998:         foreach my $key (keys(%idmap)) {
 8999:             my $lckey = lc($key);
 9000:             $idmap{$lckey} = $idmap{$key};
 9001:         }
 9002:         my %unique_formats;
 9003:         my @formatlines = &get_scantronformat_file();
 9004:         foreach my $line (@formatlines) {
 9005:             chomp($line);
 9006:             my @config = split(/:/,$line);
 9007:             my $idstart = $config[5];
 9008:             my $idlength = $config[6];
 9009:             if (($idstart ne '') && ($idlength > 0)) {
 9010:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9011:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9012:                 } else {
 9013:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9014:                 }
 9015:             }
 9016:         }
 9017:         foreach my $key (keys(%unique_formats)) {
 9018:             my ($idstart,$idlength) = split(':',$key);
 9019:             %{$counts{$key}} = (
 9020:                                'found'   => 0,
 9021:                                'total'   => 0,
 9022:                               );
 9023:             foreach my $line (@lines) {
 9024:                 next if ($line =~ /^#/);
 9025:                 next if ($line =~ /^[\s\cz]*$/);
 9026:                 my $id = substr($line,$idstart-1,$idlength);
 9027:                 $id = lc($id);
 9028:                 if (exists($idmap{$id})) {
 9029:                     $counts{$key}{'found'} ++;
 9030:                 }
 9031:                 $counts{$key}{'total'} ++;
 9032:             }
 9033:             if ($counts{$key}{'total'}) {
 9034:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9035:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9036:                     $max_match_pct = $percent_match;
 9037:                     $max_match_format = $key;
 9038:                     $found_match_count = $counts{$key}{'found'};
 9039:                     $max_match_count = $counts{$key}{'total'};
 9040:                 }
 9041:             }
 9042:         }
 9043:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9044:             my $format_descs;
 9045:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9046:             for (my $i=0; $i<$numwithformat; $i++) {
 9047:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9048:                 if ($i<$numwithformat-2) {
 9049:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9050:                 } elsif ($i==$numwithformat-2) {
 9051:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9052:                 } elsif ($i==$numwithformat-1) {
 9053:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9054:                 }
 9055:             }
 9056:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9057:             $output .= '<br />';
 9058:             if ($found_match_count == $max_match_count) {
 9059:                 # 100% matching entries
 9060:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9061:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9062:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9063:                 &mt('Comparison of student IDs in the uploaded file with'.
 9064:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9065:                     ' in the file (for the format defined for [_3]).',
 9066:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9067:             } else {
 9068:                 # Not all entries matching? -> Show warning and additional info
 9069:                 $output .=
 9070:                     &Apache::lonhtmlcommon::confirm_success(
 9071:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9072:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9073:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9074:                     &mt('Comparison of student IDs in the uploaded file with'.
 9075:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9076:                         ' in the file (for the format defined for [_3]).',
 9077:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9078:                     '<p class="LC_info">'.
 9079:                     &mt('A low percentage of matches results from one of the following:').
 9080:                     '</p><ul>'.
 9081:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9082:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9083:                                '<i>'.$cdom.'</i>').'</li>'.
 9084:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9085:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9086:                     '</ul>';
 9087:             }
 9088:         }
 9089:     } else {
 9090:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9091:     }
 9092:     return $output;
 9093: }
 9094: 
 9095: sub valid_file {
 9096:     my ($requested_file)=@_;
 9097:     foreach my $filename (sort(&scantron_filenames())) {
 9098: 	if ($requested_file eq $filename) { return 1; }
 9099:     }
 9100:     return 0;
 9101: }
 9102: 
 9103: sub scantron_download_scantron_data {
 9104:     my ($r,$symb)=@_;
 9105:     my $default_form_data=&defaultFormData($symb);
 9106:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9107:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9108:     my $file=$env{'form.scantron_selectfile'};
 9109:     if (! &valid_file($file)) {
 9110: 	$r->print('
 9111: 	<p>
 9112: 	    '.&mt('The requested filename was invalid.').'
 9113:         </p>
 9114: ');
 9115: 	return;
 9116:     }
 9117:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9118:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9119:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9120:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9121:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9122:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9123:     $r->print('
 9124:     <p>
 9125: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9126: 	      '<a href="'.$orig.'">','</a>').'
 9127:     </p>
 9128:     <p>
 9129: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9130: 	      '<a href="'.$corrected.'">','</a>').'
 9131:     </p>
 9132:     <p>
 9133: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9134: 	      '<a href="'.$skipped.'">','</a>').'
 9135:     </p>
 9136: ');
 9137:     return '';
 9138: }
 9139: 
 9140: sub checkscantron_results {
 9141:     my ($r,$symb) = @_;
 9142:     if (!$symb) {return '';}
 9143:     my $cid = $env{'request.course.id'};
 9144:     my %lettdig = &letter_to_digits();
 9145:     my $numletts = scalar(keys(%lettdig));
 9146:     my $cnum = $env{'course.'.$cid.'.num'};
 9147:     my $cdom = $env{'course.'.$cid.'.domain'};
 9148:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9149:     my %record;
 9150:     my %scantron_config =
 9151:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9152:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9153:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9154:     my $classlist=&Apache::loncoursedata::get_classlist();
 9155:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9156:     my $navmap=Apache::lonnavmaps::navmap->new();
 9157:     unless (ref($navmap)) {
 9158:         $r->print(&navmap_errormsg());
 9159:         return '';
 9160:     }
 9161:     my $map=$navmap->getResourceByUrl($sequence);
 9162:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9163:         %grader_randomlists_by_symb,%orderedforcode);
 9164:     if (ref($map)) { 
 9165:         $randomorder=$map->randomorder();
 9166:         $randompick=$map->randompick();
 9167:     }
 9168:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9169:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9170:     if ($nav_error) {
 9171:         $r->print(&navmap_errormsg());
 9172:         return '';
 9173:     }
 9174:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9175:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9176:     my ($uname,$udom);
 9177:     my (%scandata,%lastname,%bylast);
 9178:     $r->print('
 9179: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9180: 
 9181:     my @delayqueue;
 9182:     my %completedstudents;
 9183: 
 9184:     my $count=&get_todo_count($scanlines,$scan_data);
 9185:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9186:     my ($username,$domain,$started);
 9187:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9188:     if ($nav_error) {
 9189:         $r->print(&navmap_errormsg());
 9190:         return '';
 9191:     }
 9192: 
 9193:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9194:     my $start=&Time::HiRes::time();
 9195:     my $i=-1;
 9196: 
 9197:     while ($i<$scanlines->{'count'}) {
 9198:         ($username,$domain,$uname)=('','','');
 9199:         $i++;
 9200:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9201:         if ($line=~/^[\s\cz]*$/) { next; }
 9202:         if ($started) {
 9203:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9204:         }
 9205:         $started=1;
 9206:         my $scan_record=
 9207:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9208:                                                      $scan_data);
 9209:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9210:                                               \%idmap,$i)) {
 9211:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9212:                                 'Unable to find a student that matches',1);
 9213:             next;
 9214:         }
 9215:         if (exists $completedstudents{$uname}) {
 9216:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9217:                                 'Student '.$uname.' has multiple sheets',2);
 9218:             next;
 9219:         }
 9220:         my $pid = $scan_record->{'scantron.ID'};
 9221:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9222:         push(@{$bylast{$lastname{$pid}}},$pid);
 9223:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9224:         my $user = $uname.':'.$usec;
 9225:         ($username,$domain)=split(/:/,$uname);
 9226: 
 9227:         my $scancode;
 9228:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9229:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9230:             $scancode = $scan_record->{'scantron.CODE'};
 9231:         } else {
 9232:             $scancode = '';
 9233:         }
 9234: 
 9235:         my @mapresources = @resources;
 9236:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9237:         my %respnumlookup=();
 9238:         my %startline=();
 9239:         if ($randomorder || $randompick) {
 9240:             @mapresources =
 9241:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9242:                              \%orderedforcode);
 9243:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9244:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9245:                                              \%grader_partids_by_symb,\%orderedforcode,
 9246:                                              \%respnumlookup,\%startline);
 9247:             if ($randompick && $total) {
 9248:                 $lastpos = $total*$scantron_config{'Qlength'};
 9249:             }
 9250:         }
 9251:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9252:         chomp($scandata{$pid});
 9253:         $scandata{$pid} =~ s/\r$//;
 9254: 
 9255:         my $counter = -1;
 9256:         foreach my $resource (@mapresources) {
 9257:             my $parts;
 9258:             my $ressymb = $resource->symb();
 9259:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9260:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9261:                 (my $analysis,$parts) =
 9262:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9263:                                               $username,$domain,undef,
 9264:                                               $bubbles_per_row);
 9265:             } else {
 9266:                 $parts = $grader_partids_by_symb{$ressymb};
 9267:             }
 9268:             ($counter,my $recording) =
 9269:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9270:                                          $scandata{$pid},$parts,
 9271:                                          \%scantron_config,\%lettdig,$numletts,
 9272:                                          $randomorder,$randompick,
 9273:                                          \%respnumlookup,\%startline);
 9274:             $record{$pid} .= $recording;
 9275:         }
 9276:     }
 9277:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9278:     $r->print('<br />');
 9279:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9280:     $passed = 0;
 9281:     $failed = 0;
 9282:     $numstudents = 0;
 9283:     foreach my $last (sort(keys(%bylast))) {
 9284:         if (ref($bylast{$last}) eq 'ARRAY') {
 9285:             foreach my $pid (sort(@{$bylast{$last}})) {
 9286:                 my $showscandata = $scandata{$pid};
 9287:                 my $showrecord = $record{$pid};
 9288:                 $showscandata =~ s/\s/&nbsp;/g;
 9289:                 $showrecord =~ s/\s/&nbsp;/g;
 9290:                 if ($scandata{$pid} eq $record{$pid}) {
 9291:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9292:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9293: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9294: '</tr>'."\n".
 9295: '<tr class="'.$css_class.'">'."\n".
 9296: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9297:                     $passed ++;
 9298:                 } else {
 9299:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9300:                     $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".
 9301: '</tr>'."\n".
 9302: '<tr class="'.$css_class.'">'."\n".
 9303: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9304: '</tr>'."\n";
 9305:                     $failed ++;
 9306:                 }
 9307:                 $numstudents ++;
 9308:             }
 9309:         }
 9310:     }
 9311:     $r->print(
 9312:         '<p>'
 9313:        .&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).',
 9314:             '<b>',
 9315:             $numstudents,
 9316:             '</b>',
 9317:             $env{'form.scantron_maxbubble'})
 9318:        .'</p>'
 9319:     );
 9320:     $r->print('<p>'
 9321:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9322:              .'<br />'
 9323:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9324:              .'</p>'
 9325:     );
 9326:     if ($passed) {
 9327:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9328:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9329:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9330:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9331:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9332:                  $okstudents."\n".
 9333:                  &Apache::loncommon::end_data_table().'<br />');
 9334:     }
 9335:     if ($failed) {
 9336:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9337:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9338:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9339:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9340:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9341:                  $badstudents."\n".
 9342:                  &Apache::loncommon::end_data_table()).'<br />'.
 9343:                  &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.');  
 9344:     }
 9345:     $r->print('</form><br />');
 9346:     return;
 9347: }
 9348: 
 9349: sub verify_scantron_grading {
 9350:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9351:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9352:         $respnumlookup,$startline) = @_;
 9353:     my ($record,%expected,%startpos);
 9354:     return ($counter,$record) if (!ref($resource));
 9355:     return ($counter,$record) if (!$resource->is_problem());
 9356:     my $symb = $resource->symb();
 9357:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9358:     foreach my $part_id (@{$partids}) {
 9359:         $counter ++;
 9360:         $expected{$part_id} = 0;
 9361:         my $respnum = $counter;
 9362:         if ($randomorder || $randompick) {
 9363:             $respnum = $respnumlookup->{$counter};
 9364:             $startpos{$part_id} = $startline->{$counter} + 1;
 9365:         } else {
 9366:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9367:         }
 9368:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9369:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9370:             foreach my $item (@sub_lines) {
 9371:                 $expected{$part_id} += $item;
 9372:             }
 9373:         } else {
 9374:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9375:         }
 9376:     }
 9377:     if ($symb) {
 9378:         my %recorded;
 9379:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9380:         if ($returnhash{'version'}) {
 9381:             my %lasthash=();
 9382:             my $version;
 9383:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9384:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9385:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9386:                 }
 9387:             }
 9388:             foreach my $key (keys(%lasthash)) {
 9389:                 if ($key =~ /\.scantron$/) {
 9390:                     my $value = &unescape($lasthash{$key});
 9391:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9392:                     if ($value eq '') {
 9393:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9394:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9395:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9396:                             }
 9397:                         }
 9398:                     } else {
 9399:                         my @tocheck;
 9400:                         my @items = split(//,$value);
 9401:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9402:                             ($scantron_config->{'Qon'} eq 'number')) {
 9403:                             if (@items < $expected{$part_id}) {
 9404:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9405:                                 my @singles = split(//,$fragment);
 9406:                                 foreach my $pos (@singles) {
 9407:                                     if ($pos eq ' ') {
 9408:                                         push(@tocheck,$pos);
 9409:                                     } else {
 9410:                                         my $next = shift(@items);
 9411:                                         push(@tocheck,$next);
 9412:                                     }
 9413:                                 }
 9414:                             } else {
 9415:                                 @tocheck = @items;
 9416:                             }
 9417:                             foreach my $letter (@tocheck) {
 9418:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9419:                                     if ($letter !~ /^[A-J]$/) {
 9420:                                         $letter = $scantron_config->{'Qoff'};
 9421:                                     }
 9422:                                     $recorded{$part_id} .= $letter;
 9423:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9424:                                     my $digit;
 9425:                                     if ($letter !~ /^[A-J]$/) {
 9426:                                         $digit = $scantron_config->{'Qoff'};
 9427:                                     } else {
 9428:                                         $digit = $lettdig->{$letter};
 9429:                                     }
 9430:                                     $recorded{$part_id} .= $digit;
 9431:                                 }
 9432:                             }
 9433:                         } else {
 9434:                             @tocheck = @items;
 9435:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9436:                                 my $curr_sub = shift(@tocheck);
 9437:                                 my $digit;
 9438:                                 if ($curr_sub =~ /^[A-J]$/) {
 9439:                                     $digit = $lettdig->{$curr_sub}-1;
 9440:                                 }
 9441:                                 if ($curr_sub eq 'J') {
 9442:                                     $digit += scalar($numletts);
 9443:                                 }
 9444:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9445:                                     if ($j == $digit) {
 9446:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9447:                                     } else {
 9448:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9449:                                     }
 9450:                                 }
 9451:                             }
 9452:                         }
 9453:                     }
 9454:                 }
 9455:             }
 9456:         }
 9457:         foreach my $part_id (@{$partids}) {
 9458:             if ($recorded{$part_id} eq '') {
 9459:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9460:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9461:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9462:                     }
 9463:                 }
 9464:             }
 9465:             $record .= $recorded{$part_id};
 9466:         }
 9467:     }
 9468:     return ($counter,$record);
 9469: }
 9470: 
 9471: sub letter_to_digits {
 9472:     my %lettdig = (
 9473:                     A => 1,
 9474:                     B => 2,
 9475:                     C => 3,
 9476:                     D => 4,
 9477:                     E => 5,
 9478:                     F => 6,
 9479:                     G => 7,
 9480:                     H => 8,
 9481:                     I => 9,
 9482:                     J => 0,
 9483:                   );
 9484:     return %lettdig;
 9485: }
 9486: 
 9487: 
 9488: #-------- end of section for handling grading scantron forms -------
 9489: #
 9490: #-------------------------------------------------------------------
 9491: 
 9492: #-------------------------- Menu interface -------------------------
 9493: #
 9494: #--- Href with symb and command ---
 9495: 
 9496: sub href_symb_cmd {
 9497:     my ($symb,$cmd)=@_;
 9498:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9499: }
 9500: 
 9501: sub grading_menu {
 9502:     my ($request,$symb) = @_;
 9503:     if (!$symb) {return '';}
 9504: 
 9505:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9506:                   'command'=>'individual');
 9507:     
 9508:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9509: 
 9510:     $fields{'command'}='ungraded';
 9511:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9512: 
 9513:     $fields{'command'}='table';
 9514:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9515: 
 9516:     $fields{'command'}='all_for_one';
 9517:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9518: 
 9519:     $fields{'command'}='downloadfilesselect';
 9520:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9521: 
 9522:     $fields{'command'} = 'csvform';
 9523:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9524:     
 9525:     $fields{'command'} = 'processclicker';
 9526:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9527:     
 9528:     $fields{'command'} = 'scantron_selectphase';
 9529:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9530: 
 9531:     $fields{'command'} = 'initialverifyreceipt';
 9532:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9533:     
 9534:     my @menu = ({	categorytitle=>'Hand Grading',
 9535:             items =>[
 9536:                         {	linktext => 'Select individual students to grade',
 9537:                     		url => $url1a,
 9538:                     		permission => 'F',
 9539:                     		icon => 'grade_students.png',
 9540:                     		linktitle => 'Grade current resource for a selection of students.'
 9541:                         }, 
 9542:                         {       linktext => 'Grade ungraded submissions.',
 9543:                                 url => $url1b,
 9544:                                 permission => 'F',
 9545:                                 icon => 'ungrade_sub.png',
 9546:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9547:                         },
 9548: 
 9549:                         {       linktext => 'Grading table',
 9550:                                 url => $url1c,
 9551:                                 permission => 'F',
 9552:                                 icon => 'grading_table.png',
 9553:                                 linktitle => 'Grade current resource for all students.'
 9554:                         },
 9555:                         {       linktext => 'Grade page/folder for one student',
 9556:                                 url => $url1d,
 9557:                                 permission => 'F',
 9558:                                 icon => 'grade_PageFolder.png',
 9559:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9560:                         },
 9561:                         {       linktext => 'Download submissions',
 9562:                                 url => $url1e,
 9563:                                 permission => 'F',
 9564:                                 icon => 'download_sub.png',
 9565:                                 linktitle => 'Download all students submissions.'
 9566:                         }]},
 9567:                          { categorytitle=>'Automated Grading',
 9568:                items =>[
 9569: 
 9570:                 	    {	linktext => 'Upload Scores',
 9571:                     		url => $url2,
 9572:                     		permission => 'F',
 9573:                     		icon => 'uploadscores.png',
 9574:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9575:                 	    },
 9576:                 	    {	linktext => 'Process Clicker',
 9577:                     		url => $url3,
 9578:                     		permission => 'F',
 9579:                     		icon => 'addClickerInfoFile.png',
 9580:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9581:                 	    },
 9582:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9583:                     		url => $url4,
 9584:                     		permission => 'F',
 9585:                     		icon => 'bubblesheet.png',
 9586:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9587:                 	    },
 9588:                             {   linktext => 'Verify Receipt Number',
 9589:                                 url => $url5,
 9590:                                 permission => 'F',
 9591:                                 icon => 'receipt_number.png',
 9592:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9593:                             }
 9594: 
 9595:                     ]
 9596:             });
 9597: 
 9598:     # Create the menu
 9599:     my $Str;
 9600:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9601:     $Str .= '<input type="hidden" name="command" value="" />'.
 9602:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9603: 
 9604:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9605:     return $Str;    
 9606: }
 9607: 
 9608: 
 9609: sub ungraded {
 9610:     my ($request)=@_;
 9611:     &submit_options($request);
 9612: }
 9613: 
 9614: sub submit_options_sequence {
 9615:     my ($request,$symb) = @_;
 9616:     if (!$symb) {return '';}
 9617:     &commonJSfunctions($request);
 9618:     my $result;
 9619: 
 9620:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9621:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9622:     $result.=&selectfield(0).
 9623:             '<input type="hidden" name="command" value="pickStudentPage" />
 9624:             <div>
 9625:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9626:             </div>
 9627:         </div>
 9628:   </form>';
 9629:     return $result;
 9630: }
 9631: 
 9632: sub submit_options_table {
 9633:     my ($request,$symb) = @_;
 9634:     if (!$symb) {return '';}
 9635:     &commonJSfunctions($request);
 9636:     my $result;
 9637: 
 9638:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9639:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9640: 
 9641:     $result.=&selectfield(1).
 9642:             '<input type="hidden" name="command" value="viewgrades" />
 9643:             <div>
 9644:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9645:             </div>
 9646:         </div>
 9647:   </form>';
 9648:     return $result;
 9649: }
 9650: 
 9651: sub submit_options_download {
 9652:     my ($request,$symb) = @_;
 9653:     if (!$symb) {return '';}
 9654: 
 9655:     &commonJSfunctions($request);
 9656: 
 9657:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9658:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9659:     $result.='
 9660: <h2>
 9661:   '.&mt('Select Students for Which to Download Submissions').'
 9662: </h2>'.&selectfield(1).'
 9663:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9664:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9665:             </div>
 9666:           </div>
 9667: 
 9668: 
 9669:   </form>';
 9670:     return $result;
 9671: }
 9672: 
 9673: #--- Displays the submissions first page -------
 9674: sub submit_options {
 9675:     my ($request,$symb) = @_;
 9676:     if (!$symb) {return '';}
 9677: 
 9678:     &commonJSfunctions($request);
 9679:     my $result;
 9680: 
 9681:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9682: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9683:     $result.=&selectfield(1).'
 9684:                 <input type="hidden" name="command" value="submission" /> 
 9685: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9686:             </div>
 9687:           </div>
 9688: 
 9689: 
 9690:   </form>';
 9691:     return $result;
 9692: }
 9693: 
 9694: sub selectfield {
 9695:    my ($full)=@_;
 9696:    my %options = 
 9697:           (&substatus_options,
 9698:            'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9699:    my $result='<div class="LC_columnSection">
 9700:   
 9701:     <fieldset>
 9702:       <legend>
 9703:        '.&mt('Sections').'
 9704:       </legend>
 9705:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9706:     </fieldset>
 9707:   
 9708:     <fieldset>
 9709:       <legend>
 9710:         '.&mt('Groups').'
 9711:       </legend>
 9712:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9713:     </fieldset>
 9714:   
 9715:     <fieldset>
 9716:       <legend>
 9717:         '.&mt('Access Status').'
 9718:       </legend>
 9719:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9720:     </fieldset>';
 9721:     if ($full) {
 9722:        $result.='
 9723:     <fieldset>
 9724:       <legend>
 9725:         '.&mt('Submission Status').'
 9726:       </legend>'.
 9727:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9728:    '</fieldset>';
 9729:     }
 9730:     $result.='</div><br />';
 9731:     return $result;
 9732: }
 9733: 
 9734: sub substatus_options {
 9735:     return &Apache::lonlocal::texthash(
 9736:                                       'yes'       => 'with submissions',
 9737:                                       'queued'    => 'in grading queue',
 9738:                                       'graded'    => 'with ungraded submissions',
 9739:                                       'incorrect' => 'with incorrect submissions',
 9740:                                       'all'       => 'with any status',
 9741:                                       );
 9742: }
 9743: 
 9744: sub reset_perm {
 9745:     undef(%perm);
 9746: }
 9747: 
 9748: sub init_perm {
 9749:     &reset_perm();
 9750:     foreach my $test_perm ('vgr','mgr','opa') {
 9751: 
 9752: 	my $scope = $env{'request.course.id'};
 9753: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 9754: 
 9755: 	    $scope .= '/'.$env{'request.course.sec'};
 9756: 	    if ( $perm{$test_perm}=
 9757: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 9758: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 9759: 	    } else {
 9760: 		delete($perm{$test_perm});
 9761: 	    }
 9762: 	}
 9763:     }
 9764: }
 9765: 
 9766: sub init_old_essays {
 9767:     my ($symb,$apath,$adom,$aname) = @_;
 9768:     if ($symb ne '') {
 9769:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 9770:         if (keys(%essays) > 0) {
 9771:             $old_essays{$symb} = \%essays;
 9772:         }
 9773:     }
 9774:     return;
 9775: }
 9776: 
 9777: sub reset_old_essays {
 9778:     undef(%old_essays);
 9779: }
 9780: 
 9781: sub gather_clicker_ids {
 9782:     my %clicker_ids;
 9783: 
 9784:     my $classlist = &Apache::loncoursedata::get_classlist();
 9785: 
 9786:     # Set up a couple variables.
 9787:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9788:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9789:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9790: 
 9791:     foreach my $student (keys(%$classlist)) {
 9792:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9793:         my $username = $classlist->{$student}->[$username_idx];
 9794:         my $domain   = $classlist->{$student}->[$domain_idx];
 9795:         my $clickers =
 9796: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9797:         foreach my $id (split(/\,/,$clickers)) {
 9798:             $id=~s/^[\#0]+//;
 9799:             $id=~s/[\-\:]//g;
 9800:             if (exists($clicker_ids{$id})) {
 9801: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9802:             } else {
 9803: 		$clicker_ids{$id}=$username.':'.$domain;
 9804:             }
 9805:         }
 9806:     }
 9807:     return %clicker_ids;
 9808: }
 9809: 
 9810: sub gather_adv_clicker_ids {
 9811:     my %clicker_ids;
 9812:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9813:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9814:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9815:     foreach my $element (sort(keys(%coursepersonnel))) {
 9816:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9817:             my ($puname,$pudom)=split(/\:/,$person);
 9818:             my $clickers =
 9819: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9820:             foreach my $id (split(/\,/,$clickers)) {
 9821: 		$id=~s/^[\#0]+//;
 9822:                 $id=~s/[\-\:]//g;
 9823: 		if (exists($clicker_ids{$id})) {
 9824: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9825: 		} else {
 9826: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9827: 		}
 9828:             }
 9829:         }
 9830:     }
 9831:     return %clicker_ids;
 9832: }
 9833: 
 9834: sub clicker_grading_parameters {
 9835:     return ('gradingmechanism' => 'scalar',
 9836:             'upfiletype' => 'scalar',
 9837:             'specificid' => 'scalar',
 9838:             'pcorrect' => 'scalar',
 9839:             'pincorrect' => 'scalar');
 9840: }
 9841: 
 9842: sub process_clicker {
 9843:     my ($r,$symb)=@_;
 9844:     if (!$symb) {return '';}
 9845:     my $result=&checkforfile_js();
 9846:     $result.=&Apache::loncommon::start_data_table().
 9847:              &Apache::loncommon::start_data_table_header_row().
 9848:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9849:              &Apache::loncommon::end_data_table_header_row().
 9850:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9851: # Attempt to restore parameters from last session, set defaults if not present
 9852:     my %Saveable_Parameters=&clicker_grading_parameters();
 9853:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9854:                                                  \%Saveable_Parameters);
 9855:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9856:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9857:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9858:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9859: 
 9860:     my %checked;
 9861:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9862:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9863:           $checked{$gradingmechanism}=' checked="checked"';
 9864:        }
 9865:     }
 9866: 
 9867:     my $upload=&mt("Evaluate File");
 9868:     my $type=&mt("Type");
 9869:     my $attendance=&mt("Award points just for participation");
 9870:     my $personnel=&mt("Correctness determined from response by course personnel");
 9871:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9872:     my $given=&mt("Correctness determined from given list of answers").' '.
 9873:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9874:     my $pcorrect=&mt("Percentage points for correct solution");
 9875:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9876:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9877: 						   {'iclicker' => 'i>clicker',
 9878:                                                     'interwrite' => 'interwrite PRS',
 9879:                                                     'turning' => 'Turning Technologies'});
 9880:     $symb = &Apache::lonenc::check_encrypt($symb);
 9881:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9882: function sanitycheck() {
 9883: // Accept only integer percentages
 9884:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9885:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9886: // Find out grading choice
 9887:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9888:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9889:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9890:       }
 9891:    }
 9892: // By default, new choice equals user selection
 9893:    newgradingchoice=gradingchoice;
 9894: // Not good to give more points for false answers than correct ones
 9895:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9896:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9897:    }
 9898: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9899:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9900:       document.forms.gradesupload.pcorrect.value=100;
 9901:       document.forms.gradesupload.pincorrect.value=100;
 9902:    }
 9903: // If the values are different, cannot be attendance only
 9904:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9905:        (gradingchoice=='attendance')) {
 9906:        newgradingchoice='personnel';
 9907:    }
 9908: // Change grading choice to new one
 9909:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9910:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9911:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9912:       } else {
 9913:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9914:       }
 9915:    }
 9916: // Remember the old state
 9917:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9918: }
 9919: ENDUPFORM
 9920:     $result.= <<ENDUPFORM;
 9921: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9922: <input type="hidden" name="symb" value="$symb" />
 9923: <input type="hidden" name="command" value="processclickerfile" />
 9924: <input type="file" name="upfile" size="50" />
 9925: <br /><label>$type: $selectform</label>
 9926: ENDUPFORM
 9927:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9928:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9929:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9930: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9931: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9932: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9933: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9934: <br />&nbsp;&nbsp;&nbsp;
 9935: <input type="text" name="givenanswer" size="50" />
 9936: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9937: ENDGRADINGFORM
 9938:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9939:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9940:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9941: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9942: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9943: </form>'
 9944: ENDPERCFORM
 9945:     $result.='</td>'.
 9946:              &Apache::loncommon::end_data_table_row().
 9947:              &Apache::loncommon::end_data_table();
 9948:     return $result;
 9949: }
 9950: 
 9951: sub process_clicker_file {
 9952:     my ($r,$symb)=@_;
 9953:     if (!$symb) {return '';}
 9954: 
 9955:     my %Saveable_Parameters=&clicker_grading_parameters();
 9956:     &Apache::loncommon::store_course_settings('grades_clicker',
 9957:                                               \%Saveable_Parameters);
 9958:     my $result='';
 9959:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9960: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9961: 	return $result;
 9962:     }
 9963:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9964:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9965:         return $result;
 9966:     }
 9967:     my $foundgiven=0;
 9968:     if ($env{'form.gradingmechanism'} eq 'given') {
 9969:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9970:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9971:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9972:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9973:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9974:         $foundgiven=$#answers+1;
 9975:     }
 9976:     my %clicker_ids=&gather_clicker_ids();
 9977:     my %correct_ids;
 9978:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9979: 	%correct_ids=&gather_adv_clicker_ids();
 9980:     }
 9981:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9982: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9983: 	   $correct_id=~tr/a-z/A-Z/;
 9984: 	   $correct_id=~s/\s//gs;
 9985: 	   $correct_id=~s/^[\#0]+//;
 9986:            $correct_id=~s/[\-\:]//g;
 9987:            if ($correct_id) {
 9988: 	      $correct_ids{$correct_id}='specified';
 9989:            }
 9990:         }
 9991:     }
 9992:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9993: 	$result.=&mt('Score based on attendance only');
 9994:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9995:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9996:     } else {
 9997: 	my $number=0;
 9998: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9999: 	foreach my $id (sort(keys(%correct_ids))) {
10000: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10001: 	    if ($correct_ids{$id} eq 'specified') {
10002: 		$result.=&mt('specified');
10003: 	    } else {
10004: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10005: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10006: 	    }
10007: 	    $number++;
10008: 	}
10009:         $result.="</p>\n";
10010:         if ($number==0) {
10011:             $result .=
10012:                  &Apache::lonhtmlcommon::confirm_success(
10013:                      &mt('No IDs found to determine correct answer'),1);
10014:             return $result;
10015:         }
10016:     }
10017:     if (length($env{'form.upfile'}) < 2) {
10018:         $result .=
10019:             &Apache::lonhtmlcommon::confirm_success(
10020:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10021:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10022:         return $result;
10023:     }
10024: 
10025: # Were able to get all the info needed, now analyze the file
10026: 
10027:     $result.=&Apache::loncommon::studentbrowser_javascript();
10028:     $symb = &Apache::lonenc::check_encrypt($symb);
10029:     $result.=&Apache::loncommon::start_data_table().
10030:              &Apache::loncommon::start_data_table_header_row().
10031:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10032:              &Apache::loncommon::end_data_table_header_row().
10033:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10034: <td>
10035: <form method="post" action="/adm/grades" name="clickeranalysis">
10036: <input type="hidden" name="symb" value="$symb" />
10037: <input type="hidden" name="command" value="assignclickergrades" />
10038: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10039: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10040: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10041: ENDHEADER
10042:     if ($env{'form.gradingmechanism'} eq 'given') {
10043:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10044:     } 
10045:     my %responses;
10046:     my @questiontitles;
10047:     my $errormsg='';
10048:     my $number=0;
10049:     if ($env{'form.upfiletype'} eq 'iclicker') {
10050: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10051:     }
10052:     if ($env{'form.upfiletype'} eq 'interwrite') {
10053:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10054:     }
10055:     if ($env{'form.upfiletype'} eq 'turning') {
10056:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10057:     }
10058:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10059:              '<input type="hidden" name="number" value="'.$number.'" />'.
10060:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10061:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10062:              '<br />';
10063:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10064:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10065:        return $result;
10066:     } 
10067: # Remember Question Titles
10068: # FIXME: Possibly need delimiter other than ":"
10069:     for (my $i=0;$i<$number;$i++) {
10070:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10071:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10072:     }
10073:     my $correct_count=0;
10074:     my $student_count=0;
10075:     my $unknown_count=0;
10076: # Match answers with usernames
10077: # FIXME: Possibly need delimiter other than ":"
10078:     foreach my $id (keys(%responses)) {
10079:        if ($correct_ids{$id}) {
10080:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10081:           $correct_count++;
10082:        } elsif ($clicker_ids{$id}) {
10083:           if ($clicker_ids{$id}=~/\,/) {
10084: # More than one user with the same clicker!
10085:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10086:                            &Apache::loncommon::start_data_table_row()."<td>".
10087:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10088:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10089:                            "<select name='multi".$id."'>";
10090:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10091:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10092:              }
10093:              $result.='</select>';
10094:              $unknown_count++;
10095:           } else {
10096: # Good: found one and only one user with the right clicker
10097:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10098:              $student_count++;
10099:           }
10100:        } else {
10101:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10102:                            &Apache::loncommon::start_data_table_row()."<td>".
10103:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10104:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10105:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10106:                    "\n".&mt("Domain").": ".
10107:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10108:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10109:           $unknown_count++;
10110:        }
10111:     }
10112:     $result.='<hr />'.
10113:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10114:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10115:        if ($correct_count==0) {
10116:           $errormsg.="Found no correct answers for grading!";
10117:        } elsif ($correct_count>1) {
10118:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10119:        }
10120:     }
10121:     if ($number<1) {
10122:        $errormsg.="Found no questions.";
10123:     }
10124:     if ($errormsg) {
10125:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10126:     } else {
10127:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10128:     }
10129:     $result.='</form></td>'.
10130:              &Apache::loncommon::end_data_table_row().
10131:              &Apache::loncommon::end_data_table();
10132:     return $result;
10133: }
10134: 
10135: sub iclicker_eval {
10136:     my ($questiontitles,$responses)=@_;
10137:     my $number=0;
10138:     my $errormsg='';
10139:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10140:         my %components=&Apache::loncommon::record_sep($line);
10141:         my @entries=map {$components{$_}} (sort(keys(%components)));
10142: 	if ($entries[0] eq 'Question') {
10143: 	    for (my $i=3;$i<$#entries;$i+=6) {
10144: 		$$questiontitles[$number]=$entries[$i];
10145: 		$number++;
10146: 	    }
10147: 	}
10148: 	if ($entries[0]=~/^\#/) {
10149: 	    my $id=$entries[0];
10150: 	    my @idresponses;
10151: 	    $id=~s/^[\#0]+//;
10152: 	    for (my $i=0;$i<$number;$i++) {
10153: 		my $idx=3+$i*6;
10154:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10155: 		push(@idresponses,$entries[$idx]);
10156: 	    }
10157: 	    $$responses{$id}=join(',',@idresponses);
10158: 	}
10159:     }
10160:     return ($errormsg,$number);
10161: }
10162: 
10163: sub interwrite_eval {
10164:     my ($questiontitles,$responses)=@_;
10165:     my $number=0;
10166:     my $errormsg='';
10167:     my $skipline=1;
10168:     my $questionnumber=0;
10169:     my %idresponses=();
10170:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10171:         my %components=&Apache::loncommon::record_sep($line);
10172:         my @entries=map {$components{$_}} (sort(keys(%components)));
10173:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10174:         if ($entries[1] eq 'Response') { $skipline=1; }
10175:         next if $skipline;
10176:         if ($entries[0]!=$questionnumber) {
10177:            $questionnumber=$entries[0];
10178:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10179:            $number++;
10180:         }
10181:         my $id=$entries[4];
10182:         $id=~s/^[\#0]+//;
10183:         $id=~s/^v\d*\://i;
10184:         $id=~s/[\-\:]//g;
10185:         $idresponses{$id}[$number]=$entries[6];
10186:     }
10187:     foreach my $id (keys(%idresponses)) {
10188:        $$responses{$id}=join(',',@{$idresponses{$id}});
10189:        $$responses{$id}=~s/^\s*\,//;
10190:     }
10191:     return ($errormsg,$number);
10192: }
10193: 
10194: sub turning_eval {
10195:     my ($questiontitles,$responses)=@_;
10196:     my $number=0;
10197:     my $errormsg='';
10198:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10199:         my %components=&Apache::loncommon::record_sep($line);
10200:         my @entries=map {$components{$_}} (sort(keys(%components)));
10201:         if ($#entries>$number) { $number=$#entries; }
10202:         my $id=$entries[0];
10203:         my @idresponses;
10204:         $id=~s/^[\#0]+//;
10205:         unless ($id) { next; }
10206:         for (my $idx=1;$idx<=$#entries;$idx++) {
10207:             $entries[$idx]=~s/\,/\;/g;
10208:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10209:             push(@idresponses,$entries[$idx]);
10210:         }
10211:         $$responses{$id}=join(',',@idresponses);
10212:     }
10213:     for (my $i=1; $i<=$number; $i++) {
10214:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10215:     }
10216:     return ($errormsg,$number);
10217: }
10218: 
10219: 
10220: sub assign_clicker_grades {
10221:     my ($r,$symb)=@_;
10222:     if (!$symb) {return '';}
10223: # See which part we are saving to
10224:     my $res_error;
10225:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10226:     if ($res_error) {
10227:         return &navmap_errormsg();
10228:     }
10229: # FIXME: This should probably look for the first handgradeable part
10230:     my $part=$$partlist[0];
10231: # Start screen output
10232:     my $result=&Apache::loncommon::start_data_table().
10233:              &Apache::loncommon::start_data_table_header_row().
10234:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10235:              &Apache::loncommon::end_data_table_header_row().
10236:              &Apache::loncommon::start_data_table_row().'<td>';
10237: # Get correct result
10238: # FIXME: Possibly need delimiter other than ":"
10239:     my @correct=();
10240:     my $gradingmechanism=$env{'form.gradingmechanism'};
10241:     my $number=$env{'form.number'};
10242:     if ($gradingmechanism ne 'attendance') {
10243:        foreach my $key (keys(%env)) {
10244:           if ($key=~/^form\.correct\:/) {
10245:              my @input=split(/\,/,$env{$key});
10246:              for (my $i=0;$i<=$#input;$i++) {
10247:                  if (($correct[$i]) && ($input[$i]) &&
10248:                      ($correct[$i] ne $input[$i])) {
10249:                     $result.='<br /><span class="LC_warning">'.
10250:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10251:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10252:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10253:                     $correct[$i]=$input[$i];
10254:                  }
10255:              }
10256:           }
10257:        }
10258:        for (my $i=0;$i<$number;$i++) {
10259:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10260:              $result.='<br /><span class="LC_error">'.
10261:                       &mt('No correct result given for question "[_1]"!',
10262:                           $env{'form.question:'.$i}).'</span>';
10263:           }
10264:        }
10265:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10266:     }
10267: # Start grading
10268:     my $pcorrect=$env{'form.pcorrect'};
10269:     my $pincorrect=$env{'form.pincorrect'};
10270:     my $storecount=0;
10271:     my %users=();
10272:     foreach my $key (keys(%env)) {
10273:        my $user='';
10274:        if ($key=~/^form\.student\:(.*)$/) {
10275:           $user=$1;
10276:        }
10277:        if ($key=~/^form\.unknown\:(.*)$/) {
10278:           my $id=$1;
10279:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10280:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10281:           } elsif ($env{'form.multi'.$id}) {
10282:              $user=$env{'form.multi'.$id};
10283:           }
10284:        }
10285:        if ($user) {
10286:           if ($users{$user}) {
10287:              $result.='<br /><span class="LC_warning">'.
10288:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10289:                       '</span><br />';
10290:           }
10291:           $users{$user}=1; 
10292:           my @answer=split(/\,/,$env{$key});
10293:           my $sum=0;
10294:           my $realnumber=$number;
10295:           for (my $i=0;$i<$number;$i++) {
10296:              if  ($correct[$i] eq '-') {
10297:                 $realnumber--;
10298:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10299:                 if ($gradingmechanism eq 'attendance') {
10300:                    $sum+=$pcorrect;
10301:                 } elsif ($correct[$i] eq '*') {
10302:                    $sum+=$pcorrect;
10303:                 } else {
10304: # We actually grade if correct or not
10305:                    my $increment=$pincorrect;
10306: # Special case: numerical answer "0"
10307:                    if ($correct[$i] eq '0') {
10308:                       if ($answer[$i]=~/^[0\.]+$/) {
10309:                          $increment=$pcorrect;
10310:                       }
10311: # General numerical answer, both evaluate to something non-zero
10312:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10313:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10314:                          $increment=$pcorrect;
10315:                       }
10316: # Must be just alphanumeric
10317:                    } elsif ($answer[$i] eq $correct[$i]) {
10318:                       $increment=$pcorrect;
10319:                    }
10320:                    $sum+=$increment;
10321:                 }
10322:              }
10323:           }
10324:           my $ave=$sum/(100*$realnumber);
10325: # Store
10326:           my ($username,$domain)=split(/\:/,$user);
10327:           my %grades=();
10328:           $grades{"resource.$part.solved"}='correct_by_override';
10329:           $grades{"resource.$part.awarded"}=$ave;
10330:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10331:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10332:                                                  $env{'request.course.id'},
10333:                                                  $domain,$username);
10334:           if ($returncode ne 'ok') {
10335:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10336:           } else {
10337:              $storecount++;
10338:           }
10339:        }
10340:     }
10341: # We are done
10342:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10343:              '</td>'.
10344:              &Apache::loncommon::end_data_table_row().
10345:              &Apache::loncommon::end_data_table();
10346:     return $result;
10347: }
10348: 
10349: sub navmap_errormsg {
10350:     return '<div class="LC_error">'.
10351:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10352:            &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>').
10353:            '</div>';
10354: }
10355: 
10356: sub startpage {
10357:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10358:     if ($nomenu) {
10359:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10360:     } else {
10361:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10362:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10363:                                                  {'bread_crumbs' => $crumbs}));
10364:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10365:     }
10366:     unless ($nodisplayflag) {
10367:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10368:     }
10369: }
10370: 
10371: sub select_problem {
10372:     my ($r)=@_;
10373:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10374:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10375:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10376:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10377: }
10378: 
10379: sub handler {
10380:     my $request=$_[0];
10381:     &reset_caches();
10382:     if ($request->header_only) {
10383:         &Apache::loncommon::content_type($request,'text/html');
10384:         $request->send_http_header;
10385:         return OK;
10386:     }
10387:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10388: 
10389: # see what command we need to execute
10390: 
10391:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10392:     my $command=$commands[0];
10393: 
10394:     &init_perm();
10395:     if (!$env{'request.course.id'}) {
10396:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10397:                 ($command =~ /^scantronupload/)) {
10398:             # Not in a course.
10399:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10400:             return HTTP_NOT_ACCEPTABLE;
10401:         }
10402:     } elsif (!%perm) {
10403:         $request->internal_redirect('/adm/quickgrades');
10404:         return OK;
10405:     }
10406:     &Apache::loncommon::content_type($request,'text/html');
10407:     $request->send_http_header;
10408: 
10409:     if ($#commands > 0) {
10410: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10411:     }
10412: 
10413: # see what the symb is
10414: 
10415:     my $symb=$env{'form.symb'};
10416:     unless ($symb) {
10417:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10418:        $symb=&Apache::lonnet::symbread($url);
10419:     }
10420:     &Apache::lonenc::check_decrypt(\$symb);
10421: 
10422:     $ssi_error = 0;
10423:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10424: #
10425: # Not called from a resource, but inside a course
10426: #    
10427:         &startpage($request,undef,[],1,1);
10428:         &select_problem($request);
10429:     } else {
10430: 	if ($command eq 'submission' && $perm{'vgr'}) {
10431:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10432:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10433:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10434:                     &choose_task_version_form($symb,$env{'form.student'},
10435:                                               $env{'form.userdom'});
10436:             }
10437:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10438:             if ($versionform) {
10439:                 $request->print($versionform);
10440:             }
10441:             $request->print('<br clear="all" />');
10442: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10443:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10444:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10445:                 &choose_task_version_form($symb,$env{'form.student'},
10446:                                           $env{'form.userdom'},
10447:                                           $env{'form.inhibitmenu'});
10448:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10449:             if ($versionform) {
10450:                 $request->print($versionform);
10451:             }
10452:             $request->print('<br clear="all" />');
10453:             $request->print(&show_previous_task_version($request,$symb));
10454: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10455:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10456:                                        {href=>'',text=>'Select student'}],1,1);
10457: 	    &pickStudentPage($request,$symb);
10458: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10459:             &startpage($request,$symb,
10460:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10461:                                        {href=>'',text=>'Select student'},
10462:                                        {href=>'',text=>'Grade student'}],1,1);
10463: 	    &displayPage($request,$symb);
10464: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10465:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10466:                                        {href=>'',text=>'Select student'},
10467:                                        {href=>'',text=>'Grade student'},
10468:                                        {href=>'',text=>'Store grades'}],1,1);
10469: 	    &updateGradeByPage($request,$symb);
10470: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10471:             &startpage($request,$symb,[{href=>'',text=>'...'},
10472:                                        {href=>'',text=>'Modify grades'}]);
10473: 	    &processGroup($request,$symb);
10474: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10475:             &startpage($request,$symb);
10476: 	    $request->print(&grading_menu($request,$symb));
10477: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10478:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10479: 	    $request->print(&submit_options($request,$symb));
10480:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10481:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10482:             $request->print(&listStudents($request,$symb,'graded'));
10483:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10484:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10485:             $request->print(&submit_options_table($request,$symb));
10486:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10487:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10488:             $request->print(&submit_options_sequence($request,$symb));
10489: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10490:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10491: 	    $request->print(&viewgrades($request,$symb));
10492: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10493:             &startpage($request,$symb,[{href=>'',text=>'...'},
10494:                                        {href=>'',text=>'Store grades'}]);
10495: 	    $request->print(&processHandGrade($request,$symb));
10496: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10497:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10498:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10499:                                                                              text=>"Modify grades"},
10500:                                        {href=>'', text=>"Store grades"}]);
10501: 	    $request->print(&editgrades($request,$symb));
10502:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10503:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10504:             $request->print(&initialverifyreceipt($request,$symb));
10505: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10506:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10507:                                        {href=>'',text=>'Verification Result'}]);
10508: 	    $request->print(&verifyreceipt($request,$symb));
10509:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10510:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10511:             $request->print(&process_clicker($request,$symb));
10512:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10513:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10514:                                        {href=>'', text=>'Process clicker file'}]);
10515:             $request->print(&process_clicker_file($request,$symb));
10516:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10517:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10518:                                        {href=>'', text=>'Process clicker file'},
10519:                                        {href=>'', text=>'Store grades'}]);
10520:             $request->print(&assign_clicker_grades($request,$symb));
10521: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10522:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10523: 	    $request->print(&upcsvScores_form($request,$symb));
10524: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10525:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10526: 	    $request->print(&csvupload($request,$symb));
10527: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10528:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10529: 	    $request->print(&csvuploadmap($request,$symb));
10530: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10531: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10532:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10533: 		$request->print(&csvuploadoptions($request,$symb));
10534: 	    } else {
10535: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10536: 		    $env{'form.upfile_associate'} = 'reverse';
10537: 		} else {
10538: 		    $env{'form.upfile_associate'} = 'forward';
10539: 		}
10540:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10541: 		$request->print(&csvuploadmap($request,$symb));
10542: 	    }
10543: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10544:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10545: 	    $request->print(&csvuploadassign($request,$symb));
10546: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10547:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10548: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10549:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10550:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10551:  	    $request->print(&scantron_do_warning($request,$symb));
10552: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10553:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10554: 	    $request->print(&scantron_validate_file($request,$symb));
10555: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10556:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10557: 	    $request->print(&scantron_process_students($request,$symb));
10558:  	} elsif ($command eq 'scantronupload' && 
10559:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10560: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10561:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10562:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10563:  	} elsif ($command eq 'scantronupload_save' &&
10564:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10565: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10566:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10567:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10568:  	} elsif ($command eq 'scantron_download' &&
10569: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10570:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10571:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10572:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10573:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10574:             $request->print(&checkscantron_results($request,$symb));
10575:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10576:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10577:             $request->print(&submit_options_download($request,$symb));
10578:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10579:             &startpage($request,$symb,
10580:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10581:     {href=>'', text=>'Download submissions'}]);
10582:             &submit_download_link($request,$symb);
10583: 	} elsif ($command) {
10584:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10585: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10586: 	}
10587:     }
10588:     if ($ssi_error) {
10589: 	&ssi_print_error($request);
10590:     }
10591:     if ($env{'form.inhibitmenu'}) {
10592:         $request->print(&Apache::loncommon::end_page());
10593:     } else {
10594:         &Apache::lonquickgrades::endGradeScreen($request);
10595:     }
10596:     &reset_caches();
10597:     return OK;
10598: }
10599: 
10600: 1;
10601: 
10602: __END__;
10603: 
10604: 
10605: =head1 NAME
10606: 
10607: Apache::grades
10608: 
10609: =head1 SYNOPSIS
10610: 
10611: Handles the viewing of grades.
10612: 
10613: This is part of the LearningOnline Network with CAPA project
10614: described at http://www.lon-capa.org.
10615: 
10616: =head1 OVERVIEW
10617: 
10618: Do an ssi with retries:
10619: While I'd love to factor out this with the version in lonprintout,
10620: 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
10621: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10622: 
10623: At least the logic that drives this has been pulled out into loncommon.
10624: 
10625: 
10626: 
10627: ssi_with_retries - Does the server side include of a resource.
10628:                      if the ssi call returns an error we'll retry it up to
10629:                      the number of times requested by the caller.
10630:                      If we still have a problem, no text is appended to the
10631:                      output and we set some global variables.
10632:                      to indicate to the caller an SSI error occurred.  
10633:                      All of this is supposed to deal with the issues described
10634:                      in LON-CAPA BZ 5631 see:
10635:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10636:                      by informing the user that this happened.
10637: 
10638: Parameters:
10639:   resource   - The resource to include.  This is passed directly, without
10640:                interpretation to lonnet::ssi.
10641:   form       - The form hash parameters that guide the interpretation of the resource
10642:                
10643:   retries    - Number of retries allowed before giving up completely.
10644: Returns:
10645:   On success, returns the rendered resource identified by the resource parameter.
10646: Side Effects:
10647:   The following global variables can be set:
10648:    ssi_error                - If an unrecoverable error occurred this becomes true.
10649:                               It is up to the caller to initialize this to false
10650:                               if desired.
10651:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10652:                               of the resource that could not be rendered by the ssi
10653:                               call.
10654:    ssi_error_message   - The error string fetched from the ssi response
10655:                               in the event of an error.
10656: 
10657: 
10658: =head1 HANDLER SUBROUTINE
10659: 
10660: ssi_with_retries()
10661: 
10662: =head1 SUBROUTINES
10663: 
10664: =over
10665: 
10666: =head1 Routines to display previous version of a Task for a specific student
10667: 
10668: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10669: can receive another opportunity. Access to tasks is slot-based. If a slot
10670: requires a proctor to check-in the student, a new version of the Task will
10671: be created when the student is checked in to the new opportunity.
10672: 
10673: If a particular student has tried two or more versions of a particular task,
10674: the submission screen provides a user with vgr privileges (e.g., a Course
10675: Coordinator) the ability to display a previous version worked on by the
10676: student.  By default, the current version is displayed. If a previous version
10677: has been selected for display, submission data are only shown that pertain
10678: to that particular version, and the interface to submit grades is not shown.
10679: 
10680: =over 4
10681: 
10682: =item show_previous_task_version()
10683: 
10684: Displays a specified version of a student's Task, as the student sees it.
10685: 
10686: Inputs: 2
10687:         request - request object
10688:         symb    - unique symb for current instance of resource
10689: 
10690: Output: None.
10691: 
10692: Side Effects: calls &show_problem() to print version of Task, with
10693:               version contained in form item: $env{'form.previousversion'}
10694: 
10695: =item choose_task_version_form()
10696: 
10697: Displays a web form used to select which version of a student's view of a
10698: Task should be displayed.  Either launches a pop-up window, or replaces
10699: content in existing pop-up, or replaces page in main window.
10700: 
10701: Inputs: 4
10702:         symb    - unique symb for current instance of resource
10703:         uname   - username of student
10704:         udom    - domain of student
10705:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10706:                   breadcrumbs etc., are displayed
10707: 
10708: Output: 4
10709:         current   - student's current version
10710:         displayed - student's version being displayed
10711:         result    - scalar containing HTML for web form used to switch to
10712:                     a different version (or a link to close window, if pop-up).
10713:         js        - javascript for processing selection in versions web form
10714: 
10715: Side Effects: None.
10716: 
10717: =item previous_display_javascript()
10718: 
10719: Inputs: 2
10720:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10721:                   breadcrumbs etc., are displayed.
10722:         current - student's current version number.
10723: 
10724: Output: 1
10725:         js      - javascript for processing selection in versions web form.
10726: 
10727: Side Effects: None.
10728: 
10729: =back
10730: 
10731: =head1 Routines to process bubblesheet data.
10732: 
10733: =over 4
10734: 
10735: =item scantron_get_correction() : 
10736: 
10737:    Builds the interface screen to interact with the operator to fix a
10738:    specific error condition in a specific scanline
10739: 
10740:  Arguments:
10741:     $r           - Apache request object
10742:     $i           - number of the current scanline
10743:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10744:     $scan_config - hash ref as returned from &get_scantron_config()
10745:     $line        - full contents of the current scanline
10746:     $error       - error condition, valid values are
10747:                    'incorrectCODE', 'duplicateCODE',
10748:                    'doublebubble', 'missingbubble',
10749:                    'duplicateID', 'incorrectID'
10750:     $arg         - extra information needed
10751:        For errors:
10752:          - duplicateID   - paper number that this studentID was seen before on
10753:          - duplicateCODE - array ref of the paper numbers this CODE was
10754:                            seen on before
10755:          - incorrectCODE - current incorrect CODE 
10756:          - doublebubble  - array ref of the bubble lines that have double
10757:                            bubble errors
10758:          - missingbubble - array ref of the bubble lines that have missing
10759:                            bubble errors
10760: 
10761:    $randomorder - True if exam folder has randomorder set
10762:    $randompick  - True if exam folder has randompick set
10763:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10764:                      for current line to question number used for same question
10765:                      in "Master Seqence" (as seen by Course Coordinator).
10766:    $startline   - Reference to hash where key is question number (0 is first)
10767:                   and value is number of first bubble line for current student
10768:                   or code-based randompick and/or randomorder.
10769: 
10770: 
10771: 
10772: =item  scantron_get_maxbubble() : 
10773: 
10774:    Arguments:
10775:        $nav_error  - Reference to scalar which is a flag to indicate a
10776:                       failure to retrieve a navmap object.
10777:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10778:        calling routine should trap the error condition and display the warning
10779:        found in &navmap_errormsg().
10780: 
10781:        $scantron_config - Reference to bubblesheet format configuration hash.
10782: 
10783:    Returns the maximum number of bubble lines that are expected to
10784:    occur. Does this by walking the selected sequence rendering the
10785:    resource and then checking &Apache::lonxml::get_problem_counter()
10786:    for what the current value of the problem counter is.
10787: 
10788:    Caches the results to $env{'form.scantron_maxbubble'},
10789:    $env{'form.scantron.bubble_lines.n'}, 
10790:    $env{'form.scantron.first_bubble_line.n'} and
10791:    $env{"form.scantron.sub_bubblelines.n"}
10792:    which are the total number of bubble lines, the number of bubble
10793:    lines for response n and number of the first bubble line for response n,
10794:    and a comma separated list of numbers of bubble lines for sub-questions
10795:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10796: 
10797: 
10798: =item  scantron_validate_missingbubbles() : 
10799: 
10800:    Validates all scanlines in the selected file to not have any
10801:     answers that don't have bubbles that have not been verified
10802:     to be bubble free.
10803: 
10804: =item  scantron_process_students() : 
10805: 
10806:    Routine that does the actual grading of the bubblesheet information.
10807: 
10808:    The parsed scanline hash is added to %env 
10809: 
10810:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10811:    foreach resource , with the form data of
10812: 
10813: 	'submitted'     =>'scantron' 
10814: 	'grade_target'  =>'grade',
10815: 	'grade_username'=> username of student
10816: 	'grade_domain'  => domain of student
10817: 	'grade_courseid'=> of course
10818: 	'grade_symb'    => symb of resource to grade
10819: 
10820:     This triggers a grading pass. The problem grading code takes care
10821:     of converting the bubbled letter information (now in %env) into a
10822:     valid submission.
10823: 
10824: =item  scantron_upload_scantron_data() :
10825: 
10826:     Creates the screen for adding a new bubblesheet data file to a course.
10827: 
10828: =item  scantron_upload_scantron_data_save() : 
10829: 
10830:    Adds a provided bubble information data file to the course if user
10831:    has the correct privileges to do so. 
10832: 
10833: =item  valid_file() :
10834: 
10835:    Validates that the requested bubble data file exists in the course.
10836: 
10837: =item  scantron_download_scantron_data() : 
10838: 
10839:    Shows a list of the three internal files (original, corrected,
10840:    skipped) for a specific bubblesheet data file that exists in the
10841:    course.
10842: 
10843: =item  scantron_validate_ID() : 
10844: 
10845:    Validates all scanlines in the selected file to not have any
10846:    invalid or underspecified student/employee IDs
10847: 
10848: =item navmap_errormsg() :
10849: 
10850:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10851:    Should be called whenever the request to instantiate a navmap object fails.
10852: 
10853: =back
10854: 
10855: =back
10856: 
10857: =cut

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