File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.599: download - view: text, annotated - select for diffs
Fri Mar 19 21:22:34 2010 UTC (14 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
Saving my pre-cleanup work

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.599 2010/03/19 21:22:34 www 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);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &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 />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: # Returns an array of everything that the resources stores away
  100: #
  101: 
  102: sub getpartlist {
  103:     my ($symb,$errorref) = @_;
  104: 
  105:     my $navmap   = Apache::lonnavmaps::navmap->new();
  106:     unless (ref($navmap)) {
  107:         if (ref($errorref)) { 
  108:             $$errorref = 'navmap';
  109:             return;
  110:         }
  111:     }
  112:     my $res      = $navmap->getBySymb($symb);
  113:     my $partlist = $res->parts();
  114:     my $url      = $res->src();
  115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  116: 
  117:     my @stores;
  118:     foreach my $part (@{ $partlist }) {
  119: 	foreach my $key (@metakeys) {
  120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  121: 	}
  122:     }
  123:     return @stores;
  124: }
  125: 
  126: # --- Get the symbolic name of a problem and the url
  127: # Generate an error message if symb could not be found unless silent flag is set
  128: # Takes $env{'form.symb'} by default; if not present, takes $env{'form.url'} and tries to get symb from that
  129: #
  130:  
  131: sub get_symb {
  132:     my ($request,$silent) = @_;
  133:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  134:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  135:     if ($symb eq '') { 
  136: 	if (!$silent) {
  137: 	    $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
  138: 	    return ();
  139: 	}
  140:     }
  141:     &Apache::lonenc::check_decrypt(\$symb);
  142:     return ($symb);
  143: }
  144: 
  145: #--- Format fullname, username:domain if different for display
  146: #--- Use anywhere where the student names are listed
  147: sub nameUserString {
  148:     my ($type,$fullname,$uname,$udom) = @_;
  149:     if ($type eq 'header') {
  150: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  151:     } else {
  152: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  153: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  154:     }
  155: }
  156: 
  157: #--- Get the partlist and the response type for a given problem. ---
  158: #--- Indicate if a response type is coded handgraded or not. ---
  159: sub response_type {
  160:     my ($symb,$response_error) = @_;
  161: 
  162:     my $navmap = Apache::lonnavmaps::navmap->new();
  163:     unless (ref($navmap)) {
  164:         if (ref($response_error)) {
  165:             $$response_error = 1;
  166:         }
  167:         return;
  168:     }
  169:     my $res = $navmap->getBySymb($symb);
  170:     unless (ref($res)) {
  171:         $$response_error = 1;
  172:         return;
  173:     }
  174:     my $partlist = $res->parts();
  175:     my %vPart = 
  176: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  177:     my (%response_types,%handgrade);
  178:     foreach my $part (@{ $partlist }) {
  179: 	next if (%vPart && !exists($vPart{$part}));
  180: 
  181: 	my @types = $res->responseType($part);
  182: 	my @ids = $res->responseIds($part);
  183: 	for (my $i=0; $i < scalar(@ids); $i++) {
  184: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  185: 	    $handgrade{$part.'_'.$ids[$i]} = 
  186: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  187: 				     '.handgrade',$symb);
  188: 	}
  189:     }
  190:     return ($partlist,\%handgrade,\%response_types);
  191: }
  192: 
  193: sub flatten_responseType {
  194:     my ($responseType) = @_;
  195:     my @part_response_id =
  196: 	map { 
  197: 	    my $part = $_;
  198: 	    map {
  199: 		[$part,$_]
  200: 		} sort(keys(%{ $responseType->{$part} }));
  201: 	} sort(keys(%$responseType));
  202:     return @part_response_id;
  203: }
  204: 
  205: sub get_display_part {
  206:     my ($partID,$symb)=@_;
  207:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  208:     if (defined($display) and $display ne '') {
  209:         $display.= ' (<span class="LC_internal_info">'
  210:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  211:     } else {
  212: 	$display=$partID;
  213:     }
  214:     return $display;
  215: }
  216: 
  217: #--- Show resource title
  218: #--- and parts and response type
  219: #sub showResourceInfo {
  220: #    my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  221: #    my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  222: #    my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  223: #    if (ref($res_error)) {
  224: #        if ($$res_error) {
  225: #            return;
  226: #        }
  227: #    }
  228: #    $result.=&Apache::loncommon::start_data_table()
  229: #            .&Apache::loncommon::start_data_table_header_row();
  230: #    if ($checkboxes) {
  231: #        $result.='<th>&nbsp;</th>';
  232: #    }
  233: #    $result.='<th>'.&mt('Problem Part').'</th>'
  234: #            .'<th>'.&mt('Res. ID').'</th>'
  235: #            .'<th>'.&mt('Type').'</th>'
  236: #            .&Apache::loncommon::end_data_table_header_row();
  237: #    my %resptype = ();
  238: #    my $hdgrade='no';
  239: #    my %partsseen;
  240: #    foreach my $partID (sort(keys(%$responseType))) {
  241: #        foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  242: #            my $handgrade=$$handgrade{$partID.'_'.$resID};
  243: #            my $responsetype = $responseType->{$partID}->{$resID};
  244: #            $hdgrade = $handgrade if ($handgrade eq 'yes');
  245: #            $result.=&Apache::loncommon::start_data_table_row();
  246: #            if ($checkboxes) {
  247: #                if (exists($partsseen{$partID})) {
  248: #                    $result.="<td>&nbsp;</td>";
  249: #                } else {
  250: #                    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  251: #                }
  252: #                $partsseen{$partID}=1;
  253: #            }
  254: #            my $display_part=&get_display_part($partID,$symb);
  255: #            $result.='<td>'.$display_part.'</td>'
  256: #                    .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  257: #                    .'<td>'.&mt($responsetype).'</td>'
  258: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
  259: #                    .&Apache::loncommon::end_data_table_row();
  260: #       }
  261: #    }
  262: #    $result.=&Apache::loncommon::end_data_table();
  263: #    return $result,$responseType,$hdgrade,$partlist,$handgrade;
  264: #}
  265: 
  266: sub reset_caches {
  267:     &reset_analyze_cache();
  268:     &reset_perm();
  269: }
  270: 
  271: {
  272:     my %analyze_cache;
  273:     my %analyze_cache_formkeys;
  274: 
  275:     sub reset_analyze_cache {
  276: 	undef(%analyze_cache);
  277:         undef(%analyze_cache_formkeys);
  278:     }
  279: 
  280:     sub get_analyze {
  281: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  282: 	my $key = "$symb\0$uname\0$udom";
  283: 	if (exists($analyze_cache{$key})) {
  284:             my $getupdate = 0;
  285:             if (ref($add_to_hash) eq 'HASH') {
  286:                 foreach my $item (keys(%{$add_to_hash})) {
  287:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  288:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  289:                             $getupdate = 1;
  290:                             last;
  291:                         }
  292:                     } else {
  293:                         $getupdate = 1;
  294:                     }
  295:                 }
  296:             }
  297:             if (!$getupdate) {
  298:                 return $analyze_cache{$key};
  299:             }
  300:         }
  301: 
  302: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  303: 	$url=&Apache::lonnet::clutter($url);
  304:         my %form = ('grade_target'      => 'analyze',
  305:                     'grade_domain'      => $udom,
  306:                     'grade_symb'        => $symb,
  307:                     'grade_courseid'    =>  $env{'request.course.id'},
  308:                     'grade_username'    => $uname,
  309:                     'grade_noincrement' => $no_increment);
  310:         if (ref($add_to_hash)) {
  311:             %form = (%form,%{$add_to_hash});
  312:         } 
  313: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  314: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  315: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  316:         if (ref($add_to_hash) eq 'HASH') {
  317:             $analyze_cache_formkeys{$key} = $add_to_hash;
  318:         } else {
  319:             $analyze_cache_formkeys{$key} = {};
  320:         }
  321: 	return $analyze_cache{$key} = \%analyze;
  322:     }
  323: 
  324:     sub get_order {
  325: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  326: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  327: 	return $analyze->{"$partid.$respid.shown"};
  328:     }
  329: 
  330:     sub get_radiobutton_correct_foil {
  331: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  332: 	my $analyze = &get_analyze($symb,$uname,$udom);
  333:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  334:         if (ref($foils) eq 'ARRAY') {
  335: 	    foreach my $foil (@{$foils}) {
  336: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  337: 		    return $foil;
  338: 	        }
  339: 	    }
  340: 	}
  341:     }
  342: 
  343:     sub scantron_partids_tograde {
  344:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  345:         my (%analysis,@parts);
  346:         if (ref($resource)) {
  347:             my $symb = $resource->symb();
  348:             my $add_to_form;
  349:             if ($check_for_randomlist) {
  350:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  351:             }
  352:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  353:             if (ref($analyze) eq 'HASH') {
  354:                 %analysis = %{$analyze};
  355:             }
  356:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  357:                 foreach my $part (@{$analysis{'parts'}}) {
  358:                     my ($id,$respid) = split(/\./,$part);
  359:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  360:                         push(@parts,$part);
  361:                     }
  362:                 }
  363:             }
  364:         }
  365:         return (\%analysis,\@parts);
  366:     }
  367: 
  368: }
  369: 
  370: #--- Clean response type for display
  371: #--- Currently filters option/rank/radiobutton/match/essay/Task
  372: #        response types only.
  373: sub cleanRecord {
  374:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  375: 	$uname,$udom) = @_;
  376:     my $grayFont = '<span class="LC_internal_info">';
  377:     if ($response =~ /^(option|rank)$/) {
  378: 	my %answer=&Apache::lonnet::str2hash($answer);
  379: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  380: 	my ($toprow,$bottomrow);
  381: 	foreach my $foil (@$order) {
  382: 	    if ($grading{$foil} == 1) {
  383: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  384: 	    } else {
  385: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  386: 	    }
  387: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  388: 	}
  389: 	return '<blockquote><table border="1">'.
  390: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  391: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  392: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  393:     } elsif ($response eq 'match') {
  394: 	my %answer=&Apache::lonnet::str2hash($answer);
  395: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  396: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  397: 	my ($toprow,$middlerow,$bottomrow);
  398: 	foreach my $foil (@$order) {
  399: 	    my $item=shift(@items);
  400: 	    if ($grading{$foil} == 1) {
  401: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  402: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  403: 	    } else {
  404: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  405: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  406: 	    }
  407: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  408: 	}
  409: 	return '<blockquote><table border="1">'.
  410: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  411: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  412: 	    $middlerow.'</tr>'.
  413: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  414: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  415:     } elsif ($response eq 'radiobutton') {
  416: 	my %answer=&Apache::lonnet::str2hash($answer);
  417: 	my ($toprow,$bottomrow);
  418: 	my $correct = 
  419: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  420: 	foreach my $foil (@$order) {
  421: 	    if (exists($answer{$foil})) {
  422: 		if ($foil eq $correct) {
  423: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  424: 		} else {
  425: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  426: 		}
  427: 	    } else {
  428: 		$toprow.='<td>'.&mt('false').'</td>';
  429: 	    }
  430: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  431: 	}
  432: 	return '<blockquote><table border="1">'.
  433: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  434: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  435: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  436:     } elsif ($response eq 'essay') {
  437: 	if (! exists ($env{'form.'.$symb})) {
  438: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  439: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  440: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  441: 
  442: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  443: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  444: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  445: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  446: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  447: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  448: 	}
  449: 	$answer =~ s-\n-<br />-g;
  450: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  451:     } elsif ( $response eq 'organic') {
  452: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  453: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  454: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  455: 	return $result;
  456:     } elsif ( $response eq 'Task') {
  457: 	if ( $answer eq 'SUBMITTED') {
  458: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  459: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  460: 	    return $result;
  461: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  462: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  463: 			       keys(%{$record}));
  464: 	    return join('<br />',($version,@matches));
  465: 			       
  466: 			       
  467: 	} else {
  468: 	    my $result =
  469: 		'<p>'
  470: 		.&mt('Overall result: [_1]',
  471: 		     $record->{$version."resource.$respid.$partid.status"})
  472: 		.'</p>';
  473: 	    
  474: 	    $result .= '<ul>';
  475: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  476: 			     keys(%{$record}));
  477: 	    foreach my $grade (sort(@grade)) {
  478: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  479: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  480: 				     $dim, $record->{$grade}).
  481: 			  '</li>';
  482: 	    }
  483: 	    $result.='</ul>';
  484: 	    return $result;
  485: 	}
  486:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  487: 	$answer = 
  488: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  489: 							      $answer);
  490:     }
  491:     return $answer;
  492: }
  493: 
  494: #-- A couple of common js functions
  495: sub commonJSfunctions {
  496:     my $request = shift;
  497:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  498:     function radioSelection(radioButton) {
  499: 	var selection=null;
  500: 	if (radioButton.length > 1) {
  501: 	    for (var i=0; i<radioButton.length; i++) {
  502: 		if (radioButton[i].checked) {
  503: 		    return radioButton[i].value;
  504: 		}
  505: 	    }
  506: 	} else {
  507: 	    if (radioButton.checked) return radioButton.value;
  508: 	}
  509: 	return selection;
  510:     }
  511: 
  512:     function pullDownSelection(selectOne) {
  513: 	var selection="";
  514: 	if (selectOne.length > 1) {
  515: 	    for (var i=0; i<selectOne.length; i++) {
  516: 		if (selectOne[i].selected) {
  517: 		    return selectOne[i].value;
  518: 		}
  519: 	    }
  520: 	} else {
  521:             // only one value it must be the selected one
  522: 	    return selectOne.value;
  523: 	}
  524:     }
  525: COMMONJSFUNCTIONS
  526: }
  527: 
  528: #--- Dumps the class list with usernames,list of sections,
  529: #--- section, ids and fullnames for each user.
  530: sub getclasslist {
  531:     my ($getsec,$filterlist,$getgroup) = @_;
  532:     my @getsec;
  533:     my @getgroup;
  534:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  535:     if (!ref($getsec)) {
  536: 	if ($getsec ne '' && $getsec ne 'all') {
  537: 	    @getsec=($getsec);
  538: 	}
  539:     } else {
  540: 	@getsec=@{$getsec};
  541:     }
  542:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  543:     if (!ref($getgroup)) {
  544: 	if ($getgroup ne '' && $getgroup ne 'all') {
  545: 	    @getgroup=($getgroup);
  546: 	}
  547:     } else {
  548: 	@getgroup=@{$getgroup};
  549:     }
  550:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  551: 
  552:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  553:     # Bail out if we were unable to get the classlist
  554:     return if (! defined($classlist));
  555:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  556:     #
  557:     my %sections;
  558:     my %fullnames;
  559:     foreach my $student (keys(%$classlist)) {
  560:         my $end      = 
  561:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  562:         my $start    = 
  563:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  564:         my $id       = 
  565:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  566:         my $section  = 
  567:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  568:         my $fullname = 
  569:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  570:         my $status   = 
  571:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  572:         my $group   = 
  573:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  574: 	# filter students according to status selected
  575: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  576: 	    if (!($stu_status =~ $status)) {
  577: 		delete($classlist->{$student});
  578: 		next;
  579: 	    }
  580: 	}
  581: 	# filter students according to groups selected
  582: 	my @stu_groups = split(/,/,$group);
  583: 	if (@getgroup) {
  584: 	    my $exclude = 1;
  585: 	    foreach my $grp (@getgroup) {
  586: 	        foreach my $stu_group (@stu_groups) {
  587: 	            if ($stu_group eq $grp) {
  588: 	                $exclude = 0;
  589:     	            } 
  590: 	        }
  591:     	        if (($grp eq 'none') && !$group) {
  592:         	        $exclude = 0;
  593:         	}
  594: 	    }
  595: 	    if ($exclude) {
  596: 	        delete($classlist->{$student});
  597: 	    }
  598: 	}
  599: 	$section = ($section ne '' ? $section : 'none');
  600: 	if (&canview($section)) {
  601: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  602: 		$sections{$section}++;
  603: 		if ($classlist->{$student}) {
  604: 		    $fullnames{$student}=$fullname;
  605: 		}
  606: 	    } else {
  607: 		delete($classlist->{$student});
  608: 	    }
  609: 	} else {
  610: 	    delete($classlist->{$student});
  611: 	}
  612:     }
  613:     my %seen = ();
  614:     my @sections = sort(keys(%sections));
  615:     return ($classlist,\@sections,\%fullnames);
  616: }
  617: 
  618: sub canmodify {
  619:     my ($sec)=@_;
  620:     if ($perm{'mgr'}) {
  621: 	if (!defined($perm{'mgr_section'})) {
  622: 	    # can modify whole class
  623: 	    return 1;
  624: 	} else {
  625: 	    if ($sec eq $perm{'mgr_section'}) {
  626: 		#can modify the requested section
  627: 		return 1;
  628: 	    } else {
  629: 		# can't modify the request section
  630: 		return 0;
  631: 	    }
  632: 	}
  633:     }
  634:     #can't modify
  635:     return 0;
  636: }
  637: 
  638: sub canview {
  639:     my ($sec)=@_;
  640:     if ($perm{'vgr'}) {
  641: 	if (!defined($perm{'vgr_section'})) {
  642: 	    # can modify whole class
  643: 	    return 1;
  644: 	} else {
  645: 	    if ($sec eq $perm{'vgr_section'}) {
  646: 		#can modify the requested section
  647: 		return 1;
  648: 	    } else {
  649: 		# can't modify the request section
  650: 		return 0;
  651: 	    }
  652: 	}
  653:     }
  654:     #can't modify
  655:     return 0;
  656: }
  657: 
  658: #--- Retrieve the grade status of a student for all the parts
  659: sub student_gradeStatus {
  660:     my ($symb,$udom,$uname,$partlist) = @_;
  661:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  662:     my %partstatus = ();
  663:     foreach (@$partlist) {
  664: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  665: 	$status              = 'nothing' if ($status eq '');
  666: 	$partstatus{$_}      = $status;
  667: 	my $subkey           = "resource.$_.submitted_by";
  668: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  669:     }
  670:     return %partstatus;
  671: }
  672: 
  673: # hidden form and javascript that calls the form
  674: # Use by verifyscript and viewgrades
  675: # Shows a student's view of problem and submission
  676: sub jscriptNform {
  677:     my ($symb) = @_;
  678:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  679:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  680: 	'    function viewOneStudent(user,domain) {'."\n".
  681: 	'	document.onestudent.student.value = user;'."\n".
  682: 	'	document.onestudent.userdom.value = domain;'."\n".
  683: 	'	document.onestudent.submit();'."\n".
  684: 	'    }'."\n".
  685: 	"\n");
  686:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  687: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  688: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  689: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  690: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  691: 	'<input type="hidden" name="command" value="submission" />'."\n".
  692: 	'<input type="hidden" name="student" value="" />'."\n".
  693: 	'<input type="hidden" name="userdom" value="" />'."\n".
  694: 	'</form>'."\n";
  695:     return $jscript;
  696: }
  697: 
  698: 
  699: 
  700: # Given the score (as a number [0-1] and the weight) what is the final
  701: # point value? This function will round to the nearest tenth, third,
  702: # or quarter if one of those is within the tolerance of .00001.
  703: sub compute_points {
  704:     my ($score, $weight) = @_;
  705:     
  706:     my $tolerance = .00001;
  707:     my $points = $score * $weight;
  708: 
  709:     # Check for nearness to 1/x.
  710:     my $check_for_nearness = sub {
  711:         my ($factor) = @_;
  712:         my $num = ($points * $factor) + $tolerance;
  713:         my $floored_num = floor($num);
  714:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  715:             return $floored_num / $factor;
  716:         }
  717:         return $points;
  718:     };
  719: 
  720:     $points = $check_for_nearness->(10);
  721:     $points = $check_for_nearness->(3);
  722:     $points = $check_for_nearness->(4);
  723:     
  724:     return $points;
  725: }
  726: 
  727: #------------------ End of general use routines --------------------
  728: 
  729: #
  730: # Find most similar essay
  731: #
  732: 
  733: sub most_similar {
  734:     my ($uname,$udom,$uessay,$old_essays)=@_;
  735: 
  736: # ignore spaces and punctuation
  737: 
  738:     $uessay=~s/\W+/ /gs;
  739: 
  740: # ignore empty submissions (occuring when only files are sent)
  741: 
  742:     unless ($uessay=~/\w+/s) { return ''; }
  743: 
  744: # these will be returned. Do not care if not at least 50 percent similar
  745:     my $limit=0.6;
  746:     my $sname='';
  747:     my $sdom='';
  748:     my $scrsid='';
  749:     my $sessay='';
  750: # go through all essays ...
  751:     foreach my $tkey (keys(%$old_essays)) {
  752: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  753: # ... except the same student
  754:         next if (($tname eq $uname) && ($tdom eq $udom));
  755: 	my $tessay=$old_essays->{$tkey};
  756: 	$tessay=~s/\W+/ /gs;
  757: # String similarity gives up if not even limit
  758: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  759: # Found one
  760: 	if ($tsimilar>$limit) {
  761: 	    $limit=$tsimilar;
  762: 	    $sname=$tname;
  763: 	    $sdom=$tdom;
  764: 	    $scrsid=$tcrsid;
  765: 	    $sessay=$old_essays->{$tkey};
  766: 	}
  767:     }
  768:     if ($limit>0.6) {
  769:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  770:     } else {
  771:        return ('','','','',0);
  772:     }
  773: }
  774: 
  775: #-------------------------------------------------------------------
  776: 
  777: #------------------------------------ Receipt Verification Routines
  778: #
  779: #--- Check whether a receipt number is valid.---
  780: sub verifyreceipt {
  781:     my $request  = shift;
  782: 
  783:     my $courseid = $env{'request.course.id'};
  784:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  785: 	$env{'form.receipt'};
  786:     $receipt     =~ s/[^\-\d]//g;
  787:     my ($symb)   = &get_symb($request);
  788: 
  789:     my $title.=
  790: 	'<h3><span class="LC_info">'.
  791: 	&mt('Verifying Receipt No. [_1]',$receipt).
  792: 	'</span></h3>'."\n".
  793: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  794: 	'</h4>'."\n";
  795: 
  796:     my ($string,$contents,$matches) = ('','',0);
  797:     my (undef,undef,$fullname) = &getclasslist('all','0');
  798:     
  799:     my $receiptparts=0;
  800:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  801: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  802:     my $parts=['0'];
  803:     if ($receiptparts) {
  804:         my $res_error; 
  805:         ($parts)=&response_type($symb,\$res_error);
  806:         if ($res_error) {
  807:             return &navmap_errormsg();
  808:         } 
  809:     }
  810:     
  811:     my $header = 
  812: 	&Apache::loncommon::start_data_table().
  813: 	&Apache::loncommon::start_data_table_header_row().
  814: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  815: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  816: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  817:     if ($receiptparts) {
  818: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  819:     }
  820:     $header.=
  821: 	&Apache::loncommon::end_data_table_header_row();
  822: 
  823:     foreach (sort 
  824: 	     {
  825: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  826: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  827: 		 }
  828: 		 return $a cmp $b;
  829: 	     } (keys(%$fullname))) {
  830: 	my ($uname,$udom)=split(/\:/);
  831: 	foreach my $part (@$parts) {
  832: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  833: 		$contents.=
  834: 		    &Apache::loncommon::start_data_table_row().
  835: 		    '<td>&nbsp;'."\n".
  836: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  837: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  838: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  839: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  840: 		if ($receiptparts) {
  841: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  842: 		}
  843: 		$contents.= 
  844: 		    &Apache::loncommon::end_data_table_row()."\n";
  845: 		
  846: 		$matches++;
  847: 	    }
  848: 	}
  849:     }
  850:     if ($matches == 0) {
  851:         $string = $title
  852:                  .'<p class="LC_warning">'
  853:                  .&mt('No match found for the above receipt number.')
  854:                  .'</p>';
  855:     } else {
  856: 	$string = &jscriptNform($symb).$title.
  857: 	    '<p>'.
  858: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  859: 	    '</p>'.
  860: 	    $header.
  861: 	    $contents.
  862: 	    &Apache::loncommon::end_data_table()."\n";
  863:     }
  864:     return $string.&show_grading_menu_form($symb);
  865: }
  866: 
  867: #--- This is called by a number of programs.
  868: #--- Called from the Grading Menu - View/Grade an individual student
  869: #--- Also called directly when one clicks on the subm button 
  870: #    on the problem page.
  871: sub listStudents {
  872:     my ($request) = shift;
  873: 
  874:     my ($symb) = &get_symb($request);
  875:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  876:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  877:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  878:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  879:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  880:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  881:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  882: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  883: 
  884:     my $result='<h3><span class="LC_info">&nbsp;'
  885: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  886: 	.'</span></h3>';
  887: 
  888: #    my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  889:     my ($partlist,$handgrade,$responseType) = &response_type($symb
  890: #,$res_error
  891:     );
  892: 
  893:     my %lt = &Apache::lonlocal::texthash (
  894: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  895: 		'single'   => 'Please select the student before clicking on the Next button.',
  896: 	     );
  897:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  898:     function checkSelect(checkBox) {
  899: 	var ctr=0;
  900: 	var sense="";
  901: 	if (checkBox.length > 1) {
  902: 	    for (var i=0; i<checkBox.length; i++) {
  903: 		if (checkBox[i].checked) {
  904: 		    ctr++;
  905: 		}
  906: 	    }
  907: 	    sense = '$lt{'multiple'}';
  908: 	} else {
  909: 	    if (checkBox.checked) {
  910: 		ctr = 1;
  911: 	    }
  912: 	    sense = '$lt{'single'}';
  913: 	}
  914: 	if (ctr == 0) {
  915: 	    alert(sense);
  916: 	    return false;
  917: 	}
  918: 	document.gradesub.submit();
  919:     }
  920: 
  921:     function reLoadList(formname) {
  922: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  923: 	formname.command.value = 'submission';
  924: 	formname.submit();
  925:     }
  926: LISTJAVASCRIPT
  927: 
  928:     &commonJSfunctions($request);
  929:     $request->print($result);
  930: 
  931:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  932:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  933:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  934: 	"\n";
  935: 	
  936:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  937:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  938:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  939:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  940:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  941:                   .&Apache::lonhtmlcommon::row_closure();
  942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  943:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  944:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  945:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  946:                   .&Apache::lonhtmlcommon::row_closure();
  947: 
  948:     my $submission_options;
  949:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  950: 	$submission_options.=
  951: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  952:     }
  953:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  954:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  955:     $env{'form.Status'} = $saveStatus;
  956:     $submission_options.=
  957:         '<span class="LC_nobreak">'.
  958:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  959:         &mt('last submission only').' </label></span>'."\n".
  960:         '<span class="LC_nobreak">'.
  961:         '<label><input type="radio" name="lastSub" value="last" /> '.
  962:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  963:         '<span class="LC_nobreak">'.
  964:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  965:         &mt('by dates and submissions').'</label></span>'."\n".
  966:         '<span class="LC_nobreak">'.
  967:         '<label><input type="radio" name="lastSub" value="all" /> '.
  968:         &mt('all details').'</label></span>';
  969:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  970:                   .$submission_options
  971:                   .&Apache::lonhtmlcommon::row_closure();
  972: 
  973:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  974:                   .'<select name="increment">'
  975:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  976:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  977:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  978:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  979:                   .'</select>'
  980:                   .&Apache::lonhtmlcommon::row_closure();
  981: 
  982:     $gradeTable .= 
  983:         &build_section_inputs().
  984: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  985: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  986: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  987: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  988: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  989: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  990: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  991: 
  992:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  993: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  994:     } else {
  995:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  996:                       .&Apache::lonhtmlcommon::StatusOptions(
  997:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  998:                       .&Apache::lonhtmlcommon::row_closure();
  999:     }
 1000: 
 1001:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1002:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1003:                   .&Apache::lonhtmlcommon::row_closure(1)
 1004:                   .&Apache::lonhtmlcommon::end_pick_box();
 1005: 
 1006:     $gradeTable .= '<p>'
 1007:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
 1008:                   .'<input type="hidden" name="command" value="processGroup" />'
 1009:                   .'</p>';
 1010: 
 1011: # checkall buttons
 1012:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1013:     $gradeTable.='<input type="button" '."\n".
 1014:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1015:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1016:     $gradeTable.=&check_buttons();
 1017:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1018:     $gradeTable.= &Apache::loncommon::start_data_table().
 1019: 	&Apache::loncommon::start_data_table_header_row();
 1020:     my $loop = 0;
 1021:     while ($loop < 2) {
 1022: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1023: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1024: 	if ($env{'form.showgrading'} eq 'yes' 
 1025: 	    && $submitonly ne 'queued'
 1026: 	    && $submitonly ne 'all') {
 1027: 	    foreach my $part (sort(@$partlist)) {
 1028: 		my $display_part=
 1029: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1030: 		$gradeTable.=
 1031: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1032: 	    }
 1033: 	} elsif ($submitonly eq 'queued') {
 1034: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1035: 	}
 1036: 	$loop++;
 1037: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1038:     }
 1039:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1040: 
 1041:     my $ctr = 0;
 1042:     foreach my $student (sort 
 1043: 			 {
 1044: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1045: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1046: 			     }
 1047: 			     return $a cmp $b;
 1048: 			 }
 1049: 			 (keys(%$fullname))) {
 1050: 	my ($uname,$udom) = split(/:/,$student);
 1051: 
 1052: 	my %status = ();
 1053: 
 1054: 	if ($submitonly eq 'queued') {
 1055: 	    my %queue_status = 
 1056: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1057: 							$udom,$uname);
 1058: 	    next if (!defined($queue_status{'gradingqueue'}));
 1059: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1060: 	}
 1061: 
 1062: 	if ($env{'form.showgrading'} eq 'yes' 
 1063: 	    && $submitonly ne 'queued'
 1064: 	    && $submitonly ne 'all') {
 1065: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1066: 	    my $submitted = 0;
 1067: 	    my $graded = 0;
 1068: 	    my $incorrect = 0;
 1069: 	    foreach (keys(%status)) {
 1070: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1071: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1072: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1073: 		
 1074: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1075: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1076: 		    $submitted = 0;
 1077: 		    my ($part)=split(/\./,$partid);
 1078: 		    $gradeTable.='<input type="hidden" name="'.
 1079: 			$student.':'.$part.':submitted_by" value="'.
 1080: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1081: 		}
 1082: 	    }
 1083: 	    
 1084: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1085: 				     $submitonly eq 'incorrect' ||
 1086: 				     $submitonly eq 'graded'));
 1087: 	    next if (!$graded && ($submitonly eq 'graded'));
 1088: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1089: 	}
 1090: 
 1091: 	$ctr++;
 1092: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1093:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1094: 	if ( $perm{'vgr'} eq 'F' ) {
 1095: 	    if ($ctr%2 ==1) {
 1096: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1097: 	    }
 1098: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1099:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1100:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1101: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1102: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1103: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1104: 
 1105: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1106: 		foreach (sort(keys(%status))) {
 1107: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1108: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1109: 		}
 1110: 	    }
 1111: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1112: 	    if ($ctr%2 ==0) {
 1113: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1114: 	    }
 1115: 	}
 1116:     }
 1117:     if ($ctr%2 ==1) {
 1118: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1119: 	    if ($env{'form.showgrading'} eq 'yes' 
 1120: 		&& $submitonly ne 'queued'
 1121: 		&& $submitonly ne 'all') {
 1122: 		foreach (@$partlist) {
 1123: 		    $gradeTable.='<td>&nbsp;</td>';
 1124: 		}
 1125: 	    } elsif ($submitonly eq 'queued') {
 1126: 		$gradeTable.='<td>&nbsp;</td>';
 1127: 	    }
 1128: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1129:     }
 1130: 
 1131:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1132:         '<input type="button" '.
 1133:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1134:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1135:     if ($ctr == 0) {
 1136: 	my $num_students=(scalar(keys(%$fullname)));
 1137: 	if ($num_students eq 0) {
 1138: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1139: 	} else {
 1140: 	    my $submissions='submissions';
 1141: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1142: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1143: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1144: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1145: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1146: 		    $num_students).
 1147: 		'</span><br />';
 1148: 	}
 1149:     } elsif ($ctr == 1) {
 1150: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1151:     }
 1152:     $gradeTable.=&show_grading_menu_form($symb);
 1153:     $request->print($gradeTable);
 1154:     return '';
 1155: }
 1156: 
 1157: #---- Called from the listStudents routine
 1158: 
 1159: sub check_script {
 1160:     my ($form, $type)=@_;
 1161:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1162:     function checkall() {
 1163:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1164:             ele = document.forms.'.$form.'.elements[i];
 1165:             if (ele.name == "'.$type.'") {
 1166:             document.forms.'.$form.'.elements[i].checked=true;
 1167:                                        }
 1168:         }
 1169:     }
 1170: 
 1171:     function checksec() {
 1172:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1173:             ele = document.forms.'.$form.'.elements[i];
 1174:            string = document.forms.'.$form.'.chksec.value;
 1175:            if
 1176:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1177:               document.forms.'.$form.'.elements[i].checked=true;
 1178:             }
 1179:         }
 1180:     }
 1181: 
 1182: 
 1183:     function uncheckall() {
 1184:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1185:             ele = document.forms.'.$form.'.elements[i];
 1186:             if (ele.name == "'.$type.'") {
 1187:             document.forms.'.$form.'.elements[i].checked=false;
 1188:                                        }
 1189:         }
 1190:     }
 1191: 
 1192: '."\n");
 1193:     return $chkallscript;
 1194: }
 1195: 
 1196: sub check_buttons {
 1197:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1198:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1199:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1200:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1201:     return $buttons;
 1202: }
 1203: 
 1204: #     Displays the submissions for one student or a group of students
 1205: sub processGroup {
 1206:     my ($request)  = shift;
 1207:     my $ctr        = 0;
 1208:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1209:     my $total      = scalar(@stuchecked)-1;
 1210: 
 1211:     foreach my $student (@stuchecked) {
 1212: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1213: 	$env{'form.student'}        = $uname;
 1214: 	$env{'form.userdom'}        = $udom;
 1215: 	$env{'form.fullname'}       = $fullname;
 1216: 	&submission($request,$ctr,$total);
 1217: 	$ctr++;
 1218:     }
 1219:     return '';
 1220: }
 1221: 
 1222: #------------------------------------------------------------------------------------
 1223: #
 1224: #-------------------------- Next few routines handles grading by student, essentially
 1225: #                           handles essay response type problem/part
 1226: #
 1227: #--- Javascript to handle the submission page functionality ---
 1228: sub sub_page_js {
 1229:     my $request = shift;
 1230: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1231:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1232:     function updateRadio(formname,id,weight) {
 1233: 	var gradeBox = formname["GD_BOX"+id];
 1234: 	var radioButton = formname["RADVAL"+id];
 1235: 	var oldpts = formname["oldpts"+id].value;
 1236: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1237: 	gradeBox.value = pts;
 1238: 	var resetbox = false;
 1239: 	if (isNaN(pts) || pts < 0) {
 1240: 	    alert("$alertmsg"+pts);
 1241: 	    for (var i=0; i<radioButton.length; i++) {
 1242: 		if (radioButton[i].checked) {
 1243: 		    gradeBox.value = i;
 1244: 		    resetbox = true;
 1245: 		}
 1246: 	    }
 1247: 	    if (!resetbox) {
 1248: 		formtextbox.value = "";
 1249: 	    }
 1250: 	    return;
 1251: 	}
 1252: 
 1253: 	if (pts > weight) {
 1254: 	    var resp = confirm("You entered a value ("+pts+
 1255: 			       ") greater than the weight for the part. Accept?");
 1256: 	    if (resp == false) {
 1257: 		gradeBox.value = oldpts;
 1258: 		return;
 1259: 	    }
 1260: 	}
 1261: 
 1262: 	for (var i=0; i<radioButton.length; i++) {
 1263: 	    radioButton[i].checked=false;
 1264: 	    if (pts == i && pts != "") {
 1265: 		radioButton[i].checked=true;
 1266: 	    }
 1267: 	}
 1268: 	updateSelect(formname,id);
 1269: 	formname["stores"+id].value = "0";
 1270:     }
 1271: 
 1272:     function writeBox(formname,id,pts) {
 1273: 	var gradeBox = formname["GD_BOX"+id];
 1274: 	if (checkSolved(formname,id) == 'update') {
 1275: 	    gradeBox.value = pts;
 1276: 	} else {
 1277: 	    var oldpts = formname["oldpts"+id].value;
 1278: 	    gradeBox.value = oldpts;
 1279: 	    var radioButton = formname["RADVAL"+id];
 1280: 	    for (var i=0; i<radioButton.length; i++) {
 1281: 		radioButton[i].checked=false;
 1282: 		if (i == oldpts) {
 1283: 		    radioButton[i].checked=true;
 1284: 		}
 1285: 	    }
 1286: 	}
 1287: 	formname["stores"+id].value = "0";
 1288: 	updateSelect(formname,id);
 1289: 	return;
 1290:     }
 1291: 
 1292:     function clearRadBox(formname,id) {
 1293: 	if (checkSolved(formname,id) == 'noupdate') {
 1294: 	    updateSelect(formname,id);
 1295: 	    return;
 1296: 	}
 1297: 	gradeSelect = formname["GD_SEL"+id];
 1298: 	for (var i=0; i<gradeSelect.length; i++) {
 1299: 	    if (gradeSelect[i].selected) {
 1300: 		var selectx=i;
 1301: 	    }
 1302: 	}
 1303: 	var stores = formname["stores"+id];
 1304: 	if (selectx == stores.value) { return };
 1305: 	var gradeBox = formname["GD_BOX"+id];
 1306: 	gradeBox.value = "";
 1307: 	var radioButton = formname["RADVAL"+id];
 1308: 	for (var i=0; i<radioButton.length; i++) {
 1309: 	    radioButton[i].checked=false;
 1310: 	}
 1311: 	stores.value = selectx;
 1312:     }
 1313: 
 1314:     function checkSolved(formname,id) {
 1315: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1316: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1317: 	    if (!reply) {return "noupdate";}
 1318: 	    formname.overRideScore.value = 'yes';
 1319: 	}
 1320: 	return "update";
 1321:     }
 1322: 
 1323:     function updateSelect(formname,id) {
 1324: 	formname["GD_SEL"+id][0].selected = true;
 1325: 	return;
 1326:     }
 1327: 
 1328: //=========== Check that a point is assigned for all the parts  ============
 1329:     function checksubmit(formname,val,total,parttot) {
 1330: 	formname.gradeOpt.value = val;
 1331: 	if (val == "Save & Next") {
 1332: 	    for (i=0;i<=total;i++) {
 1333: 		for (j=0;j<parttot;j++) {
 1334: 		    var partid = formname["partid"+i+"_"+j].value;
 1335: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1336: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1337: 			if (points == "") {
 1338: 			    var name = formname["name"+i].value;
 1339: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1340: 			    var resp = confirm("You did not assign a score for "+studentID+
 1341: 					       ", part "+partid+". Continue?");
 1342: 			    if (resp == false) {
 1343: 				formname["GD_BOX"+i+"_"+partid].focus();
 1344: 				return false;
 1345: 			    }
 1346: 			}
 1347: 		    }
 1348: 		    
 1349: 		}
 1350: 	    }
 1351: 	    
 1352: 	}
 1353: 	if (val == "Grade Student") {
 1354: 	    formname.showgrading.value = "yes";
 1355: 	    if (formname.Status.value == "") {
 1356: 		formname.Status.value = "Active";
 1357: 	    }
 1358: 	    formname.studentNo.value = total;
 1359: 	}
 1360: 	formname.submit();
 1361:     }
 1362: 
 1363: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1364:     function checkSubmitPage(formname,total) {
 1365: 	noscore = new Array(100);
 1366: 	var ptr = 0;
 1367: 	for (i=1;i<total;i++) {
 1368: 	    var partid = formname["q_"+i].value;
 1369: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1370: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1371: 		var status = formname["solved"+i+"_"+partid].value;
 1372: 		if (points == "" && status != "correct_by_student") {
 1373: 		    noscore[ptr] = i;
 1374: 		    ptr++;
 1375: 		}
 1376: 	    }
 1377: 	}
 1378: 	if (ptr != 0) {
 1379: 	    var sense = ptr == 1 ? ": " : "s: ";
 1380: 	    var prolist = "";
 1381: 	    if (ptr == 1) {
 1382: 		prolist = noscore[0];
 1383: 	    } else {
 1384: 		var i = 0;
 1385: 		while (i < ptr-1) {
 1386: 		    prolist += noscore[i]+", ";
 1387: 		    i++;
 1388: 		}
 1389: 		prolist += "and "+noscore[i];
 1390: 	    }
 1391: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1392: 	    if (resp == false) {
 1393: 		return false;
 1394: 	    }
 1395: 	}
 1396: 
 1397: 	formname.submit();
 1398:     }
 1399: SUBJAVASCRIPT
 1400: }
 1401: 
 1402: #--- javascript for essay type problem --
 1403: sub sub_page_kw_js {
 1404:     my $request = shift;
 1405:     my $iconpath = $request->dir_config('lonIconsURL');
 1406:     &commonJSfunctions($request);
 1407: 
 1408:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1409:     function checkInput() {
 1410:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1411:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1412:       var usrctr = document.msgcenter.usrctr.value;
 1413:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1414:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1415: 
 1416:       var msgchk = "";
 1417:       if (document.msgcenter.subchk.checked) {
 1418:          msgchk = "msgsub,";
 1419:       }
 1420:       var includemsg = 0;
 1421:       for (var i=1; i<=nmsg; i++) {
 1422:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1423:           var frmmsg = document.msgcenter["msg"+i];
 1424:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1425:           var showflg = opener.document.SCORE["shownOnce"+i];
 1426:           showflg.value = "1";
 1427:           var chkbox = document.msgcenter["msgn"+i];
 1428:           if (chkbox.checked) {
 1429:              msgchk += "savemsg"+i+",";
 1430:              includemsg = 1;
 1431:           }
 1432:       }
 1433:       if (document.msgcenter.newmsgchk.checked) {
 1434:          msgchk += "newmsg"+usrctr;
 1435:          includemsg = 1;
 1436:       }
 1437:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1438:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1439:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1440:       includemsg.value = msgchk;
 1441: 
 1442:       self.close()
 1443: 
 1444:     }
 1445: INNERJS
 1446: 
 1447:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
 1448:     function updateChoice(flag) {
 1449:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1450:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1451:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1452:       opener.document.SCORE.refresh.value = "on";
 1453:       if (opener.document.SCORE.keywords.value!=""){
 1454:          opener.document.SCORE.submit();
 1455:       }
 1456:       self.close()
 1457:     }
 1458: INNERJS
 1459: 
 1460:     my $start_page_msg_central = 
 1461:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1462: 				       {'js_ready'  => 1,
 1463: 					'only_body' => 1,
 1464: 					'bgcolor'   =>'#FFFFFF',});
 1465:     my $end_page_msg_central = 
 1466: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1467: 
 1468: 
 1469:     my $start_page_highlight_central = 
 1470:         &Apache::loncommon::start_page('Highlight Central',
 1471: 				       $inner_js_highlight_central,
 1472: 				       {'js_ready'  => 1,
 1473: 					'only_body' => 1,
 1474: 					'bgcolor'   =>'#FFFFFF',});
 1475:     my $end_page_highlight_central = 
 1476: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1477: 
 1478:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1479:     $docopen=~s/^document\.//;
 1480:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1481:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1482: 
 1483: //===================== Show list of keywords ====================
 1484:   function keywords(formname) {
 1485:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1486:     if (nret==null) return;
 1487:     formname.keywords.value = nret;
 1488: 
 1489:     if (formname.keywords.value != "") {
 1490: 	formname.refresh.value = "on";
 1491: 	formname.submit();
 1492:     }
 1493:     return;
 1494:   }
 1495: 
 1496: //===================== Script to view submitted by ==================
 1497:   function viewSubmitter(submitter) {
 1498:     document.SCORE.refresh.value = "on";
 1499:     document.SCORE.NCT.value = "1";
 1500:     document.SCORE.unamedom0.value = submitter;
 1501:     document.SCORE.submit();
 1502:     return;
 1503:   }
 1504: 
 1505: //===================== Script to add keyword(s) ==================
 1506:   function getSel() {
 1507:     if (document.getSelection) txt = document.getSelection();
 1508:     else if (document.selection) txt = document.selection.createRange().text;
 1509:     else return;
 1510:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1511:     if (cleantxt=="") {
 1512: 	alert("$alertmsg");
 1513: 	return;
 1514:     }
 1515:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1516:     if (nret==null) return;
 1517:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1518:     if (document.SCORE.keywords.value != "") {
 1519: 	document.SCORE.refresh.value = "on";
 1520: 	document.SCORE.submit();
 1521:     }
 1522:     return;
 1523:   }
 1524: 
 1525: //====================== Script for composing message ==============
 1526:    // preload images
 1527:    img1 = new Image();
 1528:    img1.src = "$iconpath/mailbkgrd.gif";
 1529:    img2 = new Image();
 1530:    img2.src = "$iconpath/mailto.gif";
 1531: 
 1532:   function msgCenter(msgform,usrctr,fullname) {
 1533:     var Nmsg  = msgform.savemsgN.value;
 1534:     savedMsgHeader(Nmsg,usrctr,fullname);
 1535:     var subject = msgform.msgsub.value;
 1536:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1537:     re = /msgsub/;
 1538:     var shwsel = "";
 1539:     if (re.test(msgchk)) { shwsel = "checked" }
 1540:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1541:     displaySubject(checkEntities(subject),shwsel);
 1542:     for (var i=1; i<=Nmsg; i++) {
 1543: 	var testmsg = "savemsg"+i+",";
 1544: 	re = new RegExp(testmsg,"g");
 1545: 	shwsel = "";
 1546: 	if (re.test(msgchk)) { shwsel = "checked" }
 1547: 	var message = document.SCORE["savemsg"+i].value;
 1548: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1549: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1550: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1551:     }
 1552:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1553:     shwsel = "";
 1554:     re = /newmsg/;
 1555:     if (re.test(msgchk)) { shwsel = "checked" }
 1556:     newMsg(newmsg,shwsel);
 1557:     msgTail(); 
 1558:     return;
 1559:   }
 1560: 
 1561:   function checkEntities(strx) {
 1562:     if (strx.length == 0) return strx;
 1563:     var orgStr = ["&", "<", ">", '"']; 
 1564:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1565:     var counter = 0;
 1566:     while (counter < 4) {
 1567: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1568: 	counter++;
 1569:     }
 1570:     return strx;
 1571:   }
 1572: 
 1573:   function strReplace(strx, orgStr, newStr) {
 1574:     return strx.split(orgStr).join(newStr);
 1575:   }
 1576: 
 1577:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1578:     var height = 70*Nmsg+250;
 1579:     var scrollbar = "no";
 1580:     if (height > 600) {
 1581: 	height = 600;
 1582: 	scrollbar = "yes";
 1583:     }
 1584:     var xpos = (screen.width-600)/2;
 1585:     xpos = (xpos < 0) ? '0' : xpos;
 1586:     var ypos = (screen.height-height)/2-30;
 1587:     ypos = (ypos < 0) ? '0' : ypos;
 1588: 
 1589:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1590:     pWin.focus();
 1591:     pDoc = pWin.document;
 1592:     pDoc.$docopen;
 1593:     pDoc.write('$start_page_msg_central');
 1594: 
 1595:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1596:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1597:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1598: 
 1599:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1600:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1601:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1602: }
 1603:     function displaySubject(msg,shwsel) {
 1604:     pDoc = pWin.document;
 1605:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1606:     pDoc.write("<td>Subject<\\/td>");
 1607:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1608:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1609: }
 1610: 
 1611:   function displaySavedMsg(ctr,msg,shwsel) {
 1612:     pDoc = pWin.document;
 1613:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1614:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1615:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1616:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1617: }
 1618: 
 1619:   function newMsg(newmsg,shwsel) {
 1620:     pDoc = pWin.document;
 1621:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1622:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1623:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1624:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1625: }
 1626: 
 1627:   function msgTail() {
 1628:     pDoc = pWin.document;
 1629:     pDoc.write("<\\/table>");
 1630:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1631:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1632:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1633:     pDoc.write("<\\/form>");
 1634:     pDoc.write('$end_page_msg_central');
 1635:     pDoc.close();
 1636: }
 1637: 
 1638: //====================== Script for keyword highlight options ==============
 1639:   function kwhighlight() {
 1640:     var kwclr    = document.SCORE.kwclr.value;
 1641:     var kwsize   = document.SCORE.kwsize.value;
 1642:     var kwstyle  = document.SCORE.kwstyle.value;
 1643:     var redsel = "";
 1644:     var grnsel = "";
 1645:     var blusel = "";
 1646:     if (kwclr=="red")   {var redsel="checked"};
 1647:     if (kwclr=="green") {var grnsel="checked"};
 1648:     if (kwclr=="blue")  {var blusel="checked"};
 1649:     var sznsel = "";
 1650:     var sz1sel = "";
 1651:     var sz2sel = "";
 1652:     if (kwsize=="0")  {var sznsel="checked"};
 1653:     if (kwsize=="+1") {var sz1sel="checked"};
 1654:     if (kwsize=="+2") {var sz2sel="checked"};
 1655:     var synsel = "";
 1656:     var syisel = "";
 1657:     var sybsel = "";
 1658:     if (kwstyle=="")    {var synsel="checked"};
 1659:     if (kwstyle=="<i>") {var syisel="checked"};
 1660:     if (kwstyle=="<b>") {var sybsel="checked"};
 1661:     highlightCentral();
 1662:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1663:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1664:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1665:     highlightend();
 1666:     return;
 1667:   }
 1668: 
 1669:   function highlightCentral() {
 1670: //    if (window.hwdWin) window.hwdWin.close();
 1671:     var xpos = (screen.width-400)/2;
 1672:     xpos = (xpos < 0) ? '0' : xpos;
 1673:     var ypos = (screen.height-330)/2-30;
 1674:     ypos = (ypos < 0) ? '0' : ypos;
 1675: 
 1676:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1677:     hwdWin.focus();
 1678:     var hDoc = hwdWin.document;
 1679:     hDoc.$docopen;
 1680:     hDoc.write('$start_page_highlight_central');
 1681:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1682:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1683: 
 1684:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1685:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1686:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1687:   }
 1688: 
 1689:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1690:     var hDoc = hwdWin.document;
 1691:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1692:     hDoc.write("<td align=\\"left\\">");
 1693:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1694:     hDoc.write("<td align=\\"left\\">");
 1695:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1696:     hDoc.write("<td align=\\"left\\">");
 1697:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1698:     hDoc.write("<\\/tr>");
 1699:   }
 1700: 
 1701:   function highlightend() { 
 1702:     var hDoc = hwdWin.document;
 1703:     hDoc.write("<\\/table>");
 1704:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1705:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1706:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1707:     hDoc.write("<\\/form>");
 1708:     hDoc.write('$end_page_highlight_central');
 1709:     hDoc.close();
 1710:   }
 1711: 
 1712: SUBJAVASCRIPT
 1713: }
 1714: 
 1715: sub get_increment {
 1716:     my $increment = $env{'form.increment'};
 1717:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1718:         $increment != .1) {
 1719:         $increment = 1;
 1720:     }
 1721:     return $increment;
 1722: }
 1723: 
 1724: sub gradeBox_start {
 1725:     return (
 1726:         &Apache::loncommon::start_data_table()
 1727:        .&Apache::loncommon::start_data_table_header_row()
 1728:        .'<th>'.&mt('Part').'</th>'
 1729:        .'<th>'.&mt('Points').'</th>'
 1730:        .'<th>&nbsp;</th>'
 1731:        .'<th>'.&mt('Assign Grade').'</th>'
 1732:        .'<th>'.&mt('Weight').'</th>'
 1733:        .'<th>'.&mt('Grade Status').'</th>'
 1734:        .&Apache::loncommon::end_data_table_header_row()
 1735:     );
 1736: }
 1737: 
 1738: sub gradeBox_end {
 1739:     return (
 1740:         &Apache::loncommon::end_data_table()
 1741:     );
 1742: }
 1743: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1744: sub gradeBox {
 1745:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1746:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1747: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1748:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1749:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1750:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1751:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1752:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1753: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1754:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1755:     my $display_part= &get_display_part($partid,$symb);
 1756:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1757: 				       [$partid]);
 1758:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1759:     if ($last_resets{$partid}) {
 1760:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1761:     }
 1762:     $result.=&Apache::loncommon::start_data_table_row();
 1763:     my $ctr = 0;
 1764:     my $thisweight = 0;
 1765:     my $increment = &get_increment();
 1766: 
 1767:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1768:     while ($thisweight<=$wgt) {
 1769: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1770:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1771: 	    $thisweight.')" value="'.$thisweight.'" '.
 1772: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1773: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1774:         $thisweight += $increment;
 1775: 	$ctr++;
 1776:     }
 1777:     $radio.='</tr></table>';
 1778: 
 1779:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1780: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1781: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1782: 	$wgt.')" /></td>'."\n";
 1783:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1784: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1785: 	' </td>'."\n";
 1786:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1787: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1788:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1789: 	$line.='<option></option>'.
 1790: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1791:     } else {
 1792: 	$line.='<option selected="selected"></option>'.
 1793: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1794:     }
 1795:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1796: 
 1797: 
 1798: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
 1799:     $result .= 
 1800: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1801:     $result.=&Apache::loncommon::end_data_table_row();
 1802:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1803: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1804: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1805: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1806:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1807:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1808:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1809:         $aggtries.'" />'."\n";
 1810:     my $res_error;
 1811:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1812:     if ($res_error) {
 1813:         return &navmap_errormsg();
 1814:     }
 1815:     return $result;
 1816: }
 1817: 
 1818: sub handback_box {
 1819:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1820:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1821:     my (@respids);
 1822:      my @part_response_id = &flatten_responseType($responseType);
 1823:     foreach my $part_response_id (@part_response_id) {
 1824:     	my ($part,$resp) = @{ $part_response_id };
 1825:         if ($part eq $partid) {
 1826:             push(@respids,$resp);
 1827:         }
 1828:     }
 1829:     my $result;
 1830:     foreach my $respid (@respids) {
 1831: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1832: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1833: 	next if (!@$files);
 1834: 	my $file_counter = 1;
 1835: 	foreach my $file (@$files) {
 1836: 	    if ($file =~ /\/portfolio\//) {
 1837:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1838:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1839:     	        $file_disp = "$name.$ext";
 1840:     	        $file = $file_path.$file_disp;
 1841:     	        $result.=&mt('Return commented version of [_1] to student.',
 1842:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1843:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1844:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1845:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1846:     	        $file_counter++;
 1847: 	    }
 1848: 	}
 1849:     }
 1850:     return $result;    
 1851: }
 1852: 
 1853: sub show_problem {
 1854:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1855:     my $rendered;
 1856:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1857:     &Apache::lonxml::remember_problem_counter();
 1858:     if ($mode eq 'both' or $mode eq 'text') {
 1859: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1860: 						       $env{'request.course.id'},
 1861: 						       undef,\%form);
 1862:     }
 1863:     if ($removeform) {
 1864: 	$rendered=~s|<form(.*?)>||g;
 1865: 	$rendered=~s|</form>||g;
 1866: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1867:     }
 1868:     my $companswer;
 1869:     if ($mode eq 'both' or $mode eq 'answer') {
 1870: 	&Apache::lonxml::restore_problem_counter();
 1871: 	$companswer=
 1872: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1873: 						    $env{'request.course.id'},
 1874: 						    %form);
 1875:     }
 1876:     if ($removeform) {
 1877: 	$companswer=~s|<form(.*?)>||g;
 1878: 	$companswer=~s|</form>||g;
 1879: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1880:     }
 1881:     $rendered=
 1882:         '<div class="LC_Box">'
 1883:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1884:        .$rendered
 1885:        .'</div>';
 1886:     $companswer=
 1887:         '<div class="LC_Box">'
 1888:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1889:        .$companswer
 1890:        .'</div>';
 1891:     my $result;
 1892:     if ($mode eq 'both') {
 1893:         $result=$rendered.$companswer;
 1894:     } elsif ($mode eq 'text') {
 1895:         $result=$rendered;
 1896:     } elsif ($mode eq 'answer') {
 1897:         $result=$companswer;
 1898:     }
 1899:     return $result;
 1900: }
 1901: 
 1902: sub files_exist {
 1903:     my ($r, $symb) = @_;
 1904:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1905: 
 1906:     foreach my $student (@students) {
 1907:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1908:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1909: 					      $udom,$uname);
 1910:         my ($string,$timestamp)= &get_last_submission(\%record);
 1911:         foreach my $submission (@$string) {
 1912:             my ($partid,$respid) =
 1913: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1914:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1915: 					   \%record);
 1916:             return 1 if (@$files);
 1917:         }
 1918:     }
 1919:     return 0;
 1920: }
 1921: 
 1922: sub download_all_link {
 1923:     my ($r,$symb) = @_;
 1924:     my $all_students = 
 1925: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1926: 
 1927:     my $parts =
 1928: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1929: 
 1930:     my $identifier = &Apache::loncommon::get_cgi_id();
 1931:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1932:                              'cgi.'.$identifier.'.symb' => $symb,
 1933:                              'cgi.'.$identifier.'.parts' => $parts,});
 1934:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1935: 	      &mt('Download All Submitted Documents').'</a>');
 1936:     return
 1937: }
 1938: 
 1939: sub build_section_inputs {
 1940:     my $section_inputs;
 1941:     if ($env{'form.section'} eq '') {
 1942:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1943:     } else {
 1944:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1945:         foreach my $section (@sections) {
 1946:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1947:         }
 1948:     }
 1949:     return $section_inputs;
 1950: }
 1951: 
 1952: # --------------------------- show submissions of a student, option to grade 
 1953: sub submission {
 1954:     my ($request,$counter,$total) = @_;
 1955:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1956:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1957:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1958:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1959:     my $symb = &get_symb($request); 
 1960:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1961: 
 1962:     if (!&canview($usec)) {
 1963: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1964: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1965: 			$env{'request.course.id'}.')</span>');
 1966: 	$request->print(&show_grading_menu_form($symb));
 1967: 	return;
 1968:     }
 1969: 
 1970:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1971:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1972:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1973:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1974:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1975: 	'" src="'.$request->dir_config('lonIconsURL').
 1976: 	'/check.gif" height="16" border="0" />';
 1977: 
 1978:     my %old_essays;
 1979:     # header info
 1980:     if ($counter == 0) {
 1981: 	&sub_page_js($request);
 1982: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1983: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1984: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1985: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1986: 	    &download_all_link($request, $symb);
 1987: 	}
 1988: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1989: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1990: 
 1991: 	# option to display problem, only once else it cause problems 
 1992:         # with the form later since the problem has a form.
 1993: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1994: 	    my $mode;
 1995: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1996: 		$mode='both';
 1997: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1998: 		$mode='text';
 1999: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2000: 		$mode='answer';
 2001: 	    }
 2002: 	    &Apache::lonxml::clear_problem_counter();
 2003: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2004: 	}
 2005: 
 2006: 	# kwclr is the only variable that is guaranteed to be non blank 
 2007:         # if this subroutine has been called once.
 2008: 	my %keyhash = ();
 2009: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2010: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2011: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2012: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2013: 
 2014: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2015: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2016: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2017: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2018: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2019: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2020: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2021: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2022: 	}
 2023: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2024: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2025: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2026: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2027: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2028: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2029: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2030: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2031: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2032: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2033: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2034: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2035: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2036: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2037: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2038: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2039: 			&build_section_inputs().
 2040: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2041: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2042: 			'<input type="hidden" name="NCT"'.
 2043: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2044: 	if ($env{'form.handgrade'} eq 'yes') {
 2045: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2046: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2047: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2048: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2049: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2050: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2051: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2052: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2053: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2054: 	    }
 2055: 	}
 2056: 	
 2057: 	my ($cts,$prnmsg) = (1,'');
 2058: 	while ($cts <= $env{'form.savemsgN'}) {
 2059: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2060: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2061: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2062: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2063: 		'" />'."\n".
 2064: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2065: 	    $cts++;
 2066: 	}
 2067: 	$request->print($prnmsg);
 2068: 
 2069: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2070: #
 2071: # Print out the keyword options line
 2072: #
 2073: 	    $request->print(<<KEYWORDS);
 2074: &nbsp;<b>Keyword Options:</b>&nbsp;
 2075: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2076: <a href="#" onmousedown="javascript:getSel(); return false"
 2077:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2078: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2079: KEYWORDS
 2080: #
 2081: # Load the other essays for similarity check
 2082: #
 2083:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2084: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2085: 	    $apath=&escape($apath);
 2086: 	    $apath=~s/\W/\_/gs;
 2087: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2088:         }
 2089:     }
 2090: 
 2091: # This is where output for one specific student would start
 2092:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2093:     $request->print(
 2094:         "\n\n"
 2095:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2096:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2097:        ."\n"
 2098:     );
 2099: 
 2100:     # Show additional functions if allowed
 2101:     if ($perm{'vgr'}) {
 2102:         $request->print(
 2103:             &Apache::loncommon::track_student_link(
 2104:                 &mt('View recent activity'),
 2105:                 $uname,$udom,'check')
 2106:            .' '
 2107:         );
 2108:     }
 2109:     if ($perm{'opa'}) {
 2110:         $request->print(
 2111:             &Apache::loncommon::pprmlink(
 2112:                 &mt('Set/Change parameters'),
 2113:                 $uname,$udom,$symb,'check'));
 2114:     }
 2115: 
 2116:     # Show Problem
 2117:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2118: 	my $mode;
 2119: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2120: 	    $mode='both';
 2121: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2122: 	    $mode='text';
 2123: 	} elsif ($env{'form.vAns'} eq 'all') {
 2124: 	    $mode='answer';
 2125: 	}
 2126: 	&Apache::lonxml::clear_problem_counter();
 2127: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2128:     }
 2129: 
 2130:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2131:     my $res_error;
 2132:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2133:     if ($res_error) {
 2134:         $request->print(&navmap_errormsg());
 2135:         return;
 2136:     }
 2137: 
 2138:     # Display student info
 2139:     $request->print(($counter == 0 ? '' : '<br />'));
 2140: 
 2141:     my $result='<div class="LC_Box">'
 2142:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2143:     $result.='<input type="hidden" name="name'.$counter.
 2144:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2145:     if ($env{'form.handgrade'} eq 'no') {
 2146:         $result.='<p class="LC_info">'
 2147:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2148:                 ."</p>\n";
 2149:     }
 2150: 
 2151:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2152:     my $fullname;
 2153:     my $col_fullnames = [];
 2154:     if ($env{'form.handgrade'} eq 'yes') {
 2155: 	(my $sub_result,$fullname,$col_fullnames)=
 2156: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2157: 				 $counter);
 2158: 	$result.=$sub_result;
 2159:     }
 2160:     $request->print($result."\n");
 2161: 
 2162:     # print student answer/submission
 2163:     # Options are (1) Handgraded submission only
 2164:     #             (2) Last submission, includes submission that is not handgraded 
 2165:     #                  (for multi-response type part)
 2166:     #             (3) Last submission plus the parts info
 2167:     #             (4) The whole record for this student
 2168:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2169: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2170: 	
 2171: 	my $lastsubonly;
 2172: 
 2173:         if ($$timestamp eq '') {
 2174:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2175:         } else {
 2176:             $lastsubonly =
 2177:                 '<div class="LC_grade_submissions_body">'
 2178:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2179: 
 2180: 	    my %seenparts;
 2181: 	    my @part_response_id = &flatten_responseType($responseType);
 2182: 	    foreach my $part (@part_response_id) {
 2183: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2184: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2185: 
 2186: 		my ($partid,$respid) = @{ $part };
 2187: 		my $display_part=&get_display_part($partid,$symb);
 2188: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2189: 		    if (exists($seenparts{$partid})) { next; }
 2190: 		    $seenparts{$partid}=1;
 2191: 		    my $submitby='<b>Part:</b> '.$display_part.
 2192: 			' <b>Collaborative submission by:</b> '.
 2193: 			'<a href="javascript:viewSubmitter(\''.
 2194: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2195: 			'\');" target="_self">'.
 2196: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2197: 		    $request->print($submitby);
 2198: 		    next;
 2199: 		}
 2200: 		my $responsetype = $responseType->{$partid}->{$respid};
 2201: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2202:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2203:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2204:                         ' <span class="LC_internal_info">'.
 2205:                         '('.&mt('Part ID: [_1]',$respid).')'.
 2206:                         '</span>&nbsp; &nbsp;'.
 2207: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2208: 		    next;
 2209: 		}
 2210: 		foreach my $submission (@$string) {
 2211: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2212: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2213: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2214: 		    # Similarity check
 2215: 		    my $similar='';
 2216: 		    if($env{'form.checkPlag'}){
 2217: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2218: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2219: 			if ($osim) {
 2220: 			    $osim=int($osim*100.0);
 2221: 			    my %old_course_desc = 
 2222: 				&Apache::lonnet::coursedescription($ocrsid,
 2223: 								   {'one_time' => 1});
 2224: 
 2225:                             if ($hide) {
 2226:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2227:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2228:                             } else {
 2229: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2230: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2231: 				        $osim,
 2232: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2233: 				        $old_course_desc{'description'},
 2234: 				        $old_course_desc{'num'},
 2235: 				        $old_course_desc{'domain'}).
 2236: 				    '</span></h3><blockquote><i>'.
 2237: 				    &keywords_highlight($oessay).
 2238: 				    '</i></blockquote><hr />';
 2239:                             }
 2240: 			}
 2241: 		    }
 2242: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2243: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2244: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2245: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2246: 			my $display_part=&get_display_part($partid,$symb);
 2247:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2248:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2249:                             ' <span class="LC_internal_info">'.
 2250:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2251:                             '</span>&nbsp; &nbsp;';
 2252: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2253: 			if (@$files) {
 2254:                             if ($hide) {
 2255:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2256:                             } else {
 2257:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2258:                                 foreach my $file (@$files) {
 2259:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2260:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2261:                                 }
 2262:                             }
 2263: 			    $lastsubonly.='<br />';
 2264: 			}
 2265:                         if ($hide) {
 2266:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2267:                         } else {
 2268: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2269: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2270: 					     $respid,\%record,$order,undef,$uname,$udom);
 2271:                         }
 2272: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2273: 			$lastsubonly.='</div>';
 2274: 		    }
 2275: 		}
 2276: 	    }
 2277: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2278: 	}
 2279: 	$request->print($lastsubonly);
 2280:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2281: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2282:     my ($parts,$handgrade,$responseType) = &response_type($symb);
 2283: 
 2284: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2285:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2286: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2287: 								 $env{'request.course.id'},
 2288: 								 $last,'.submission',
 2289: 								 'Apache::grades::keywords_highlight'));
 2290:     }
 2291: 
 2292:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2293: 	.$udom.'" />'."\n");
 2294:     # return if view submission with no grading option
 2295:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2296: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2297: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2298: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2299: 	$toGrade.='</div>'."\n";
 2300: 	if (($env{'form.command'} eq 'submission') || 
 2301: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2302: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2303: 	}
 2304: 	$request->print($toGrade);
 2305: 	return;
 2306:     } else {
 2307: 	$request->print('</div>'."\n");
 2308:     }
 2309: 
 2310:     # essay grading message center
 2311:     if ($env{'form.handgrade'} eq 'yes') {
 2312: 	my $result='<div class="LC_grade_message_center">';
 2313:     
 2314: 	$result.='<div class="LC_grade_message_center_header">'.
 2315: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2316: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2317: 	my $msgfor = $givenn.' '.$lastname;
 2318: 	if (scalar(@$col_fullnames) > 0) {
 2319: 	    my $lastone = pop(@$col_fullnames);
 2320: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2321: 	}
 2322: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2323: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2324: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2325: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2326: 	    ',\''.$msgfor.'\');" target="_self">'.
 2327: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2328: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2329: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2330: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2331: 	    '<br />&nbsp;('.
 2332: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2333: 	$result.='</div></div>';
 2334: 	$request->print($result);
 2335:     }
 2336: 
 2337:     my %seen = ();
 2338:     my @partlist;
 2339:     my @gradePartRespid;
 2340:     my @part_response_id = &flatten_responseType($responseType);
 2341:     $request->print(
 2342:         '<div class="LC_Box">'
 2343:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2344:     );
 2345:     $request->print(&gradeBox_start());
 2346:     foreach my $part_response_id (@part_response_id) {
 2347:     	my ($partid,$respid) = @{ $part_response_id };
 2348: 	my $part_resp = join('_',@{ $part_response_id });
 2349: 	next if ($seen{$partid} > 0);
 2350: 	$seen{$partid}++;
 2351: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2352: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2353: 	push(@partlist,$partid);
 2354: 	push(@gradePartRespid,$partid.'.'.$respid);
 2355: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2356:     }
 2357:     $request->print(&gradeBox_end()); # </div>
 2358:     $request->print('</div>');
 2359: 
 2360:     $request->print('<div class="LC_grade_info_links">');
 2361:     $request->print('</div>');
 2362: 
 2363:     $result='<input type="hidden" name="partlist'.$counter.
 2364: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2365:     $result.='<input type="hidden" name="gradePartRespid'.
 2366: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2367:     my $ctr = 0;
 2368:     while ($ctr < scalar(@partlist)) {
 2369: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2370: 	    $partlist[$ctr].'" />'."\n";
 2371: 	$ctr++;
 2372:     }
 2373:     $request->print($result.''."\n");
 2374: 
 2375: # Done with printing info for one student
 2376: 
 2377:     $request->print('</div>');#LC_grade_show_user
 2378: 
 2379: 
 2380:     # print end of form
 2381:     if ($counter == $total) {
 2382:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2383: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2384: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2385: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2386: 	my $ntstu ='<select name="NTSTU">'.
 2387: 	    '<option>1</option><option>2</option>'.
 2388: 	    '<option>3</option><option>5</option>'.
 2389: 	    '<option>7</option><option>10</option></select>'."\n";
 2390: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2391: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2392:         $endform.=&mt('[_1]student(s)',$ntstu);
 2393: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2394: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2395: 	    '<input type="button" value="'.&mt('Next').'" '.
 2396: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2397:         $endform.='<span class="LC_warning">'.
 2398:                   &mt('(Next and Previous (student) do not save the scores.)').
 2399:                   '</span>'."\n" ;
 2400:         $endform.="<input type='hidden' value='".&get_increment().
 2401:             "' name='increment' />";
 2402: 	$endform.='</td></tr></table></form>';
 2403: 	$endform.=&show_grading_menu_form($symb);
 2404: 	$request->print($endform);
 2405:     }
 2406:     return '';
 2407: }
 2408: 
 2409: sub check_collaborators {
 2410:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2411:     my ($result,@col_fullnames);
 2412:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2413:     foreach my $part (keys(%$handgrade)) {
 2414: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2415: 					'.maxcollaborators',
 2416: 					$symb,$udom,$uname);
 2417: 	next if ($ncol <= 0);
 2418: 	$part =~ s/\_/\./g;
 2419: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2420: 	my (@good_collaborators, @bad_collaborators);
 2421: 	foreach my $possible_collaborator
 2422: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2423: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2424: 	    next if ($possible_collaborator eq '');
 2425: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2426: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2427: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2428: 	    # Doing this grep allows 'fuzzy' specification
 2429: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2430: 			       keys(%$classlist));
 2431: 	    if (! scalar(@matches)) {
 2432: 		push(@bad_collaborators, $possible_collaborator);
 2433: 	    } else {
 2434: 		push(@good_collaborators, @matches);
 2435: 	    }
 2436: 	}
 2437: 	if (scalar(@good_collaborators) != 0) {
 2438: 	    $result.='<br />'.&mt('Collaborators: ');
 2439: 	    foreach my $name (@good_collaborators) {
 2440: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2441: 		push(@col_fullnames, $givenn.' '.$lastname);
 2442: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2443: 	    }
 2444: 	    $result.='<br />'."\n";
 2445: 	    my ($part)=split(/\./,$part);
 2446: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2447: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2448: 		"\n";
 2449: 	}
 2450: 	if (scalar(@bad_collaborators) > 0) {
 2451: 	    $result.='<div class="LC_warning">';
 2452: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2453: 	    $result .= '</div>';
 2454: 	}         
 2455: 	if (scalar(@bad_collaborators > $ncol)) {
 2456: 	    $result .= '<div class="LC_warning">';
 2457: 	    $result .= &mt('This student has submitted too many '.
 2458: 		'collaborators.  Maximum is [_1].',$ncol);
 2459: 	    $result .= '</div>';
 2460: 	}
 2461:     }
 2462:     return ($result,$fullname,\@col_fullnames);
 2463: }
 2464: 
 2465: #--- Retrieve the last submission for all the parts
 2466: sub get_last_submission {
 2467:     my ($returnhash)=@_;
 2468:     my (@string,$timestamp,%lasthidden);
 2469:     if ($$returnhash{'version'}) {
 2470: 	my %lasthash=();
 2471: 	my ($version);
 2472: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2473: 	    foreach my $key (sort(split(/\:/,
 2474: 					$$returnhash{$version.':keys'}))) {
 2475: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2476: 		$timestamp = 
 2477: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2478: 	    }
 2479: 	}
 2480:         my %typeparts;
 2481:         my $showsurv = 
 2482:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2483:         foreach my $key (sort(keys(%lasthash))) {
 2484:             if ($key =~ /\.type$/) {
 2485:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2486:                     ($lasthash{$key} eq 'anonsurveycred')) {
 2487:                     my ($ign,@parts) = split(/\./,$key);
 2488:                     pop(@parts);
 2489:                     unless ($showsurv) {
 2490:                         my $id = join(',',@parts);
 2491:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2492:                     }
 2493:                     delete($lasthash{$key});
 2494:                 }
 2495:             }
 2496:         }
 2497:         my @hidden = keys(%typeparts);
 2498: 	foreach my $key (keys(%lasthash)) {
 2499: 	    next if ($key !~ /\.submission$/);
 2500:             my $hide;
 2501:             if (@hidden) {
 2502:                 foreach my $id (@hidden) {
 2503:                     if ($key =~ /^\Q$id\E/) {
 2504:                         $hide = 1;
 2505:                         last;
 2506:                     }
 2507:                 }
 2508:             }
 2509: 	    my ($partid,$foo) = split(/submission$/,$key);
 2510: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2511: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2512: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2513: 	}
 2514:     }
 2515:     if (!@string) {
 2516: 	$string[0] =
 2517: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2518:     }
 2519:     return (\@string,\$timestamp);
 2520: }
 2521: 
 2522: #--- High light keywords, with style choosen by user.
 2523: sub keywords_highlight {
 2524:     my $string    = shift;
 2525:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2526:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2527:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2528:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2529:     foreach my $keyword (@keylist) {
 2530: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2531:     }
 2532:     return $string;
 2533: }
 2534: 
 2535: #--- Called from submission routine
 2536: sub processHandGrade {
 2537:     my ($request) = shift;
 2538:     my $symb   = &get_symb($request);
 2539:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2540:     my $button = $env{'form.gradeOpt'};
 2541:     my $ngrade = $env{'form.NCT'};
 2542:     my $ntstu  = $env{'form.NTSTU'};
 2543:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2544:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2545: 
 2546:     if ($button eq 'Save & Next') {
 2547: 	my $ctr = 0;
 2548: 	while ($ctr < $ngrade) {
 2549: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2550: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2551: 	    if ($errorflag eq 'no_score') {
 2552: 		$ctr++;
 2553: 		next;
 2554: 	    }
 2555: 	    if ($errorflag eq 'not_allowed') {
 2556: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2557: 		$ctr++;
 2558: 		next;
 2559: 	    }
 2560: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2561: 	    my ($subject,$message,$msgstatus) = ('','','');
 2562: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2563:             my ($feedurl,$showsymb) =
 2564: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2565: 	    my $messagetail;
 2566: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2567: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2568: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2569: 		$subject.=' ['.$restitle.']';
 2570: 		my (@msgnum) = split(/,/,$includemsg);
 2571: 		foreach (@msgnum) {
 2572: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2573: 		}
 2574: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2575: 		if ($env{'form.withgrades'.$ctr}) {
 2576: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2577: 		    $messagetail = " for <a href=\"".
 2578: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2579: 		}
 2580: 		$msgstatus = 
 2581:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2582: 						     $message.$messagetail,
 2583:                                                      undef,$feedurl,undef,
 2584:                                                      undef,undef,$showsymb,
 2585:                                                      $restitle);
 2586: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2587: 				$msgstatus);
 2588: 	    }
 2589: 	    if ($env{'form.collaborator'.$ctr}) {
 2590: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2591: 		foreach my $collabstr (@collabstrs) {
 2592: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2593: 		    foreach my $collaborator (@collaborators) {
 2594: 			my ($errorflag,$pts,$wgt) = 
 2595: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2596: 					   $env{'form.unamedom'.$ctr},$part);
 2597: 			if ($errorflag eq 'not_allowed') {
 2598: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2599: 			    next;
 2600: 			} elsif ($message ne '') {
 2601: 			    my ($baseurl,$showsymb) = 
 2602: 				&get_feedurl_and_symb($symb,$collaborator,
 2603: 						      $udom);
 2604: 			    if ($env{'form.withgrades'.$ctr}) {
 2605: 				$messagetail = " for <a href=\"".
 2606:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2607: 			    }
 2608: 			    $msgstatus = 
 2609: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2610: 			}
 2611: 		    }
 2612: 		}
 2613: 	    }
 2614: 	    $ctr++;
 2615: 	}
 2616:     }
 2617: 
 2618:     if ($env{'form.handgrade'} eq 'yes') {
 2619: 	# Keywords sorted in alphabatical order
 2620: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2621: 	my %keyhash = ();
 2622: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2623: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2624: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2625: 	$env{'form.keywords'} = join(' ',@keywords);
 2626: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2627: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2628: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2629: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2630: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2631: 
 2632: 	# message center - Order of message gets changed. Blank line is eliminated.
 2633: 	# New messages are saved in env for the next student.
 2634: 	# All messages are saved in nohist_handgrade.db
 2635: 	my ($ctr,$idx) = (1,1);
 2636: 	while ($ctr <= $env{'form.savemsgN'}) {
 2637: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2638: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2639: 		$idx++;
 2640: 	    }
 2641: 	    $ctr++;
 2642: 	}
 2643: 	$ctr = 0;
 2644: 	while ($ctr < $ngrade) {
 2645: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2646: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2647: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2648: 		$idx++;
 2649: 	    }
 2650: 	    $ctr++;
 2651: 	}
 2652: 	$env{'form.savemsgN'} = --$idx;
 2653: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2654: 	my $putresult = &Apache::lonnet::put
 2655: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2656:     }
 2657:     # Called by Save & Refresh from Highlight Attribute Window
 2658:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2659:     if ($env{'form.refresh'} eq 'on') {
 2660: 	my ($ctr,$total) = (0,0);
 2661: 	while ($ctr < $ngrade) {
 2662: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2663: 	    $ctr++;
 2664: 	}
 2665: 	$env{'form.NTSTU'}=$ngrade;
 2666: 	$ctr = 0;
 2667: 	while ($ctr < $total) {
 2668: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2669: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2670: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2671: 	    &submission($request,$ctr,$total-1);
 2672: 	    $ctr++;
 2673: 	}
 2674: 	return '';
 2675:     }
 2676: 
 2677: # Go directly to grade student - from submission or link from chart page
 2678:     if ($button eq 'Grade Student') {
 2679: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2680: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2681: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2682: 	$env{'form.fullname'} = $$fullname{$processUser};
 2683: 	&submission($request,0,0);
 2684: 	return '';
 2685:     }
 2686: 
 2687:     # Get the next/previous one or group of students
 2688:     my $firststu = $env{'form.unamedom0'};
 2689:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2690:     my $ctr = 2;
 2691:     while ($laststu eq '') {
 2692: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2693: 	$ctr++;
 2694: 	$laststu = $firststu if ($ctr > $ngrade);
 2695:     }
 2696: 
 2697:     my (@parsedlist,@nextlist);
 2698:     my ($nextflg) = 0;
 2699:     foreach my $item (sort 
 2700: 	     {
 2701: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2702: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2703: 		 }
 2704: 		 return $a cmp $b;
 2705: 	     } (keys(%$fullname))) {
 2706: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2707: 	    push(@parsedlist,$item);
 2708: 	}
 2709: 	$nextflg = 1 if ($item eq $laststu);
 2710: 	if ($button eq 'Previous') {
 2711: 	    last if ($item eq $firststu);
 2712: 	    push(@parsedlist,$item);
 2713: 	}
 2714:     }
 2715:     $ctr = 0;
 2716:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2717:     my $res_error;
 2718:     my ($partlist) = &response_type($symb,\$res_error);
 2719:     if ($res_error) {
 2720:         $request->print(&navmap_errormsg());
 2721:         return;
 2722:     }
 2723:     foreach my $student (@parsedlist) {
 2724: 	my $submitonly=$env{'form.submitonly'};
 2725: 	my ($uname,$udom) = split(/:/,$student);
 2726: 	
 2727: 	if ($submitonly eq 'queued') {
 2728: 	    my %queue_status = 
 2729: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2730: 							$udom,$uname);
 2731: 	    next if (!defined($queue_status{'gradingqueue'}));
 2732: 	}
 2733: 
 2734: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2735: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2736: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2737: 	    my $submitted = 0;
 2738: 	    my $ungraded = 0;
 2739: 	    my $incorrect = 0;
 2740: 	    foreach my $item (keys(%status)) {
 2741: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2742: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2743: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2744: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2745: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2746: 		    $submitted = 0;
 2747: 		}
 2748: 	    }
 2749: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2750: 				     $submitonly eq 'incorrect' ||
 2751: 				     $submitonly eq 'graded'));
 2752: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2753: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2754: 	}
 2755: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2756: 	last if ($ctr == $ntstu);
 2757: 	$ctr++;
 2758:     }
 2759: 
 2760:     $ctr = 0;
 2761:     my $total = scalar(@nextlist)-1;
 2762: 
 2763:     foreach (sort(@nextlist)) {
 2764: 	my ($uname,$udom,$submitter) = split(/:/);
 2765: 	$env{'form.student'}  = $uname;
 2766: 	$env{'form.userdom'}  = $udom;
 2767: 	$env{'form.fullname'} = $$fullname{$_};
 2768: 	&submission($request,$ctr,$total);
 2769: 	$ctr++;
 2770:     }
 2771:     if ($total < 0) {
 2772: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2773: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2774: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2775: 	$the_end.=&show_grading_menu_form($symb);
 2776: 	$request->print($the_end);
 2777:     }
 2778:     return '';
 2779: }
 2780: 
 2781: #---- Save the score and award for each student, if changed
 2782: sub saveHandGrade {
 2783:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2784:     my @version_parts;
 2785:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2786: 					   $env{'request.course.id'});
 2787:     if (!&canmodify($usec)) { return('not_allowed'); }
 2788:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2789:     my @parts_graded;
 2790:     my %newrecord  = ();
 2791:     my ($pts,$wgt) = ('','');
 2792:     my %aggregate = ();
 2793:     my $aggregateflag = 0;
 2794:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2795:     foreach my $new_part (@parts) {
 2796: 	#collaborator ($submi may vary for different parts
 2797: 	if ($submitter && $new_part ne $part) { next; }
 2798: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2799: 	if ($dropMenu eq 'excused') {
 2800: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2801: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2802: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2803: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2804: 		}
 2805: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2806: 	    }
 2807: 	} elsif ($dropMenu eq 'reset status'
 2808: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2809: 	    foreach my $key (keys(%record)) {
 2810: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2811: 	    }
 2812: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2813: 		"$env{'user.name'}:$env{'user.domain'}";
 2814:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2815: 
 2816:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2817: 					       [$new_part]);
 2818:             my $aggtries =$totaltries;
 2819:             if ($last_resets{$new_part}) {
 2820:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2821: 					   $new_part);
 2822:             }
 2823: 
 2824:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2825:             if ($aggtries > 0) {
 2826:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2827:                 $aggregateflag = 1;
 2828:             }
 2829: 	} elsif ($dropMenu eq '') {
 2830: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2831: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2832: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2833: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2834: 		next;
 2835: 	    }
 2836: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2837: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2838: 	    my $partial= $pts/$wgt;
 2839: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2840: 		#do not update score for part if not changed.
 2841:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2842: 		next;
 2843: 	    } else {
 2844: 	        push(@parts_graded,$new_part);
 2845: 	    }
 2846: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2847: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2848: 	    }
 2849: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2850: 	    if ($partial == 0) {
 2851: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2852: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2853: 		}
 2854: 	    } else {
 2855: 		if ($record{$reckey} ne 'correct_by_override') {
 2856: 		    $newrecord{$reckey} = 'correct_by_override';
 2857: 		}
 2858: 	    }	    
 2859: 	    if ($submitter && 
 2860: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2861: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2862: 	    }
 2863: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2864: 		"$env{'user.name'}:$env{'user.domain'}";
 2865: 	}
 2866: 	# unless problem has been graded, set flag to version the submitted files
 2867: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2868: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2869: 	        $dropMenu eq 'reset status')
 2870: 	   {
 2871: 	    push(@version_parts,$new_part);
 2872: 	}
 2873:     }
 2874:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2875:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2876: 
 2877:     if (%newrecord) {
 2878:         if (@version_parts) {
 2879:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2880:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2881: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2882: 	    foreach my $new_part (@version_parts) {
 2883: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2884: 				$new_part,\%newrecord);
 2885: 	    }
 2886:         }
 2887: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2888: 				$env{'request.course.id'},$domain,$stuname);
 2889: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2890: 				     $cdom,$cnum,$domain,$stuname);
 2891:     }
 2892:     if ($aggregateflag) {
 2893:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2894: 			      $cdom,$cnum);
 2895:     }
 2896:     return ('',$pts,$wgt);
 2897: }
 2898: 
 2899: sub check_and_remove_from_queue {
 2900:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2901:     my @ungraded_parts;
 2902:     foreach my $part (@{$parts}) {
 2903: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2904: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2905: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2906: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2907: 		) {
 2908: 	    push(@ungraded_parts, $part);
 2909: 	}
 2910:     }
 2911:     if ( !@ungraded_parts ) {
 2912: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2913: 					       $cnum,$domain,$stuname);
 2914:     }
 2915: }
 2916: 
 2917: sub handback_files {
 2918:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2919:     my $portfolio_root = '/userfiles/portfolio';
 2920:     my $res_error;
 2921:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2922:     if ($res_error) {
 2923:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2924:         return;
 2925:     }
 2926:     my @part_response_id = &flatten_responseType($responseType);
 2927:     foreach my $part_response_id (@part_response_id) {
 2928:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2929: 	my $part_resp = join('_',@{ $part_response_id });
 2930:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2931:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2932:                 my $file_counter = 1;
 2933: 		my $file_msg;
 2934:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2935:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2936:                     my ($directory,$answer_file) = 
 2937:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2938:                     my ($answer_name,$answer_ver,$answer_ext) =
 2939: 		        &file_name_version_ext($answer_file);
 2940: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2941:                     my $getpropath = 1;
 2942: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2943: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2944:                     # fix file name
 2945:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2946:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2947:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2948:             	                                $save_file_name);
 2949:                     if ($result !~ m|^/uploaded/|) {
 2950:                         $request->print('<br /><span class="LC_error">'.
 2951:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2952:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2953:                                         '</span>');
 2954:                     } else {
 2955:                         # mark the file as read only
 2956:                         my @files = ($save_file_name);
 2957:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2958:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2959: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2960: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2961: 			}
 2962:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2963: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2964: 
 2965:                     }
 2966:                     $request->print("<br />".$fname." will be the uploaded file name");
 2967:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2968:                     $file_counter++;
 2969:                 }
 2970: 		my $subject = "File Handed Back by Instructor ";
 2971: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2972: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2973: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2974: 		$message .= " and can be found in your portfolio space.";
 2975: 		my ($feedurl,$showsymb) = 
 2976: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2977:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2978: 		my $msgstatus = 
 2979:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2980: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2981:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2982:             }
 2983:         }
 2984:     return;
 2985: }
 2986: 
 2987: sub get_feedurl_and_symb {
 2988:     my ($symb,$uname,$udom) = @_;
 2989:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2990:     $url = &Apache::lonnet::clutter($url);
 2991:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2992: 					$symb,$udom,$uname);
 2993:     if ($encrypturl =~ /^yes$/i) {
 2994: 	&Apache::lonenc::encrypted(\$url,1);
 2995: 	&Apache::lonenc::encrypted(\$symb,1);
 2996:     }
 2997:     return ($url,$symb);
 2998: }
 2999: 
 3000: sub get_submitted_files {
 3001:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3002:     my @files;
 3003:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3004:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3005:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3006:     	    push(@files,$file_url.$file);
 3007:         }
 3008:     }
 3009:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3010:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3011:     }
 3012:     return (\@files);
 3013: }
 3014: 
 3015: # ----------- Provides number of tries since last reset.
 3016: sub get_num_tries {
 3017:     my ($record,$last_reset,$part) = @_;
 3018:     my $timestamp = '';
 3019:     my $num_tries = 0;
 3020:     if ($$record{'version'}) {
 3021:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3022:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3023:                 $timestamp = $$record{$version.':timestamp'};
 3024:                 if ($timestamp > $last_reset) {
 3025:                     $num_tries ++;
 3026:                 } else {
 3027:                     last;
 3028:                 }
 3029:             }
 3030:         }
 3031:     }
 3032:     return $num_tries;
 3033: }
 3034: 
 3035: # ----------- Determine decrements required in aggregate totals 
 3036: sub decrement_aggs {
 3037:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3038:     my %decrement = (
 3039:                         attempts => 0,
 3040:                         users => 0,
 3041:                         correct => 0
 3042:                     );
 3043:     $decrement{'attempts'} = $aggtries;
 3044:     if ($solvedstatus =~ /^correct/) {
 3045:         $decrement{'correct'} = 1;
 3046:     }
 3047:     if ($aggtries == $totaltries) {
 3048:         $decrement{'users'} = 1;
 3049:     }
 3050:     foreach my $type (keys(%decrement)) {
 3051:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3052:     }
 3053:     return;
 3054: }
 3055: 
 3056: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3057: sub get_last_resets {
 3058:     my ($symb,$courseid,$partids) =@_;
 3059:     my %last_resets;
 3060:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3061:     my $cname = $env{'course.'.$courseid.'.num'};
 3062:     my @keys;
 3063:     foreach my $part (@{$partids}) {
 3064: 	push(@keys,"$symb\0$part\0resettime");
 3065:     }
 3066:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3067: 				     $cdom,$cname);
 3068:     foreach my $part (@{$partids}) {
 3069: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3070:     }
 3071:     return %last_resets;
 3072: }
 3073: 
 3074: # ----------- Handles creating versions for portfolio files as answers
 3075: sub version_portfiles {
 3076:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3077:     my $version_parts = join('|',@$v_flag);
 3078:     my @returned_keys;
 3079:     my $parts = join('|', @$parts_graded);
 3080:     my $portfolio_root = '/userfiles/portfolio';
 3081:     foreach my $key (keys(%$record)) {
 3082:         my $new_portfiles;
 3083:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3084:             my @versioned_portfiles;
 3085:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3086:             foreach my $file (@portfiles) {
 3087:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3088:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3089: 		my ($answer_name,$answer_ver,$answer_ext) =
 3090: 		    &file_name_version_ext($answer_file);
 3091:                 my $getpropath = 1;    
 3092:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3093:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3094:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3095:                 if ($new_answer ne 'problem getting file') {
 3096:                     push(@versioned_portfiles, $directory.$new_answer);
 3097:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3098:                         [$directory.$new_answer],
 3099:                         [$symb,$env{'request.course.id'},'graded']);
 3100:                 }
 3101:             }
 3102:             $$record{$key} = join(',',@versioned_portfiles);
 3103:             push(@returned_keys,$key);
 3104:         }
 3105:     } 
 3106:     return (@returned_keys);   
 3107: }
 3108: 
 3109: sub get_next_version {
 3110:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3111:     my $version;
 3112:     foreach my $row (@$dir_list) {
 3113:         my ($file) = split(/\&/,$row,2);
 3114:         my ($file_name,$file_version,$file_ext) =
 3115: 	    &file_name_version_ext($file);
 3116:         if (($file_name eq $answer_name) && 
 3117: 	    ($file_ext eq $answer_ext)) {
 3118:                 # gets here if filename and extension match, regardless of version
 3119:                 if ($file_version ne '') {
 3120:                 # a versioned file is found  so save it for later
 3121:                 if ($file_version > $version) {
 3122: 		    $version = $file_version;
 3123: 	        }
 3124:             }
 3125:         }
 3126:     } 
 3127:     $version ++;
 3128:     return($version);
 3129: }
 3130: 
 3131: sub version_selected_portfile {
 3132:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3133:     my ($answer_name,$answer_ver,$answer_ext) =
 3134:         &file_name_version_ext($file_name);
 3135:     my $new_answer;
 3136:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3137:     if($env{'form.copy'} eq '-1') {
 3138:         $new_answer = 'problem getting file';
 3139:     } else {
 3140:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3141:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3142:                             $stu_name,$domain,'copy',
 3143: 		        '/portfolio'.$directory.$new_answer);
 3144:     }    
 3145:     return ($new_answer);
 3146: }
 3147: 
 3148: sub file_name_version_ext {
 3149:     my ($file)=@_;
 3150:     my @file_parts = split(/\./, $file);
 3151:     my ($name,$version,$ext);
 3152:     if (@file_parts > 1) {
 3153: 	$ext=pop(@file_parts);
 3154: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3155: 	    $version=pop(@file_parts);
 3156: 	}
 3157: 	$name=join('.',@file_parts);
 3158:     } else {
 3159: 	$name=join('.',@file_parts);
 3160:     }
 3161:     return($name,$version,$ext);
 3162: }
 3163: 
 3164: #--------------------------------------------------------------------------------------
 3165: #
 3166: #-------------------------- Next few routines handles grading by section or whole class
 3167: #
 3168: #--- Javascript to handle grading by section or whole class
 3169: sub viewgrades_js {
 3170:     my ($request) = shift;
 3171: 
 3172:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3173:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3174:    function writePoint(partid,weight,point) {
 3175: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3176: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3177: 	if (point == "textval") {
 3178: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3179: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3180: 		alert("$alertmsg"+parseFloat(point));
 3181: 		var resetbox = false;
 3182: 		for (var i=0; i<radioButton.length; i++) {
 3183: 		    if (radioButton[i].checked) {
 3184: 			textbox.value = i;
 3185: 			resetbox = true;
 3186: 		    }
 3187: 		}
 3188: 		if (!resetbox) {
 3189: 		    textbox.value = "";
 3190: 		}
 3191: 		return;
 3192: 	    }
 3193: 	    if (parseFloat(point) > parseFloat(weight)) {
 3194: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3195: 				   ") greater than the weight for the part. Accept?");
 3196: 		if (resp == false) {
 3197: 		    textbox.value = "";
 3198: 		    return;
 3199: 		}
 3200: 	    }
 3201: 	    for (var i=0; i<radioButton.length; i++) {
 3202: 		radioButton[i].checked=false;
 3203: 		if (parseFloat(point) == i) {
 3204: 		    radioButton[i].checked=true;
 3205: 		}
 3206: 	    }
 3207: 
 3208: 	} else {
 3209: 	    textbox.value = parseFloat(point);
 3210: 	}
 3211: 	for (i=0;i<document.classgrade.total.value;i++) {
 3212: 	    var user = document.classgrade["ctr"+i].value;
 3213: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3214: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3215: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3216: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3217: 	    if (saveval != "correct") {
 3218: 		scorename.value = point;
 3219: 		if (selname[0].selected != true) {
 3220: 		    selname[0].selected = true;
 3221: 		}
 3222: 	    }
 3223: 	}
 3224: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3225:     }
 3226: 
 3227:     function writeRadText(partid,weight) {
 3228: 	var selval   = document.classgrade["SELVAL_"+partid];
 3229: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3230:         var override = document.classgrade["FORCE_"+partid].checked;
 3231: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3232: 	if (selval[1].selected || selval[2].selected) {
 3233: 	    for (var i=0; i<radioButton.length; i++) {
 3234: 		radioButton[i].checked=false;
 3235: 
 3236: 	    }
 3237: 	    textbox.value = "";
 3238: 
 3239: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3240: 		var user = document.classgrade["ctr"+i].value;
 3241: 		user = user.replace(new RegExp(':', 'g'),"_");
 3242: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3243: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3244: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3245: 		if ((saveval != "correct") || override) {
 3246: 		    scorename.value = "";
 3247: 		    if (selval[1].selected) {
 3248: 			selname[1].selected = true;
 3249: 		    } else {
 3250: 			selname[2].selected = true;
 3251: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3252: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3253: 		    }
 3254: 		}
 3255: 	    }
 3256: 	} else {
 3257: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3258: 		var user = document.classgrade["ctr"+i].value;
 3259: 		user = user.replace(new RegExp(':', 'g'),"_");
 3260: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3261: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3262: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3263: 		if ((saveval != "correct") || override) {
 3264: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3265: 		    selname[0].selected = true;
 3266: 		}
 3267: 	    }
 3268: 	}	    
 3269:     }
 3270: 
 3271:     function changeSelect(partid,user) {
 3272: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3273: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3274: 	var point  = textbox.value;
 3275: 	var weight = document.classgrade["weight_"+partid].value;
 3276: 
 3277: 	if (isNaN(point) || parseFloat(point) < 0) {
 3278: 	    alert("$alertmsg"+parseFloat(point));
 3279: 	    textbox.value = "";
 3280: 	    return;
 3281: 	}
 3282: 	if (parseFloat(point) > parseFloat(weight)) {
 3283: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3284: 			       ") greater than the weight of the part. Accept?");
 3285: 	    if (resp == false) {
 3286: 		textbox.value = "";
 3287: 		return;
 3288: 	    }
 3289: 	}
 3290: 	selval[0].selected = true;
 3291:     }
 3292: 
 3293:     function changeOneScore(partid,user) {
 3294: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3295: 	if (selval[1].selected || selval[2].selected) {
 3296: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3297: 	    if (selval[2].selected) {
 3298: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3299: 	    }
 3300:         }
 3301:     }
 3302: 
 3303:     function resetEntry(numpart) {
 3304: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3305: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3306: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3307: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3308: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3309: 	    for (var i=0; i<radioButton.length; i++) {
 3310: 		radioButton[i].checked=false;
 3311: 
 3312: 	    }
 3313: 	    textbox.value = "";
 3314: 	    selval[0].selected = true;
 3315: 
 3316: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3317: 		var user = document.classgrade["ctr"+i].value;
 3318: 		user = user.replace(new RegExp(':', 'g'),"_");
 3319: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3320: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3321: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3322: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3323: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3324: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3325: 		if (saveselval == "excused") {
 3326: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3327: 		} else {
 3328: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3329: 		}
 3330: 	    }
 3331: 	}
 3332:     }
 3333: 
 3334: VIEWJAVASCRIPT
 3335: }
 3336: 
 3337: #--- show scores for a section or whole class w/ option to change/update a score
 3338: sub viewgrades {
 3339:     my ($request) = shift;
 3340:     &viewgrades_js($request);
 3341: 
 3342:     my ($symb) = &get_symb($request);
 3343:     #need to make sure we have the correct data for later EXT calls, 
 3344:     #thus invalidate the cache
 3345:     &Apache::lonnet::devalidatecourseresdata(
 3346:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3347:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3348:     &Apache::lonnet::clear_EXT_cache_status();
 3349: 
 3350:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3351:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3352: 
 3353:     #view individual student submission form - called using Javascript viewOneStudent
 3354:     $result.=&jscriptNform($symb);
 3355: 
 3356:     #beginning of class grading form
 3357:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3358:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3359: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3360: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3361: 	&build_section_inputs().
 3362: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3363: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3364: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3365: 
 3366:     my ($common_header,$specific_header);
 3367:     if ($env{'form.section'} eq 'all') {
 3368: 	$common_header = &mt('Assign Common Grade to Class');
 3369:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3370:     } elsif ($env{'form.section'} eq 'none') {
 3371:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3372: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3373:     } else {
 3374:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3375:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3376: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3377:     }
 3378:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3379:     #radio buttons/text box for assigning points for a section or class.
 3380:     #handles different parts of a problem
 3381:     my $res_error;
 3382:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3383:     if ($res_error) {
 3384:         return &navmap_errormsg();
 3385:     }
 3386:     my %weight = ();
 3387:     my $ctsparts = 0;
 3388:     my %seen = ();
 3389:     my @part_response_id = &flatten_responseType($responseType);
 3390:     foreach my $part_response_id (@part_response_id) {
 3391:     	my ($partid,$respid) = @{ $part_response_id };
 3392: 	my $part_resp = join('_',@{ $part_response_id });
 3393: 	next if $seen{$partid};
 3394: 	$seen{$partid}++;
 3395: 	my $handgrade=$$handgrade{$part_resp};
 3396: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3397: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3398: 
 3399: 	my $display_part=&get_display_part($partid,$symb);
 3400: 	my $radio.='<table border="0"><tr>';  
 3401: 	my $ctr = 0;
 3402: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3403: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3404: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3405: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3406: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3407: 	    $ctr++;
 3408: 	}
 3409: 	$radio.='</tr></table>';
 3410: 	my $line = '<input type="text" name="TEXTVAL_'.
 3411: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3412: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3413: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3414: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3415: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3416: 		$weight{$partid}.')"> '.
 3417: 	    '<option selected="selected"> </option>'.
 3418: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3419: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3420: 	    '</select></td>'.
 3421:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3422: 	$line.='<input type="hidden" name="partid_'.
 3423: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3424: 	$line.='<input type="hidden" name="weight_'.
 3425: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3426: 
 3427: 	$result.=
 3428: 	    &Apache::loncommon::start_data_table_row()."\n".
 3429: 	    '<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>'.
 3430: 	    &Apache::loncommon::end_data_table_row()."\n";
 3431: 	$ctsparts++;
 3432:     }
 3433:     $result.=&Apache::loncommon::end_data_table()."\n".
 3434: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3435:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3436: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3437: 
 3438:     #table listing all the students in a section/class
 3439:     #header of table
 3440:     $result.= '<h3>'.$specific_header.'</h3>'.
 3441:               &Apache::loncommon::start_data_table().
 3442: 	      &Apache::loncommon::start_data_table_header_row().
 3443: 	      '<th>'.&mt('No.').'</th>'.
 3444: 	      '<th>'.&nameUserString('header')."</th>\n";
 3445:     my $partserror;
 3446:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3447:     if ($partserror) {
 3448:         return &navmap_errormsg();
 3449:     }
 3450:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3451:     my @partids = ();
 3452:     foreach my $part (@parts) {
 3453: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3454:         my $narrowtext = &mt('Tries');
 3455: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3456: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3457: 	my ($partid) = &split_part_type($part);
 3458:         push(@partids,$partid);
 3459: 	my $display_part=&get_display_part($partid,$symb);
 3460: 	if ($display =~ /^Partial Credit Factor/) {
 3461: 	    $result.='<th>'.
 3462: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3463: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3464: 	    next;
 3465: 	    
 3466: 	} else {
 3467: 	    if ($display =~ /Problem Status/) {
 3468: 		my $grade_status_mt = &mt('Grade Status');
 3469: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3470: 	    }
 3471: 	    my $part_mt = &mt('Part:');
 3472: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3473: 	}
 3474: 
 3475: 	$result.='<th>'.$display.'</th>'."\n";
 3476:     }
 3477:     $result.=&Apache::loncommon::end_data_table_header_row();
 3478: 
 3479:     my %last_resets = 
 3480: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3481: 
 3482:     #get info for each student
 3483:     #list all the students - with points and grade status
 3484:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3485:     my $ctr = 0;
 3486:     foreach (sort 
 3487: 	     {
 3488: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3489: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3490: 		 }
 3491: 		 return $a cmp $b;
 3492: 	     } (keys(%$fullname))) {
 3493: 	$ctr++;
 3494: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3495: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3496:     }
 3497:     $result.=&Apache::loncommon::end_data_table();
 3498:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3499:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3500: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3501:     if (scalar(%$fullname) eq 0) {
 3502: 	my $colspan=3+scalar(@parts);
 3503: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3504:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3505: 	$result='<span class="LC_warning">'.
 3506: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3507: 	        $section_display, $stu_status).
 3508: 	    '</span>';
 3509:     }
 3510:     $result.=&show_grading_menu_form($symb);
 3511:     return $result;
 3512: }
 3513: 
 3514: #--- call by previous routine to display each student
 3515: sub viewstudentgrade {
 3516:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3517:     my ($uname,$udom) = split(/:/,$student);
 3518:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3519:     my %aggregates = (); 
 3520:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3521: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3522: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3523: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3524: 	'\');" target="_self">'.$fullname.'</a> '.
 3525: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3526:     $student=~s/:/_/; # colon doen't work in javascript for names
 3527:     foreach my $apart (@$parts) {
 3528: 	my ($part,$type) = &split_part_type($apart);
 3529: 	my $score=$record{"resource.$part.$type"};
 3530:         $result.='<td align="center">';
 3531:         my ($aggtries,$totaltries);
 3532:         unless (exists($aggregates{$part})) {
 3533: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3534: 
 3535: 	    $aggtries = $totaltries;
 3536:             if ($$last_resets{$part}) {  
 3537:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3538: 					   $part);
 3539:             }
 3540:             $result.='<input type="hidden" name="'.
 3541:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3542:             $result.='<input type="hidden" name="'.
 3543:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3544:             $aggregates{$part} = 1;
 3545:         }
 3546: 	if ($type eq 'awarded') {
 3547: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3548: 	    $result.='<input type="hidden" name="'.
 3549: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3550: 	    $result.='<input type="text" name="'.
 3551: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3552:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3553: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3554: 	} elsif ($type eq 'solved') {
 3555: 	    my ($status,$foo)=split(/_/,$score,2);
 3556: 	    $status = 'nothing' if ($status eq '');
 3557: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3558: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3559: 	    $result.='&nbsp;<select name="'.
 3560: 		'GD_'.$student.'_'.$part.'_solved" '.
 3561:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3562: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3563: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3564: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3565: 	    $result.="</select>&nbsp;</td>\n";
 3566: 	} else {
 3567: 	    $result.='<input type="hidden" name="'.
 3568: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3569: 		    "\n";
 3570: 	    $result.='<input type="text" name="'.
 3571: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3572: 		'value="'.$score.'" size="4" /></td>'."\n";
 3573: 	}
 3574:     }
 3575:     $result.=&Apache::loncommon::end_data_table_row();
 3576:     return $result;
 3577: }
 3578: 
 3579: #--- change scores for all the students in a section/class
 3580: #    record does not get update if unchanged
 3581: sub editgrades {
 3582:     my ($request) = @_;
 3583: 
 3584:     my $symb=&get_symb($request);
 3585:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3586:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3587:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3588:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3589: 
 3590:     my $result= &Apache::loncommon::start_data_table().
 3591: 	&Apache::loncommon::start_data_table_header_row().
 3592: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3593: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3594:     my %scoreptr = (
 3595: 		    'correct'  =>'correct_by_override',
 3596: 		    'incorrect'=>'incorrect_by_override',
 3597: 		    'excused'  =>'excused',
 3598: 		    'ungraded' =>'ungraded_attempted',
 3599:                     'credited' =>'credit_attempted',
 3600: 		    'nothing'  => '',
 3601: 		    );
 3602:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3603: 
 3604:     my (@partid);
 3605:     my %weight = ();
 3606:     my %columns = ();
 3607:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3608: 
 3609:     my $partserror;
 3610:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3611:     if ($partserror) {
 3612:         return &navmap_errormsg();
 3613:     }
 3614:     my $header;
 3615:     while ($ctr < $env{'form.totalparts'}) {
 3616: 	my $partid = $env{'form.partid_'.$ctr};
 3617: 	push(@partid,$partid);
 3618: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3619: 	$ctr++;
 3620:     }
 3621:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3622:     foreach my $partid (@partid) {
 3623: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3624: 	    '<th align="center">'.&mt('New Score').'</th>';
 3625: 	$columns{$partid}=2;
 3626: 	foreach my $stores (@parts) {
 3627: 	    my ($part,$type) = &split_part_type($stores);
 3628: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3629: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3630: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3631: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3632:             my $narrowtext = &mt('Tries');
 3633: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3634: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3635: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3636: 	    $columns{$partid}+=2;
 3637: 	}
 3638:     }
 3639:     foreach my $partid (@partid) {
 3640: 	my $display_part=&get_display_part($partid,$symb);
 3641: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3642: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3643: 	    '</th>';
 3644: 
 3645:     }
 3646:     $result .= &Apache::loncommon::end_data_table_header_row().
 3647: 	&Apache::loncommon::start_data_table_header_row().
 3648: 	$header.
 3649: 	&Apache::loncommon::end_data_table_header_row();
 3650:     my @noupdate;
 3651:     my ($updateCtr,$noupdateCtr) = (1,1);
 3652:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3653: 	my $line;
 3654: 	my $user = $env{'form.ctr'.$i};
 3655: 	my ($uname,$udom)=split(/:/,$user);
 3656: 	my %newrecord;
 3657: 	my $updateflag = 0;
 3658: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3659: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3660: 	if (!&canmodify($usec)) {
 3661: 	    my $numcols=scalar(@partid)*4+2;
 3662: 	    push(@noupdate,
 3663: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3664: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3665: 	    next;
 3666: 	}
 3667:         my %aggregate = ();
 3668:         my $aggregateflag = 0;
 3669: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3670: 	foreach (@partid) {
 3671: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3672: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3673: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3674: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3675: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3676: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3677: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3678: 	    my $score;
 3679: 	    if ($partial eq '') {
 3680: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3681: 	    } elsif ($partial > 0) {
 3682: 		$score = 'correct_by_override';
 3683: 	    } elsif ($partial == 0) {
 3684: 		$score = 'incorrect_by_override';
 3685: 	    }
 3686: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3687: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3688: 
 3689: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3690: 		"$env{'user.name'}:$env{'user.domain'}";
 3691: 	    if ($dropMenu eq 'reset status' &&
 3692: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3693: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3694: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3695: 		$newrecord{'resource.'.$_.'.award'} = '';
 3696: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3697: 		$updateflag = 1;
 3698:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3699:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3700:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3701:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3702:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3703:                     $aggregateflag = 1;
 3704:                 }
 3705: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3706: 		$updateflag = 1;
 3707: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3708: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3709: 		$rec_update++;
 3710: 	    }
 3711: 
 3712: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3713: 		'<td align="center">'.$awarded.
 3714: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3715: 
 3716: 
 3717: 	    my $partid=$_;
 3718: 	    foreach my $stores (@parts) {
 3719: 		my ($part,$type) = &split_part_type($stores);
 3720: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3721: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3722: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3723: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3724: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3725: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3726: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3727: 		    $updateflag=1;
 3728: 		}
 3729: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3730: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3731: 	    }
 3732: 	}
 3733: 	$line.="\n";
 3734: 
 3735: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3736: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3737: 
 3738: 	if ($updateflag) {
 3739: 	    $count++;
 3740: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3741: 				    $udom,$uname);
 3742: 
 3743: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3744: 					      $cnum,$udom,$uname)) {
 3745: 		# need to figure out if should be in queue.
 3746: 		my %record =  
 3747: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3748: 					     $udom,$uname);
 3749: 		my $all_graded = 1;
 3750: 		my $none_graded = 1;
 3751: 		foreach my $part (@parts) {
 3752: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3753: 			$all_graded = 0;
 3754: 		    } else {
 3755: 			$none_graded = 0;
 3756: 		    }
 3757: 		}
 3758: 
 3759: 		if ($all_graded || $none_graded) {
 3760: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3761: 							   $symb,$cdom,$cnum,
 3762: 							   $udom,$uname);
 3763: 		}
 3764: 	    }
 3765: 
 3766: 	    $result.=&Apache::loncommon::start_data_table_row().
 3767: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3768: 		&Apache::loncommon::end_data_table_row();
 3769: 	    $updateCtr++;
 3770: 	} else {
 3771: 	    push(@noupdate,
 3772: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3773: 	    $noupdateCtr++;
 3774: 	}
 3775:         if ($aggregateflag) {
 3776:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3777: 				  $cdom,$cnum);
 3778:         }
 3779:     }
 3780:     if (@noupdate) {
 3781: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3782: 	my $numcols=scalar(@partid)*4+2;
 3783: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3784: 	    '<td align="center" colspan="'.$numcols.'">'.
 3785: 	    &mt('No Changes Occurred For the Students Below').
 3786: 	    '</td>'.
 3787: 	    &Apache::loncommon::end_data_table_row();
 3788: 	foreach my $line (@noupdate) {
 3789: 	    $result.=
 3790: 		&Apache::loncommon::start_data_table_row().
 3791: 		$line.
 3792: 		&Apache::loncommon::end_data_table_row();
 3793: 	}
 3794:     }
 3795:     $result .= &Apache::loncommon::end_data_table().
 3796: 	&show_grading_menu_form($symb);
 3797:     my $msg = '<p><b>'.
 3798: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3799: 	    $rec_update,$count).'</b><br />'.
 3800: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3801: 	'</b></p>';
 3802:     return $title.$msg.$result;
 3803: }
 3804: 
 3805: sub split_part_type {
 3806:     my ($partstr) = @_;
 3807:     my ($temp,@allparts)=split(/_/,$partstr);
 3808:     my $type=pop(@allparts);
 3809:     my $part=join('_',@allparts);
 3810:     return ($part,$type);
 3811: }
 3812: 
 3813: #------------- end of section for handling grading by section/class ---------
 3814: #
 3815: #----------------------------------------------------------------------------
 3816: 
 3817: 
 3818: #----------------------------------------------------------------------------
 3819: #
 3820: #-------------------------- Next few routines handles grading by csv upload
 3821: #
 3822: #--- Javascript to handle csv upload
 3823: sub csvupload_javascript_reverse_associate {
 3824:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3825:     my $error2=&mt('You need to specify at least one grading field');
 3826:   return(<<ENDPICK);
 3827:   function verify(vf) {
 3828:     var foundsomething=0;
 3829:     var founduname=0;
 3830:     var foundID=0;
 3831:     for (i=0;i<=vf.nfields.value;i++) {
 3832:       tw=eval('vf.f'+i+'.selectedIndex');
 3833:       if (i==0 && tw!=0) { foundID=1; }
 3834:       if (i==1 && tw!=0) { founduname=1; }
 3835:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3836:     }
 3837:     if (founduname==0 && foundID==0) {
 3838: 	alert('$error1');
 3839: 	return;
 3840:     }
 3841:     if (foundsomething==0) {
 3842: 	alert('$error2');
 3843: 	return;
 3844:     }
 3845:     vf.submit();
 3846:   }
 3847:   function flip(vf,tf) {
 3848:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3849:     var i;
 3850:     for (i=0;i<=vf.nfields.value;i++) {
 3851:       //can not pick the same destination field for both name and domain
 3852:       if (((i ==0)||(i ==1)) && 
 3853:           ((tf==0)||(tf==1)) && 
 3854:           (i!=tf) &&
 3855:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3856:         eval('vf.f'+i+'.selectedIndex=0;')
 3857:       }
 3858:     }
 3859:   }
 3860: ENDPICK
 3861: }
 3862: 
 3863: sub csvupload_javascript_forward_associate {
 3864:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3865:     my $error2=&mt('You need to specify at least one grading field');
 3866:   return(<<ENDPICK);
 3867:   function verify(vf) {
 3868:     var foundsomething=0;
 3869:     var founduname=0;
 3870:     var foundID=0;
 3871:     for (i=0;i<=vf.nfields.value;i++) {
 3872:       tw=eval('vf.f'+i+'.selectedIndex');
 3873:       if (tw==1) { foundID=1; }
 3874:       if (tw==2) { founduname=1; }
 3875:       if (tw>3) { foundsomething=1; }
 3876:     }
 3877:     if (founduname==0 && foundID==0) {
 3878: 	alert('$error1');
 3879: 	return;
 3880:     }
 3881:     if (foundsomething==0) {
 3882: 	alert('$error2');
 3883: 	return;
 3884:     }
 3885:     vf.submit();
 3886:   }
 3887:   function flip(vf,tf) {
 3888:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3889:     var i;
 3890:     //can not pick the same destination field twice
 3891:     for (i=0;i<=vf.nfields.value;i++) {
 3892:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3893:         eval('vf.f'+i+'.selectedIndex=0;')
 3894:       }
 3895:     }
 3896:   }
 3897: ENDPICK
 3898: }
 3899: 
 3900: sub csvuploadmap_header {
 3901:     my ($request,$symb,$datatoken,$distotal)= @_;
 3902:     my $javascript;
 3903:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3904: 	$javascript=&csvupload_javascript_reverse_associate();
 3905:     } else {
 3906: 	$javascript=&csvupload_javascript_forward_associate();
 3907:     }
 3908: 
 3909: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3910:     my $result='';
 3911:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3912:     my $ignore=&mt('Ignore First Line');
 3913:     $symb = &Apache::lonenc::check_encrypt($symb);
 3914:     $request->print(<<ENDPICK);
 3915: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3916: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3917: $result
 3918: <hr />
 3919: <h3>Identify fields</h3>
 3920: Total number of records found in file: $distotal <hr />
 3921: Enter as many fields as you can. The system will inform you and bring you back
 3922: to this page if the data selected is insufficient to run your class.<hr />
 3923: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3924: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3925: <input type="hidden" name="associate"  value="" />
 3926: <input type="hidden" name="phase"      value="three" />
 3927: <input type="hidden" name="datatoken"  value="$datatoken" />
 3928: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3929: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3930: <input type="hidden" name="upfile_associate" 
 3931:                                        value="$env{'form.upfile_associate'}" />
 3932: <input type="hidden" name="symb"       value="$symb" />
 3933: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3934: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3935: <input type="hidden" name="command"    value="csvuploadoptions" />
 3936: <hr />
 3937: ENDPICK
 3938:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 3939:     return '';
 3940: 
 3941: }
 3942: 
 3943: sub csvupload_fields {
 3944:     my ($symb,$errorref) = @_;
 3945:     my (@parts) = &getpartlist($symb,$errorref);
 3946:     if (ref($errorref)) {
 3947:         if ($$errorref) {
 3948:             return;
 3949:         }
 3950:     }
 3951: 
 3952:     my @fields=(['ID','Student/Employee ID'],
 3953: 		['username','Student Username'],
 3954: 		['domain','Student Domain']);
 3955:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3956:     foreach my $part (sort(@parts)) {
 3957: 	my @datum;
 3958: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3959: 	my $name=$part;
 3960: 	if  (!$display) { $display = $name; }
 3961: 	@datum=($name,$display);
 3962: 	if ($name=~/^stores_(.*)_awarded/) {
 3963: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3964: 	}
 3965: 	push(@fields,\@datum);
 3966:     }
 3967:     return (@fields);
 3968: }
 3969: 
 3970: sub csvuploadmap_footer {
 3971:     my ($request,$i,$keyfields) =@_;
 3972:     $request->print(<<ENDPICK);
 3973: </table>
 3974: <input type="hidden" name="nfields" value="$i" />
 3975: <input type="hidden" name="keyfields" value="$keyfields" />
 3976: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3977: </form>
 3978: ENDPICK
 3979: }
 3980: 
 3981: sub checkforfile_js {
 3982:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3983:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 3984:     function checkUpload(formname) {
 3985: 	if (formname.upfile.value == "") {
 3986: 	    alert("$alertmsg");
 3987: 	    return false;
 3988: 	}
 3989: 	formname.submit();
 3990:     }
 3991: CSVFORMJS
 3992:     return $result;
 3993: }
 3994: 
 3995: sub upcsvScores_form {
 3996:     my ($request) = shift;
 3997:     my ($symb)=&get_symb($request);
 3998:     if (!$symb) {return '';}
 3999:     my $result=&checkforfile_js();
 4000:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4001: #    my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4002: #    $result.=$table;
 4003:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4004:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4005:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4006: 	'</b></td></tr>'."\n";
 4007:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 4008:     my $upload=&mt("Upload Scores");
 4009:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4010:     my $ignore=&mt('Ignore First Line');
 4011:     $symb = &Apache::lonenc::check_encrypt($symb);
 4012:     $result.=<<ENDUPFORM;
 4013: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4014: <input type="hidden" name="symb" value="$symb" />
 4015: <input type="hidden" name="command" value="csvuploadmap" />
 4016: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4017: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4018: $upfile_select
 4019: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4020: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4021: </form>
 4022: ENDUPFORM
 4023:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4024:                            &mt("How do I create a CSV file from a spreadsheet"))
 4025:     .'</td></tr></table>'."\n";
 4026:     $result.='</td></tr></table><br /><br />'."\n";
 4027:     $result.=&show_grading_menu_form($symb);
 4028:     return $result;
 4029: }
 4030: 
 4031: 
 4032: sub csvuploadmap {
 4033:     my ($request)= @_;
 4034:     my ($symb)=&get_symb($request);
 4035:     if (!$symb) {return '';}
 4036: 
 4037:     my $datatoken;
 4038:     if (!$env{'form.datatoken'}) {
 4039: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4040:     } else {
 4041: 	$datatoken=$env{'form.datatoken'};
 4042: 	&Apache::loncommon::load_tmp_file($request);
 4043:     }
 4044:     my @records=&Apache::loncommon::upfile_record_sep();
 4045:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4046:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4047:     my ($i,$keyfields);
 4048:     if (@records) {
 4049:         my $fieldserror;
 4050: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4051:         if ($fieldserror) {
 4052:             $request->print(&navmap_errormsg());
 4053:             return;
 4054:         }
 4055: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4056: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4057: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4058: 							  \@fields);
 4059: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4060: 	    chop($keyfields);
 4061: 	} else {
 4062: 	    unshift(@fields,['none','']);
 4063: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4064: 							    \@fields);
 4065:             foreach my $rec (@records) {
 4066:                 my %temp = &Apache::loncommon::record_sep($rec);
 4067:                 if (%temp) {
 4068:                     $keyfields=join(',',sort(keys(%temp)));
 4069:                     last;
 4070:                 }
 4071:             }
 4072: 	}
 4073:     }
 4074:     &csvuploadmap_footer($request,$i,$keyfields);
 4075:     $request->print(&show_grading_menu_form($symb));
 4076: 
 4077:     return '';
 4078: }
 4079: 
 4080: sub csvuploadoptions {
 4081:     my ($request)= @_;
 4082:     my ($symb)=&get_symb($request);
 4083:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4084:     my $ignore=&mt('Ignore First Line');
 4085:     $request->print(<<ENDPICK);
 4086: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4087: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4088: <input type="hidden" name="command"    value="csvuploadassign" />
 4089: <!--
 4090: <p>
 4091: <label>
 4092:    <input type="checkbox" name="show_full_results" />
 4093:    Show a table of all changes
 4094: </label>
 4095: </p>
 4096: -->
 4097: <p>
 4098: <label>
 4099:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4100:    Overwrite any existing score
 4101: </label>
 4102: </p>
 4103: ENDPICK
 4104:     my %fields=&get_fields();
 4105:     if (!defined($fields{'domain'})) {
 4106: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4107: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4108:     }
 4109:     foreach my $key (sort(keys(%env))) {
 4110: 	if ($key !~ /^form\.(.*)$/) { next; }
 4111: 	my $cleankey=$1;
 4112: 	if ($cleankey eq 'command') { next; }
 4113: 	$request->print('<input type="hidden" name="'.$cleankey.
 4114: 			'"  value="'.$env{$key}.'" />'."\n");
 4115:     }
 4116:     # FIXME do a check for any duplicated user ids...
 4117:     # FIXME do a check for any invalid user ids?...
 4118:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4119: <hr /></form>'."\n");
 4120:     $request->print(&show_grading_menu_form($symb));
 4121:     return '';
 4122: }
 4123: 
 4124: sub get_fields {
 4125:     my %fields;
 4126:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4127:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4128: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4129: 	    if ($env{'form.f'.$i} ne 'none') {
 4130: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4131: 	    }
 4132: 	} else {
 4133: 	    if ($env{'form.f'.$i} ne 'none') {
 4134: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4135: 	    }
 4136: 	}
 4137:     }
 4138:     return %fields;
 4139: }
 4140: 
 4141: sub csvuploadassign {
 4142:     my ($request)= @_;
 4143:     my ($symb)=&get_symb($request);
 4144:     if (!$symb) {return '';}
 4145:     my $error_msg = '';
 4146:     &Apache::loncommon::load_tmp_file($request);
 4147:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4148:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4149:     my %fields=&get_fields();
 4150:     $request->print('<h3>Assigning Grades</h3>');
 4151:     my $courseid=$env{'request.course.id'};
 4152:     my ($classlist) = &getclasslist('all',0);
 4153:     my @notallowed;
 4154:     my @skipped;
 4155:     my $countdone=0;
 4156:     foreach my $grade (@gradedata) {
 4157: 	my %entries=&Apache::loncommon::record_sep($grade);
 4158: 	my $domain;
 4159: 	if ($entries{$fields{'domain'}}) {
 4160: 	    $domain=$entries{$fields{'domain'}};
 4161: 	} else {
 4162: 	    $domain=$env{'form.default_domain'};
 4163: 	}
 4164: 	$domain=~s/\s//g;
 4165: 	my $username=$entries{$fields{'username'}};
 4166: 	$username=~s/\s//g;
 4167: 	if (!$username) {
 4168: 	    my $id=$entries{$fields{'ID'}};
 4169: 	    $id=~s/\s//g;
 4170: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4171: 	    $username=$ids{$id};
 4172: 	}
 4173: 	if (!exists($$classlist{"$username:$domain"})) {
 4174: 	    my $id=$entries{$fields{'ID'}};
 4175: 	    $id=~s/\s//g;
 4176: 	    if ($id) {
 4177: 		push(@skipped,"$id:$domain");
 4178: 	    } else {
 4179: 		push(@skipped,"$username:$domain");
 4180: 	    }
 4181: 	    next;
 4182: 	}
 4183: 	my $usec=$classlist->{"$username:$domain"}[5];
 4184: 	if (!&canmodify($usec)) {
 4185: 	    push(@notallowed,"$username:$domain");
 4186: 	    next;
 4187: 	}
 4188: 	my %points;
 4189: 	my %grades;
 4190: 	foreach my $dest (keys(%fields)) {
 4191: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4192: 		$dest eq 'domain') { next; }
 4193: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4194: 	    if ($dest=~/stores_(.*)_points/) {
 4195: 		my $part=$1;
 4196: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4197: 					      $symb,$domain,$username);
 4198:                 if ($wgt) {
 4199:                     $entries{$fields{$dest}}=~s/\s//g;
 4200:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4201:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4202:                                           : 'correct_by_override';
 4203:                     $grades{"resource.$part.awarded"}=$pcr;
 4204:                     $grades{"resource.$part.solved"}=$award;
 4205:                     $points{$part}=1;
 4206:                 } else {
 4207:                     $error_msg = "<br />" .
 4208:                         &mt("Some point values were assigned"
 4209:                             ." for problems with a weight "
 4210:                             ."of zero. These values were "
 4211:                             ."ignored.");
 4212:                 }
 4213: 	    } else {
 4214: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4215: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4216: 		my $store_key=$dest;
 4217: 		$store_key=~s/^stores/resource/;
 4218: 		$store_key=~s/_/\./g;
 4219: 		$grades{$store_key}=$entries{$fields{$dest}};
 4220: 	    }
 4221: 	}
 4222: 	if (! %grades) { 
 4223:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4224:         } else {
 4225: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4226: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4227: 					   $env{'request.course.id'},
 4228: 					   $domain,$username);
 4229: 	   if ($result eq 'ok') {
 4230: 	      $request->print('.');
 4231: 	   } else {
 4232: 	      $request->print("<p><span class=\"LC_error\">".
 4233:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4234:                                   "$username:$domain",$result)."</span></p>");
 4235: 	   }
 4236: 	   $request->rflush();
 4237: 	   $countdone++;
 4238:         }
 4239:     }
 4240:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4241:     if (@skipped) {
 4242: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4243:         $request->print(join(', ',@skipped));
 4244:     }
 4245:     if (@notallowed) {
 4246: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4247: 	$request->print(join(', ',@notallowed));
 4248:     }
 4249:     $request->print("<br />\n");
 4250:     $request->print(&show_grading_menu_form($symb));
 4251:     return $error_msg;
 4252: }
 4253: #------------- end of section for handling csv file upload ---------
 4254: #
 4255: #-------------------------------------------------------------------
 4256: #
 4257: #-------------- Next few routines handle grading by page/sequence
 4258: #
 4259: #--- Select a page/sequence and a student to grade
 4260: sub pickStudentPage {
 4261:     my ($request) = shift;
 4262: 
 4263:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4264:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4265: 
 4266: function checkPickOne(formname) {
 4267:     if (radioSelection(formname.student) == null) {
 4268: 	alert("$alertmsg");
 4269: 	return;
 4270:     }
 4271:     ptr = pullDownSelection(formname.selectpage);
 4272:     formname.page.value = formname["page"+ptr].value;
 4273:     formname.title.value = formname["title"+ptr].value;
 4274:     formname.submit();
 4275: }
 4276: 
 4277: LISTJAVASCRIPT
 4278:     &commonJSfunctions($request);
 4279:     my ($symb) = &get_symb($request);
 4280:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4281:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4282:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4283: 
 4284:     my $result='<h3><span class="LC_info">&nbsp;'.
 4285: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4286: 
 4287:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4288:     my $map_error;
 4289:     my ($titles,$symbx) = &getSymbMap($map_error);
 4290:     if ($map_error) {
 4291:         $request->print(&navmap_errormsg());
 4292:         return; 
 4293:     }
 4294:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4295: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4296: #    my $type=($curpage =~ /\.(page|sequence)/);
 4297:     my $select = '<select name="selectpage">'."\n";
 4298:     my $ctr=0;
 4299:     foreach (@$titles) {
 4300: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4301: 	$select.='<option value="'.$ctr.'" '.
 4302: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4303: 	    '>'.$showtitle.'</option>'."\n";
 4304: 	$ctr++;
 4305:     }
 4306:     $select.= '</select>';
 4307:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4308: 
 4309:     $ctr=0;
 4310:     foreach (@$titles) {
 4311: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4312: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4313: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4314: 	$ctr++;
 4315:     }
 4316:     $result.='<input type="hidden" name="page" />'."\n".
 4317: 	'<input type="hidden" name="title" />'."\n";
 4318: 
 4319:     my $options =
 4320: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4321: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4322:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4323: 
 4324:     $options =
 4325: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4326: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4327: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4328:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4329:     
 4330:     $result.=&build_section_inputs();
 4331:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4332:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4333: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4334: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4335: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4336: 
 4337:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4338: 
 4339:     $result.='&nbsp;<input type="button" '.
 4340:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4341: 
 4342:     $request->print($result);
 4343: 
 4344:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4345: 	&Apache::loncommon::start_data_table().
 4346: 	&Apache::loncommon::start_data_table_header_row().
 4347: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4348: 	'<th>'.&nameUserString('header').'</th>'.
 4349: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4350: 	'<th>'.&nameUserString('header').'</th>'.
 4351: 	&Apache::loncommon::end_data_table_header_row();
 4352:  
 4353:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4354:     my $ptr = 1;
 4355:     foreach my $student (sort 
 4356: 			 {
 4357: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4358: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4359: 			     }
 4360: 			     return $a cmp $b;
 4361: 			 } (keys(%$fullname))) {
 4362: 	my ($uname,$udom) = split(/:/,$student);
 4363: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4364:                                   : '</td>');
 4365: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4366: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4367: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4368: 	$studentTable.=
 4369: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4370:                          : '');
 4371: 	$ptr++;
 4372:     }
 4373:     if ($ptr%2 == 0) {
 4374: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4375: 	    &Apache::loncommon::end_data_table_row();
 4376:     }
 4377:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4378:     $studentTable.='<input type="button" '.
 4379:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4380: 
 4381:     $studentTable.=&show_grading_menu_form($symb);
 4382:     $request->print($studentTable);
 4383: 
 4384:     return '';
 4385: }
 4386: 
 4387: sub getSymbMap {
 4388:     my ($map_error) = @_;
 4389:     my $navmap = Apache::lonnavmaps::navmap->new();
 4390:     unless (ref($navmap)) {
 4391:         if (ref($map_error)) {
 4392:             $$map_error = 'navmap';
 4393:         }
 4394:         return;
 4395:     }
 4396:     my %symbx = ();
 4397:     my @titles = ();
 4398:     my $minder = 0;
 4399: 
 4400:     # Gather every sequence that has problems.
 4401:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4402: 					       1,0,1);
 4403:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4404: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4405: 	    my $title = $minder.'.'.
 4406: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4407: 	    push(@titles, $title); # minder in case two titles are identical
 4408: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4409: 	    $minder++;
 4410: 	}
 4411:     }
 4412:     return \@titles,\%symbx;
 4413: }
 4414: 
 4415: #
 4416: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4417: sub displayPage {
 4418:     my ($request) = shift;
 4419: 
 4420:     my ($symb) = &get_symb($request);
 4421:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4422:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4423:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4424:     my $pageTitle = $env{'form.page'};
 4425:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4426:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4427:     my $usec=$classlist->{$env{'form.student'}}[5];
 4428: 
 4429:     #need to make sure we have the correct data for later EXT calls, 
 4430:     #thus invalidate the cache
 4431:     &Apache::lonnet::devalidatecourseresdata(
 4432:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4433:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4434:     &Apache::lonnet::clear_EXT_cache_status();
 4435: 
 4436:     if (!&canview($usec)) {
 4437: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4438: 	$request->print(&show_grading_menu_form($symb));
 4439: 	return;
 4440:     }
 4441:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4442:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4443: 	'</h3>'."\n";
 4444:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4445:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4446: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4447:     } else {
 4448: 	delete($env{'form.CODE'});
 4449:     }
 4450:     &sub_page_js($request);
 4451:     $request->print($result);
 4452: 
 4453:     my $navmap = Apache::lonnavmaps::navmap->new();
 4454:     unless (ref($navmap)) {
 4455:         $request->print(&navmap_errormsg());
 4456:         $request->print(&show_grading_menu_form($symb));
 4457:         return;
 4458:     }
 4459:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4460:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4461:     if (!$map) {
 4462: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4463: 	$request->print(&show_grading_menu_form($symb));
 4464: 	return; 
 4465:     }
 4466:     my $iterator = $navmap->getIterator($map->map_start(),
 4467: 					$map->map_finish());
 4468: 
 4469:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4470: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4471: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4472: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4473: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4474: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4475: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4476: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4477: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4478: 
 4479:     if (defined($env{'form.CODE'})) {
 4480: 	$studentTable.=
 4481: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4482:     }
 4483:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4484: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4485: 
 4486:     $studentTable.='&nbsp;<span class="LC_info">'.
 4487:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4488:         '</span>'."\n".
 4489: 	&Apache::loncommon::start_data_table().
 4490: 	&Apache::loncommon::start_data_table_header_row().
 4491: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4492: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4493: 	&Apache::loncommon::end_data_table_header_row();
 4494: 
 4495:     &Apache::lonxml::clear_problem_counter();
 4496:     my ($depth,$question,$prob) = (1,1,1);
 4497:     $iterator->next(); # skip the first BEGIN_MAP
 4498:     my $curRes = $iterator->next(); # for "current resource"
 4499:     while ($depth > 0) {
 4500:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4501:         if($curRes == $iterator->END_MAP) { $depth--; }
 4502: 
 4503:         if (ref($curRes) && $curRes->is_problem()) {
 4504: 	    my $parts = $curRes->parts();
 4505:             my $title = $curRes->compTitle();
 4506: 	    my $symbx = $curRes->symb();
 4507: 	    $studentTable.=
 4508: 		&Apache::loncommon::start_data_table_row().
 4509: 		'<td align="center" valign="top" >'.$prob.
 4510: 		(scalar(@{$parts}) == 1 ? '' 
 4511: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4512: 							scalar(@{$parts}))
 4513: 		 ).
 4514: 		 '</td>';
 4515: 	    $studentTable.='<td valign="top">';
 4516: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4517: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4518: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4519: 					     undef,'both',\%form);
 4520: 	    } else {
 4521: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4522: 		$companswer =~ s|<form(.*?)>||g;
 4523: 		$companswer =~ s|</form>||g;
 4524: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4525: #		    $companswer =~ s/$1/ /ms;
 4526: #		    $request->print('match='.$1."<br />\n");
 4527: #		}
 4528: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4529: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4530: 	    }
 4531: 
 4532: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4533: 
 4534: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4535: 		if ($record{'version'} eq '') {
 4536: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4537: 		} else {
 4538: 		    my %responseType = ();
 4539: 		    foreach my $partid (@{$parts}) {
 4540: 			my @responseIds =$curRes->responseIds($partid);
 4541: 			my @responseType =$curRes->responseType($partid);
 4542: 			my %responseIds;
 4543: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4544: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4545: 			}
 4546: 			$responseType{$partid} = \%responseIds;
 4547: 		    }
 4548: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4549: 
 4550: 		}
 4551: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4552: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4553: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4554: 									$env{'request.course.id'},
 4555: 									'','.submission');
 4556:  
 4557: 	    }
 4558: 	    if (&canmodify($usec)) {
 4559:             $studentTable.=&gradeBox_start();
 4560: 		foreach my $partid (@{$parts}) {
 4561: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4562: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4563: 		    $question++;
 4564: 		}
 4565:             $studentTable.=&gradeBox_end();
 4566: 		$prob++;
 4567: 	    }
 4568: 	    $studentTable.='</td></tr>';
 4569: 
 4570: 	}
 4571:         $curRes = $iterator->next();
 4572:     }
 4573: 
 4574:     $studentTable.=
 4575:         '</table>'."\n".
 4576:         '<input type="button" value="'.&mt('Save').'" '.
 4577:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4578:         '</form>'."\n";
 4579:     $studentTable.=&show_grading_menu_form($symb);
 4580:     $request->print($studentTable);
 4581: 
 4582:     return '';
 4583: }
 4584: 
 4585: sub displaySubByDates {
 4586:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4587:     my $isCODE=0;
 4588:     my $isTask = ($symb =~/\.task$/);
 4589:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4590:     my $studentTable=&Apache::loncommon::start_data_table().
 4591: 	&Apache::loncommon::start_data_table_header_row().
 4592: 	'<th>'.&mt('Date/Time').'</th>'.
 4593: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4594: 	'<th>'.&mt('Submission').'</th>'.
 4595: 	'<th>'.&mt('Status').'</th>'.
 4596: 	&Apache::loncommon::end_data_table_header_row();
 4597:     my ($version);
 4598:     my %mark;
 4599:     my %orders;
 4600:     $mark{'correct_by_student'} = $checkIcon;
 4601:     if (!exists($$record{'1:timestamp'})) {
 4602: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4603:     }
 4604: 
 4605:     my $interaction;
 4606:     my $no_increment = 1;
 4607:     for ($version=1;$version<=$$record{'version'};$version++) {
 4608: 	my $timestamp = 
 4609: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4610: 	if (exists($$record{$version.':resource.0.version'})) {
 4611: 	    $interaction = $$record{$version.':resource.0.version'};
 4612: 	}
 4613: 
 4614: 	my $where = ($isTask ? "$version:resource.$interaction"
 4615: 		             : "$version:resource");
 4616: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4617: 	    '<td>'.$timestamp.'</td>';
 4618: 	if ($isCODE) {
 4619: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4620: 	}
 4621: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4622: 	my @displaySub = ();
 4623: 	foreach my $partid (@{$parts}) {
 4624:             my $hidden;
 4625:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
 4626:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
 4627:                 $hidden = 1;
 4628:             }
 4629: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4630: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4631: 	    
 4632: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4633: 	    my $display_part=&get_display_part($partid,$symb);
 4634: 	    foreach my $matchKey (@matchKey) {
 4635: 		if (exists($$record{$version.':'.$matchKey}) &&
 4636: 		    $$record{$version.':'.$matchKey} ne '') {
 4637:                     
 4638: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4639: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4640:                     $displaySub[0].='<span class="LC_nobreak"';
 4641:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4642:                                    .' <span class="LC_internal_info">'
 4643:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4644:                                    .'</span>'
 4645:                                    .' <b>';
 4646:                     if ($hidden) {
 4647:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4648:                     } else {
 4649: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4650: 			    $displaySub[0].=&mt('Trial not counted');
 4651: 		        } else {
 4652: 			    $displaySub[0].=&mt('Trial: [_1]',
 4653: 					    $$record{"$where.$partid.tries"});
 4654: 		        }
 4655: 		        my $responseType=($isTask ? 'Task'
 4656:                                               : $responseType->{$partid}->{$responseId});
 4657: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4658: 		        if (!exists($orders{$partid}->{$responseId})) {
 4659: 			    $orders{$partid}->{$responseId}=
 4660: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4661:                                            $no_increment);
 4662: 		        }
 4663: 		        $displaySub[0].='</b></span>'; # /nobreak
 4664: 		        $displaySub[0].='&nbsp; '.
 4665: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4666:                     }
 4667: 		}
 4668: 	    }
 4669: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4670: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4671: 				    $$record{"$where.$partid.checkedin"},
 4672: 				    $$record{"$where.$partid.checkedin.slot"}).
 4673: 					'<br />';
 4674: 	    }
 4675: 	    if (exists $$record{"$where.$partid.award"}) {
 4676: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4677: 		    lc($$record{"$where.$partid.award"}).' '.
 4678: 		    $mark{$$record{"$where.$partid.solved"}}.
 4679: 		    '<br />';
 4680: 	    }
 4681: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4682: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4683: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4684: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4685: 		$displaySub[2].=
 4686: 		    $$record{"$version:resource.$partid.regrader"}.
 4687: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4688: 	    }
 4689: 	}
 4690: 	# needed because old essay regrader has not parts info
 4691: 	if (exists $$record{"$version:resource.regrader"}) {
 4692: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4693: 	}
 4694: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4695: 	if ($displaySub[2]) {
 4696: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4697: 	}
 4698: 	$studentTable.='&nbsp;</td>'.
 4699: 	    &Apache::loncommon::end_data_table_row();
 4700:     }
 4701:     $studentTable.=&Apache::loncommon::end_data_table();
 4702:     return $studentTable;
 4703: }
 4704: 
 4705: sub updateGradeByPage {
 4706:     my ($request) = shift;
 4707: 
 4708:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4709:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4710:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4711:     my $pageTitle = $env{'form.page'};
 4712:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4713:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4714:     my $usec=$classlist->{$env{'form.student'}}[5];
 4715:     if (!&canmodify($usec)) {
 4716: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4717: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4718: 	return;
 4719:     }
 4720:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4721:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4722: 	'</h3>'."\n";
 4723: 
 4724:     $request->print($result);
 4725: 
 4726: 
 4727:     my $navmap = Apache::lonnavmaps::navmap->new();
 4728:     unless (ref($navmap)) {
 4729:         $request->print(&navmap_errormsg());
 4730:         return;
 4731:     }
 4732:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4733:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4734:     if (!$map) {
 4735: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4736: 	my ($symb)=&get_symb($request);
 4737: 	$request->print(&show_grading_menu_form($symb));
 4738: 	return; 
 4739:     }
 4740:     my $iterator = $navmap->getIterator($map->map_start(),
 4741: 					$map->map_finish());
 4742: 
 4743:     my $studentTable=
 4744: 	&Apache::loncommon::start_data_table().
 4745: 	&Apache::loncommon::start_data_table_header_row().
 4746: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4747: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4748: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4749: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4750: 	&Apache::loncommon::end_data_table_header_row();
 4751: 
 4752:     $iterator->next(); # skip the first BEGIN_MAP
 4753:     my $curRes = $iterator->next(); # for "current resource"
 4754:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4755:     while ($depth > 0) {
 4756:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4757:         if($curRes == $iterator->END_MAP) { $depth--; }
 4758: 
 4759:         if (ref($curRes) && $curRes->is_problem()) {
 4760: 	    my $parts = $curRes->parts();
 4761:             my $title = $curRes->compTitle();
 4762: 	    my $symbx = $curRes->symb();
 4763: 	    $studentTable.=
 4764: 		&Apache::loncommon::start_data_table_row().
 4765: 		'<td align="center" valign="top" >'.$prob.
 4766: 		(scalar(@{$parts}) == 1 ? '' 
 4767:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4768: 		.')').'</td>';
 4769: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4770: 
 4771: 	    my %newrecord=();
 4772: 	    my @displayPts=();
 4773:             my %aggregate = ();
 4774:             my $aggregateflag = 0;
 4775: 	    foreach my $partid (@{$parts}) {
 4776: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4777: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4778: 
 4779: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4780: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4781: 		my $partial = $newpts/$wgt;
 4782: 		my $score;
 4783: 		if ($partial > 0) {
 4784: 		    $score = 'correct_by_override';
 4785: 		} elsif ($newpts ne '') { #empty is taken as 0
 4786: 		    $score = 'incorrect_by_override';
 4787: 		}
 4788: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4789: 		if ($dropMenu eq 'excused') {
 4790: 		    $partial = '';
 4791: 		    $score = 'excused';
 4792: 		} elsif ($dropMenu eq 'reset status'
 4793: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4794: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4795: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4796: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4797: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4798: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4799: 		    $changeflag++;
 4800: 		    $newpts = '';
 4801:                     
 4802:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4803:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4804:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4805:                     if ($aggtries > 0) {
 4806:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4807:                         $aggregateflag = 1;
 4808:                     }
 4809: 		}
 4810: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4811: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4812: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4813: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4814: 		    '&nbsp;<br />';
 4815: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4816: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4817: 		    '&nbsp;<br />';
 4818: 		$question++;
 4819: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4820: 
 4821: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4822: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4823: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4824: 		    if (scalar(keys(%newrecord)) > 0);
 4825: 
 4826: 		$changeflag++;
 4827: 	    }
 4828: 	    if (scalar(keys(%newrecord)) > 0) {
 4829: 		my %record = 
 4830: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4831: 					     $udom,$uname);
 4832: 
 4833: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4834: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4835: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4836: 		    $newrecord{'resource.CODE'} = '';
 4837: 		}
 4838: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4839: 					$udom,$uname);
 4840: 		%record = &Apache::lonnet::restore($symbx,
 4841: 						   $env{'request.course.id'},
 4842: 						   $udom,$uname);
 4843: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4844: 					     $cdom,$cnum,$udom,$uname);
 4845: 	    }
 4846: 	    
 4847:             if ($aggregateflag) {
 4848:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4849:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4850:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4851:             }
 4852: 
 4853: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4854: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4855: 		&Apache::loncommon::end_data_table_row();
 4856: 
 4857: 	    $prob++;
 4858: 	}
 4859:         $curRes = $iterator->next();
 4860:     }
 4861: 
 4862:     $studentTable.=&Apache::loncommon::end_data_table();
 4863:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4864:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4865: 		  &mt('The scores were changed for [quant,_1,problem].',
 4866: 		  $changeflag));
 4867:     $request->print($grademsg.$studentTable);
 4868: 
 4869:     return '';
 4870: }
 4871: 
 4872: #-------- end of section for handling grading by page/sequence ---------
 4873: #
 4874: #-------------------------------------------------------------------
 4875: 
 4876: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4877: #
 4878: #------ start of section for handling grading by page/sequence ---------
 4879: 
 4880: =pod
 4881: 
 4882: =head1 Bubble sheet grading routines
 4883: 
 4884:   For this documentation:
 4885: 
 4886:    'scanline' refers to the full line of characters
 4887:    from the file that we are parsing that represents one entire sheet
 4888: 
 4889:    'bubble line' refers to the data
 4890:    representing the line of bubbles that are on the physical bubble sheet
 4891: 
 4892: 
 4893: The overall process is that a scanned in bubble sheet data is uploaded
 4894: into a course. When a user wants to grade, they select a
 4895: sequence/folder of resources, a file of bubble sheet info, and pick
 4896: one of the predefined configurations for what each scanline looks
 4897: like.
 4898: 
 4899: Next each scanline is checked for any errors of either 'missing
 4900: bubbles' (it's an error because it may have been mis-scanned
 4901: because too light bubbling), 'double bubble' (each bubble line should
 4902: have no more that one letter picked), invalid or duplicated CODE,
 4903: invalid student/employee ID
 4904: 
 4905: If the CODE option is used that determines the randomization of the
 4906: homework problems, either way the student/employee ID is looked up into a
 4907: username:domain.
 4908: 
 4909: During the validation phase the instructor can choose to skip scanlines. 
 4910: 
 4911: After the validation phase, there are now 3 bubble sheet files
 4912: 
 4913:   scantron_original_filename (unmodified original file)
 4914:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4915:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4916: 
 4917: Also there is a separate hash nohist_scantrondata that contains extra
 4918: correction information that isn't representable in the bubble sheet
 4919: file (see &scantron_getfile() for more information)
 4920: 
 4921: After all scanlines are either valid, marked as valid or skipped, then
 4922: foreach line foreach problem in the picked sequence, an ssi request is
 4923: made that simulates a user submitting their selected letter(s) against
 4924: the homework problem.
 4925: 
 4926: =over 4
 4927: 
 4928: 
 4929: 
 4930: =item defaultFormData
 4931: 
 4932:   Returns html hidden inputs used to hold context/default values.
 4933: 
 4934:  Arguments:
 4935:   $symb - $symb of the current resource 
 4936: 
 4937: =cut
 4938: 
 4939: sub defaultFormData {
 4940:     my ($symb)=@_;
 4941:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4942:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4943:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4944: }
 4945: 
 4946: 
 4947: =pod 
 4948: 
 4949: =item getSequenceDropDown
 4950: 
 4951:    Return html dropdown of possible sequences to grade
 4952:  
 4953:  Arguments:
 4954:    $symb - $symb of the current resource
 4955:    $map_error - ref to scalar which will container error if
 4956:                 $navmap object is unavailable in &getSymbMap().
 4957: 
 4958: =cut
 4959: 
 4960: sub getSequenceDropDown {
 4961:     my ($symb,$map_error)=@_;
 4962:     my $result='<select name="selectpage">'."\n";
 4963:     my ($titles,$symbx) = &getSymbMap($map_error);
 4964:     if (ref($map_error)) {
 4965:         return if ($$map_error);
 4966:     }
 4967:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4968:     my $ctr=0;
 4969:     foreach (@$titles) {
 4970: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4971: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4972: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4973: 	    '>'.$showtitle.'</option>'."\n";
 4974: 	$ctr++;
 4975:     }
 4976:     $result.= '</select>';
 4977:     return $result;
 4978: }
 4979: 
 4980: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4981:                                    # key is zero-based index - 0, 1, 2 ...
 4982: 
 4983: my %first_bubble_line;             # First bubble line no. for each bubble.
 4984: 
 4985: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4986:                                    # matchresponse or rankresponse, where 
 4987:                                    # an individual response can have multiple 
 4988:                                    # lines
 4989: 
 4990: my %responsetype_per_response;     # responsetype for each response
 4991: 
 4992: # Save and restore the bubble lines array to the form env.
 4993: 
 4994: 
 4995: sub save_bubble_lines {
 4996:     foreach my $line (keys(%bubble_lines_per_response)) {
 4997: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4998: 	$env{"form.scantron.first_bubble_line.$line"} =
 4999: 	    $first_bubble_line{$line};
 5000:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5001:             $subdivided_bubble_lines{$line};
 5002:         $env{"form.scantron.responsetype.$line"} =
 5003:             $responsetype_per_response{$line};
 5004:     }
 5005: }
 5006: 
 5007: 
 5008: sub restore_bubble_lines {
 5009:     my $line = 0;
 5010:     %bubble_lines_per_response = ();
 5011:     while ($env{"form.scantron.bubblelines.$line"}) {
 5012: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5013: 	$bubble_lines_per_response{$line} = $value;
 5014: 	$first_bubble_line{$line}  =
 5015: 	    $env{"form.scantron.first_bubble_line.$line"};
 5016:         $subdivided_bubble_lines{$line} =
 5017:             $env{"form.scantron.sub_bubblelines.$line"};
 5018:         $responsetype_per_response{$line} =
 5019:             $env{"form.scantron.responsetype.$line"};
 5020: 	$line++;
 5021:     }
 5022: }
 5023: 
 5024: #  Given the parsed scanline, get the response for 
 5025: #  'answer' number n:
 5026: 
 5027: sub get_response_bubbles {
 5028:     my ($parsed_line, $response)  = @_;
 5029: 
 5030:     my $bubble_line = $first_bubble_line{$response-1} +1;
 5031:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 5032:     
 5033:     my $selected = "";
 5034: 
 5035:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 5036: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 5037: 	$bubble_line++;
 5038:     }
 5039:     return $selected;
 5040: }
 5041: 
 5042: =pod 
 5043: 
 5044: =item scantron_filenames
 5045: 
 5046:    Returns a list of the scantron files in the current course 
 5047: 
 5048: =cut
 5049: 
 5050: sub scantron_filenames {
 5051:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5052:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5053:     my $getpropath = 1;
 5054:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 5055:                                        $getpropath);
 5056:     my @possiblenames;
 5057:     foreach my $filename (sort(@files)) {
 5058: 	($filename)=split(/&/,$filename);
 5059: 	if ($filename!~/^scantron_orig_/) { next ; }
 5060: 	$filename=~s/^scantron_orig_//;
 5061: 	push(@possiblenames,$filename);
 5062:     }
 5063:     return @possiblenames;
 5064: }
 5065: 
 5066: =pod 
 5067: 
 5068: =item scantron_uploads
 5069: 
 5070:    Returns  html drop-down list of scantron files in current course.
 5071: 
 5072:  Arguments:
 5073:    $file2grade - filename to set as selected in the dropdown
 5074: 
 5075: =cut
 5076: 
 5077: sub scantron_uploads {
 5078:     my ($file2grade) = @_;
 5079:     my $result=	'<select name="scantron_selectfile">';
 5080:     $result.="<option></option>";
 5081:     foreach my $filename (sort(&scantron_filenames())) {
 5082: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5083:     }
 5084:     $result.="</select>";
 5085:     return $result;
 5086: }
 5087: 
 5088: =pod 
 5089: 
 5090: =item scantron_scantab
 5091: 
 5092:   Returns html drop down of the scantron formats in the scantronformat.tab
 5093:   file.
 5094: 
 5095: =cut
 5096: 
 5097: sub scantron_scantab {
 5098:     my $result='<select name="scantron_format">'."\n";
 5099:     $result.='<option></option>'."\n";
 5100:     my @lines = &get_scantronformat_file();
 5101:     if (@lines > 0) {
 5102:         foreach my $line (@lines) {
 5103:             next if (($line =~ /^\#/) || ($line eq ''));
 5104: 	    my ($name,$descrip)=split(/:/,$line);
 5105: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5106:         }
 5107:     }
 5108:     $result.='</select>'."\n";
 5109:     return $result;
 5110: }
 5111: 
 5112: =pod
 5113: 
 5114: =item get_scantronformat_file
 5115: 
 5116:   Returns an array containing lines from the scantron format file for
 5117:   the domain of the course.
 5118: 
 5119:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5120:   lines are from this file.
 5121: 
 5122:   Otherwise, if a default.tab has been published in RES space by the 
 5123:   domainconfig user, lines are from this file.
 5124: 
 5125:   Otherwise, fall back to getting lines from the legacy file on the
 5126:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5127: 
 5128: =cut
 5129: 
 5130: sub get_scantronformat_file {
 5131:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5132:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5133:     my $gottab = 0;
 5134:     my @lines;
 5135:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5136:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5137:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5138:             if ($formatfile ne '-1') {
 5139:                 @lines = split("\n",$formatfile,-1);
 5140:                 $gottab = 1;
 5141:             }
 5142:         }
 5143:     }
 5144:     if (!$gottab) {
 5145:         my $confname = $cdom.'-domainconfig';
 5146:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5147:         my $formatfile =  &Apache::lonnet::getfile($default);
 5148:         if ($formatfile ne '-1') {
 5149:             @lines = split("\n",$formatfile,-1);
 5150:             $gottab = 1;
 5151:         }
 5152:     }
 5153:     if (!$gottab) {
 5154:         my @domains = &Apache::lonnet::current_machine_domains();
 5155:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5156:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5157:             @lines = <$fh>;
 5158:             close($fh);
 5159:         } else {
 5160:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5161:             @lines = <$fh>;
 5162:             close($fh);
 5163:         }
 5164:     }
 5165:     return @lines;
 5166: }
 5167: 
 5168: =pod 
 5169: 
 5170: =item scantron_CODElist
 5171: 
 5172:   Returns html drop down of the saved CODE lists from current course,
 5173:   generated from earlier printings.
 5174: 
 5175: =cut
 5176: 
 5177: sub scantron_CODElist {
 5178:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5179:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5180:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5181:     my $namechoice='<option></option>';
 5182:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5183: 	if ($name =~ /^error: 2 /) { next; }
 5184: 	if ($name =~ /^type\0/) { next; }
 5185: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5186:     }
 5187:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5188:     return $namechoice;
 5189: }
 5190: 
 5191: =pod 
 5192: 
 5193: =item scantron_CODEunique
 5194: 
 5195:   Returns the html for "Each CODE to be used once" radio.
 5196: 
 5197: =cut
 5198: 
 5199: sub scantron_CODEunique {
 5200:     my $result='<span class="LC_nobreak">
 5201:                  <label><input type="radio" name="scantron_CODEunique"
 5202:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5203:                 </span>
 5204:                 <span class="LC_nobreak">
 5205:                  <label><input type="radio" name="scantron_CODEunique"
 5206:                         value="no" />'.&mt('No').' </label>
 5207:                 </span>';
 5208:     return $result;
 5209: }
 5210: 
 5211: =pod 
 5212: 
 5213: =item scantron_selectphase
 5214: 
 5215:   Generates the initial screen to start the bubble sheet process.
 5216:   Allows for - starting a grading run.
 5217:              - downloading existing scan data (original, corrected
 5218:                                                 or skipped info)
 5219: 
 5220:              - uploading new scan data
 5221: 
 5222:  Arguments:
 5223:   $r          - The Apache request object
 5224:   $file2grade - name of the file that contain the scanned data to score
 5225: 
 5226: =cut
 5227: 
 5228: sub scantron_selectphase {
 5229:     my ($r,$file2grade) = @_;
 5230:     my ($symb)=&get_symb($r);
 5231:     if (!$symb) {return '';}
 5232:     my $map_error;
 5233:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5234:     if ($map_error) {
 5235:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5236:         return;
 5237:     }
 5238:     my $default_form_data=&defaultFormData($symb);
 5239:     my $grading_menu_button=&show_grading_menu_form($symb);
 5240:     my $file_selector=&scantron_uploads($file2grade);
 5241:     my $format_selector=&scantron_scantab();
 5242:     my $CODE_selector=&scantron_CODElist();
 5243:     my $CODE_unique=&scantron_CODEunique();
 5244:     my $result;
 5245: 
 5246:     $ssi_error = 0;
 5247: 
 5248:     # Chunk of form to prompt for a file to grade and how:
 5249: 
 5250:     $result.= '
 5251:     <br />
 5252:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5253:     <input type="hidden" name="command" value="scantron_warning" />
 5254:     '.$default_form_data.'
 5255:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5256:        '.&Apache::loncommon::start_data_table_header_row().'
 5257:             <th colspan="2">
 5258:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5259:             </th>
 5260:        '.&Apache::loncommon::end_data_table_header_row().'
 5261:        '.&Apache::loncommon::start_data_table_row().'
 5262:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5263:        '.&Apache::loncommon::end_data_table_row().'
 5264:        '.&Apache::loncommon::start_data_table_row().'
 5265:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5266:        '.&Apache::loncommon::end_data_table_row().'
 5267:        '.&Apache::loncommon::start_data_table_row().'
 5268:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5269:        '.&Apache::loncommon::end_data_table_row().'
 5270:        '.&Apache::loncommon::start_data_table_row().'
 5271:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5272:        '.&Apache::loncommon::end_data_table_row().'
 5273:        '.&Apache::loncommon::start_data_table_row().'
 5274:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5275:        '.&Apache::loncommon::end_data_table_row().'
 5276:        '.&Apache::loncommon::start_data_table_row().'
 5277: 	    <td> '.&mt('Options:').' </td>
 5278:             <td>
 5279: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5280:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5281:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5282: 	    </td>
 5283:        '.&Apache::loncommon::end_data_table_row().'
 5284:        '.&Apache::loncommon::start_data_table_row().'
 5285:             <td colspan="2">
 5286:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5287:             </td>
 5288:        '.&Apache::loncommon::end_data_table_row().'
 5289:     '.&Apache::loncommon::end_data_table().'
 5290:     </form>
 5291: ';
 5292:    
 5293:     $r->print($result);
 5294: 
 5295:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5296:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5297: 
 5298: 	# Chunk of form to prompt for a scantron file upload.
 5299: 
 5300:         $r->print('
 5301:     <br />
 5302:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5303:        '.&Apache::loncommon::start_data_table_header_row().'
 5304:             <th>
 5305:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5306:             </th>
 5307:        '.&Apache::loncommon::end_data_table_header_row().'
 5308:        '.&Apache::loncommon::start_data_table_row().'
 5309:             <td>
 5310: ');
 5311:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5312:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5313:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5314:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5315:     function checkUpload(formname) {
 5316: 	if (formname.upfile.value == "") {
 5317: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5318: 	    return false;
 5319: 	}
 5320: 	formname.submit();
 5321:     }'));
 5322:     $r->print('
 5323:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5324:                 '.$default_form_data.'
 5325:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5326:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5327:                 <input name="command" value="scantronupload_save" type="hidden" />
 5328:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5329:                 <br />
 5330:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5331:               </form>
 5332: ');
 5333: 
 5334:         $r->print('
 5335:             </td>
 5336:        '.&Apache::loncommon::end_data_table_row().'
 5337:        '.&Apache::loncommon::end_data_table().'
 5338: ');
 5339:     }
 5340: 
 5341:     # Chunk of the form that prompts to view a scoring office file,
 5342:     # corrected file, skipped records in a file.
 5343: 
 5344:     $r->print('
 5345:    <br />
 5346:    <form action="/adm/grades" name="scantron_download">
 5347:      '.$default_form_data.'
 5348:      <input type="hidden" name="command" value="scantron_download" />
 5349:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5350:        '.&Apache::loncommon::start_data_table_header_row().'
 5351:               <th>
 5352:                 &nbsp;'.&mt('Download a scoring office file').'
 5353:               </th>
 5354:        '.&Apache::loncommon::end_data_table_header_row().'
 5355:        '.&Apache::loncommon::start_data_table_row().'
 5356:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5357:                 <br />
 5358:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5359:        '.&Apache::loncommon::end_data_table_row().'
 5360:      '.&Apache::loncommon::end_data_table().'
 5361:    </form>
 5362:    <br />
 5363: ');
 5364: 
 5365:     &Apache::lonpickcode::code_list($r,2);
 5366: 
 5367:     $r->print('<br /><form method="post" name="checkscantron">'.
 5368:              $default_form_data."\n".
 5369:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5370:              &Apache::loncommon::start_data_table_header_row()."\n".
 5371:              '<th colspan="2">
 5372:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5373:              '</th>'."\n".
 5374:               &Apache::loncommon::end_data_table_header_row()."\n".
 5375:               &Apache::loncommon::start_data_table_row()."\n".
 5376:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5377:               '<td> '.$sequence_selector.' </td>'.
 5378:               &Apache::loncommon::end_data_table_row()."\n".
 5379:               &Apache::loncommon::start_data_table_row()."\n".
 5380:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5381:               '<td> '.$file_selector.' </td>'."\n".
 5382:               &Apache::loncommon::end_data_table_row()."\n".
 5383:               &Apache::loncommon::start_data_table_row()."\n".
 5384:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5385:               '<td> '.$format_selector.' </td>'."\n".
 5386:               &Apache::loncommon::end_data_table_row()."\n".
 5387:               &Apache::loncommon::start_data_table_row()."\n".
 5388:               '<td> '.&mt('Options').' </td>'."\n".
 5389:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5390:               &Apache::loncommon::end_data_table_row()."\n".
 5391:               &Apache::loncommon::start_data_table_row()."\n".
 5392:               '<td colspan="2">'."\n".
 5393:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5394:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5395:               '</td>'."\n".
 5396:               &Apache::loncommon::end_data_table_row()."\n".
 5397:               &Apache::loncommon::end_data_table()."\n".
 5398:               '</form><br />');
 5399:     $r->print($grading_menu_button);
 5400:     return;
 5401: }
 5402: 
 5403: =pod
 5404: 
 5405: =item get_scantron_config
 5406: 
 5407:    Parse and return the scantron configuration line selected as a
 5408:    hash of configuration file fields.
 5409: 
 5410:  Arguments:
 5411:     which - the name of the configuration to parse from the file.
 5412: 
 5413: 
 5414:  Returns:
 5415:             If the named configuration is not in the file, an empty
 5416:             hash is returned.
 5417:     a hash with the fields
 5418:       name         - internal name for the this configuration setup
 5419:       description  - text to display to operator that describes this config
 5420:       CODElocation - if 0 or the string 'none'
 5421:                           - no CODE exists for this config
 5422:                      if -1 || the string 'letter'
 5423:                           - a CODE exists for this config and is
 5424:                             a string of letters
 5425:                      Unsupported value (but planned for future support)
 5426:                           if a positive integer
 5427:                                - The CODE exists as the first n items from
 5428:                                  the question section of the form
 5429:                           if the string 'number'
 5430:                                - The CODE exists for this config and is
 5431:                                  a string of numbers
 5432:       CODEstart   - (only matter if a CODE exists) column in the line where
 5433:                      the CODE starts
 5434:       CODElength  - length of the CODE
 5435:       IDstart     - column where the student/employee ID starts
 5436:       IDlength    - length of the student/employee ID info
 5437:       Qstart      - column where the information from the bubbled
 5438:                     'questions' start
 5439:       Qlength     - number of columns comprising a single bubble line from
 5440:                     the sheet. (usually either 1 or 10)
 5441:       Qon         - either a single character representing the character used
 5442:                     to signal a bubble was chosen in the positional setup, or
 5443:                     the string 'letter' if the letter of the chosen bubble is
 5444:                     in the final, or 'number' if a number representing the
 5445:                     chosen bubble is in the file (1->A 0->J)
 5446:       Qoff        - the character used to represent that a bubble was
 5447:                     left blank
 5448:       PaperID     - if the scanning process generates a unique number for each
 5449:                     sheet scanned the column that this ID number starts in
 5450:       PaperIDlength - number of columns that comprise the unique ID number
 5451:                       for the sheet of paper
 5452:       FirstName   - column that the first name starts in
 5453:       FirstNameLength - number of columns that the first name spans
 5454:  
 5455:       LastName    - column that the last name starts in
 5456:       LastNameLength - number of columns that the last name spans
 5457: 
 5458: =cut
 5459: 
 5460: sub get_scantron_config {
 5461:     my ($which) = @_;
 5462:     my @lines = &get_scantronformat_file();
 5463:     my %config;
 5464:     #FIXME probably should move to XML it has already gotten a bit much now
 5465:     foreach my $line (@lines) {
 5466: 	my ($name,$descrip)=split(/:/,$line);
 5467: 	if ($name ne $which ) { next; }
 5468: 	chomp($line);
 5469: 	my @config=split(/:/,$line);
 5470: 	$config{'name'}=$config[0];
 5471: 	$config{'description'}=$config[1];
 5472: 	$config{'CODElocation'}=$config[2];
 5473: 	$config{'CODEstart'}=$config[3];
 5474: 	$config{'CODElength'}=$config[4];
 5475: 	$config{'IDstart'}=$config[5];
 5476: 	$config{'IDlength'}=$config[6];
 5477: 	$config{'Qstart'}=$config[7];
 5478:  	$config{'Qlength'}=$config[8];
 5479: 	$config{'Qoff'}=$config[9];
 5480: 	$config{'Qon'}=$config[10];
 5481: 	$config{'PaperID'}=$config[11];
 5482: 	$config{'PaperIDlength'}=$config[12];
 5483: 	$config{'FirstName'}=$config[13];
 5484: 	$config{'FirstNamelength'}=$config[14];
 5485: 	$config{'LastName'}=$config[15];
 5486: 	$config{'LastNamelength'}=$config[16];
 5487: 	last;
 5488:     }
 5489:     return %config;
 5490: }
 5491: 
 5492: =pod 
 5493: 
 5494: =item username_to_idmap
 5495: 
 5496:     creates a hash keyed by student/employee ID with values of the corresponding
 5497:     student username:domain.
 5498: 
 5499:   Arguments:
 5500: 
 5501:     $classlist - reference to the class list hash. This is a hash
 5502:                  keyed by student name:domain  whose elements are references
 5503:                  to arrays containing various chunks of information
 5504:                  about the student. (See loncoursedata for more info).
 5505: 
 5506:   Returns
 5507:     %idmap - the constructed hash
 5508: 
 5509: =cut
 5510: 
 5511: sub username_to_idmap {
 5512:     my ($classlist)= @_;
 5513:     my %idmap;
 5514:     foreach my $student (keys(%$classlist)) {
 5515: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5516: 	    $student;
 5517:     }
 5518:     return %idmap;
 5519: }
 5520: 
 5521: =pod
 5522: 
 5523: =item scantron_fixup_scanline
 5524: 
 5525:    Process a requested correction to a scanline.
 5526: 
 5527:   Arguments:
 5528:     $scantron_config   - hash from &get_scantron_config()
 5529:     $scan_data         - hash of correction information 
 5530:                           (see &scantron_getfile())
 5531:     $line              - existing scanline
 5532:     $whichline         - line number of the passed in scanline
 5533:     $field             - type of change to process 
 5534:                          (either 
 5535:                           'ID'     -> correct the student/employee ID
 5536:                           'CODE'   -> correct the CODE
 5537:                           'answer' -> fixup the submitted answers)
 5538:     
 5539:    $args               - hash of additional info,
 5540:                           - 'ID' 
 5541:                                'newid' -> studentID to use in replacement
 5542:                                           of existing one
 5543:                           - 'CODE' 
 5544:                                'CODE_ignore_dup' - set to true if duplicates
 5545:                                                    should be ignored.
 5546: 	                       'CODE' - is new code or 'use_unfound'
 5547:                                         if the existing unfound code should
 5548:                                         be used as is
 5549:                           - 'answer'
 5550:                                'response' - new answer or 'none' if blank
 5551:                                'question' - the bubble line to change
 5552:                                'questionnum' - the question identifier,
 5553:                                                may include subquestion. 
 5554: 
 5555:   Returns:
 5556:     $line - the modified scanline
 5557: 
 5558:   Side effects: 
 5559:     $scan_data - may be updated
 5560: 
 5561: =cut
 5562: 
 5563: 
 5564: sub scantron_fixup_scanline {
 5565:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5566:     if ($field eq 'ID') {
 5567: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5568: 	    return ($line,1,'New value too large');
 5569: 	}
 5570: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5571: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5572: 				     $args->{'newid'});
 5573: 	}
 5574: 	substr($line,$$scantron_config{'IDstart'}-1,
 5575: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5576: 	if ($args->{'newid'}=~/^\s*$/) {
 5577: 	    &scan_data($scan_data,"$whichline.user",
 5578: 		       $args->{'username'}.':'.$args->{'domain'});
 5579: 	}
 5580:     } elsif ($field eq 'CODE') {
 5581: 	if ($args->{'CODE_ignore_dup'}) {
 5582: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5583: 	}
 5584: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5585: 	if ($args->{'CODE'} ne 'use_unfound') {
 5586: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5587: 		return ($line,1,'New CODE value too large');
 5588: 	    }
 5589: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5590: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5591: 	    }
 5592: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5593: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5594: 	}
 5595:     } elsif ($field eq 'answer') {
 5596: 	my $length=$scantron_config->{'Qlength'};
 5597: 	my $off=$scantron_config->{'Qoff'};
 5598: 	my $on=$scantron_config->{'Qon'};
 5599: 	my $answer=${off}x$length;
 5600: 	if ($args->{'response'} eq 'none') {
 5601: 	    &scan_data($scan_data,
 5602: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5603: 	} else {
 5604: 	    if ($on eq 'letter') {
 5605: 		my @alphabet=('A'..'Z');
 5606: 		$answer=$alphabet[$args->{'response'}];
 5607: 	    } elsif ($on eq 'number') {
 5608: 		$answer=$args->{'response'}+1;
 5609: 		if ($answer == 10) { $answer = '0'; }
 5610: 	    } else {
 5611: 		substr($answer,$args->{'response'},1)=$on;
 5612: 	    }
 5613: 	    &scan_data($scan_data,
 5614: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5615: 	}
 5616: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5617: 	substr($line,$where-1,$length)=$answer;
 5618:     }
 5619:     return $line;
 5620: }
 5621: 
 5622: =pod
 5623: 
 5624: =item scan_data
 5625: 
 5626:     Edit or look up  an item in the scan_data hash.
 5627: 
 5628:   Arguments:
 5629:     $scan_data  - The hash (see scantron_getfile)
 5630:     $key        - shorthand of the key to edit (actual key is
 5631:                   scantronfilename_key).
 5632:     $data        - New value of the hash entry.
 5633:     $delete      - If true, the entry is removed from the hash.
 5634: 
 5635:   Returns:
 5636:     The new value of the hash table field (undefined if deleted).
 5637: 
 5638: =cut
 5639: 
 5640: 
 5641: sub scan_data {
 5642:     my ($scan_data,$key,$value,$delete)=@_;
 5643:     my $filename=$env{'form.scantron_selectfile'};
 5644:     if (defined($value)) {
 5645: 	$scan_data->{$filename.'_'.$key} = $value;
 5646:     }
 5647:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5648:     return $scan_data->{$filename.'_'.$key};
 5649: }
 5650: 
 5651: # ----- These first few routines are general use routines.----
 5652: 
 5653: # Return the number of occurences of a pattern in a string.
 5654: 
 5655: sub occurence_count {
 5656:     my ($string, $pattern) = @_;
 5657: 
 5658:     my @matches = ($string =~ /$pattern/g);
 5659: 
 5660:     return scalar(@matches);
 5661: }
 5662: 
 5663: 
 5664: # Take a string known to have digits and convert all the
 5665: # digits into letters in the range J,A..I.
 5666: 
 5667: sub digits_to_letters {
 5668:     my ($input) = @_;
 5669: 
 5670:     my @alphabet = ('J', 'A'..'I');
 5671: 
 5672:     my @input    = split(//, $input);
 5673:     my $output ='';
 5674:     for (my $i = 0; $i < scalar(@input); $i++) {
 5675: 	if ($input[$i] =~ /\d/) {
 5676: 	    $output .= $alphabet[$input[$i]];
 5677: 	} else {
 5678: 	    $output .= $input[$i];
 5679: 	}
 5680:     }
 5681:     return $output;
 5682: }
 5683: 
 5684: =pod 
 5685: 
 5686: =item scantron_parse_scanline
 5687: 
 5688:   Decodes a scanline from the selected scantron file
 5689: 
 5690:  Arguments:
 5691:     line             - The text of the scantron file line to process
 5692:     whichline        - Line number
 5693:     scantron_config  - Hash describing the format of the scantron lines.
 5694:     scan_data        - Hash of extra information about the scanline
 5695:                        (see scantron_getfile for more information)
 5696:     just_header      - True if should not process question answers but only
 5697:                        the stuff to the left of the answers.
 5698:  Returns:
 5699:    Hash containing the result of parsing the scanline
 5700: 
 5701:    Keys are all proceeded by the string 'scantron.'
 5702: 
 5703:        CODE    - the CODE in use for this scanline
 5704:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5705:                  by the operator
 5706:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5707:                             CODEs were selected, but the usage has been
 5708:                             forced by the operator
 5709:        ID  - student/employee ID
 5710:        PaperID - if used, the ID number printed on the sheet when the 
 5711:                  paper was scanned
 5712:        FirstName - first name from the sheet
 5713:        LastName  - last name from the sheet
 5714: 
 5715:      if just_header was not true these key may also exist
 5716: 
 5717:        missingerror - a list of bubble ranges that are considered to be answers
 5718:                       to a single question that don't have any bubbles filled in.
 5719:                       Of the form questionnumber:firstbubblenumber:count.
 5720:        doubleerror  - a list of bubble ranges that are considered to be answers
 5721:                       to a single question that have more than one bubble filled in.
 5722:                       Of the form questionnumber::firstbubblenumber:count
 5723:    
 5724:                 In the above, count is the number of bubble responses in the
 5725:                 input line needed to represent the possible answers to the question.
 5726:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5727:                 per line would have count = 2.
 5728: 
 5729:        maxquest     - the number of the last bubble line that was parsed
 5730: 
 5731:        (<number> starts at 1)
 5732:        <number>.answer - zero or more letters representing the selected
 5733:                          letters from the scanline for the bubble line 
 5734:                          <number>.
 5735:                          if blank there was either no bubble or there where
 5736:                          multiple bubbles, (consult the keys missingerror and
 5737:                          doubleerror if this is an error condition)
 5738: 
 5739: =cut
 5740: 
 5741: sub scantron_parse_scanline {
 5742:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5743: 
 5744:     my %record;
 5745:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5746:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5747:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5748:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5749: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5750: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5751: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5752: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5753: 	    $record{'scantron.CODE'}=substr($data,
 5754: 					    $$scantron_config{'CODEstart'}-1,
 5755: 					    $$scantron_config{'CODElength'});
 5756: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5757: 		$record{'scantron.useCODE'}=1;
 5758: 	    }
 5759: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5760: 		$record{'scantron.CODE_ignore_dup'}=1;
 5761: 	    }
 5762: 	} else {
 5763: 	    #FIXME interpret first N questions
 5764: 	}
 5765:     }
 5766:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5767: 				  $$scantron_config{'IDlength'});
 5768:     $record{'scantron.PaperID'}=
 5769: 	substr($data,$$scantron_config{'PaperID'}-1,
 5770: 	       $$scantron_config{'PaperIDlength'});
 5771:     $record{'scantron.FirstName'}=
 5772: 	substr($data,$$scantron_config{'FirstName'}-1,
 5773: 	       $$scantron_config{'FirstNamelength'});
 5774:     $record{'scantron.LastName'}=
 5775: 	substr($data,$$scantron_config{'LastName'}-1,
 5776: 	       $$scantron_config{'LastNamelength'});
 5777:     if ($just_header) { return \%record; }
 5778: 
 5779:     my @alphabet=('A'..'Z');
 5780:     my $questnum=0;
 5781:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5782: 
 5783:     chomp($questions);		# Get rid of any trailing \n.
 5784:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5785:     while (length($questions)) {
 5786: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5787:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5788:                              || 1;
 5789:         $questnum++;
 5790:         my $quest_id = $questnum;
 5791:         my $currentquest = substr($questions,0,$answer_length);
 5792:         $questions       = substr($questions,$answer_length);
 5793:         if (length($currentquest) < $answer_length) { next; }
 5794: 
 5795:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5796:             my $subquestnum = 1;
 5797:             my $subquestions = $currentquest;
 5798:             my @subanswers_needed = 
 5799:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5800:             foreach my $subans (@subanswers_needed) {
 5801:                 my $subans_length =
 5802:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5803:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5804:                 $subquestions   = substr($subquestions,$subans_length);
 5805:                 $quest_id = "$questnum.$subquestnum";
 5806:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5807:                     ($$scantron_config{'Qon'} eq 'number')) {
 5808:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5809:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5810:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5811:                 } else {
 5812:                     $ansnum = &scantron_validator_positional($ansnum,
 5813:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5814:                 }
 5815:                 $subquestnum ++;
 5816:             }
 5817:         } else {
 5818:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5819:                 ($$scantron_config{'Qon'} eq 'number')) {
 5820:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5821:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5822:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5823:             } else {
 5824:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5825:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5826:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5827:             }
 5828:         }
 5829:     }
 5830:     $record{'scantron.maxquest'}=$questnum;
 5831:     return \%record;
 5832: }
 5833: 
 5834: sub scantron_validator_lettnum {
 5835:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5836:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5837: 
 5838:     # Qon 'letter' implies for each slot in currquest we have:
 5839:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5840:     #    about anything else (esp. a value of Qoff) for missing
 5841:     #    bubbles.
 5842:     #
 5843:     # Qon 'number' implies each slot gives a digit that indexes the
 5844:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5845:     #    and * or ? for double bubbles on a single line.
 5846:     #
 5847: 
 5848:     my $matchon;
 5849:     if ($$scantron_config{'Qon'} eq 'letter') {
 5850:         $matchon = '[A-Z]';
 5851:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5852:         $matchon = '\d';
 5853:     }
 5854:     my $occurrences = 0;
 5855:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5856:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5857:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5858:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5859:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5860:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5861:         my @singlelines = split('',$currquest);
 5862:         foreach my $entry (@singlelines) {
 5863:             $occurrences = &occurence_count($entry,$matchon);
 5864:             if ($occurrences > 1) {
 5865:                 last;
 5866:             }
 5867:         } 
 5868:     } else {
 5869:         $occurrences = &occurence_count($currquest,$matchon); 
 5870:     }
 5871:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5872:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5873:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5874:             my $bubble = substr($currquest,$ans,1);
 5875:             if ($bubble =~ /$matchon/ ) {
 5876:                 if ($$scantron_config{'Qon'} eq 'number') {
 5877:                     if ($bubble == 0) {
 5878:                         $bubble = 10; 
 5879:                     }
 5880:                     $record->{"scantron.$ansnum.answer"} = 
 5881:                         $alphabet->[$bubble-1];
 5882:                 } else {
 5883:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5884:                 }
 5885:             } else {
 5886:                 $record->{"scantron.$ansnum.answer"}='';
 5887:             }
 5888:             $ansnum++;
 5889:         }
 5890:     } elsif (!defined($currquest)
 5891:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5892:             || (&occurence_count($currquest,$matchon) == 0)) {
 5893:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5894:             $record->{"scantron.$ansnum.answer"}='';
 5895:             $ansnum++;
 5896:         }
 5897:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5898:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5899:         }
 5900:     } else {
 5901:         if ($$scantron_config{'Qon'} eq 'number') {
 5902:             $currquest = &digits_to_letters($currquest);            
 5903:         }
 5904:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5905:             my $bubble = substr($currquest,$ans,1);
 5906:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5907:             $ansnum++;
 5908:         }
 5909:     }
 5910:     return $ansnum;
 5911: }
 5912: 
 5913: sub scantron_validator_positional {
 5914:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5915:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5916: 
 5917:     # Otherwise there's a positional notation;
 5918:     # each bubble line requires Qlength items, and there are filled in
 5919:     # bubbles for each case where there 'Qon' characters.
 5920:     #
 5921: 
 5922:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5923: 
 5924:     # If the split only gives us one element.. the full length of the
 5925:     # answer string, no bubbles are filled in:
 5926: 
 5927:     if ($answers_needed eq '') {
 5928:         return;
 5929:     }
 5930: 
 5931:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5932:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5933:             $record->{"scantron.$ansnum.answer"}='';
 5934:             $ansnum++;
 5935:         }
 5936:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5937:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5938:         }
 5939:     } elsif (scalar(@array) == 2) {
 5940:         my $location = length($array[0]);
 5941:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5942:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5943:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5944:             if ($ans eq $line_num) {
 5945:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5946:             } else {
 5947:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5948:             }
 5949:             $ansnum++;
 5950:          }
 5951:     } else {
 5952:         #  If there's more than one instance of a bubble character
 5953:         #  That's a double bubble; with positional notation we can
 5954:         #  record all the bubbles filled in as well as the
 5955:         #  fact this response consists of multiple bubbles.
 5956:         #
 5957:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5958:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5959:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5960:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5961:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5962:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5963:             my $doubleerror = 0;
 5964:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5965:                    (!$doubleerror)) {
 5966:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5967:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5968:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5969:                if (length(@currarray) > 2) {
 5970:                    $doubleerror = 1;
 5971:                } 
 5972:             }
 5973:             if ($doubleerror) {
 5974:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5975:             }
 5976:         } else {
 5977:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5978:         }
 5979:         my $item = $ansnum;
 5980:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5981:             $record->{"scantron.$item.answer"} = '';
 5982:             $item ++;
 5983:         }
 5984: 
 5985:         my @ans=@array;
 5986:         my $i=0;
 5987:         my $increment = 0;
 5988:         while ($#ans) {
 5989:             $i+=length($ans[0]) + $increment;
 5990:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5991:             my $bubble = $i%$$scantron_config{'Qlength'};
 5992:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5993:             shift(@ans);
 5994:             $increment = 1;
 5995:         }
 5996:         $ansnum += $answers_needed;
 5997:     }
 5998:     return $ansnum;
 5999: }
 6000: 
 6001: =pod
 6002: 
 6003: =item scantron_add_delay
 6004: 
 6005:    Adds an error message that occurred during the grading phase to a
 6006:    queue of messages to be shown after grading pass is complete
 6007: 
 6008:  Arguments:
 6009:    $delayqueue  - arrary ref of hash ref of error messages
 6010:    $scanline    - the scanline that caused the error
 6011:    $errormesage - the error message
 6012:    $errorcode   - a numeric code for the error
 6013: 
 6014:  Side Effects:
 6015:    updates the $delayqueue to have a new hash ref of the error
 6016: 
 6017: =cut
 6018: 
 6019: sub scantron_add_delay {
 6020:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6021:     push(@$delayqueue,
 6022: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6023: 	  'ecode' => $errorcode }
 6024: 	 );
 6025: }
 6026: 
 6027: =pod
 6028: 
 6029: =item scantron_find_student
 6030: 
 6031:    Finds the username for the current scanline
 6032: 
 6033:   Arguments:
 6034:    $scantron_record - hash result from scantron_parse_scanline
 6035:    $scan_data       - hash of correction information 
 6036:                       (see &scantron_getfile() form more information)
 6037:    $idmap           - hash from &username_to_idmap()
 6038:    $line            - number of current scanline
 6039:  
 6040:   Returns:
 6041:    Either 'username:domain' or undef if unknown
 6042: 
 6043: =cut
 6044: 
 6045: sub scantron_find_student {
 6046:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6047:     my $scanID=$$scantron_record{'scantron.ID'};
 6048:     if ($scanID =~ /^\s*$/) {
 6049:  	return &scan_data($scan_data,"$line.user");
 6050:     }
 6051:     foreach my $id (keys(%$idmap)) {
 6052:  	if (lc($id) eq lc($scanID)) {
 6053:  	    return $$idmap{$id};
 6054:  	}
 6055:     }
 6056:     return undef;
 6057: }
 6058: 
 6059: =pod
 6060: 
 6061: =item scantron_filter
 6062: 
 6063:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6064:    hidden resources was selected
 6065: 
 6066: =cut
 6067: 
 6068: sub scantron_filter {
 6069:     my ($curres)=@_;
 6070: 
 6071:     if (ref($curres) && $curres->is_problem()) {
 6072: 	# if the user has asked to not have either hidden
 6073: 	# or 'randomout' controlled resources to be graded
 6074: 	# don't include them
 6075: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6076: 	    && $curres->randomout) {
 6077: 	    return 0;
 6078: 	}
 6079: 	return 1;
 6080:     }
 6081:     return 0;
 6082: }
 6083: 
 6084: =pod
 6085: 
 6086: =item scantron_process_corrections
 6087: 
 6088:    Gets correction information out of submitted form data and corrects
 6089:    the scanline
 6090: 
 6091: =cut
 6092: 
 6093: sub scantron_process_corrections {
 6094:     my ($r) = @_;
 6095:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6096:     my ($scanlines,$scan_data)=&scantron_getfile();
 6097:     my $classlist=&Apache::loncoursedata::get_classlist();
 6098:     my $which=$env{'form.scantron_line'};
 6099:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6100:     my ($skip,$err,$errmsg);
 6101:     if ($env{'form.scantron_skip_record'}) {
 6102: 	$skip=1;
 6103:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6104: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6105: 	    $env{'form.scantron_domain'};
 6106: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6107: 	($line,$err,$errmsg)=
 6108: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6109: 				     'ID',{'newid'=>$newid,
 6110: 				    'username'=>$env{'form.scantron_username'},
 6111: 				    'domain'=>$env{'form.scantron_domain'}});
 6112:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6113: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6114: 	my $newCODE;
 6115: 	my %args;
 6116: 	if      ($resolution eq 'use_unfound') {
 6117: 	    $newCODE='use_unfound';
 6118: 	} elsif ($resolution eq 'use_found') {
 6119: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6120: 	} elsif ($resolution eq 'use_typed') {
 6121: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6122: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6123: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6124: 	}
 6125: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6126: 	    $args{'CODE_ignore_dup'}=1;
 6127: 	}
 6128: 	$args{'CODE'}=$newCODE;
 6129: 	($line,$err,$errmsg)=
 6130: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6131: 				     'CODE',\%args);
 6132:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6133: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6134: 	    ($line,$err,$errmsg)=
 6135: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6136: 					 $which,'answer',
 6137: 					 { 'question'=>$question,
 6138: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6139:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6140: 	    if ($err) { last; }
 6141: 	}
 6142:     }
 6143:     if ($err) {
 6144: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6145:     } else {
 6146: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6147: 	&scantron_putfile($scanlines,$scan_data);
 6148:     }
 6149: }
 6150: 
 6151: =pod
 6152: 
 6153: =item reset_skipping_status
 6154: 
 6155:    Forgets the current set of remember skipped scanlines (and thus
 6156:    reverts back to considering all lines in the
 6157:    scantron_skipped_<filename> file)
 6158: 
 6159: =cut
 6160: 
 6161: sub reset_skipping_status {
 6162:     my ($scanlines,$scan_data)=&scantron_getfile();
 6163:     &scan_data($scan_data,'remember_skipping',undef,1);
 6164:     &scantron_putfile(undef,$scan_data);
 6165: }
 6166: 
 6167: =pod
 6168: 
 6169: =item start_skipping
 6170: 
 6171:    Marks a scanline to be skipped. 
 6172: 
 6173: =cut
 6174: 
 6175: sub start_skipping {
 6176:     my ($scan_data,$i)=@_;
 6177:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6178:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6179: 	$remembered{$i}=2;
 6180:     } else {
 6181: 	$remembered{$i}=1;
 6182:     }
 6183:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6184: }
 6185: 
 6186: =pod
 6187: 
 6188: =item should_be_skipped
 6189: 
 6190:    Checks whether a scanline should be skipped.
 6191: 
 6192: =cut
 6193: 
 6194: sub should_be_skipped {
 6195:     my ($scanlines,$scan_data,$i)=@_;
 6196:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6197: 	# not redoing old skips
 6198: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6199: 	return 0;
 6200:     }
 6201:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6202: 
 6203:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6204: 	return 0;
 6205:     }
 6206:     return 1;
 6207: }
 6208: 
 6209: =pod
 6210: 
 6211: =item remember_current_skipped
 6212: 
 6213:    Discovers what scanlines are in the scantron_skipped_<filename>
 6214:    file and remembers them into scan_data for later use.
 6215: 
 6216: =cut
 6217: 
 6218: sub remember_current_skipped {
 6219:     my ($scanlines,$scan_data)=&scantron_getfile();
 6220:     my %to_remember;
 6221:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6222: 	if ($scanlines->{'skipped'}[$i]) {
 6223: 	    $to_remember{$i}=1;
 6224: 	}
 6225:     }
 6226: 
 6227:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6228:     &scantron_putfile(undef,$scan_data);
 6229: }
 6230: 
 6231: =pod
 6232: 
 6233: =item check_for_error
 6234: 
 6235:     Checks if there was an error when attempting to remove a specific
 6236:     scantron_.. bubble sheet data file. Prints out an error if
 6237:     something went wrong.
 6238: 
 6239: =cut
 6240: 
 6241: sub check_for_error {
 6242:     my ($r,$result)=@_;
 6243:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6244: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6245:     }
 6246: }
 6247: 
 6248: =pod
 6249: 
 6250: =item scantron_warning_screen
 6251: 
 6252:    Interstitial screen to make sure the operator has selected the
 6253:    correct options before we start the validation phase.
 6254: 
 6255: =cut
 6256: 
 6257: sub scantron_warning_screen {
 6258:     my ($button_text)=@_;
 6259:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6260:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6261:     my $CODElist;
 6262:     if ($scantron_config{'CODElocation'} &&
 6263: 	$scantron_config{'CODEstart'} &&
 6264: 	$scantron_config{'CODElength'}) {
 6265: 	$CODElist=$env{'form.scantron_CODElist'};
 6266: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6267: 	$CODElist=
 6268: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6269: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6270:     }
 6271:     return ('
 6272: <p>
 6273: <span class="LC_warning">
 6274: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6275: </p>
 6276: <table>
 6277: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6278: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6279: '.$CODElist.'
 6280: </table>
 6281: <br />
 6282: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6283: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6284: 
 6285: <br />
 6286: ');
 6287: }
 6288: 
 6289: =pod
 6290: 
 6291: =item scantron_do_warning
 6292: 
 6293:    Check if the operator has picked something for all required
 6294:    fields. Error out if something is missing.
 6295: 
 6296: =cut
 6297: 
 6298: sub scantron_do_warning {
 6299:     my ($r)=@_;
 6300:     my ($symb)=&get_symb($r);
 6301:     if (!$symb) {return '';}
 6302:     my $default_form_data=&defaultFormData($symb);
 6303:     $r->print(&scantron_form_start().$default_form_data);
 6304:     if ( $env{'form.selectpage'} eq '' ||
 6305: 	 $env{'form.scantron_selectfile'} eq '' ||
 6306: 	 $env{'form.scantron_format'} eq '' ) {
 6307: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6308: 	if ( $env{'form.selectpage'} eq '') {
 6309: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6310: 	} 
 6311: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6312: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6313: 	} 
 6314: 	if ( $env{'form.scantron_format'} eq '') {
 6315: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6316: 	} 
 6317:     } else {
 6318: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6319: 	$r->print('
 6320: '.$warning.'
 6321: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6322: <input type="hidden" name="command" value="scantron_validate" />
 6323: ');
 6324:     }
 6325:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6326:     return '';
 6327: }
 6328: 
 6329: =pod
 6330: 
 6331: =item scantron_form_start
 6332: 
 6333:     html hidden input for remembering all selected grading options
 6334: 
 6335: =cut
 6336: 
 6337: sub scantron_form_start {
 6338:     my ($max_bubble)=@_;
 6339:     my $result= <<SCANTRONFORM;
 6340: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6341:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6342:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6343:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6344:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6345:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6346:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6347:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6348:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6349:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6350: SCANTRONFORM
 6351: 
 6352:   my $line = 0;
 6353:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6354:        my $chunk =
 6355: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6356:        $chunk .=
 6357: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6358:        $chunk .= 
 6359:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6360:        $chunk .=
 6361:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6362:        $result .= $chunk;
 6363:        $line++;
 6364:    }
 6365:     return $result;
 6366: }
 6367: 
 6368: =pod
 6369: 
 6370: =item scantron_validate_file
 6371: 
 6372:     Dispatch routine for doing validation of a bubble sheet data file.
 6373: 
 6374:     Also processes any necessary information resets that need to
 6375:     occur before validation begins (ignore previous corrections,
 6376:     restarting the skipped records processing)
 6377: 
 6378: =cut
 6379: 
 6380: sub scantron_validate_file {
 6381:     my ($r) = @_;
 6382:     my ($symb)=&get_symb($r);
 6383:     if (!$symb) {return '';}
 6384:     my $default_form_data=&defaultFormData($symb);
 6385:     
 6386:     # do the detection of only doing skipped records first befroe we delete
 6387:     # them when doing the corrections reset
 6388:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6389: 	&reset_skipping_status();
 6390:     }
 6391:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6392: 	&remember_current_skipped();
 6393: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6394:     }
 6395: 
 6396:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6397: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6398: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6399: 	&check_for_error($r,&scantron_remove_scan_data());
 6400: 	$env{'form.scantron_options_ignore'}='done';
 6401:     }
 6402: 
 6403:     if ($env{'form.scantron_corrections'}) {
 6404: 	&scantron_process_corrections($r);
 6405:     }
 6406:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6407:     #get the student pick code ready
 6408:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6409:     my $nav_error;
 6410:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6411:     if ($nav_error) {
 6412:         $r->print(&navmap_errormsg());
 6413:         return '';
 6414:     }
 6415:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6416:     $r->print($result);
 6417:     
 6418:     my @validate_phases=( 'sequence',
 6419: 			  'ID',
 6420: 			  'CODE',
 6421: 			  'doublebubble',
 6422: 			  'missingbubbles');
 6423:     if (!$env{'form.validatepass'}) {
 6424: 	$env{'form.validatepass'} = 0;
 6425:     }
 6426:     my $currentphase=$env{'form.validatepass'};
 6427: 
 6428: 
 6429:     my $stop=0;
 6430:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6431: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6432: 	$r->rflush();
 6433: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6434: 	{
 6435: 	    no strict 'refs';
 6436: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6437: 	}
 6438:     }
 6439:     if (!$stop) {
 6440: 	my $warning=&scantron_warning_screen('Start Grading');
 6441: 	$r->print(&mt('Validation process complete.').'<br />'.
 6442:                   $warning.
 6443:                   &mt('Perform verification for each student after storage of submissions?').
 6444:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6445:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6446:                   ('&nbsp;'x3).'<label>'.
 6447:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6448:                   '</label></span><br />'.
 6449:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6450:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6451:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6452:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6453:     } else {
 6454: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6455: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6456:     }
 6457:     if ($stop) {
 6458: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6459: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6460: 	    $r->print(' '.&mt('this error').' <br />');
 6461: 
 6462: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6463: 	} else {
 6464:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6465: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6466:             } else {
 6467:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6468:             }
 6469: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6470: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6471: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6472: 	}
 6473:     }
 6474:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6475:     return '';
 6476: }
 6477: 
 6478: 
 6479: =pod
 6480: 
 6481: =item scantron_remove_file
 6482: 
 6483:    Removes the requested bubble sheet data file, makes sure that
 6484:    scantron_original_<filename> is never removed
 6485: 
 6486: 
 6487: =cut
 6488: 
 6489: sub scantron_remove_file {
 6490:     my ($which)=@_;
 6491:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6492:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6493:     my $file='scantron_';
 6494:     if ($which eq 'corrected' || $which eq 'skipped') {
 6495: 	$file.=$which.'_';
 6496:     } else {
 6497: 	return 'refused';
 6498:     }
 6499:     $file.=$env{'form.scantron_selectfile'};
 6500:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6501: }
 6502: 
 6503: 
 6504: =pod
 6505: 
 6506: =item scantron_remove_scan_data
 6507: 
 6508:    Removes all scan_data correction for the requested bubble sheet
 6509:    data file.  (In the case that both the are doing skipped records we need
 6510:    to remember the old skipped lines for the time being so that element
 6511:    persists for a while.)
 6512: 
 6513: =cut
 6514: 
 6515: sub scantron_remove_scan_data {
 6516:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6517:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6518:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6519:     my @todelete;
 6520:     my $filename=$env{'form.scantron_selectfile'};
 6521:     foreach my $key (@keys) {
 6522: 	if ($key=~/^\Q$filename\E_/) {
 6523: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6524: 		$key=~/remember_skipping/) {
 6525: 		next;
 6526: 	    }
 6527: 	    push(@todelete,$key);
 6528: 	}
 6529:     }
 6530:     my $result;
 6531:     if (@todelete) {
 6532: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6533: 				       \@todelete,$cdom,$cname);
 6534:     } else {
 6535: 	$result = 'ok';
 6536:     }
 6537:     return $result;
 6538: }
 6539: 
 6540: 
 6541: =pod
 6542: 
 6543: =item scantron_getfile
 6544: 
 6545:     Fetches the requested bubble sheet data file (all 3 versions), and
 6546:     the scan_data hash
 6547:   
 6548:   Arguments:
 6549:     None
 6550: 
 6551:   Returns:
 6552:     2 hash references
 6553: 
 6554:      - first one has 
 6555:          orig      -
 6556:          corrected -
 6557:          skipped   -  each of which points to an array ref of the specified
 6558:                       file broken up into individual lines
 6559:          count     - number of scanlines
 6560:  
 6561:      - second is the scan_data hash possible keys are
 6562:        ($number refers to scanline numbered $number and thus the key affects
 6563:         only that scanline
 6564:         $bubline refers to the specific bubble line element and the aspects
 6565:         refers to that specific bubble line element)
 6566: 
 6567:        $number.user - username:domain to use
 6568:        $number.CODE_ignore_dup 
 6569:                     - ignore the duplicate CODE error 
 6570:        $number.useCODE
 6571:                     - use the CODE in the scanline as is
 6572:        $number.no_bubble.$bubline
 6573:                     - it is valid that there is no bubbled in bubble
 6574:                       at $number $bubline
 6575:        remember_skipping
 6576:                     - a frozen hash containing keys of $number and values
 6577:                       of either 
 6578:                         1 - we are on a 'do skipped records pass' and plan
 6579:                             on processing this line
 6580:                         2 - we are on a 'do skipped records pass' and this
 6581:                             scanline has been marked to skip yet again
 6582: 
 6583: =cut
 6584: 
 6585: sub scantron_getfile {
 6586:     #FIXME really would prefer a scantron directory
 6587:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6588:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6589:     my $lines;
 6590:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6591: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6592:     my %scanlines;
 6593:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6594:     my $temp=$scanlines{'orig'};
 6595:     $scanlines{'count'}=$#$temp;
 6596: 
 6597:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6598: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6599:     if ($lines eq '-1') {
 6600: 	$scanlines{'corrected'}=[];
 6601:     } else {
 6602: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6603:     }
 6604:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6605: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6606:     if ($lines eq '-1') {
 6607: 	$scanlines{'skipped'}=[];
 6608:     } else {
 6609: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6610:     }
 6611:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6612:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6613:     my %scan_data = @tmp;
 6614:     return (\%scanlines,\%scan_data);
 6615: }
 6616: 
 6617: =pod
 6618: 
 6619: =item lonnet_putfile
 6620: 
 6621:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6622: 
 6623:  Arguments:
 6624:    $contents - data to store
 6625:    $filename - filename to store $contents into
 6626: 
 6627:  Returns:
 6628:    result value from &Apache::lonnet::finishuserfileupload
 6629: 
 6630: =cut
 6631: 
 6632: sub lonnet_putfile {
 6633:     my ($contents,$filename)=@_;
 6634:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6635:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6636:     $env{'form.sillywaytopassafilearound'}=$contents;
 6637:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6638: 
 6639: }
 6640: 
 6641: =pod
 6642: 
 6643: =item scantron_putfile
 6644: 
 6645:     Stores the current version of the bubble sheet data files, and the
 6646:     scan_data hash. (Does not modify the original version only the
 6647:     corrected and skipped versions.
 6648: 
 6649:  Arguments:
 6650:     $scanlines - hash ref that looks like the first return value from
 6651:                  &scantron_getfile()
 6652:     $scan_data - hash ref that looks like the second return value from
 6653:                  &scantron_getfile()
 6654: 
 6655: =cut
 6656: 
 6657: sub scantron_putfile {
 6658:     my ($scanlines,$scan_data) = @_;
 6659:     #FIXME really would prefer a scantron directory
 6660:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6661:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6662:     if ($scanlines) {
 6663: 	my $prefix='scantron_';
 6664: # no need to update orig, shouldn't change
 6665: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6666: #		    $env{'form.scantron_selectfile'});
 6667: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6668: 			$prefix.'corrected_'.
 6669: 			$env{'form.scantron_selectfile'});
 6670: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6671: 			$prefix.'skipped_'.
 6672: 			$env{'form.scantron_selectfile'});
 6673:     }
 6674:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6675: }
 6676: 
 6677: =pod
 6678: 
 6679: =item scantron_get_line
 6680: 
 6681:    Returns the correct version of the scanline
 6682: 
 6683:  Arguments:
 6684:     $scanlines - hash ref that looks like the first return value from
 6685:                  &scantron_getfile()
 6686:     $scan_data - hash ref that looks like the second return value from
 6687:                  &scantron_getfile()
 6688:     $i         - number of the requested line (starts at 0)
 6689: 
 6690:  Returns:
 6691:    A scanline, (either the original or the corrected one if it
 6692:    exists), or undef if the requested scanline should be
 6693:    skipped. (Either because it's an skipped scanline, or it's an
 6694:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6695:    pass.
 6696: 
 6697: =cut
 6698: 
 6699: sub scantron_get_line {
 6700:     my ($scanlines,$scan_data,$i)=@_;
 6701:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6702:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6703:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6704:     return $scanlines->{'orig'}[$i]; 
 6705: }
 6706: 
 6707: =pod
 6708: 
 6709: =item scantron_todo_count
 6710: 
 6711:     Counts the number of scanlines that need processing.
 6712: 
 6713:  Arguments:
 6714:     $scanlines - hash ref that looks like the first return value from
 6715:                  &scantron_getfile()
 6716:     $scan_data - hash ref that looks like the second return value from
 6717:                  &scantron_getfile()
 6718: 
 6719:  Returns:
 6720:     $count - number of scanlines to process
 6721: 
 6722: =cut
 6723: 
 6724: sub get_todo_count {
 6725:     my ($scanlines,$scan_data)=@_;
 6726:     my $count=0;
 6727:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6728: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6729: 	if ($line=~/^[\s\cz]*$/) { next; }
 6730: 	$count++;
 6731:     }
 6732:     return $count;
 6733: }
 6734: 
 6735: =pod
 6736: 
 6737: =item scantron_put_line
 6738: 
 6739:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6740:     data file.
 6741: 
 6742:  Arguments:
 6743:     $scanlines - hash ref that looks like the first return value from
 6744:                  &scantron_getfile()
 6745:     $scan_data - hash ref that looks like the second return value from
 6746:                  &scantron_getfile()
 6747:     $i         - line number to update
 6748:     $newline   - contents of the updated scanline
 6749:     $skip      - if true make the line for skipping and update the
 6750:                  'skipped' file
 6751: 
 6752: =cut
 6753: 
 6754: sub scantron_put_line {
 6755:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6756:     if ($skip) {
 6757: 	$scanlines->{'skipped'}[$i]=$newline;
 6758: 	&start_skipping($scan_data,$i);
 6759: 	return;
 6760:     }
 6761:     $scanlines->{'corrected'}[$i]=$newline;
 6762: }
 6763: 
 6764: =pod
 6765: 
 6766: =item scantron_clear_skip
 6767: 
 6768:    Remove a line from the 'skipped' file
 6769: 
 6770:  Arguments:
 6771:     $scanlines - hash ref that looks like the first return value from
 6772:                  &scantron_getfile()
 6773:     $scan_data - hash ref that looks like the second return value from
 6774:                  &scantron_getfile()
 6775:     $i         - line number to update
 6776: 
 6777: =cut
 6778: 
 6779: sub scantron_clear_skip {
 6780:     my ($scanlines,$scan_data,$i)=@_;
 6781:     if (exists($scanlines->{'skipped'}[$i])) {
 6782: 	undef($scanlines->{'skipped'}[$i]);
 6783: 	return 1;
 6784:     }
 6785:     return 0;
 6786: }
 6787: 
 6788: =pod
 6789: 
 6790: =item scantron_filter_not_exam
 6791: 
 6792:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6793:    filter out resources that are not marked as 'exam' mode
 6794: 
 6795: =cut
 6796: 
 6797: sub scantron_filter_not_exam {
 6798:     my ($curres)=@_;
 6799:     
 6800:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6801: 	# if the user has asked to not have either hidden
 6802: 	# or 'randomout' controlled resources to be graded
 6803: 	# don't include them
 6804: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6805: 	    && $curres->randomout) {
 6806: 	    return 0;
 6807: 	}
 6808: 	return 1;
 6809:     }
 6810:     return 0;
 6811: }
 6812: 
 6813: =pod
 6814: 
 6815: =item scantron_validate_sequence
 6816: 
 6817:     Validates the selected sequence, checking for resource that are
 6818:     not set to exam mode.
 6819: 
 6820: =cut
 6821: 
 6822: sub scantron_validate_sequence {
 6823:     my ($r,$currentphase) = @_;
 6824: 
 6825:     my $navmap=Apache::lonnavmaps::navmap->new();
 6826:     unless (ref($navmap)) {
 6827:         $r->print(&navmap_errormsg());
 6828:         return (1,$currentphase);
 6829:     }
 6830:     my (undef,undef,$sequence)=
 6831: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6832: 
 6833:     my $map=$navmap->getResourceByUrl($sequence);
 6834: 
 6835:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6836:                                     value="ignore" />');
 6837:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6838: 	my @resources=
 6839: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6840: 	if (@resources) {
 6841: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
 6842: 	    return (1,$currentphase);
 6843: 	}
 6844:     }
 6845: 
 6846:     return (0,$currentphase+1);
 6847: }
 6848: 
 6849: 
 6850: 
 6851: sub scantron_validate_ID {
 6852:     my ($r,$currentphase) = @_;
 6853:     
 6854:     #get student info
 6855:     my $classlist=&Apache::loncoursedata::get_classlist();
 6856:     my %idmap=&username_to_idmap($classlist);
 6857: 
 6858:     #get scantron line setup
 6859:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6860:     my ($scanlines,$scan_data)=&scantron_getfile();
 6861: 
 6862:     my $nav_error;
 6863:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6864:     if ($nav_error) {
 6865:         $r->print(&navmap_errormsg());
 6866:         return(1,$currentphase);
 6867:     }
 6868: 
 6869:     my %found=('ids'=>{},'usernames'=>{});
 6870:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6871: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6872: 	if ($line=~/^[\s\cz]*$/) { next; }
 6873: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6874: 						 $scan_data);
 6875: 	my $id=$$scan_record{'scantron.ID'};
 6876: 	my $found;
 6877: 	foreach my $checkid (keys(%idmap)) {
 6878: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6879: 	}
 6880: 	if ($found) {
 6881: 	    my $username=$idmap{$found};
 6882: 	    if ($found{'ids'}{$found}) {
 6883: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6884: 					 $line,'duplicateID',$found);
 6885: 		return(1,$currentphase);
 6886: 	    } elsif ($found{'usernames'}{$username}) {
 6887: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6888: 					 $line,'duplicateID',$username);
 6889: 		return(1,$currentphase);
 6890: 	    }
 6891: 	    #FIXME store away line we previously saw the ID on to use above
 6892: 	    $found{'ids'}{$found}++;
 6893: 	    $found{'usernames'}{$username}++;
 6894: 	} else {
 6895: 	    if ($id =~ /^\s*$/) {
 6896: 		my $username=&scan_data($scan_data,"$i.user");
 6897: 		if (defined($username) && $found{'usernames'}{$username}) {
 6898: 		    &scantron_get_correction($r,$i,$scan_record,
 6899: 					     \%scantron_config,
 6900: 					     $line,'duplicateID',$username);
 6901: 		    return(1,$currentphase);
 6902: 		} elsif (!defined($username)) {
 6903: 		    &scantron_get_correction($r,$i,$scan_record,
 6904: 					     \%scantron_config,
 6905: 					     $line,'incorrectID');
 6906: 		    return(1,$currentphase);
 6907: 		}
 6908: 		$found{'usernames'}{$username}++;
 6909: 	    } else {
 6910: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6911: 					 $line,'incorrectID');
 6912: 		return(1,$currentphase);
 6913: 	    }
 6914: 	}
 6915:     }
 6916: 
 6917:     return (0,$currentphase+1);
 6918: }
 6919: 
 6920: 
 6921: sub scantron_get_correction {
 6922:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6923: #FIXME in the case of a duplicated ID the previous line, probably need
 6924: #to show both the current line and the previous one and allow skipping
 6925: #the previous one or the current one
 6926: 
 6927:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6928: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6929: 			    " for PaperID <tt>[_1]</tt>",
 6930: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6931:     } else {
 6932: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6933: 			    " in scanline [_1] <pre>[_2]</pre>",
 6934: 			    $i,$line)."</p> \n");
 6935:     }
 6936:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6937: 			  "The name on the paper is [_2],[_3]",
 6938: 			  $$scan_record{'scantron.ID'},
 6939: 			  $$scan_record{'scantron.LastName'},
 6940: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6941: 
 6942:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6943:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6944:                            # Array populated for doublebubble or
 6945:     my @lines_to_correct;  # missingbubble errors to build javascript
 6946:                            # to validate radio button checking   
 6947: 
 6948:     if ($error =~ /ID$/) {
 6949: 	if ($error eq 'incorrectID') {
 6950: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6951: 		      "</p>\n");
 6952: 	} elsif ($error eq 'duplicateID') {
 6953: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6954: 	}
 6955: 	$r->print($message);
 6956: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6957: 	$r->print("\n<ul><li> ");
 6958: 	#FIXME it would be nice if this sent back the user ID and
 6959: 	#could do partial userID matches
 6960: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6961: 				       'scantron_username','scantron_domain'));
 6962: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6963: 	$r->print("\n@".
 6964: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6965: 
 6966: 	$r->print('</li>');
 6967:     } elsif ($error =~ /CODE$/) {
 6968: 	if ($error eq 'incorrectCODE') {
 6969: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6970: 	} elsif ($error eq 'duplicateCODE') {
 6971: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 6972: 	}
 6973: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6974: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6975: 	$r->print($message);
 6976: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6977: 	$r->print("\n<br /> ");
 6978: 	my $i=0;
 6979: 	if ($error eq 'incorrectCODE' 
 6980: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6981: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6982: 	    if ($closest > 0) {
 6983: 		foreach my $testcode (@{$closest}) {
 6984: 		    my $checked='';
 6985: 		    if (!$i) { $checked=' checked="checked"'; }
 6986: 		    $r->print("
 6987:    <label>
 6988:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6989:        ".&mt("Use the similar CODE [_1] instead.",
 6990: 	    "<b><tt>".$testcode."</tt></b>")."
 6991:     </label>
 6992:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6993: 		    $r->print("\n<br />");
 6994: 		    $i++;
 6995: 		}
 6996: 	    }
 6997: 	}
 6998: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6999: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7000: 	    $r->print("
 7001:     <label>
 7002:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7003:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 7004: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7005:     </label>");
 7006: 	    $r->print("\n<br />");
 7007: 	}
 7008: 
 7009: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7010: function change_radio(field) {
 7011:     var slct=document.scantronupload.scantron_CODE_resolution;
 7012:     var i;
 7013:     for (i=0;i<slct.length;i++) {
 7014:         if (slct[i].value==field) { slct[i].checked=true; }
 7015:     }
 7016: }
 7017: ENDSCRIPT
 7018: 	my $href="/adm/pickcode?".
 7019: 	   "form=".&escape("scantronupload").
 7020: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7021: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7022: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7023: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7024: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7025: 	    $r->print("
 7026:     <label>
 7027:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7028:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7029: 	     "<a target='_blank' href='$href'>","</a>")."
 7030:     </label> 
 7031:     ".&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\')" />'));
 7032: 	    $r->print("\n<br />");
 7033: 	}
 7034: 	$r->print("
 7035:     <label>
 7036:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7037:        ".&mt("Use [_1] as the CODE.",
 7038: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7039: 	$r->print("\n<br /><br />");
 7040:     } elsif ($error eq 'doublebubble') {
 7041: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7042: 
 7043: 	# The form field scantron_questions is acutally a list of line numbers.
 7044: 	# represented by this form so:
 7045: 
 7046: 	my $line_list = &questions_to_line_list($arg);
 7047: 
 7048: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7049: 		  $line_list.'" />');
 7050: 	$r->print($message);
 7051: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7052: 	foreach my $question (@{$arg}) {
 7053: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7054:                                                    $scan_record, $error);
 7055:             push(@lines_to_correct,@linenums);
 7056: 	}
 7057:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7058:     } elsif ($error eq 'missingbubble') {
 7059: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 7060: 	$r->print($message);
 7061: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7062: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7063: 
 7064: 	# The form field scantron_questions is actually a list of line numbers not
 7065: 	# a list of question numbers. Therefore:
 7066: 	#
 7067: 	
 7068: 	my $line_list = &questions_to_line_list($arg);
 7069: 
 7070: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7071: 		  $line_list.'" />');
 7072: 	foreach my $question (@{$arg}) {
 7073: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7074:                                                    $scan_record, $error);
 7075:             push(@lines_to_correct,@linenums);
 7076: 	}
 7077:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7078:     } else {
 7079: 	$r->print("\n<ul>");
 7080:     }
 7081:     $r->print("\n</li></ul>");
 7082: }
 7083: 
 7084: sub verify_bubbles_checked {
 7085:     my (@ansnums) = @_;
 7086:     my $ansnumstr = join('","',@ansnums);
 7087:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7088:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7089: function verify_bubble_radio(form) {
 7090:     var ansnumArray = new Array ("$ansnumstr");
 7091:     var need_bubble_count = 0;
 7092:     for (var i=0; i<ansnumArray.length; i++) {
 7093:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7094:             var bubble_picked = 0; 
 7095:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7096:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7097:                     bubble_picked = 1;
 7098:                 }
 7099:             }
 7100:             if (bubble_picked == 0) {
 7101:                 need_bubble_count ++;
 7102:             }
 7103:         }
 7104:     }
 7105:     if (need_bubble_count) {
 7106:         alert("$warning");
 7107:         return;
 7108:     }
 7109:     form.submit(); 
 7110: }
 7111: ENDSCRIPT
 7112:     return $output;
 7113: }
 7114: 
 7115: =pod
 7116: 
 7117: =item  questions_to_line_list
 7118: 
 7119: Converts a list of questions into a string of comma separated
 7120: line numbers in the answer sheet used by the questions.  This is
 7121: used to fill in the scantron_questions form field.
 7122: 
 7123:   Arguments:
 7124:      questions    - Reference to an array of questions.
 7125: 
 7126: =cut
 7127: 
 7128: 
 7129: sub questions_to_line_list {
 7130:     my ($questions) = @_;
 7131:     my @lines;
 7132: 
 7133:     foreach my $item (@{$questions}) {
 7134:         my $question = $item;
 7135:         my ($first,$count,$last);
 7136:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7137:             $question = $1;
 7138:             my $subquestion = $2;
 7139:             $first = $first_bubble_line{$question-1} + 1;
 7140:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7141:             my $subcount = 1;
 7142:             while ($subcount<$subquestion) {
 7143:                 $first += $subans[$subcount-1];
 7144:                 $subcount ++;
 7145:             }
 7146:             $count = $subans[$subquestion-1];
 7147:         } else {
 7148: 	    $first   = $first_bubble_line{$question-1} + 1;
 7149: 	    $count   = $bubble_lines_per_response{$question-1};
 7150:         }
 7151:         $last = $first+$count-1;
 7152:         push(@lines, ($first..$last));
 7153:     }
 7154:     return join(',', @lines);
 7155: }
 7156: 
 7157: =pod 
 7158: 
 7159: =item prompt_for_corrections
 7160: 
 7161: Prompts for a potentially multiline correction to the
 7162: user's bubbling (factors out common code from scantron_get_correction
 7163: for multi and missing bubble cases).
 7164: 
 7165:  Arguments:
 7166:    $r           - Apache request object.
 7167:    $question    - The question number to prompt for.
 7168:    $scan_config - The scantron file configuration hash.
 7169:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7170:    $error       - Type of error
 7171: 
 7172:  Implicit inputs:
 7173:    %bubble_lines_per_response   - Starting line numbers for each question.
 7174:                                   Numbered from 0 (but question numbers are from
 7175:                                   1.
 7176:    %first_bubble_line           - Starting bubble line for each question.
 7177:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7178:                                   type problems render as separate sub-questions, 
 7179:                                   in exam mode. This hash contains a 
 7180:                                   comma-separated list of the lines per 
 7181:                                   sub-question.
 7182:    %responsetype_per_response   - essayresponse, formularesponse,
 7183:                                   stringresponse, imageresponse, reactionresponse,
 7184:                                   and organicresponse type problem parts can have
 7185:                                   multiple lines per response if the weight
 7186:                                   assigned exceeds 10.  In this case, only
 7187:                                   one bubble per line is permitted, but more 
 7188:                                   than one line might contain bubbles, e.g.
 7189:                                   bubbling of: line 1 - J, line 2 - J, 
 7190:                                   line 3 - B would assign 22 points.  
 7191: 
 7192: =cut
 7193: 
 7194: sub prompt_for_corrections {
 7195:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7196:     my ($current_line,$lines);
 7197:     my @linenums;
 7198:     my $questionnum = $question;
 7199:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7200:         $question = $1;
 7201:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7202:         my $subquestion = $2;
 7203:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7204:         my $subcount = 1;
 7205:         while ($subcount<$subquestion) {
 7206:             $current_line += $subans[$subcount-1];
 7207:             $subcount ++;
 7208:         }
 7209:         $lines = $subans[$subquestion-1];
 7210:     } else {
 7211:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7212:         $lines        = $bubble_lines_per_response{$question-1};
 7213:     }
 7214:     if ($lines > 1) {
 7215:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7216:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7217:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7218:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7219:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7220:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7221:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7222:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7223:         } else {
 7224:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7225:         }
 7226:     }
 7227:     for (my $i =0; $i < $lines; $i++) {
 7228:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7229: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7230: 	        		  $questionnum,$error,split('', $selected));
 7231:         push(@linenums,$current_line);
 7232: 	$current_line++;
 7233:     }
 7234:     if ($lines > 1) {
 7235: 	$r->print("<hr /><br />");
 7236:     }
 7237:     return @linenums;
 7238: }
 7239: 
 7240: =pod
 7241: 
 7242: =item scantron_bubble_selector
 7243:   
 7244:    Generates the html radiobuttons to correct a single bubble line
 7245:    possibly showing the existing the selected bubbles if known
 7246: 
 7247:  Arguments:
 7248:     $r           - Apache request object
 7249:     $scan_config - hash from &get_scantron_config()
 7250:     $line        - Number of the line being displayed.
 7251:     $questionnum - Question number (may include subquestion)
 7252:     $error       - Type of error.
 7253:     @selected    - Array of bubbles picked on this line.
 7254: 
 7255: =cut
 7256: 
 7257: sub scantron_bubble_selector {
 7258:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7259:     my $max=$$scan_config{'Qlength'};
 7260: 
 7261:     my $scmode=$$scan_config{'Qon'};
 7262:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7263: 
 7264:     my @alphabet=('A'..'Z');
 7265:     $r->print(&Apache::loncommon::start_data_table().
 7266:               &Apache::loncommon::start_data_table_row());
 7267:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7268:     for (my $i=0;$i<$max+1;$i++) {
 7269: 	$r->print("\n".'<td align="center">');
 7270: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7271: 	else { $r->print('&nbsp;'); }
 7272: 	$r->print('</td>');
 7273:     }
 7274:     $r->print(&Apache::loncommon::end_data_table_row().
 7275:               &Apache::loncommon::start_data_table_row());
 7276:     for (my $i=0;$i<$max;$i++) {
 7277: 	$r->print("\n".
 7278: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7279: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7280:     }
 7281:     my $nobub_checked = ' ';
 7282:     if ($error eq 'missingbubble') {
 7283:         $nobub_checked = ' checked = "checked" ';
 7284:     }
 7285:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7286: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7287:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7288:               $line.'" value="'.$questionnum.'" /></td>');
 7289:     $r->print(&Apache::loncommon::end_data_table_row().
 7290:               &Apache::loncommon::end_data_table());
 7291: }
 7292: 
 7293: =pod
 7294: 
 7295: =item num_matches
 7296: 
 7297:    Counts the number of characters that are the same between the two arguments.
 7298: 
 7299:  Arguments:
 7300:    $orig - CODE from the scanline
 7301:    $code - CODE to match against
 7302: 
 7303:  Returns:
 7304:    $count - integer count of the number of same characters between the
 7305:             two arguments
 7306: 
 7307: =cut
 7308: 
 7309: sub num_matches {
 7310:     my ($orig,$code) = @_;
 7311:     my @code=split(//,$code);
 7312:     my @orig=split(//,$orig);
 7313:     my $same=0;
 7314:     for (my $i=0;$i<scalar(@code);$i++) {
 7315: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7316:     }
 7317:     return $same;
 7318: }
 7319: 
 7320: =pod
 7321: 
 7322: =item scantron_get_closely_matching_CODEs
 7323: 
 7324:    Cycles through all CODEs and finds the set that has the greatest
 7325:    number of same characters as the provided CODE
 7326: 
 7327:  Arguments:
 7328:    $allcodes - hash ref returned by &get_codes()
 7329:    $CODE     - CODE from the current scanline
 7330: 
 7331:  Returns:
 7332:    2 element list
 7333:     - first elements is number of how closely matching the best fit is 
 7334:       (5 means best set has 5 matching characters)
 7335:     - second element is an arrary ref containing the set of valid CODEs
 7336:       that best fit the passed in CODE
 7337: 
 7338: =cut
 7339: 
 7340: sub scantron_get_closely_matching_CODEs {
 7341:     my ($allcodes,$CODE)=@_;
 7342:     my @CODEs;
 7343:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7344: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7345:     }
 7346: 
 7347:     return ($#CODEs,$CODEs[-1]);
 7348: }
 7349: 
 7350: =pod
 7351: 
 7352: =item get_codes
 7353: 
 7354:    Builds a hash which has keys of all of the valid CODEs from the selected
 7355:    set of remembered CODEs.
 7356: 
 7357:  Arguments:
 7358:   $old_name - name of the set of remembered CODEs
 7359:   $cdom     - domain of the course
 7360:   $cnum     - internal course name
 7361: 
 7362:  Returns:
 7363:   %allcodes - keys are the valid CODEs, values are all 1
 7364: 
 7365: =cut
 7366: 
 7367: sub get_codes {
 7368:     my ($old_name, $cdom, $cnum) = @_;
 7369:     if (!$old_name) {
 7370: 	$old_name=$env{'form.scantron_CODElist'};
 7371:     }
 7372:     if (!$cdom) {
 7373: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7374:     }
 7375:     if (!$cnum) {
 7376: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7377:     }
 7378:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7379: 				    $cdom,$cnum);
 7380:     my %allcodes;
 7381:     if ($result{"type\0$old_name"} eq 'number') {
 7382: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7383:     } else {
 7384: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7385:     }
 7386:     return %allcodes;
 7387: }
 7388: 
 7389: =pod
 7390: 
 7391: =item scantron_validate_CODE
 7392: 
 7393:    Validates all scanlines in the selected file to not have any
 7394:    invalid or underspecified CODEs and that none of the codes are
 7395:    duplicated if this was requested.
 7396: 
 7397: =cut
 7398: 
 7399: sub scantron_validate_CODE {
 7400:     my ($r,$currentphase) = @_;
 7401:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7402:     if ($scantron_config{'CODElocation'} &&
 7403: 	$scantron_config{'CODEstart'} &&
 7404: 	$scantron_config{'CODElength'}) {
 7405: 	if (!defined($env{'form.scantron_CODElist'})) {
 7406: 	    &FIXME_blow_up()
 7407: 	}
 7408:     } else {
 7409: 	return (0,$currentphase+1);
 7410:     }
 7411:     
 7412:     my %usedCODEs;
 7413: 
 7414:     my %allcodes=&get_codes();
 7415: 
 7416:     my $nav_error;
 7417:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7418:     if ($nav_error) {
 7419:         $r->print(&navmap_errormsg());
 7420:         return(1,$currentphase);
 7421:     }
 7422: 
 7423:     my ($scanlines,$scan_data)=&scantron_getfile();
 7424:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7425: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7426: 	if ($line=~/^[\s\cz]*$/) { next; }
 7427: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7428: 						 $scan_data);
 7429: 	my $CODE=$$scan_record{'scantron.CODE'};
 7430: 	my $error=0;
 7431: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7432: 	    &scantron_get_correction($r,$i,$scan_record,
 7433: 				     \%scantron_config,
 7434: 				     $line,'incorrectCODE',\%allcodes);
 7435: 	    return(1,$currentphase);
 7436: 	}
 7437: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7438: 	    && !$$scan_record{'scantron.useCODE'}) {
 7439: 	    &scantron_get_correction($r,$i,$scan_record,
 7440: 				     \%scantron_config,
 7441: 				     $line,'incorrectCODE',\%allcodes);
 7442: 	    return(1,$currentphase);
 7443: 	}
 7444: 	if (exists($usedCODEs{$CODE}) 
 7445: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7446: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7447: 	    &scantron_get_correction($r,$i,$scan_record,
 7448: 				     \%scantron_config,
 7449: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7450: 	    return(1,$currentphase);
 7451: 	}
 7452: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7453:     }
 7454:     return (0,$currentphase+1);
 7455: }
 7456: 
 7457: =pod
 7458: 
 7459: =item scantron_validate_doublebubble
 7460: 
 7461:    Validates all scanlines in the selected file to not have any
 7462:    bubble lines with multiple bubbles marked.
 7463: 
 7464: =cut
 7465: 
 7466: sub scantron_validate_doublebubble {
 7467:     my ($r,$currentphase) = @_;
 7468:     #get student info
 7469:     my $classlist=&Apache::loncoursedata::get_classlist();
 7470:     my %idmap=&username_to_idmap($classlist);
 7471: 
 7472:     #get scantron line setup
 7473:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7474:     my ($scanlines,$scan_data)=&scantron_getfile();
 7475:     my $nav_error;
 7476:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7477:     if ($nav_error) {
 7478:         $r->print(&navmap_errormsg());
 7479:         return(1,$currentphase);
 7480:     }
 7481: 
 7482:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7483: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7484: 	if ($line=~/^[\s\cz]*$/) { next; }
 7485: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7486: 						 $scan_data);
 7487: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7488: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7489: 				 'doublebubble',
 7490: 				 $$scan_record{'scantron.doubleerror'});
 7491:     	return (1,$currentphase);
 7492:     }
 7493:     return (0,$currentphase+1);
 7494: }
 7495: 
 7496: 
 7497: sub scantron_get_maxbubble {
 7498:     my ($nav_error) = @_;
 7499:     if (defined($env{'form.scantron_maxbubble'}) &&
 7500: 	$env{'form.scantron_maxbubble'}) {
 7501: 	&restore_bubble_lines();
 7502: 	return $env{'form.scantron_maxbubble'};
 7503:     }
 7504: 
 7505:     my (undef, undef, $sequence) =
 7506: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7507: 
 7508:     my $navmap=Apache::lonnavmaps::navmap->new();
 7509:     unless (ref($navmap)) {
 7510:         if (ref($nav_error)) {
 7511:             $$nav_error = 1;
 7512:         }
 7513:         return;
 7514:     }
 7515:     my $map=$navmap->getResourceByUrl($sequence);
 7516:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7517: 
 7518:     &Apache::lonxml::clear_problem_counter();
 7519: 
 7520:     my $uname       = $env{'user.name'};
 7521:     my $udom        = $env{'user.domain'};
 7522:     my $cid         = $env{'request.course.id'};
 7523:     my $total_lines = 0;
 7524:     %bubble_lines_per_response = ();
 7525:     %first_bubble_line         = ();
 7526:     %subdivided_bubble_lines   = ();
 7527:     %responsetype_per_response = ();
 7528: 
 7529:     my $response_number = 0;
 7530:     my $bubble_line     = 0;
 7531:     foreach my $resource (@resources) {
 7532:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7533:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7534: 	    foreach my $part_id (@{$parts}) {
 7535:                 my $lines;
 7536: 
 7537: 	        # TODO - make this a persistent hash not an array.
 7538: 
 7539:                 # optionresponse, matchresponse and rankresponse type items 
 7540:                 # render as separate sub-questions in exam mode.
 7541:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7542:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7543:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7544:                     my ($numbub,$numshown);
 7545:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7546:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7547:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7548:                         }
 7549:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7550:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7551:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7552:                         }
 7553:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7554:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7555:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7556:                         }
 7557:                     }
 7558:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7559:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7560:                     }
 7561:                     my $bubbles_per_line = 10;
 7562:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7563:                     if (($numbub % $bubbles_per_line) != 0) {
 7564:                         $inner_bubble_lines++;
 7565:                     }
 7566:                     for (my $i=0; $i<$numshown; $i++) {
 7567:                         $subdivided_bubble_lines{$response_number} .= 
 7568:                             $inner_bubble_lines.',';
 7569:                     }
 7570:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7571:                     $lines = $numshown * $inner_bubble_lines;
 7572:                 } else {
 7573:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7574:                 } 
 7575: 
 7576:                 $first_bubble_line{$response_number} = $bubble_line;
 7577: 	        $bubble_lines_per_response{$response_number} = $lines;
 7578:                 $responsetype_per_response{$response_number} = 
 7579:                     $analysis->{$part_id.'.type'};
 7580: 	        $response_number++;
 7581: 
 7582: 	        $bubble_line +=  $lines;
 7583: 	        $total_lines +=  $lines;
 7584: 	    }
 7585:         }
 7586:     }
 7587:     &Apache::lonnet::delenv('scantron.');
 7588: 
 7589:     &save_bubble_lines();
 7590:     $env{'form.scantron_maxbubble'} =
 7591: 	$total_lines;
 7592:     return $env{'form.scantron_maxbubble'};
 7593: }
 7594: 
 7595: sub scantron_validate_missingbubbles {
 7596:     my ($r,$currentphase) = @_;
 7597:     #get student info
 7598:     my $classlist=&Apache::loncoursedata::get_classlist();
 7599:     my %idmap=&username_to_idmap($classlist);
 7600: 
 7601:     #get scantron line setup
 7602:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7603:     my ($scanlines,$scan_data)=&scantron_getfile();
 7604:     my $nav_error;
 7605:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7606:     if ($nav_error) {
 7607:         return(1,$currentphase);
 7608:     }
 7609:     if (!$max_bubble) { $max_bubble=2**31; }
 7610:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7611: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7612: 	if ($line=~/^[\s\cz]*$/) { next; }
 7613: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7614: 						 $scan_data);
 7615: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7616: 	my @to_correct;
 7617: 	
 7618: 	# Probably here's where the error is...
 7619: 
 7620: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7621:             my $lastbubble;
 7622:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7623:                my $question = $1;
 7624:                my $subquestion = $2;
 7625:                if (!defined($first_bubble_line{$question -1})) { next; }
 7626:                my $first = $first_bubble_line{$question-1};
 7627:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7628:                my $subcount = 1;
 7629:                while ($subcount<$subquestion) {
 7630:                    $first += $subans[$subcount-1];
 7631:                    $subcount ++;
 7632:                }
 7633:                my $count = $subans[$subquestion-1];
 7634:                $lastbubble = $first + $count;
 7635:             } else {
 7636:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7637:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7638:             }
 7639:             if ($lastbubble > $max_bubble) { next; }
 7640: 	    push(@to_correct,$missing);
 7641: 	}
 7642: 	if (@to_correct) {
 7643: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7644: 				     $line,'missingbubble',\@to_correct);
 7645: 	    return (1,$currentphase);
 7646: 	}
 7647: 
 7648:     }
 7649:     return (0,$currentphase+1);
 7650: }
 7651: 
 7652: 
 7653: sub scantron_process_students {
 7654:     my ($r) = @_;
 7655: 
 7656:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7657:     my ($symb)=&get_symb($r);
 7658:     if (!$symb) {
 7659: 	return '';
 7660:     }
 7661:     my $default_form_data=&defaultFormData($symb);
 7662: 
 7663:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7664:     my ($scanlines,$scan_data)=&scantron_getfile();
 7665:     my $classlist=&Apache::loncoursedata::get_classlist();
 7666:     my %idmap=&username_to_idmap($classlist);
 7667:     my $navmap=Apache::lonnavmaps::navmap->new();
 7668:     unless (ref($navmap)) {
 7669:         $r->print(&navmap_errormsg());
 7670:         return '';
 7671:     }  
 7672:     my $map=$navmap->getResourceByUrl($sequence);
 7673:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7674:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7675:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7676:                             \%grader_randomlists_by_symb);
 7677:     my $resource_error;
 7678:     foreach my $resource (@resources) {
 7679:         my $ressymb;
 7680:         if (ref($resource)) {
 7681:             $ressymb = $resource->symb();
 7682:         } else {
 7683:             $resource_error = 1;
 7684:             last;
 7685:         }
 7686:         my ($analysis,$parts) =
 7687:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7688:                                       $env{'user.name'},$env{'user.domain'},1);
 7689:         $grader_partids_by_symb{$ressymb} = $parts;
 7690:         if (ref($analysis) eq 'HASH') {
 7691:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7692:                 $grader_randomlists_by_symb{$ressymb} = 
 7693:                     $analysis->{'parts_withrandomlist'};
 7694:             }
 7695:         }
 7696:     }
 7697:     if ($resource_error) {
 7698:         $r->print(&navmap_errormsg());
 7699:         return '';
 7700:     }
 7701: 
 7702:     my ($uname,$udom);
 7703:     my $result= <<SCANTRONFORM;
 7704: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7705:   <input type="hidden" name="command" value="scantron_configphase" />
 7706:   $default_form_data
 7707: SCANTRONFORM
 7708:     $r->print($result);
 7709: 
 7710:     my @delayqueue;
 7711:     my (%completedstudents,%scandata);
 7712:     
 7713:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7714:     my $count=&get_todo_count($scanlines,$scan_data);
 7715:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7716:  				    'Bubblesheet Progress',$count,
 7717: 				    'inline',undef,'scantronupload');
 7718:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7719: 					  'Processing first student');
 7720:     $r->print('<br />');
 7721:     my $start=&Time::HiRes::time();
 7722:     my $i=-1;
 7723:     my $started;
 7724: 
 7725:     my $nav_error;
 7726:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7727:     if ($nav_error) {
 7728:         $r->print(&navmap_errormsg());
 7729:         return '';
 7730:     }
 7731: 
 7732:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7733:     # the user and return.
 7734: 
 7735:     if ($ssi_error) {
 7736: 	$r->print("</form>");
 7737: 	&ssi_print_error($r);
 7738: 	$r->print(&show_grading_menu_form($symb));
 7739:         &Apache::lonnet::remove_lock($lock);
 7740: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7741:     }
 7742: 
 7743:     my %lettdig = &letter_to_digits();
 7744:     my $numletts = scalar(keys(%lettdig));
 7745: 
 7746:     while ($i<$scanlines->{'count'}) {
 7747:  	($uname,$udom)=('','');
 7748:  	$i++;
 7749:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7750:  	if ($line=~/^[\s\cz]*$/) { next; }
 7751: 	if ($started) {
 7752: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7753: 						     'last student');
 7754: 	}
 7755: 	$started=1;
 7756:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7757:  						 $scan_data);
 7758:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7759:  					      \%idmap,$i)) {
 7760:   	    &scantron_add_delay(\@delayqueue,$line,
 7761:  				'Unable to find a student that matches',1);
 7762:  	    next;
 7763:   	}
 7764:  	if (exists $completedstudents{$uname}) {
 7765:  	    &scantron_add_delay(\@delayqueue,$line,
 7766:  				'Student '.$uname.' has multiple sheets',2);
 7767:  	    next;
 7768:  	}
 7769:   	($uname,$udom)=split(/:/,$uname);
 7770: 
 7771:         my (%partids_by_symb,$res_error);
 7772:         foreach my $resource (@resources) {
 7773:             my $ressymb;
 7774:             if (ref($resource)) {
 7775:                 $ressymb = $resource->symb();
 7776:             } else {
 7777:                 $res_error = 1;
 7778:                 last;
 7779:             }
 7780:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7781:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7782:                 my ($analysis,$parts) =
 7783:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7784:                 $partids_by_symb{$ressymb} = $parts;
 7785:             } else {
 7786:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7787:             }
 7788:         }
 7789: 
 7790:         if ($res_error) {
 7791:             &scantron_add_delay(\@delayqueue,$line,
 7792:                                 'An error occurred while grading student '.$uname,2);
 7793:             next;
 7794:         }
 7795: 
 7796: 	&Apache::lonxml::clear_problem_counter();
 7797:   	&Apache::lonnet::appenv($scan_record);
 7798: 
 7799: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7800: 	    &scantron_putfile($scanlines,$scan_data);
 7801: 	}
 7802: 	
 7803:         my $scancode;
 7804:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7805:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7806:             $scancode = $scan_record->{'scantron.CODE'};
 7807:         } else {
 7808:             $scancode = '';
 7809:         }
 7810: 
 7811:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7812:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7813:             $ssi_error = 0; # So end of handler error message does not trigger.
 7814:             $r->print("</form>");
 7815:             &ssi_print_error($r);
 7816:             $r->print(&show_grading_menu_form($symb));
 7817:             &Apache::lonnet::remove_lock($lock);
 7818:             return '';      # Why return ''?  Beats me.
 7819:         }
 7820: 
 7821: 	$completedstudents{$uname}={'line'=>$line};
 7822:         if ($env{'form.verifyrecord'}) {
 7823:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7824:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7825:             chomp($studentdata);
 7826:             $studentdata =~ s/\r$//;
 7827:             my $studentrecord = '';
 7828:             my $counter = -1;
 7829:             foreach my $resource (@resources) {
 7830:                 my $ressymb = $resource->symb();
 7831:                 ($counter,my $recording) =
 7832:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7833:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7834:                                              \%scantron_config,\%lettdig,$numletts);
 7835:                 $studentrecord .= $recording;
 7836:             }
 7837:             if ($studentrecord ne $studentdata) {
 7838:                 &Apache::lonxml::clear_problem_counter();
 7839:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7840:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7841:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7842:                     $r->print("</form>");
 7843:                     &ssi_print_error($r);
 7844:                     $r->print(&show_grading_menu_form($symb));
 7845:                     &Apache::lonnet::remove_lock($lock);
 7846:                     delete($completedstudents{$uname});
 7847:                     return '';
 7848:                 }
 7849:                 $counter = -1;
 7850:                 $studentrecord = '';
 7851:                 foreach my $resource (@resources) {
 7852:                     my $ressymb = $resource->symb();
 7853:                     ($counter,my $recording) =
 7854:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7855:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7856:                                                  \%scantron_config,\%lettdig,$numletts);
 7857:                     $studentrecord .= $recording;
 7858:                 }
 7859:                 if ($studentrecord ne $studentdata) {
 7860:                     $r->print('<p><span class="LC_error">');
 7861:                     if ($scancode eq '') {
 7862:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7863:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7864:                     } else {
 7865:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7866:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7867:                     }
 7868:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7869:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7870:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7871:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7872:                               &Apache::loncommon::start_data_table_row().
 7873:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7874:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7875:                               &Apache::loncommon::end_data_table_row().
 7876:                               &Apache::loncommon::start_data_table_row().
 7877:                               '<td>Stored submissions</td>'.
 7878:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7879:                               &Apache::loncommon::end_data_table_row().
 7880:                               &Apache::loncommon::end_data_table().'</p>');
 7881:                 } else {
 7882:                     $r->print('<br /><span class="LC_warning">'.
 7883:                              &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 />'.
 7884:                              &mt("As a consequence, this user's submission history records two tries.").
 7885:                                  '</span><br />');
 7886:                 }
 7887:             }
 7888:         }
 7889:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7890:     } continue {
 7891: 	&Apache::lonxml::clear_problem_counter();
 7892: 	&Apache::lonnet::delenv('scantron.');
 7893:     }
 7894:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7895:     &Apache::lonnet::remove_lock($lock);
 7896: #    my $lasttime = &Time::HiRes::time()-$start;
 7897: #    $r->print("<p>took $lasttime</p>");
 7898: 
 7899:     $r->print("</form>");
 7900:     $r->print(&show_grading_menu_form($symb));
 7901:     return '';
 7902: }
 7903: 
 7904: sub graders_resources_pass {
 7905:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7906:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7907:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7908:         foreach my $resource (@{$resources}) {
 7909:             my $ressymb = $resource->symb();
 7910:             my ($analysis,$parts) =
 7911:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7912:                                           $env{'user.name'},$env{'user.domain'},1);
 7913:             $grader_partids_by_symb->{$ressymb} = $parts;
 7914:             if (ref($analysis) eq 'HASH') {
 7915:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7916:                     $grader_randomlists_by_symb->{$ressymb} =
 7917:                         $analysis->{'parts_withrandomlist'};
 7918:                 }
 7919:             }
 7920:         }
 7921:     }
 7922:     return;
 7923: }
 7924: 
 7925: sub grade_student_bubbles {
 7926:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7927:     if (ref($resources) eq 'ARRAY') {
 7928:         my $count = 0;
 7929:         foreach my $resource (@{$resources}) {
 7930:             my $ressymb = $resource->symb();
 7931:             my %form = ('submitted'      => 'scantron',
 7932:                         'grade_target'   => 'grade',
 7933:                         'grade_username' => $uname,
 7934:                         'grade_domain'   => $udom,
 7935:                         'grade_courseid' => $env{'request.course.id'},
 7936:                         'grade_symb'     => $ressymb,
 7937:                         'CODE'           => $scancode
 7938:                        );
 7939:             if (ref($parts) eq 'HASH') {
 7940:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7941:                     foreach my $part (@{$parts->{$ressymb}}) {
 7942:                         $form{'scantron_questnum_start.'.$part} =
 7943:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7944:                         $count++;
 7945:                     }
 7946:                 }
 7947:             }
 7948:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7949:             return 'ssi_error' if ($ssi_error);
 7950:             last if (&Apache::loncommon::connection_aborted($r));
 7951:         }
 7952:     }
 7953:     return;
 7954: }
 7955: 
 7956: sub scantron_upload_scantron_data {
 7957:     my ($r)=@_;
 7958:     my $dom = $env{'request.role.domain'};
 7959:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7960:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7961:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7962: 							  'domainid',
 7963: 							  'coursename',$dom);
 7964:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7965:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7966:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7967:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7968:     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.");
 7969:     $r->print(&Apache::lonhtmlcommon::scripttag('
 7970:     function checkUpload(formname) {
 7971: 	if (formname.upfile.value == "") {
 7972: 	    alert("'.$nofile_alert.'");
 7973: 	    return false;
 7974: 	}
 7975:         if (formname.courseid.value == "") {
 7976:             alert("'.$nocourseid_alert.'");
 7977:             return false;
 7978:         }
 7979: 	formname.submit();
 7980:     }
 7981: 
 7982:     function ToSyllabus() {
 7983:         var cdom = '."'$dom'".';
 7984:         var cnum = document.rules.courseid.value;
 7985:         if (cdom == "" || cdom == null) {
 7986:             return;
 7987:         }
 7988:         if (cnum == "" || cnum == null) {
 7989:            return;
 7990:         }
 7991:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7992:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7993:         return;
 7994:     }
 7995: 
 7996: '));
 7997:     $r->print('
 7998: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7999: 
 8000: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8001: '.$default_form_data.
 8002:   &Apache::lonhtmlcommon::start_pick_box().
 8003:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8004:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8005:   &Apache::lonhtmlcommon::row_closure().
 8006:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8007:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8008:   &Apache::lonhtmlcommon::row_closure().
 8009:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8010:   '<input name="domainid" type="hidden" />'.$domdesc.
 8011:   &Apache::lonhtmlcommon::row_closure().
 8012:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8013:   '<input type="file" name="upfile" size="50" />'.
 8014:   &Apache::lonhtmlcommon::row_closure(1).
 8015:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8016: 
 8017: <input name="command" value="scantronupload_save" type="hidden" />
 8018: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8019: </form>
 8020: ');
 8021:     return '';
 8022: }
 8023: 
 8024: 
 8025: sub scantron_upload_scantron_data_save {
 8026:     my($r)=@_;
 8027:     my ($symb)=&get_symb($r,1);
 8028:     my $doanotherupload=
 8029: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8030: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8031: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8032: 	'</form>'."\n";
 8033:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8034: 	!&Apache::lonnet::allowed('usc',
 8035: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8036: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8037: 	if ($symb) {
 8038: 	    $r->print(&show_grading_menu_form($symb));
 8039: 	} else {
 8040: 	    $r->print($doanotherupload);
 8041: 	}
 8042: 	return '';
 8043:     }
 8044:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8045:     my $uploadedfile;
 8046:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8047:     if (length($env{'form.upfile'}) < 2) {
 8048:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8049:     } else {
 8050:         my $result = 
 8051:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8052:                                             $env{'form.courseid'},$env{'form.domainid'});
 8053: 	if ($result =~ m{^/uploaded/}) {
 8054: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8055:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8056: 			  '<span class="LC_filename">'.$result.'</span>'));
 8057:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8058:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8059:                                                        $env{'form.courseid'},$uploadedfile));
 8060: 	} else {
 8061: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8062:                           '<span class="LC_error">','</span>',$result,
 8063: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8064: 	}
 8065:     }
 8066:     if ($symb) {
 8067: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8068:     } else {
 8069: 	$r->print($doanotherupload);
 8070:     }
 8071:     return '';
 8072: }
 8073: 
 8074: sub validate_uploaded_scantron_file {
 8075:     my ($cdom,$cname,$fname) = @_;
 8076:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8077:     my @lines;
 8078:     if ($scanlines ne '-1') {
 8079:         @lines=split("\n",$scanlines,-1);
 8080:     }
 8081:     my $output;
 8082:     if (@lines) {
 8083:         my (%counts,$max_match_format);
 8084:         my ($max_match_count,$max_match_pct) = (0,0);
 8085:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8086:         my %idmap = &username_to_idmap($classlist);
 8087:         foreach my $key (keys(%idmap)) {
 8088:             my $lckey = lc($key);
 8089:             $idmap{$lckey} = $idmap{$key};
 8090:         }
 8091:         my %unique_formats;
 8092:         my @formatlines = &get_scantronformat_file();
 8093:         foreach my $line (@formatlines) {
 8094:             chomp($line);
 8095:             my @config = split(/:/,$line);
 8096:             my $idstart = $config[5];
 8097:             my $idlength = $config[6];
 8098:             if (($idstart ne '') && ($idlength > 0)) {
 8099:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8100:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8101:                 } else {
 8102:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8103:                 }
 8104:             }
 8105:         }
 8106:         foreach my $key (keys(%unique_formats)) {
 8107:             my ($idstart,$idlength) = split(':',$key);
 8108:             %{$counts{$key}} = (
 8109:                                'found'   => 0,
 8110:                                'total'   => 0,
 8111:                               );
 8112:             foreach my $line (@lines) {
 8113:                 next if ($line =~ /^#/);
 8114:                 next if ($line =~ /^[\s\cz]*$/);
 8115:                 my $id = substr($line,$idstart-1,$idlength);
 8116:                 $id = lc($id);
 8117:                 if (exists($idmap{$id})) {
 8118:                     $counts{$key}{'found'} ++;
 8119:                 }
 8120:                 $counts{$key}{'total'} ++;
 8121:             }
 8122:             if ($counts{$key}{'total'}) {
 8123:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8124:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8125:                     $max_match_pct = $percent_match;
 8126:                     $max_match_format = $key;
 8127:                     $max_match_count = $counts{$key}{'total'};
 8128:                 }
 8129:             }
 8130:         }
 8131:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8132:             my $format_descs;
 8133:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8134:             for (my $i=0; $i<$numwithformat; $i++) {
 8135:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8136:                 if ($i<$numwithformat-2) {
 8137:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8138:                 } elsif ($i==$numwithformat-2) {
 8139:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8140:                 } elsif ($i==$numwithformat-1) {
 8141:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8142:                 }
 8143:             }
 8144:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8145:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8146:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8147:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8148:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8149:                                   '<i>'.$cdom.'</i>').'</li>'.
 8150:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8151:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8152:                        '</ul>';
 8153:         }
 8154:     } else {
 8155:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8156:     }
 8157:     return $output;
 8158: }
 8159: 
 8160: sub valid_file {
 8161:     my ($requested_file)=@_;
 8162:     foreach my $filename (sort(&scantron_filenames())) {
 8163: 	if ($requested_file eq $filename) { return 1; }
 8164:     }
 8165:     return 0;
 8166: }
 8167: 
 8168: sub scantron_download_scantron_data {
 8169:     my ($r)=@_;
 8170:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8171:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8172:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8173:     my $file=$env{'form.scantron_selectfile'};
 8174:     if (! &valid_file($file)) {
 8175: 	$r->print('
 8176: 	<p>
 8177: 	    '.&mt('The requested file name was invalid.').'
 8178:         </p>
 8179: ');
 8180: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8181: 	return;
 8182:     }
 8183:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8184:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8185:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8186:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8187:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8188:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8189:     $r->print('
 8190:     <p>
 8191: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8192: 	      '<a href="'.$orig.'">','</a>').'
 8193:     </p>
 8194:     <p>
 8195: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8196: 	      '<a href="'.$corrected.'">','</a>').'
 8197:     </p>
 8198:     <p>
 8199: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8200: 	      '<a href="'.$skipped.'">','</a>').'
 8201:     </p>
 8202: ');
 8203:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8204:     return '';
 8205: }
 8206: 
 8207: sub checkscantron_results {
 8208:     my ($r) = @_;
 8209:     my ($symb)=&get_symb($r);
 8210:     if (!$symb) {return '';}
 8211:     my $grading_menu_button=&show_grading_menu_form($symb);
 8212:     my $cid = $env{'request.course.id'};
 8213:     my %lettdig = &letter_to_digits();
 8214:     my $numletts = scalar(keys(%lettdig));
 8215:     my $cnum = $env{'course.'.$cid.'.num'};
 8216:     my $cdom = $env{'course.'.$cid.'.domain'};
 8217:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8218:     my %record;
 8219:     my %scantron_config =
 8220:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8221:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8222:     my $classlist=&Apache::loncoursedata::get_classlist();
 8223:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8224:     my $navmap=Apache::lonnavmaps::navmap->new();
 8225:     unless (ref($navmap)) {
 8226:         $r->print(&navmap_errormsg());
 8227:         return '';
 8228:     }
 8229:     my $map=$navmap->getResourceByUrl($sequence);
 8230:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8231:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8232:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8233: 
 8234:     my ($uname,$udom);
 8235:     my (%scandata,%lastname,%bylast);
 8236:     $r->print('
 8237: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8238: 
 8239:     my @delayqueue;
 8240:     my %completedstudents;
 8241: 
 8242:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8243:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8244:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8245:                                     'inline',undef,'checkscantron');
 8246:     my ($username,$domain,$started);
 8247:     my $nav_error;
 8248:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8249:     if ($nav_error) {
 8250:         $r->print(&navmap_errormsg());
 8251:         return '';
 8252:     }
 8253: 
 8254:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8255:                                           'Processing first student');
 8256:     my $start=&Time::HiRes::time();
 8257:     my $i=-1;
 8258: 
 8259:     while ($i<$scanlines->{'count'}) {
 8260:         ($username,$domain,$uname)=('','','');
 8261:         $i++;
 8262:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8263:         if ($line=~/^[\s\cz]*$/) { next; }
 8264:         if ($started) {
 8265:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8266:                                                      'last student');
 8267:         }
 8268:         $started=1;
 8269:         my $scan_record=
 8270:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8271:                                                      $scan_data);
 8272:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8273:                                                               \%idmap,$i)) {
 8274:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8275:                                 'Unable to find a student that matches',1);
 8276:             next;
 8277:         }
 8278:         if (exists $completedstudents{$uname}) {
 8279:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8280:                                 'Student '.$uname.' has multiple sheets',2);
 8281:             next;
 8282:         }
 8283:         my $pid = $scan_record->{'scantron.ID'};
 8284:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8285:         push(@{$bylast{$lastname{$pid}}},$pid);
 8286:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8287:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8288:         chomp($scandata{$pid});
 8289:         $scandata{$pid} =~ s/\r$//;
 8290:         ($username,$domain)=split(/:/,$uname);
 8291:         my $counter = -1;
 8292:         foreach my $resource (@resources) {
 8293:             my $parts;
 8294:             my $ressymb = $resource->symb();
 8295:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8296:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8297:                 (my $analysis,$parts) =
 8298:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8299:             } else {
 8300:                 $parts = $grader_partids_by_symb{$ressymb};
 8301:             }
 8302:             ($counter,my $recording) =
 8303:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8304:                                          $scandata{$pid},$parts,
 8305:                                          \%scantron_config,\%lettdig,$numletts);
 8306:             $record{$pid} .= $recording;
 8307:         }
 8308:     }
 8309:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8310:     $r->print('<br />');
 8311:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8312:     $passed = 0;
 8313:     $failed = 0;
 8314:     $numstudents = 0;
 8315:     foreach my $last (sort(keys(%bylast))) {
 8316:         if (ref($bylast{$last}) eq 'ARRAY') {
 8317:             foreach my $pid (sort(@{$bylast{$last}})) {
 8318:                 my $showscandata = $scandata{$pid};
 8319:                 my $showrecord = $record{$pid};
 8320:                 $showscandata =~ s/\s/&nbsp;/g;
 8321:                 $showrecord =~ s/\s/&nbsp;/g;
 8322:                 if ($scandata{$pid} eq $record{$pid}) {
 8323:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8324:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8325: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8326: '</tr>'."\n".
 8327: '<tr class="'.$css_class.'">'."\n".
 8328: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8329:                     $passed ++;
 8330:                 } else {
 8331:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8332:                     $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".
 8333: '</tr>'."\n".
 8334: '<tr class="'.$css_class.'">'."\n".
 8335: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8336: '</tr>'."\n";
 8337:                     $failed ++;
 8338:                 }
 8339:                 $numstudents ++;
 8340:             }
 8341:         }
 8342:     }
 8343:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 8344:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
 8345:     if ($passed) {
 8346:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8347:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8348:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8349:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8350:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8351:                  $okstudents."\n".
 8352:                  &Apache::loncommon::end_data_table().'<br />');
 8353:     }
 8354:     if ($failed) {
 8355:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8356:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8357:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8358:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8359:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8360:                  $badstudents."\n".
 8361:                  &Apache::loncommon::end_data_table()).'<br />'.
 8362:                  &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.');  
 8363:     }
 8364:     $r->print('</form><br />'.$grading_menu_button);
 8365:     return;
 8366: }
 8367: 
 8368: sub verify_scantron_grading {
 8369:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8370:         $scantron_config,$lettdig,$numletts) = @_;
 8371:     my ($record,%expected,%startpos);
 8372:     return ($counter,$record) if (!ref($resource));
 8373:     return ($counter,$record) if (!$resource->is_problem());
 8374:     my $symb = $resource->symb();
 8375:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8376:     foreach my $part_id (@{$partids}) {
 8377:         $counter ++;
 8378:         $expected{$part_id} = 0;
 8379:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8380:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8381:             foreach my $item (@sub_lines) {
 8382:                 $expected{$part_id} += $item;
 8383:             }
 8384:         } else {
 8385:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8386:         }
 8387:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8388:     }
 8389:     if ($symb) {
 8390:         my %recorded;
 8391:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8392:         if ($returnhash{'version'}) {
 8393:             my %lasthash=();
 8394:             my $version;
 8395:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8396:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8397:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8398:                 }
 8399:             }
 8400:             foreach my $key (keys(%lasthash)) {
 8401:                 if ($key =~ /\.scantron$/) {
 8402:                     my $value = &unescape($lasthash{$key});
 8403:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8404:                     if ($value eq '') {
 8405:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8406:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8407:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8408:                             }
 8409:                         }
 8410:                     } else {
 8411:                         my @tocheck;
 8412:                         my @items = split(//,$value);
 8413:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8414:                             ($scantron_config->{'Qon'} eq 'number')) {
 8415:                             if (@items < $expected{$part_id}) {
 8416:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8417:                                 my @singles = split(//,$fragment);
 8418:                                 foreach my $pos (@singles) {
 8419:                                     if ($pos eq ' ') {
 8420:                                         push(@tocheck,$pos);
 8421:                                     } else {
 8422:                                         my $next = shift(@items);
 8423:                                         push(@tocheck,$next);
 8424:                                     }
 8425:                                 }
 8426:                             } else {
 8427:                                 @tocheck = @items;
 8428:                             }
 8429:                             foreach my $letter (@tocheck) {
 8430:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8431:                                     if ($letter !~ /^[A-J]$/) {
 8432:                                         $letter = $scantron_config->{'Qoff'};
 8433:                                     }
 8434:                                     $recorded{$part_id} .= $letter;
 8435:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8436:                                     my $digit;
 8437:                                     if ($letter !~ /^[A-J]$/) {
 8438:                                         $digit = $scantron_config->{'Qoff'};
 8439:                                     } else {
 8440:                                         $digit = $lettdig->{$letter};
 8441:                                     }
 8442:                                     $recorded{$part_id} .= $digit;
 8443:                                 }
 8444:                             }
 8445:                         } else {
 8446:                             @tocheck = @items;
 8447:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8448:                                 my $curr_sub = shift(@tocheck);
 8449:                                 my $digit;
 8450:                                 if ($curr_sub =~ /^[A-J]$/) {
 8451:                                     $digit = $lettdig->{$curr_sub}-1;
 8452:                                 }
 8453:                                 if ($curr_sub eq 'J') {
 8454:                                     $digit += scalar($numletts);
 8455:                                 }
 8456:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8457:                                     if ($j == $digit) {
 8458:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8459:                                     } else {
 8460:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8461:                                     }
 8462:                                 }
 8463:                             }
 8464:                         }
 8465:                     }
 8466:                 }
 8467:             }
 8468:         }
 8469:         foreach my $part_id (@{$partids}) {
 8470:             if ($recorded{$part_id} eq '') {
 8471:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8472:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8473:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8474:                     }
 8475:                 }
 8476:             }
 8477:             $record .= $recorded{$part_id};
 8478:         }
 8479:     }
 8480:     return ($counter,$record);
 8481: }
 8482: 
 8483: sub letter_to_digits { 
 8484:     my %lettdig = (
 8485:                     A => 1,
 8486:                     B => 2,
 8487:                     C => 3,
 8488:                     D => 4,
 8489:                     E => 5,
 8490:                     F => 6,
 8491:                     G => 7,
 8492:                     H => 8,
 8493:                     I => 9,
 8494:                     J => 0,
 8495:                   );
 8496:     return %lettdig;
 8497: }
 8498: 
 8499: 
 8500: #-------- end of section for handling grading scantron forms -------
 8501: #
 8502: #-------------------------------------------------------------------
 8503: 
 8504: #-------------------------- Menu interface -------------------------
 8505: #
 8506: #--- Show a Grading Menu button - Calls the next routine ---
 8507: sub show_grading_menu_form {
 8508:     my ($symb)=@_;
 8509:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8510: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8511: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8512: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8513: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8514: 	'</form>'."\n";
 8515:     return $result;
 8516: }
 8517: 
 8518: # -- Retrieve choices for grading form
 8519: sub savedState {
 8520:     my %savedState = ();
 8521:     if ($env{'form.saveState'}) {
 8522: 	foreach (split(/:/,$env{'form.saveState'})) {
 8523: 	    my ($key,$value) = split(/=/,$_,2);
 8524: 	    $savedState{$key} = $value;
 8525: 	}
 8526:     }
 8527:     return \%savedState;
 8528: }
 8529: 
 8530: sub grading_menu {
 8531:     my ($request) = @_;
 8532:     my ($symb)=&get_symb($request);
 8533:     if (!$symb) {return '';}
 8534:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8535: 
 8536: #    $request->print($table);
 8537:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8538:                   'probTitle'=>$probTitle,
 8539:                   'command'=>'individual',
 8540:                   'saveState'=>"",
 8541:                   'gradingMenu'=>1,
 8542:                   'showgrading'=>"yes");
 8543:     
 8544:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8545: 
 8546:     $fields{'command'}='ungraded';
 8547:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8548: 
 8549:     $fields{'command'}='table';
 8550:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8551: 
 8552:     $fields{'command'}='all_for_one';
 8553:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8554: 
 8555:     $fields{'command'} = 'csvform';
 8556:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8557:     
 8558:     $fields{'command'} = 'processclicker';
 8559:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8560:     
 8561:     $fields{'command'} = 'scantron_selectphase';
 8562:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8563:     
 8564:     my @menu = ({	categorytitle=>'Hand Grading',
 8565:             items =>[
 8566:                         {	linktext => 'Select individual students to grade',
 8567:                     		url => $url1a,
 8568:                     		permission => 'F',
 8569:                     		icon => 'edit-find-replace.png',
 8570:                     		linktitle => 'Grade current resource for a selection of students.'
 8571:                         }, 
 8572:                         {       linktext => 'Grade ungraded submissions.',
 8573:                                 url => $url1b,
 8574:                                 permission => 'F',
 8575:                                 icon => 'edit-find-replace.png',
 8576:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8577:                         },
 8578: 
 8579:                         {       linktext => 'Grading table',
 8580:                                 url => $url1c,
 8581:                                 permission => 'F',
 8582:                                 icon => 'edit-find-replace.png',
 8583:                                 linktitle => 'Grade current resource for all students.'
 8584:                         },
 8585:                         {       linktext => 'Grade complete page/sequence/folder for one student.',
 8586:                                 url => $url1d,
 8587:                                 permission => 'F',
 8588:                                 icon => 'edit-find-replace.png',
 8589:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8590:                         }]},
 8591:                          { categorytitle=>'Automated Grading',
 8592:                items =>[
 8593: 
 8594:                 	    {	linktext => 'Upload Scores',
 8595:                     		url => $url2,
 8596:                     		permission => 'F',
 8597:                     		icon => 'uploadscores.png',
 8598:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8599:                 	    },
 8600:                 	    {	linktext => 'Process Clicker',
 8601:                     		url => $url3,
 8602:                     		permission => 'F',
 8603:                     		icon => 'addClickerInfoFile.png',
 8604:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8605:                 	    },
 8606:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8607:                     		url => $url4,
 8608:                     		permission => 'F',
 8609:                     		icon => 'stat.png',
 8610:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8611:                 	    }
 8612:                     ]
 8613:             });
 8614: 
 8615:     #$fields{'command'} = 'verify';
 8616:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8617:     #
 8618:     # Create the menu
 8619:     my $Str;
 8620:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8621:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8622:     $Str .= '<input type="hidden" name="command" value="" />'.
 8623:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8624: #	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8625: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8626: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8627: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8628: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8629: 
 8630:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8631:     #$menudata->{'jscript'}
 8632:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8633:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8634:         ' /> '.
 8635:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8636:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8637: 
 8638:     $Str .="</form>\n";
 8639:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8640:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
 8641:     function checkChoice(formname,val,cmdx) {
 8642: 	if (val <= 2) {
 8643: 	    var cmd = radioSelection(formname.radioChoice);
 8644: 	    var cmdsave = cmd;
 8645: 	} else {
 8646: 	    cmd = cmdx;
 8647: 	    cmdsave = 'submission';
 8648: 	}
 8649: 	formname.command.value = cmd;
 8650: 	if (val < 5) formname.submit();
 8651: 	if (val == 5) {
 8652: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8653: 	        return false;
 8654: 	    } else {
 8655: 	        formname.submit();
 8656: 	    }
 8657: 	}
 8658:     }
 8659: 
 8660:     function checkReceiptNo(formname,nospace) {
 8661: 	var receiptNo = formname.receipt.value;
 8662: 	var checkOpt = false;
 8663: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8664: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8665: 	if (checkOpt) {
 8666: 	    alert("$receiptalert");
 8667: 	    formname.receipt.value = "";
 8668: 	    formname.receipt.focus();
 8669: 	    return false;
 8670: 	}
 8671: 	return true;
 8672:     }
 8673: GRADINGMENUJS
 8674:     &commonJSfunctions($request);
 8675:     return $Str;    
 8676: }
 8677: 
 8678: sub individual {
 8679:     my ($request)=@_;
 8680:     &submit_options($request);
 8681: }
 8682: 
 8683: sub ungraded {
 8684:     my ($request)=@_;
 8685:     &submit_options($request);
 8686: }
 8687: 
 8688: sub table {
 8689:     my ($request)=@_;
 8690:     &submit_options($request);
 8691: }
 8692: 
 8693: sub all_for_one {
 8694:     my ($request)=@_;
 8695:     &submit_options($request);
 8696: }
 8697: 
 8698: sub submit_options_sequence {
 8699:     my ($request) = @_;
 8700:     my ($symb)=&get_symb($request);
 8701:     if (!$symb) {return '';}
 8702:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8703: 
 8704:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8705:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
 8706:     function checkChoice(formname,val,cmdx) {
 8707:         if (val <= 2) {
 8708:             var cmd = radioSelection(formname.radioChoice);
 8709:             var cmdsave = cmd;
 8710:         } else {
 8711:             cmd = cmdx;
 8712:             cmdsave = 'submission';
 8713:         }
 8714:         formname.command.value = cmd;
 8715:         formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8716:             ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8717:         if (val < 5) formname.submit();
 8718:         if (val == 5) {
 8719:             if (!checkReceiptNo(formname,'notOK')) { return false;}
 8720:             formname.submit();
 8721:         }
 8722:         if (val < 7) formname.submit();
 8723:     }
 8724: 
 8725:     function checkReceiptNo(formname,nospace) {
 8726:         var receiptNo = formname.receipt.value;
 8727:         var checkOpt = false;
 8728:         if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8729:         if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8730:         if (checkOpt) {
 8731:             alert("$receiptalert");
 8732:             formname.receipt.value = "";
 8733:             formname.receipt.focus();
 8734:             return false;
 8735:         }
 8736:         return true;
 8737:     }
 8738: GRADINGMENUJS
 8739:     &commonJSfunctions($request);
 8740: #    my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8741:     my $result;
 8742:     my (undef,$sections) = &getclasslist('all','0');
 8743:     my $savedState = &savedState();
 8744:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8745:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8746:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8747:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8748: 
 8749:     # Preselect sections
 8750:     my $selsec="";
 8751:     if (ref($sections)) {
 8752:         foreach my $section (sort(@$sections)) {
 8753:             $selsec.='<option value="'.$section.'" '.
 8754:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8755:         }
 8756:     }
 8757: 
 8758:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8759:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8760:         '<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8761:         '<input type="hidden" name="saveState"   value="" />'."\n".
 8762:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8763:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
 8764: 
 8765:     $result.='
 8766: <h2>
 8767:   '.&mt('Grade Complete Folder for One Student').'
 8768: </h2>
 8769: 
 8770: <div class="LC_columnSection">
 8771:   
 8772:     <fieldset>
 8773:       <legend>
 8774:        '.&mt('Sections').'
 8775:       </legend>
 8776:       <select name="section" multiple="multiple" size="5">'."\n";
 8777:     $result.= $selsec;
 8778:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8779:     $result.='
 8780:     </fieldset>
 8781:   
 8782:     <fieldset>
 8783:       <legend>
 8784:         '.&mt('Groups').'
 8785:       </legend>
 8786:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8787:     </fieldset>
 8788:   
 8789:     <fieldset>
 8790:       <legend>
 8791:         '.&mt('Access Status').'
 8792:       </legend>
 8793:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8794:     </fieldset>
 8795:   
 8796: </div>
 8797: 
 8798: <br />
 8799: 
 8800:             <input type="hidden" name="command" value="pickStudentPage" />
 8801:             <div>
 8802:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8803:             </div>
 8804:         </div>
 8805:   </form>';
 8806:     $result .= &show_grading_menu_form($symb);
 8807:     return $result;
 8808: }
 8809: 
 8810: #--- Displays the submissions first page -------
 8811: sub submit_options {
 8812:     my ($request) = @_;
 8813:     my ($symb)=&get_symb($request);
 8814:     if (!$symb) {return '';}
 8815:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8816: 
 8817:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8818:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
 8819:     function checkChoice(formname,val,cmdx) {
 8820: 	if (val <= 2) {
 8821: 	    var cmd = radioSelection(formname.radioChoice);
 8822: 	    var cmdsave = cmd;
 8823: 	} else {
 8824: 	    cmd = cmdx;
 8825: 	    cmdsave = 'submission';
 8826: 	}
 8827: 	formname.command.value = cmd;
 8828: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8829: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8830: 	if (val < 5) formname.submit();
 8831: 	if (val == 5) {
 8832: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8833: 	    formname.submit();
 8834: 	}
 8835: 	if (val < 7) formname.submit();
 8836:     }
 8837: 
 8838:     function checkReceiptNo(formname,nospace) {
 8839: 	var receiptNo = formname.receipt.value;
 8840: 	var checkOpt = false;
 8841: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8842: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8843: 	if (checkOpt) {
 8844: 	    alert("$receiptalert");
 8845: 	    formname.receipt.value = "";
 8846: 	    formname.receipt.focus();
 8847: 	    return false;
 8848: 	}
 8849: 	return true;
 8850:     }
 8851: GRADINGMENUJS
 8852:     &commonJSfunctions($request);
 8853: #    my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8854:     my $result;
 8855:     my (undef,$sections) = &getclasslist('all','0');
 8856:     my $savedState = &savedState();
 8857:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8858:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8859:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8860:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8861: 
 8862:     # Preselect sections
 8863:     my $selsec="";
 8864:     if (ref($sections)) {
 8865:         foreach my $section (sort(@$sections)) {
 8866:             $selsec.='<option value="'.$section.'" '.
 8867:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8868:         }
 8869:     }
 8870: 
 8871:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8872: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8873: #	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8874: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8875: 	'<input type="hidden" name="command"     value="" />'."\n".
 8876: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8877: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8878: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8879: 
 8880:     $result.='
 8881: <h2>
 8882:   '.&mt('Grade Current Resource').'
 8883: </h2>
 8884: 
 8885: <div class="LC_columnSection">
 8886:   
 8887:     <fieldset>
 8888:       <legend>
 8889:        '.&mt('Sections').'
 8890:       </legend>
 8891:       <select name="section" multiple="multiple" size="5">'."\n";
 8892:     $result.= $selsec;
 8893:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8894:     $result.='
 8895:     </fieldset>
 8896:   
 8897:     <fieldset>
 8898:       <legend>
 8899:         '.&mt('Groups').'
 8900:       </legend>
 8901:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8902:     </fieldset>
 8903:   
 8904:     <fieldset>
 8905:       <legend>
 8906:         '.&mt('Access Status').'
 8907:       </legend>
 8908:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8909:     </fieldset>
 8910:   
 8911:     <fieldset>
 8912:       <legend>
 8913:         '.&mt('Submission Status').'
 8914:       </legend>
 8915:       <select name="submitonly" size="5">
 8916: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8917: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8918: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8919: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8920:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8921:       </select>
 8922:     </fieldset>
 8923:   
 8924: </div>
 8925: 
 8926: <br />
 8927:           <div>
 8928:             <div>
 8929:               <label>
 8930:                 <input type="radio" name="radioChoice" value="submission" '.
 8931:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8932:              &mt('Select individual students to grade and view submissions.').'
 8933: 	      </label> 
 8934:             </div>
 8935:             <div>
 8936: 	      <label>
 8937:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8938:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8939:                     &mt('Grade all selected students in a grading table.').'
 8940:               </label>
 8941:             </div>
 8942:             <div>
 8943: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8944:             </div>
 8945:           </div>
 8946: 
 8947: 
 8948:   </form>';
 8949:     $result .= &show_grading_menu_form($symb);
 8950:     return $result;
 8951: }
 8952: 
 8953: sub reset_perm {
 8954:     undef(%perm);
 8955: }
 8956: 
 8957: sub init_perm {
 8958:     &reset_perm();
 8959:     foreach my $test_perm ('vgr','mgr','opa') {
 8960: 
 8961: 	my $scope = $env{'request.course.id'};
 8962: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8963: 
 8964: 	    $scope .= '/'.$env{'request.course.sec'};
 8965: 	    if ( $perm{$test_perm}=
 8966: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8967: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8968: 	    } else {
 8969: 		delete($perm{$test_perm});
 8970: 	    }
 8971: 	}
 8972:     }
 8973: }
 8974: 
 8975: sub gather_clicker_ids {
 8976:     my %clicker_ids;
 8977: 
 8978:     my $classlist = &Apache::loncoursedata::get_classlist();
 8979: 
 8980:     # Set up a couple variables.
 8981:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8982:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8983:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8984: 
 8985:     foreach my $student (keys(%$classlist)) {
 8986:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8987:         my $username = $classlist->{$student}->[$username_idx];
 8988:         my $domain   = $classlist->{$student}->[$domain_idx];
 8989:         my $clickers =
 8990: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8991:         foreach my $id (split(/\,/,$clickers)) {
 8992:             $id=~s/^[\#0]+//;
 8993:             $id=~s/[\-\:]//g;
 8994:             if (exists($clicker_ids{$id})) {
 8995: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8996:             } else {
 8997: 		$clicker_ids{$id}=$username.':'.$domain;
 8998:             }
 8999:         }
 9000:     }
 9001:     return %clicker_ids;
 9002: }
 9003: 
 9004: sub gather_adv_clicker_ids {
 9005:     my %clicker_ids;
 9006:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9007:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9008:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9009:     foreach my $element (sort(keys(%coursepersonnel))) {
 9010:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9011:             my ($puname,$pudom)=split(/\:/,$person);
 9012:             my $clickers =
 9013: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9014:             foreach my $id (split(/\,/,$clickers)) {
 9015: 		$id=~s/^[\#0]+//;
 9016:                 $id=~s/[\-\:]//g;
 9017: 		if (exists($clicker_ids{$id})) {
 9018: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9019: 		} else {
 9020: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9021: 		}
 9022:             }
 9023:         }
 9024:     }
 9025:     return %clicker_ids;
 9026: }
 9027: 
 9028: sub clicker_grading_parameters {
 9029:     return ('gradingmechanism' => 'scalar',
 9030:             'upfiletype' => 'scalar',
 9031:             'specificid' => 'scalar',
 9032:             'pcorrect' => 'scalar',
 9033:             'pincorrect' => 'scalar');
 9034: }
 9035: 
 9036: sub process_clicker {
 9037:     my ($r)=@_;
 9038:     my ($symb)=&get_symb($r);
 9039:     if (!$symb) {return '';}
 9040:     my $result=&checkforfile_js();
 9041:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 9042: #    my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 9043: #    $result.=$table;
 9044:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 9045:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 9046:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 9047:         '</b></td></tr>'."\n";
 9048:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 9049: # Attempt to restore parameters from last session, set defaults if not present
 9050:     my %Saveable_Parameters=&clicker_grading_parameters();
 9051:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9052:                                                  \%Saveable_Parameters);
 9053:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9054:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9055:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9056:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9057: 
 9058:     my %checked;
 9059:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9060:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9061:           $checked{$gradingmechanism}=' checked="checked"';
 9062:        }
 9063:     }
 9064: 
 9065:     my $upload=&mt("Upload File");
 9066:     my $type=&mt("Type");
 9067:     my $attendance=&mt("Award points just for participation");
 9068:     my $personnel=&mt("Correctness determined from response by course personnel");
 9069:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9070:     my $given=&mt("Correctness determined from given list of answers").' '.
 9071:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9072:     my $pcorrect=&mt("Percentage points for correct solution");
 9073:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9074:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9075: 						   ('iclicker' => 'i>clicker',
 9076:                                                     'interwrite' => 'interwrite PRS'));
 9077:     $symb = &Apache::lonenc::check_encrypt($symb);
 9078:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9079: function sanitycheck() {
 9080: // Accept only integer percentages
 9081:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9082:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9083: // Find out grading choice
 9084:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9085:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9086:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9087:       }
 9088:    }
 9089: // By default, new choice equals user selection
 9090:    newgradingchoice=gradingchoice;
 9091: // Not good to give more points for false answers than correct ones
 9092:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9093:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9094:    }
 9095: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9096:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9097:       document.forms.gradesupload.pcorrect.value=100;
 9098:       document.forms.gradesupload.pincorrect.value=100;
 9099:    }
 9100: // If the values are different, cannot be attendance only
 9101:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9102:        (gradingchoice=='attendance')) {
 9103:        newgradingchoice='personnel';
 9104:    }
 9105: // Change grading choice to new one
 9106:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9107:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9108:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9109:       } else {
 9110:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9111:       }
 9112:    }
 9113: // Remember the old state
 9114:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9115: }
 9116: ENDUPFORM
 9117:     $result.= <<ENDUPFORM;
 9118: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9119: <input type="hidden" name="symb" value="$symb" />
 9120: <input type="hidden" name="command" value="processclickerfile" />
 9121: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9122: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9123: <input type="file" name="upfile" size="50" />
 9124: <br /><label>$type: $selectform</label>
 9125: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9126: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9127: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9128: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9129: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9130: <br />&nbsp;&nbsp;&nbsp;
 9131: <input type="text" name="givenanswer" size="50" />
 9132: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9133: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9134: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9135: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9136: </form>'
 9137: ENDUPFORM
 9138:     $result.='</td></tr></table>'."\n".
 9139:              '</td></tr></table><br /><br />'."\n";
 9140:     $result.=&show_grading_menu_form($symb);
 9141:     return $result;
 9142: }
 9143: 
 9144: sub process_clicker_file {
 9145:     my ($r)=@_;
 9146:     my ($symb)=&get_symb($r);
 9147:     if (!$symb) {return '';}
 9148: 
 9149:     my %Saveable_Parameters=&clicker_grading_parameters();
 9150:     &Apache::loncommon::store_course_settings('grades_clicker',
 9151:                                               \%Saveable_Parameters);
 9152:     my $result='';
 9153: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9154:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9155: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9156: 	return $result.&show_grading_menu_form($symb);
 9157:     }
 9158:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9159:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9160:         return $result.&show_grading_menu_form($symb);
 9161:     }
 9162:     my $foundgiven=0;
 9163:     if ($env{'form.gradingmechanism'} eq 'given') {
 9164:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9165:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9166:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 9167:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9168:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9169:         $foundgiven=$#answers+1;
 9170:     }
 9171:     my %clicker_ids=&gather_clicker_ids();
 9172:     my %correct_ids;
 9173:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9174: 	%correct_ids=&gather_adv_clicker_ids();
 9175:     }
 9176:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9177: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9178: 	   $correct_id=~tr/a-z/A-Z/;
 9179: 	   $correct_id=~s/\s//gs;
 9180: 	   $correct_id=~s/^[\#0]+//;
 9181:            $correct_id=~s/[\-\:]//g;
 9182:            if ($correct_id) {
 9183: 	      $correct_ids{$correct_id}='specified';
 9184:            }
 9185:         }
 9186:     }
 9187:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9188: 	$result.=&mt('Score based on attendance only');
 9189:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9190:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9191:     } else {
 9192: 	my $number=0;
 9193: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9194: 	foreach my $id (sort(keys(%correct_ids))) {
 9195: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9196: 	    if ($correct_ids{$id} eq 'specified') {
 9197: 		$result.=&mt('specified');
 9198: 	    } else {
 9199: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9200: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9201: 	    }
 9202: 	    $number++;
 9203: 	}
 9204:         $result.="</p>\n";
 9205: 	if ($number==0) {
 9206: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9207: 	    return $result.&show_grading_menu_form($symb);
 9208: 	}
 9209:     }
 9210:     if (length($env{'form.upfile'}) < 2) {
 9211:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9212: 		     '<span class="LC_error">',
 9213: 		     '</span>',
 9214: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9215:         return $result.&show_grading_menu_form($symb);
 9216:     }
 9217: 
 9218: # Were able to get all the info needed, now analyze the file
 9219: 
 9220:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9221:     $symb = &Apache::lonenc::check_encrypt($symb);
 9222:     my $heading=&mt('Scanning clicker file');
 9223:     $result.=(<<ENDHEADER);
 9224: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9225: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9226: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9227: <form method="post" action="/adm/grades" name="clickeranalysis">
 9228: <input type="hidden" name="symb" value="$symb" />
 9229: <input type="hidden" name="command" value="assignclickergrades" />
 9230: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9231: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9232: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9233: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9234: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9235: ENDHEADER
 9236:     if ($env{'form.gradingmechanism'} eq 'given') {
 9237:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9238:     } 
 9239:     my %responses;
 9240:     my @questiontitles;
 9241:     my $errormsg='';
 9242:     my $number=0;
 9243:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9244: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9245:     }
 9246:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9247:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9248:     }
 9249:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9250:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9251:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9252:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9253:              '<br />';
 9254:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9255:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9256:        return $result.&show_grading_menu_form($symb);
 9257:     } 
 9258: # Remember Question Titles
 9259: # FIXME: Possibly need delimiter other than ":"
 9260:     for (my $i=0;$i<$number;$i++) {
 9261:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9262:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9263:     }
 9264:     my $correct_count=0;
 9265:     my $student_count=0;
 9266:     my $unknown_count=0;
 9267: # Match answers with usernames
 9268: # FIXME: Possibly need delimiter other than ":"
 9269:     foreach my $id (keys(%responses)) {
 9270:        if ($correct_ids{$id}) {
 9271:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9272:           $correct_count++;
 9273:        } elsif ($clicker_ids{$id}) {
 9274:           if ($clicker_ids{$id}=~/\,/) {
 9275: # More than one user with the same clicker!
 9276:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9277:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9278:                            "<select name='multi".$id."'>";
 9279:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9280:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9281:              }
 9282:              $result.='</select>';
 9283:              $unknown_count++;
 9284:           } else {
 9285: # Good: found one and only one user with the right clicker
 9286:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9287:              $student_count++;
 9288:           }
 9289:        } else {
 9290:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9291:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9292:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9293:                    "\n".&mt("Domain").": ".
 9294:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9295:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9296:           $unknown_count++;
 9297:        }
 9298:     }
 9299:     $result.='<hr />'.
 9300:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9301:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9302:        if ($correct_count==0) {
 9303:           $errormsg.="Found no correct answers answers for grading!";
 9304:        } elsif ($correct_count>1) {
 9305:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9306:        }
 9307:     }
 9308:     if ($number<1) {
 9309:        $errormsg.="Found no questions.";
 9310:     }
 9311:     if ($errormsg) {
 9312:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9313:     } else {
 9314:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9315:     }
 9316:     $result.='</form></td></tr></table>'."\n".
 9317:              '</td></tr></table><br /><br />'."\n";
 9318:     return $result.&show_grading_menu_form($symb);
 9319: }
 9320: 
 9321: sub iclicker_eval {
 9322:     my ($questiontitles,$responses)=@_;
 9323:     my $number=0;
 9324:     my $errormsg='';
 9325:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9326:         my %components=&Apache::loncommon::record_sep($line);
 9327:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9328: 	if ($entries[0] eq 'Question') {
 9329: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9330: 		$$questiontitles[$number]=$entries[$i];
 9331: 		$number++;
 9332: 	    }
 9333: 	}
 9334: 	if ($entries[0]=~/^\#/) {
 9335: 	    my $id=$entries[0];
 9336: 	    my @idresponses;
 9337: 	    $id=~s/^[\#0]+//;
 9338: 	    for (my $i=0;$i<$number;$i++) {
 9339: 		my $idx=3+$i*6;
 9340: 		push(@idresponses,$entries[$idx]);
 9341: 	    }
 9342: 	    $$responses{$id}=join(',',@idresponses);
 9343: 	}
 9344:     }
 9345:     return ($errormsg,$number);
 9346: }
 9347: 
 9348: sub interwrite_eval {
 9349:     my ($questiontitles,$responses)=@_;
 9350:     my $number=0;
 9351:     my $errormsg='';
 9352:     my $skipline=1;
 9353:     my $questionnumber=0;
 9354:     my %idresponses=();
 9355:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9356:         my %components=&Apache::loncommon::record_sep($line);
 9357:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9358:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9359:         if ($entries[1] eq 'Response') { $skipline=1; }
 9360:         next if $skipline;
 9361:         if ($entries[0]!=$questionnumber) {
 9362:            $questionnumber=$entries[0];
 9363:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9364:            $number++;
 9365:         }
 9366:         my $id=$entries[4];
 9367:         $id=~s/^[\#0]+//;
 9368:         $id=~s/^v\d*\://i;
 9369:         $id=~s/[\-\:]//g;
 9370:         $idresponses{$id}[$number]=$entries[6];
 9371:     }
 9372:     foreach my $id (keys(%idresponses)) {
 9373:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9374:        $$responses{$id}=~s/^\s*\,//;
 9375:     }
 9376:     return ($errormsg,$number);
 9377: }
 9378: 
 9379: sub assign_clicker_grades {
 9380:     my ($r)=@_;
 9381:     my ($symb)=&get_symb($r);
 9382:     if (!$symb) {return '';}
 9383: # See which part we are saving to
 9384:     my $res_error;
 9385:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9386:     if ($res_error) {
 9387:         return &navmap_errormsg();
 9388:     }
 9389: # FIXME: This should probably look for the first handgradeable part
 9390:     my $part=$$partlist[0];
 9391: # Start screen output
 9392:     my $result='';
 9393: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9394: 
 9395:     my $heading=&mt('Assigning grades based on clicker file');
 9396:     $result.=(<<ENDHEADER);
 9397: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9398: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9399: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9400: ENDHEADER
 9401: # Get correct result
 9402: # FIXME: Possibly need delimiter other than ":"
 9403:     my @correct=();
 9404:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9405:     my $number=$env{'form.number'};
 9406:     if ($gradingmechanism ne 'attendance') {
 9407:        foreach my $key (keys(%env)) {
 9408:           if ($key=~/^form\.correct\:/) {
 9409:              my @input=split(/\,/,$env{$key});
 9410:              for (my $i=0;$i<=$#input;$i++) {
 9411:                  if (($correct[$i]) && ($input[$i]) &&
 9412:                      ($correct[$i] ne $input[$i])) {
 9413:                     $result.='<br /><span class="LC_warning">'.
 9414:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9415:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9416:                  } elsif ($input[$i]) {
 9417:                     $correct[$i]=$input[$i];
 9418:                  }
 9419:              }
 9420:           }
 9421:        }
 9422:        for (my $i=0;$i<$number;$i++) {
 9423:           if (!$correct[$i]) {
 9424:              $result.='<br /><span class="LC_error">'.
 9425:                       &mt('No correct result given for question "[_1]"!',
 9426:                           $env{'form.question:'.$i}).'</span>';
 9427:           }
 9428:        }
 9429:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9430:     }
 9431: # Start grading
 9432:     my $pcorrect=$env{'form.pcorrect'};
 9433:     my $pincorrect=$env{'form.pincorrect'};
 9434:     my $storecount=0;
 9435:     foreach my $key (keys(%env)) {
 9436:        my $user='';
 9437:        if ($key=~/^form\.student\:(.*)$/) {
 9438:           $user=$1;
 9439:        }
 9440:        if ($key=~/^form\.unknown\:(.*)$/) {
 9441:           my $id=$1;
 9442:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9443:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9444:           } elsif ($env{'form.multi'.$id}) {
 9445:              $user=$env{'form.multi'.$id};
 9446:           }
 9447:        }
 9448:        if ($user) { 
 9449:           my @answer=split(/\,/,$env{$key});
 9450:           my $sum=0;
 9451:           my $realnumber=$number;
 9452:           for (my $i=0;$i<$number;$i++) {
 9453:              if  ($correct[$i] eq '-') {
 9454:                 $realnumber--;
 9455:              } elsif ($answer[$i]) {
 9456:                 if ($gradingmechanism eq 'attendance') {
 9457:                    $sum+=$pcorrect;
 9458:                 } elsif ($correct[$i] eq '*') {
 9459:                    $sum+=$pcorrect;
 9460:                 } else {
 9461:                    if ($answer[$i] eq $correct[$i]) {
 9462:                       $sum+=$pcorrect;
 9463:                    } else {
 9464:                       $sum+=$pincorrect;
 9465:                    }
 9466:                 }
 9467:              }
 9468:           }
 9469:           my $ave=$sum/(100*$realnumber);
 9470: # Store
 9471:           my ($username,$domain)=split(/\:/,$user);
 9472:           my %grades=();
 9473:           $grades{"resource.$part.solved"}='correct_by_override';
 9474:           $grades{"resource.$part.awarded"}=$ave;
 9475:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9476:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9477:                                                  $env{'request.course.id'},
 9478:                                                  $domain,$username);
 9479:           if ($returncode ne 'ok') {
 9480:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9481:           } else {
 9482:              $storecount++;
 9483:           }
 9484:        }
 9485:     }
 9486: # We are done
 9487:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9488:              '</td></tr></table>'."\n".
 9489:              '</td></tr></table><br /><br />'."\n";
 9490:     return $result.&show_grading_menu_form($symb);
 9491: }
 9492: 
 9493: sub navmap_errormsg {
 9494:     return '<div class="LC_error">'.
 9495:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9496:            &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>').
 9497:            '</div>';
 9498: }
 9499: 
 9500: sub handler {
 9501:     my $request=$_[0];
 9502:     &reset_caches();
 9503:     if ($env{'browser.mathml'}) {
 9504: 	&Apache::loncommon::content_type($request,'text/xml');
 9505:     } else {
 9506: 	&Apache::loncommon::content_type($request,'text/html');
 9507:     }
 9508:     $request->send_http_header;
 9509:     return '' if $request->header_only;
 9510:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9511:     my $symb=&get_symb($request,1);
 9512:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9513:     my $command=$commands[0];
 9514: 
 9515:     if ($#commands > 0) {
 9516: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9517:     }
 9518: 
 9519:     $ssi_error = 0;
 9520:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9521:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9522:                                           {'bread_crumbs' => $brcrum}));
 9523:     if ($symb eq '' && $command eq '') {
 9524: 	if ($env{'user.adv'}) {
 9525: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9526: 		($env{'form.codethree'})) {
 9527: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9528: 		    $env{'form.codethree'};
 9529: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9530: 		    &Apache::lonnet::checkin($token);
 9531: 		if ($tsymb) {
 9532: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9533: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9534: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9535: 					  ('grade_username' => $tuname,
 9536: 					   'grade_domain' => $tudom,
 9537: 					   'grade_courseid' => $tcrsid,
 9538: 					   'grade_symb' => $tsymb)));
 9539: 		    } else {
 9540: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9541: 		    }
 9542: 		} else {
 9543: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9544: 		}
 9545: 	    } else {
 9546: 		$request->print(&Apache::lonxml::tokeninputfield());
 9547: 	    }
 9548: 	}
 9549:     } else {
 9550: 	&init_perm();
 9551: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9552: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9553: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9554: 	    &pickStudentPage($request);
 9555: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9556: 	    &displayPage($request);
 9557: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9558: 	    &updateGradeByPage($request);
 9559: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9560: 	    &processGroup($request);
 9561: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9562: 	    $request->print(&grading_menu($request));
 9563: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9564: 	    $request->print(&individual($request));
 9565:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9566:             $request->print(&submit_options($request));
 9567:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9568:             $request->print(&submit_options($request));
 9569:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9570:             $request->print(&submit_options_sequence($request));
 9571: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9572: 	    $request->print(&viewgrades($request));
 9573: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9574: 	    $request->print(&processHandGrade($request));
 9575: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9576: 	    $request->print(&editgrades($request));
 9577: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9578: 	    $request->print(&verifyreceipt($request));
 9579:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9580:             $request->print(&process_clicker($request));
 9581:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9582:             $request->print(&process_clicker_file($request));
 9583:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9584:             $request->print(&assign_clicker_grades($request));
 9585: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9586: 	    $request->print(&upcsvScores_form($request));
 9587: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9588: 	    $request->print(&csvupload($request));
 9589: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9590: 	    $request->print(&csvuploadmap($request));
 9591: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9592: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9593: 		$request->print(&csvuploadoptions($request));
 9594: 	    } else {
 9595: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9596: 		    $env{'form.upfile_associate'} = 'reverse';
 9597: 		} else {
 9598: 		    $env{'form.upfile_associate'} = 'forward';
 9599: 		}
 9600: 		$request->print(&csvuploadmap($request));
 9601: 	    }
 9602: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9603: 	    $request->print(&csvuploadassign($request));
 9604: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9605: 	    $request->print(&scantron_selectphase($request));
 9606:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9607:  	    $request->print(&scantron_do_warning($request));
 9608: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9609: 	    $request->print(&scantron_validate_file($request));
 9610: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9611: 	    $request->print(&scantron_process_students($request));
 9612:  	} elsif ($command eq 'scantronupload' && 
 9613:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9614: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9615:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9616:  	} elsif ($command eq 'scantronupload_save' &&
 9617:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9618: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9619:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9620:  	} elsif ($command eq 'scantron_download' &&
 9621: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9622:  	    $request->print(&scantron_download_scantron_data($request));
 9623:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9624:             $request->print(&checkscantron_results($request));     
 9625: 	} elsif ($command) {
 9626: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9627: 	}
 9628:     }
 9629:     if ($ssi_error) {
 9630: 	&ssi_print_error($request);
 9631:     }
 9632:     $request->print(&Apache::loncommon::end_page());
 9633:     &reset_caches();
 9634:     return '';
 9635: }
 9636: 
 9637: 1;
 9638: 
 9639: __END__;
 9640: 
 9641: 
 9642: =head1 NAME
 9643: 
 9644: Apache::grades
 9645: 
 9646: =head1 SYNOPSIS
 9647: 
 9648: Handles the viewing of grades.
 9649: 
 9650: This is part of the LearningOnline Network with CAPA project
 9651: described at http://www.lon-capa.org.
 9652: 
 9653: =head1 OVERVIEW
 9654: 
 9655: Do an ssi with retries:
 9656: While I'd love to factor out this with the vesrion in lonprintout,
 9657: 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
 9658: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9659: 
 9660: At least the logic that drives this has been pulled out into loncommon.
 9661: 
 9662: 
 9663: 
 9664: ssi_with_retries - Does the server side include of a resource.
 9665:                      if the ssi call returns an error we'll retry it up to
 9666:                      the number of times requested by the caller.
 9667:                      If we still have a proble, no text is appended to the
 9668:                      output and we set some global variables.
 9669:                      to indicate to the caller an SSI error occurred.  
 9670:                      All of this is supposed to deal with the issues described
 9671:                      in LonCAPA BZ 5631 see:
 9672:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9673:                      by informing the user that this happened.
 9674: 
 9675: Parameters:
 9676:   resource   - The resource to include.  This is passed directly, without
 9677:                interpretation to lonnet::ssi.
 9678:   form       - The form hash parameters that guide the interpretation of the resource
 9679:                
 9680:   retries    - Number of retries allowed before giving up completely.
 9681: Returns:
 9682:   On success, returns the rendered resource identified by the resource parameter.
 9683: Side Effects:
 9684:   The following global variables can be set:
 9685:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9686:                               It is up to the caller to initialize this to false
 9687:                               if desired.
 9688:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9689:                               of the resource that could not be rendered by the ssi
 9690:                               call.
 9691:    ssi_error_message   - The error string fetched from the ssi response
 9692:                               in the event of an error.
 9693: 
 9694: 
 9695: =head1 HANDLER SUBROUTINE
 9696: 
 9697: ssi_with_retries()
 9698: 
 9699: =head1 SUBROUTINES
 9700: 
 9701: =over
 9702: 
 9703: =item scantron_get_correction() : 
 9704: 
 9705:    Builds the interface screen to interact with the operator to fix a
 9706:    specific error condition in a specific scanline
 9707: 
 9708:  Arguments:
 9709:     $r           - Apache request object
 9710:     $i           - number of the current scanline
 9711:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9712:     $scan_config - hash ref as returned from &get_scantron_config()
 9713:     $line        - full contents of the current scanline
 9714:     $error       - error condition, valid values are
 9715:                    'incorrectCODE', 'duplicateCODE',
 9716:                    'doublebubble', 'missingbubble',
 9717:                    'duplicateID', 'incorrectID'
 9718:     $arg         - extra information needed
 9719:        For errors:
 9720:          - duplicateID   - paper number that this studentID was seen before on
 9721:          - duplicateCODE - array ref of the paper numbers this CODE was
 9722:                            seen on before
 9723:          - incorrectCODE - current incorrect CODE 
 9724:          - doublebubble  - array ref of the bubble lines that have double
 9725:                            bubble errors
 9726:          - missingbubble - array ref of the bubble lines that have missing
 9727:                            bubble errors
 9728: 
 9729: =item  scantron_get_maxbubble() : 
 9730: 
 9731:    Arguments:
 9732:        $nav_error  - Reference to scalar which is a flag to indicate a
 9733:                       failure to retrieve a navmap object.
 9734:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9735:        calling routine should trap the error condition and display the warning
 9736:        found in &navmap_errormsg().
 9737: 
 9738:    Returns the maximum number of bubble lines that are expected to
 9739:    occur. Does this by walking the selected sequence rendering the
 9740:    resource and then checking &Apache::lonxml::get_problem_counter()
 9741:    for what the current value of the problem counter is.
 9742: 
 9743:    Caches the results to $env{'form.scantron_maxbubble'},
 9744:    $env{'form.scantron.bubble_lines.n'}, 
 9745:    $env{'form.scantron.first_bubble_line.n'} and
 9746:    $env{"form.scantron.sub_bubblelines.n"}
 9747:    which are the total number of bubble, lines, the number of bubble
 9748:    lines for response n and number of the first bubble line for response n,
 9749:    and a comma separated list of numbers of bubble lines for sub-questions
 9750:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9751: 
 9752: 
 9753: =item  scantron_validate_missingbubbles() : 
 9754: 
 9755:    Validates all scanlines in the selected file to not have any
 9756:     answers that don't have bubbles that have not been verified
 9757:     to be bubble free.
 9758: 
 9759: =item  scantron_process_students() : 
 9760: 
 9761:    Routine that does the actual grading of the bubble sheet information.
 9762: 
 9763:    The parsed scanline hash is added to %env 
 9764: 
 9765:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9766:    foreach resource , with the form data of
 9767: 
 9768: 	'submitted'     =>'scantron' 
 9769: 	'grade_target'  =>'grade',
 9770: 	'grade_username'=> username of student
 9771: 	'grade_domain'  => domain of student
 9772: 	'grade_courseid'=> of course
 9773: 	'grade_symb'    => symb of resource to grade
 9774: 
 9775:     This triggers a grading pass. The problem grading code takes care
 9776:     of converting the bubbled letter information (now in %env) into a
 9777:     valid submission.
 9778: 
 9779: =item  scantron_upload_scantron_data() :
 9780: 
 9781:     Creates the screen for adding a new bubble sheet data file to a course.
 9782: 
 9783: =item  scantron_upload_scantron_data_save() : 
 9784: 
 9785:    Adds a provided bubble information data file to the course if user
 9786:    has the correct privileges to do so. 
 9787: 
 9788: =item  valid_file() :
 9789: 
 9790:    Validates that the requested bubble data file exists in the course.
 9791: 
 9792: =item  scantron_download_scantron_data() : 
 9793: 
 9794:    Shows a list of the three internal files (original, corrected,
 9795:    skipped) for a specific bubble sheet data file that exists in the
 9796:    course.
 9797: 
 9798: =item  scantron_validate_ID() : 
 9799: 
 9800:    Validates all scanlines in the selected file to not have any
 9801:    invalid or underspecified student/employee IDs
 9802: 
 9803: =item navmap_errormsg() :
 9804: 
 9805:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9806:    Should be called whenever the request to instantiate a navmap object fails.  
 9807: 
 9808: =back
 9809: 
 9810: =cut

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