File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.569: download - view: text, annotated - select for diffs
Wed May 6 16:19:26 2009 UTC (14 years, 11 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
XHTML conform selected/checked/multiple HTML attributes
and optimized spacing

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.569 2009/05/06 16:19:26 bisitz 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: sub getpartlist {
  100:     my ($symb) = @_;
  101: 
  102:     my $navmap   = Apache::lonnavmaps::navmap->new();
  103:     my $res      = $navmap->getBySymb($symb);
  104:     my $partlist = $res->parts();
  105:     my $url      = $res->src();
  106:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  107: 
  108:     my @stores;
  109:     foreach my $part (@{ $partlist }) {
  110: 	foreach my $key (@metakeys) {
  111: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  112: 	}
  113:     }
  114:     return @stores;
  115: }
  116: 
  117: # --- Get the symbolic name of a problem and the url
  118: sub get_symb {
  119:     my ($request,$silent) = @_;
  120:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  121:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  122:     if ($symb eq '') { 
  123: 	if (!$silent) {
  124: 	    $request->print("Unable to handle ambiguous references:$url:.");
  125: 	    return ();
  126: 	}
  127:     }
  128:     &Apache::lonenc::check_decrypt(\$symb);
  129:     return ($symb);
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: sub response_type {
  147:     my ($symb) = shift;
  148: 
  149:     my $navmap = Apache::lonnavmaps::navmap->new();
  150:     my $res = $navmap->getBySymb($symb);
  151:     my $partlist = $res->parts();
  152:     my %vPart = 
  153: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  154:     my (%response_types,%handgrade);
  155:     foreach my $part (@{ $partlist }) {
  156: 	next if (%vPart && !exists($vPart{$part}));
  157: 
  158: 	my @types = $res->responseType($part);
  159: 	my @ids = $res->responseIds($part);
  160: 	for (my $i=0; $i < scalar(@ids); $i++) {
  161: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  162: 	    $handgrade{$part.'_'.$ids[$i]} = 
  163: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  164: 				     '.handgrade',$symb);
  165: 	}
  166:     }
  167:     return ($partlist,\%handgrade,\%response_types);
  168: }
  169: 
  170: sub flatten_responseType {
  171:     my ($responseType) = @_;
  172:     my @part_response_id =
  173: 	map { 
  174: 	    my $part = $_;
  175: 	    map {
  176: 		[$part,$_]
  177: 		} sort(keys(%{ $responseType->{$part} }));
  178: 	} sort(keys(%$responseType));
  179:     return @part_response_id;
  180: }
  181: 
  182: sub get_display_part {
  183:     my ($partID,$symb)=@_;
  184:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  185:     if (defined($display) and $display ne '') {
  186: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  187:     } else {
  188: 	$display=$partID;
  189:     }
  190:     return $display;
  191: }
  192: 
  193: #--- Show resource title
  194: #--- and parts and response type
  195: sub showResourceInfo {
  196:     my ($symb,$probTitle,$checkboxes) = @_;
  197:     my $col=3;
  198:     if ($checkboxes) { $col=4; }
  199:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  200:     $result .='<table border="0">';
  201:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  202:     my %resptype = ();
  203:     my $hdgrade='no';
  204:     my %partsseen;
  205:     foreach my $partID (sort(keys(%$responseType))) {
  206: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  207: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  208: 	    my $responsetype = $responseType->{$partID}->{$resID};
  209: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  210: 	    $result.='<tr>';
  211: 	    if ($checkboxes) {
  212: 		if (exists($partsseen{$partID})) {
  213: 		    $result.="<td>&nbsp;</td>";
  214: 		} else {
  215: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  216: 		}
  217: 		$partsseen{$partID}=1;
  218: 	    }
  219: 	    my $display_part=&get_display_part($partID,$symb);
  220: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
  221:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  222: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
  223: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  224: 	}
  225:     }
  226:     $result.='</table>'."\n";
  227:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  228: }
  229: 
  230: sub reset_caches {
  231:     &reset_analyze_cache();
  232:     &reset_perm();
  233: }
  234: 
  235: {
  236:     my %analyze_cache;
  237:     my %analyze_cache_formkeys;
  238: 
  239:     sub reset_analyze_cache {
  240: 	undef(%analyze_cache);
  241:         undef(%analyze_cache_formkeys);
  242:     }
  243: 
  244:     sub get_analyze {
  245: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  246: 	my $key = "$symb\0$uname\0$udom";
  247: 	if (exists($analyze_cache{$key})) {
  248:             my $getupdate = 0;
  249:             if (ref($add_to_hash) eq 'HASH') {
  250:                 foreach my $item (keys(%{$add_to_hash})) {
  251:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  252:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  253:                             $getupdate = 1;
  254:                             last;
  255:                         }
  256:                     } else {
  257:                         $getupdate = 1;
  258:                     }
  259:                 }
  260:             }
  261:             if (!$getupdate) {
  262:                 return $analyze_cache{$key};
  263:             }
  264:         }
  265: 
  266: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  267: 	$url=&Apache::lonnet::clutter($url);
  268:         my %form = ('grade_target'      => 'analyze',
  269:                     'grade_domain'      => $udom,
  270:                     'grade_symb'        => $symb,
  271:                     'grade_courseid'    =>  $env{'request.course.id'},
  272:                     'grade_username'    => $uname,
  273:                     'grade_noincrement' => $no_increment);
  274:         if (ref($add_to_hash)) {
  275:             %form = (%form,%{$add_to_hash});
  276:         } 
  277: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  278: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  279: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  280:         if (ref($add_to_hash) eq 'HASH') {
  281:             $analyze_cache_formkeys{$key} = $add_to_hash;
  282:         } else {
  283:             $analyze_cache_formkeys{$key} = {};
  284:         }
  285: 	return $analyze_cache{$key} = \%analyze;
  286:     }
  287: 
  288:     sub get_order {
  289: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  290: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  291: 	return $analyze->{"$partid.$respid.shown"};
  292:     }
  293: 
  294:     sub get_radiobutton_correct_foil {
  295: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  296: 	my $analyze = &get_analyze($symb,$uname,$udom);
  297:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  298:         if (ref($foils) eq 'ARRAY') {
  299: 	    foreach my $foil (@{$foils}) {
  300: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  301: 		    return $foil;
  302: 	        }
  303: 	    }
  304: 	}
  305:     }
  306: 
  307:     sub scantron_partids_tograde {
  308:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  309:         my (%analysis,@parts);
  310:         if (ref($resource)) {
  311:             my $symb = $resource->symb();
  312:             my $add_to_form;
  313:             if ($check_for_randomlist) {
  314:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  315:             }
  316:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  317:             if (ref($analyze) eq 'HASH') {
  318:                 %analysis = %{$analyze};
  319:             }
  320:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  321:                 foreach my $part (@{$analysis{'parts'}}) {
  322:                     my ($id,$respid) = split(/\./,$part);
  323:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  324:                         push(@parts,$part);
  325:                     }
  326:                 }
  327:             }
  328:         }
  329:         return (\%analysis,\@parts);
  330:     }
  331: 
  332: }
  333: 
  334: #--- Clean response type for display
  335: #--- Currently filters option/rank/radiobutton/match/essay/Task
  336: #        response types only.
  337: sub cleanRecord {
  338:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  339: 	$uname,$udom) = @_;
  340:     my $grayFont = '<span class="LC_internal_info">';
  341:     if ($response =~ /^(option|rank)$/) {
  342: 	my %answer=&Apache::lonnet::str2hash($answer);
  343: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  344: 	my ($toprow,$bottomrow);
  345: 	foreach my $foil (@$order) {
  346: 	    if ($grading{$foil} == 1) {
  347: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  348: 	    } else {
  349: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  350: 	    }
  351: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  352: 	}
  353: 	return '<blockquote><table border="1">'.
  354: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  355: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  356: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  357:     } elsif ($response eq 'match') {
  358: 	my %answer=&Apache::lonnet::str2hash($answer);
  359: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  360: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  361: 	my ($toprow,$middlerow,$bottomrow);
  362: 	foreach my $foil (@$order) {
  363: 	    my $item=shift(@items);
  364: 	    if ($grading{$foil} == 1) {
  365: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  366: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  367: 	    } else {
  368: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  369: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  370: 	    }
  371: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  372: 	}
  373: 	return '<blockquote><table border="1">'.
  374: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  375: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  376: 	    $middlerow.'</tr>'.
  377: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  378: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  379:     } elsif ($response eq 'radiobutton') {
  380: 	my %answer=&Apache::lonnet::str2hash($answer);
  381: 	my ($toprow,$bottomrow);
  382: 	my $correct = 
  383: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  384: 	foreach my $foil (@$order) {
  385: 	    if (exists($answer{$foil})) {
  386: 		if ($foil eq $correct) {
  387: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  388: 		} else {
  389: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  390: 		}
  391: 	    } else {
  392: 		$toprow.='<td>'.&mt('false').'</td>';
  393: 	    }
  394: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  395: 	}
  396: 	return '<blockquote><table border="1">'.
  397: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  398: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  399: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  400:     } elsif ($response eq 'essay') {
  401: 	if (! exists ($env{'form.'.$symb})) {
  402: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  403: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  404: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  405: 
  406: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  407: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  408: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  409: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  410: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  411: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  412: 	}
  413: 	$answer =~ s-\n-<br />-g;
  414: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  415:     } elsif ( $response eq 'organic') {
  416: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  417: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  418: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  419: 	return $result;
  420:     } elsif ( $response eq 'Task') {
  421: 	if ( $answer eq 'SUBMITTED') {
  422: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  423: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  424: 	    return $result;
  425: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  426: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  427: 			       keys(%{$record}));
  428: 	    return join('<br />',($version,@matches));
  429: 			       
  430: 			       
  431: 	} else {
  432: 	    my $result =
  433: 		'<p>'
  434: 		.&mt('Overall result: [_1]',
  435: 		     $record->{$version."resource.$respid.$partid.status"})
  436: 		.'</p>';
  437: 	    
  438: 	    $result .= '<ul>';
  439: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  440: 			     keys(%{$record}));
  441: 	    foreach my $grade (sort(@grade)) {
  442: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  443: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  444: 				     $dim, $record->{$grade}).
  445: 			  '</li>';
  446: 	    }
  447: 	    $result.='</ul>';
  448: 	    return $result;
  449: 	}
  450:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  451: 	$answer = 
  452: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  453: 							      $answer);
  454:     }
  455:     return $answer;
  456: }
  457: 
  458: #-- A couple of common js functions
  459: sub commonJSfunctions {
  460:     my $request = shift;
  461:     $request->print(<<COMMONJSFUNCTIONS);
  462: <script type="text/javascript" language="javascript">
  463:     function radioSelection(radioButton) {
  464: 	var selection=null;
  465: 	if (radioButton.length > 1) {
  466: 	    for (var i=0; i<radioButton.length; i++) {
  467: 		if (radioButton[i].checked) {
  468: 		    return radioButton[i].value;
  469: 		}
  470: 	    }
  471: 	} else {
  472: 	    if (radioButton.checked) return radioButton.value;
  473: 	}
  474: 	return selection;
  475:     }
  476: 
  477:     function pullDownSelection(selectOne) {
  478: 	var selection="";
  479: 	if (selectOne.length > 1) {
  480: 	    for (var i=0; i<selectOne.length; i++) {
  481: 		if (selectOne[i].selected) {
  482: 		    return selectOne[i].value;
  483: 		}
  484: 	    }
  485: 	} else {
  486:             // only one value it must be the selected one
  487: 	    return selectOne.value;
  488: 	}
  489:     }
  490: </script>
  491: COMMONJSFUNCTIONS
  492: }
  493: 
  494: #--- Dumps the class list with usernames,list of sections,
  495: #--- section, ids and fullnames for each user.
  496: sub getclasslist {
  497:     my ($getsec,$filterlist,$getgroup) = @_;
  498:     my @getsec;
  499:     my @getgroup;
  500:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  501:     if (!ref($getsec)) {
  502: 	if ($getsec ne '' && $getsec ne 'all') {
  503: 	    @getsec=($getsec);
  504: 	}
  505:     } else {
  506: 	@getsec=@{$getsec};
  507:     }
  508:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  509:     if (!ref($getgroup)) {
  510: 	if ($getgroup ne '' && $getgroup ne 'all') {
  511: 	    @getgroup=($getgroup);
  512: 	}
  513:     } else {
  514: 	@getgroup=@{$getgroup};
  515:     }
  516:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  517: 
  518:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  519:     # Bail out if we were unable to get the classlist
  520:     return if (! defined($classlist));
  521:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  522:     #
  523:     my %sections;
  524:     my %fullnames;
  525:     foreach my $student (keys(%$classlist)) {
  526:         my $end      = 
  527:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  528:         my $start    = 
  529:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  530:         my $id       = 
  531:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  532:         my $section  = 
  533:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  534:         my $fullname = 
  535:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  536:         my $status   = 
  537:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  538:         my $group   = 
  539:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  540: 	# filter students according to status selected
  541: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  542: 	    if (!($stu_status =~ $status)) {
  543: 		delete($classlist->{$student});
  544: 		next;
  545: 	    }
  546: 	}
  547: 	# filter students according to groups selected
  548: 	my @stu_groups = split(/,/,$group);
  549: 	if (@getgroup) {
  550: 	    my $exclude = 1;
  551: 	    foreach my $grp (@getgroup) {
  552: 	        foreach my $stu_group (@stu_groups) {
  553: 	            if ($stu_group eq $grp) {
  554: 	                $exclude = 0;
  555:     	            } 
  556: 	        }
  557:     	        if (($grp eq 'none') && !$group) {
  558:         	        $exclude = 0;
  559:         	}
  560: 	    }
  561: 	    if ($exclude) {
  562: 	        delete($classlist->{$student});
  563: 	    }
  564: 	}
  565: 	$section = ($section ne '' ? $section : 'none');
  566: 	if (&canview($section)) {
  567: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  568: 		$sections{$section}++;
  569: 		if ($classlist->{$student}) {
  570: 		    $fullnames{$student}=$fullname;
  571: 		}
  572: 	    } else {
  573: 		delete($classlist->{$student});
  574: 	    }
  575: 	} else {
  576: 	    delete($classlist->{$student});
  577: 	}
  578:     }
  579:     my %seen = ();
  580:     my @sections = sort(keys(%sections));
  581:     return ($classlist,\@sections,\%fullnames);
  582: }
  583: 
  584: sub canmodify {
  585:     my ($sec)=@_;
  586:     if ($perm{'mgr'}) {
  587: 	if (!defined($perm{'mgr_section'})) {
  588: 	    # can modify whole class
  589: 	    return 1;
  590: 	} else {
  591: 	    if ($sec eq $perm{'mgr_section'}) {
  592: 		#can modify the requested section
  593: 		return 1;
  594: 	    } else {
  595: 		# can't modify the request section
  596: 		return 0;
  597: 	    }
  598: 	}
  599:     }
  600:     #can't modify
  601:     return 0;
  602: }
  603: 
  604: sub canview {
  605:     my ($sec)=@_;
  606:     if ($perm{'vgr'}) {
  607: 	if (!defined($perm{'vgr_section'})) {
  608: 	    # can modify whole class
  609: 	    return 1;
  610: 	} else {
  611: 	    if ($sec eq $perm{'vgr_section'}) {
  612: 		#can modify the requested section
  613: 		return 1;
  614: 	    } else {
  615: 		# can't modify the request section
  616: 		return 0;
  617: 	    }
  618: 	}
  619:     }
  620:     #can't modify
  621:     return 0;
  622: }
  623: 
  624: #--- Retrieve the grade status of a student for all the parts
  625: sub student_gradeStatus {
  626:     my ($symb,$udom,$uname,$partlist) = @_;
  627:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  628:     my %partstatus = ();
  629:     foreach (@$partlist) {
  630: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  631: 	$status              = 'nothing' if ($status eq '');
  632: 	$partstatus{$_}      = $status;
  633: 	my $subkey           = "resource.$_.submitted_by";
  634: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  635:     }
  636:     return %partstatus;
  637: }
  638: 
  639: # hidden form and javascript that calls the form
  640: # Use by verifyscript and viewgrades
  641: # Shows a student's view of problem and submission
  642: sub jscriptNform {
  643:     my ($symb) = @_;
  644:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  645:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  646: 	'    function viewOneStudent(user,domain) {'."\n".
  647: 	'	document.onestudent.student.value = user;'."\n".
  648: 	'	document.onestudent.userdom.value = domain;'."\n".
  649: 	'	document.onestudent.submit();'."\n".
  650: 	'    }'."\n".
  651: 	'</script>'."\n";
  652:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  653: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  654: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  655: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  656: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  657: 	'<input type="hidden" name="command" value="submission" />'."\n".
  658: 	'<input type="hidden" name="student" value="" />'."\n".
  659: 	'<input type="hidden" name="userdom" value="" />'."\n".
  660: 	'</form>'."\n";
  661:     return $jscript;
  662: }
  663: 
  664: 
  665: 
  666: # Given the score (as a number [0-1] and the weight) what is the final
  667: # point value? This function will round to the nearest tenth, third,
  668: # or quarter if one of those is within the tolerance of .00001.
  669: sub compute_points {
  670:     my ($score, $weight) = @_;
  671:     
  672:     my $tolerance = .00001;
  673:     my $points = $score * $weight;
  674: 
  675:     # Check for nearness to 1/x.
  676:     my $check_for_nearness = sub {
  677:         my ($factor) = @_;
  678:         my $num = ($points * $factor) + $tolerance;
  679:         my $floored_num = floor($num);
  680:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  681:             return $floored_num / $factor;
  682:         }
  683:         return $points;
  684:     };
  685: 
  686:     $points = $check_for_nearness->(10);
  687:     $points = $check_for_nearness->(3);
  688:     $points = $check_for_nearness->(4);
  689:     
  690:     return $points;
  691: }
  692: 
  693: #------------------ End of general use routines --------------------
  694: 
  695: #
  696: # Find most similar essay
  697: #
  698: 
  699: sub most_similar {
  700:     my ($uname,$udom,$uessay,$old_essays)=@_;
  701: 
  702: # ignore spaces and punctuation
  703: 
  704:     $uessay=~s/\W+/ /gs;
  705: 
  706: # ignore empty submissions (occuring when only files are sent)
  707: 
  708:     unless ($uessay=~/\w+/) { return ''; }
  709: 
  710: # these will be returned. Do not care if not at least 50 percent similar
  711:     my $limit=0.6;
  712:     my $sname='';
  713:     my $sdom='';
  714:     my $scrsid='';
  715:     my $sessay='';
  716: # go through all essays ...
  717:     foreach my $tkey (keys(%$old_essays)) {
  718: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  719: # ... except the same student
  720:         next if (($tname eq $uname) && ($tdom eq $udom));
  721: 	my $tessay=$old_essays->{$tkey};
  722: 	$tessay=~s/\W+/ /gs;
  723: # String similarity gives up if not even limit
  724: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  725: # Found one
  726: 	if ($tsimilar>$limit) {
  727: 	    $limit=$tsimilar;
  728: 	    $sname=$tname;
  729: 	    $sdom=$tdom;
  730: 	    $scrsid=$tcrsid;
  731: 	    $sessay=$old_essays->{$tkey};
  732: 	}
  733:     }
  734:     if ($limit>0.6) {
  735:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  736:     } else {
  737:        return ('','','','',0);
  738:     }
  739: }
  740: 
  741: #-------------------------------------------------------------------
  742: 
  743: #------------------------------------ Receipt Verification Routines
  744: #
  745: #--- Check whether a receipt number is valid.---
  746: sub verifyreceipt {
  747:     my $request  = shift;
  748: 
  749:     my $courseid = $env{'request.course.id'};
  750:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  751: 	$env{'form.receipt'};
  752:     $receipt     =~ s/[^\-\d]//g;
  753:     my ($symb)   = &get_symb($request);
  754: 
  755:     my $title.=
  756: 	'<h3><span class="LC_info">'.
  757: 	&mt('Verifying  Receipt No. [_1]',$receipt).
  758: 	'</span></h3>'."\n".
  759: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  760: 	'</h4>'."\n";
  761: 
  762:     my ($string,$contents,$matches) = ('','',0);
  763:     my (undef,undef,$fullname) = &getclasslist('all','0');
  764:     
  765:     my $receiptparts=0;
  766:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  767: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  768:     my $parts=['0'];
  769:     if ($receiptparts) { ($parts)=&response_type($symb); }
  770:     
  771:     my $header = 
  772: 	&Apache::loncommon::start_data_table().
  773: 	&Apache::loncommon::start_data_table_header_row().
  774: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  775: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  776: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  777:     if ($receiptparts) {
  778: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  779:     }
  780:     $header.=
  781: 	&Apache::loncommon::end_data_table_header_row();
  782: 
  783:     foreach (sort 
  784: 	     {
  785: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  786: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  787: 		 }
  788: 		 return $a cmp $b;
  789: 	     } (keys(%$fullname))) {
  790: 	my ($uname,$udom)=split(/\:/);
  791: 	foreach my $part (@$parts) {
  792: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  793: 		$contents.=
  794: 		    &Apache::loncommon::start_data_table_row().
  795: 		    '<td>&nbsp;'."\n".
  796: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  797: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  798: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  799: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  800: 		if ($receiptparts) {
  801: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  802: 		}
  803: 		$contents.= 
  804: 		    &Apache::loncommon::end_data_table_row()."\n";
  805: 		
  806: 		$matches++;
  807: 	    }
  808: 	}
  809:     }
  810:     if ($matches == 0) {
  811: 	$string = $title.&mt('No match found for the above receipt.');
  812:     } else {
  813: 	$string = &jscriptNform($symb).$title.
  814: 	    '<p>'.
  815: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  816: 	    '</p>'.
  817: 	    $header.
  818: 	    $contents.
  819: 	    &Apache::loncommon::end_data_table()."\n";
  820:     }
  821:     return $string.&show_grading_menu_form($symb);
  822: }
  823: 
  824: #--- This is called by a number of programs.
  825: #--- Called from the Grading Menu - View/Grade an individual student
  826: #--- Also called directly when one clicks on the subm button 
  827: #    on the problem page.
  828: sub listStudents {
  829:     my ($request) = shift;
  830: 
  831:     my ($symb) = &get_symb($request);
  832:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  833:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  834:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  835:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  836:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  837:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  838:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  839: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  840: 
  841:     my $result='<h3><span class="LC_info">&nbsp;'
  842: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  843: 	.'</span></h3>';
  844: 
  845:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  846: 
  847:     my %lt = &Apache::lonlocal::texthash (
  848: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  849: 		'single'   => 'Please select the student before clicking on the Next button.',
  850: 	     );
  851:     $request->print(<<LISTJAVASCRIPT);
  852: <script type="text/javascript" language="javascript">
  853:     function checkSelect(checkBox) {
  854: 	var ctr=0;
  855: 	var sense="";
  856: 	if (checkBox.length > 1) {
  857: 	    for (var i=0; i<checkBox.length; i++) {
  858: 		if (checkBox[i].checked) {
  859: 		    ctr++;
  860: 		}
  861: 	    }
  862: 	    sense = '$lt{'multiple'}';
  863: 	} else {
  864: 	    if (checkBox.checked) {
  865: 		ctr = 1;
  866: 	    }
  867: 	    sense = '$lt{'single'}';
  868: 	}
  869: 	if (ctr == 0) {
  870: 	    alert(sense);
  871: 	    return false;
  872: 	}
  873: 	document.gradesub.submit();
  874:     }
  875: 
  876:     function reLoadList(formname) {
  877: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  878: 	formname.command.value = 'submission';
  879: 	formname.submit();
  880:     }
  881: </script>
  882: LISTJAVASCRIPT
  883: 
  884:     &commonJSfunctions($request);
  885:     $request->print($result);
  886: 
  887:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  888:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  889:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  890: 	"\n".$table;
  891: 	
  892:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  893:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  894:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  895:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  896:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  897:                   .&Apache::lonhtmlcommon::row_closure();
  898:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  899:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  900:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  901:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  902:                   .&Apache::lonhtmlcommon::row_closure();
  903: 
  904:     my $submission_options;
  905:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  906: 	$submission_options.=
  907: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  908:     }
  909:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  910:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  911:     $env{'form.Status'} = $saveStatus;
  912:     $submission_options.=
  913: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  914: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  915: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  916: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  917:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  918:                   .$submission_options
  919:                   .&Apache::lonhtmlcommon::row_closure();
  920: 
  921:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  922:                   .'<select name="increment">'
  923:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  924:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  925:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  926:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  927:                   .'</select>'
  928:                   .&Apache::lonhtmlcommon::row_closure();
  929: 
  930:     $gradeTable .= 
  931:         &build_section_inputs().
  932: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  933: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  934: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  935: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  936: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  937: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  938: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  939: 
  940:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  941: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  942:     } else {
  943:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  944:                       .&Apache::lonhtmlcommon::StatusOptions(
  945:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  946:                       .&Apache::lonhtmlcommon::row_closure();
  947:     }
  948: 
  949:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  950:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  951:                   .&Apache::lonhtmlcommon::row_closure(1)
  952:                   .&Apache::lonhtmlcommon::end_pick_box();
  953: 
  954:     $gradeTable .= '<p>'
  955:                   .&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"
  956:                   .'<input type="hidden" name="command" value="processGroup" />'
  957:                   .'</p>';
  958: 
  959: # checkall buttons
  960:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  961:     $gradeTable.='<input type="button" '."\n".
  962: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  963: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  964:     $gradeTable.=&check_buttons();
  965:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  966:     $gradeTable.= &Apache::loncommon::start_data_table().
  967: 	&Apache::loncommon::start_data_table_header_row();
  968:     my $loop = 0;
  969:     while ($loop < 2) {
  970: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  971: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  972: 	if ($env{'form.showgrading'} eq 'yes' 
  973: 	    && $submitonly ne 'queued'
  974: 	    && $submitonly ne 'all') {
  975: 	    foreach my $part (sort(@$partlist)) {
  976: 		my $display_part=
  977: 		    &get_display_part((split(/_/,$part))[0],$symb);
  978: 		$gradeTable.=
  979: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  980: 	    }
  981: 	} elsif ($submitonly eq 'queued') {
  982: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  983: 	}
  984: 	$loop++;
  985: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  986:     }
  987:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  988: 
  989:     my $ctr = 0;
  990:     foreach my $student (sort 
  991: 			 {
  992: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  993: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  994: 			     }
  995: 			     return $a cmp $b;
  996: 			 }
  997: 			 (keys(%$fullname))) {
  998: 	my ($uname,$udom) = split(/:/,$student);
  999: 
 1000: 	my %status = ();
 1001: 
 1002: 	if ($submitonly eq 'queued') {
 1003: 	    my %queue_status = 
 1004: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1005: 							$udom,$uname);
 1006: 	    next if (!defined($queue_status{'gradingqueue'}));
 1007: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1008: 	}
 1009: 
 1010: 	if ($env{'form.showgrading'} eq 'yes' 
 1011: 	    && $submitonly ne 'queued'
 1012: 	    && $submitonly ne 'all') {
 1013: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1014: 	    my $submitted = 0;
 1015: 	    my $graded = 0;
 1016: 	    my $incorrect = 0;
 1017: 	    foreach (keys(%status)) {
 1018: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1019: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1020: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1021: 		
 1022: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1023: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1024: 		    $submitted = 0;
 1025: 		    my ($part)=split(/\./,$partid);
 1026: 		    $gradeTable.='<input type="hidden" name="'.
 1027: 			$student.':'.$part.':submitted_by" value="'.
 1028: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1029: 		}
 1030: 	    }
 1031: 	    
 1032: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1033: 				     $submitonly eq 'incorrect' ||
 1034: 				     $submitonly eq 'graded'));
 1035: 	    next if (!$graded && ($submitonly eq 'graded'));
 1036: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1037: 	}
 1038: 
 1039: 	$ctr++;
 1040: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1041:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1042: 	if ( $perm{'vgr'} eq 'F' ) {
 1043: 	    if ($ctr%2 ==1) {
 1044: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1045: 	    }
 1046: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1047:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1048:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1049: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1050: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1051: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1052: 
 1053: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1054: 		foreach (sort(keys(%status))) {
 1055: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1056: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1057: 		}
 1058: 	    }
 1059: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1060: 	    if ($ctr%2 ==0) {
 1061: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1062: 	    }
 1063: 	}
 1064:     }
 1065:     if ($ctr%2 ==1) {
 1066: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1067: 	    if ($env{'form.showgrading'} eq 'yes' 
 1068: 		&& $submitonly ne 'queued'
 1069: 		&& $submitonly ne 'all') {
 1070: 		foreach (@$partlist) {
 1071: 		    $gradeTable.='<td>&nbsp;</td>';
 1072: 		}
 1073: 	    } elsif ($submitonly eq 'queued') {
 1074: 		$gradeTable.='<td>&nbsp;</td>';
 1075: 	    }
 1076: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1077:     }
 1078: 
 1079:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1080: 	'<input type="button" '.
 1081: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1082: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1083:     if ($ctr == 0) {
 1084: 	my $num_students=(scalar(keys(%$fullname)));
 1085: 	if ($num_students eq 0) {
 1086: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1087: 	} else {
 1088: 	    my $submissions='submissions';
 1089: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1090: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1091: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1092: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1093: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1094: 		    $num_students).
 1095: 		'</span><br />';
 1096: 	}
 1097:     } elsif ($ctr == 1) {
 1098: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1099:     }
 1100:     $gradeTable.=&show_grading_menu_form($symb);
 1101:     $request->print($gradeTable);
 1102:     return '';
 1103: }
 1104: 
 1105: #---- Called from the listStudents routine
 1106: 
 1107: sub check_script {
 1108:     my ($form, $type)=@_;
 1109:     my $chkallscript='<script type="text/javascript">
 1110:     function checkall() {
 1111:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1112:             ele = document.forms.'.$form.'.elements[i];
 1113:             if (ele.name == "'.$type.'") {
 1114:             document.forms.'.$form.'.elements[i].checked=true;
 1115:                                        }
 1116:         }
 1117:     }
 1118: 
 1119:     function checksec() {
 1120:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1121:             ele = document.forms.'.$form.'.elements[i];
 1122:            string = document.forms.'.$form.'.chksec.value;
 1123:            if
 1124:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1125:               document.forms.'.$form.'.elements[i].checked=true;
 1126:             }
 1127:         }
 1128:     }
 1129: 
 1130: 
 1131:     function uncheckall() {
 1132:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1133:             ele = document.forms.'.$form.'.elements[i];
 1134:             if (ele.name == "'.$type.'") {
 1135:             document.forms.'.$form.'.elements[i].checked=false;
 1136:                                        }
 1137:         }
 1138:     }
 1139: 
 1140: </script>'."\n";
 1141:     return $chkallscript;
 1142: }
 1143: 
 1144: sub check_buttons {
 1145:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1146:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1147:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1148:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1149:     return $buttons;
 1150: }
 1151: 
 1152: #     Displays the submissions for one student or a group of students
 1153: sub processGroup {
 1154:     my ($request)  = shift;
 1155:     my $ctr        = 0;
 1156:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1157:     my $total      = scalar(@stuchecked)-1;
 1158: 
 1159:     foreach my $student (@stuchecked) {
 1160: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1161: 	$env{'form.student'}        = $uname;
 1162: 	$env{'form.userdom'}        = $udom;
 1163: 	$env{'form.fullname'}       = $fullname;
 1164: 	&submission($request,$ctr,$total);
 1165: 	$ctr++;
 1166:     }
 1167:     return '';
 1168: }
 1169: 
 1170: #------------------------------------------------------------------------------------
 1171: #
 1172: #-------------------------- Next few routines handles grading by student, essentially
 1173: #                           handles essay response type problem/part
 1174: #
 1175: #--- Javascript to handle the submission page functionality ---
 1176: sub sub_page_js {
 1177:     my $request = shift;
 1178: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1179:     $request->print(<<SUBJAVASCRIPT);
 1180: <script type="text/javascript" language="javascript">
 1181:     function updateRadio(formname,id,weight) {
 1182: 	var gradeBox = formname["GD_BOX"+id];
 1183: 	var radioButton = formname["RADVAL"+id];
 1184: 	var oldpts = formname["oldpts"+id].value;
 1185: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1186: 	gradeBox.value = pts;
 1187: 	var resetbox = false;
 1188: 	if (isNaN(pts) || pts < 0) {
 1189: 	    alert("$alertmsg"+pts);
 1190: 	    for (var i=0; i<radioButton.length; i++) {
 1191: 		if (radioButton[i].checked) {
 1192: 		    gradeBox.value = i;
 1193: 		    resetbox = true;
 1194: 		}
 1195: 	    }
 1196: 	    if (!resetbox) {
 1197: 		formtextbox.value = "";
 1198: 	    }
 1199: 	    return;
 1200: 	}
 1201: 
 1202: 	if (pts > weight) {
 1203: 	    var resp = confirm("You entered a value ("+pts+
 1204: 			       ") greater than the weight for the part. Accept?");
 1205: 	    if (resp == false) {
 1206: 		gradeBox.value = oldpts;
 1207: 		return;
 1208: 	    }
 1209: 	}
 1210: 
 1211: 	for (var i=0; i<radioButton.length; i++) {
 1212: 	    radioButton[i].checked=false;
 1213: 	    if (pts == i && pts != "") {
 1214: 		radioButton[i].checked=true;
 1215: 	    }
 1216: 	}
 1217: 	updateSelect(formname,id);
 1218: 	formname["stores"+id].value = "0";
 1219:     }
 1220: 
 1221:     function writeBox(formname,id,pts) {
 1222: 	var gradeBox = formname["GD_BOX"+id];
 1223: 	if (checkSolved(formname,id) == 'update') {
 1224: 	    gradeBox.value = pts;
 1225: 	} else {
 1226: 	    var oldpts = formname["oldpts"+id].value;
 1227: 	    gradeBox.value = oldpts;
 1228: 	    var radioButton = formname["RADVAL"+id];
 1229: 	    for (var i=0; i<radioButton.length; i++) {
 1230: 		radioButton[i].checked=false;
 1231: 		if (i == oldpts) {
 1232: 		    radioButton[i].checked=true;
 1233: 		}
 1234: 	    }
 1235: 	}
 1236: 	formname["stores"+id].value = "0";
 1237: 	updateSelect(formname,id);
 1238: 	return;
 1239:     }
 1240: 
 1241:     function clearRadBox(formname,id) {
 1242: 	if (checkSolved(formname,id) == 'noupdate') {
 1243: 	    updateSelect(formname,id);
 1244: 	    return;
 1245: 	}
 1246: 	gradeSelect = formname["GD_SEL"+id];
 1247: 	for (var i=0; i<gradeSelect.length; i++) {
 1248: 	    if (gradeSelect[i].selected) {
 1249: 		var selectx=i;
 1250: 	    }
 1251: 	}
 1252: 	var stores = formname["stores"+id];
 1253: 	if (selectx == stores.value) { return };
 1254: 	var gradeBox = formname["GD_BOX"+id];
 1255: 	gradeBox.value = "";
 1256: 	var radioButton = formname["RADVAL"+id];
 1257: 	for (var i=0; i<radioButton.length; i++) {
 1258: 	    radioButton[i].checked=false;
 1259: 	}
 1260: 	stores.value = selectx;
 1261:     }
 1262: 
 1263:     function checkSolved(formname,id) {
 1264: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1265: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1266: 	    if (!reply) {return "noupdate";}
 1267: 	    formname.overRideScore.value = 'yes';
 1268: 	}
 1269: 	return "update";
 1270:     }
 1271: 
 1272:     function updateSelect(formname,id) {
 1273: 	formname["GD_SEL"+id][0].selected = true;
 1274: 	return;
 1275:     }
 1276: 
 1277: //=========== Check that a point is assigned for all the parts  ============
 1278:     function checksubmit(formname,val,total,parttot) {
 1279: 	formname.gradeOpt.value = val;
 1280: 	if (val == "Save & Next") {
 1281: 	    for (i=0;i<=total;i++) {
 1282: 		for (j=0;j<parttot;j++) {
 1283: 		    var partid = formname["partid"+i+"_"+j].value;
 1284: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1285: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1286: 			if (points == "") {
 1287: 			    var name = formname["name"+i].value;
 1288: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1289: 			    var resp = confirm("You did not assign a score for "+studentID+
 1290: 					       ", part "+partid+". Continue?");
 1291: 			    if (resp == false) {
 1292: 				formname["GD_BOX"+i+"_"+partid].focus();
 1293: 				return false;
 1294: 			    }
 1295: 			}
 1296: 		    }
 1297: 		    
 1298: 		}
 1299: 	    }
 1300: 	    
 1301: 	}
 1302: 	if (val == "Grade Student") {
 1303: 	    formname.showgrading.value = "yes";
 1304: 	    if (formname.Status.value == "") {
 1305: 		formname.Status.value = "Active";
 1306: 	    }
 1307: 	    formname.studentNo.value = total;
 1308: 	}
 1309: 	formname.submit();
 1310:     }
 1311: 
 1312: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1313:     function checkSubmitPage(formname,total) {
 1314: 	noscore = new Array(100);
 1315: 	var ptr = 0;
 1316: 	for (i=1;i<total;i++) {
 1317: 	    var partid = formname["q_"+i].value;
 1318: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1319: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1320: 		var status = formname["solved"+i+"_"+partid].value;
 1321: 		if (points == "" && status != "correct_by_student") {
 1322: 		    noscore[ptr] = i;
 1323: 		    ptr++;
 1324: 		}
 1325: 	    }
 1326: 	}
 1327: 	if (ptr != 0) {
 1328: 	    var sense = ptr == 1 ? ": " : "s: ";
 1329: 	    var prolist = "";
 1330: 	    if (ptr == 1) {
 1331: 		prolist = noscore[0];
 1332: 	    } else {
 1333: 		var i = 0;
 1334: 		while (i < ptr-1) {
 1335: 		    prolist += noscore[i]+", ";
 1336: 		    i++;
 1337: 		}
 1338: 		prolist += "and "+noscore[i];
 1339: 	    }
 1340: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1341: 	    if (resp == false) {
 1342: 		return false;
 1343: 	    }
 1344: 	}
 1345: 
 1346: 	formname.submit();
 1347:     }
 1348: </script>
 1349: SUBJAVASCRIPT
 1350: }
 1351: 
 1352: #--- javascript for essay type problem --
 1353: sub sub_page_kw_js {
 1354:     my $request = shift;
 1355:     my $iconpath = $request->dir_config('lonIconsURL');
 1356:     &commonJSfunctions($request);
 1357: 
 1358:     my $inner_js_msg_central=<<INNERJS;
 1359:     <script text="text/javascript">
 1360:     function checkInput() {
 1361:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1362:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1363:       var usrctr = document.msgcenter.usrctr.value;
 1364:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1365:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1366: 
 1367:       var msgchk = "";
 1368:       if (document.msgcenter.subchk.checked) {
 1369:          msgchk = "msgsub,";
 1370:       }
 1371:       var includemsg = 0;
 1372:       for (var i=1; i<=nmsg; i++) {
 1373:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1374:           var frmmsg = document.msgcenter["msg"+i];
 1375:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1376:           var showflg = opener.document.SCORE["shownOnce"+i];
 1377:           showflg.value = "1";
 1378:           var chkbox = document.msgcenter["msgn"+i];
 1379:           if (chkbox.checked) {
 1380:              msgchk += "savemsg"+i+",";
 1381:              includemsg = 1;
 1382:           }
 1383:       }
 1384:       if (document.msgcenter.newmsgchk.checked) {
 1385:          msgchk += "newmsg"+usrctr;
 1386:          includemsg = 1;
 1387:       }
 1388:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1389:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1390:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1391:       includemsg.value = msgchk;
 1392: 
 1393:       self.close()
 1394: 
 1395:     }
 1396:     </script>
 1397: INNERJS
 1398: 
 1399:     my $inner_js_highlight_central=<<INNERJS;
 1400:  <script type="text/javascript">
 1401:     function updateChoice(flag) {
 1402:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1403:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1404:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1405:       opener.document.SCORE.refresh.value = "on";
 1406:       if (opener.document.SCORE.keywords.value!=""){
 1407:          opener.document.SCORE.submit();
 1408:       }
 1409:       self.close()
 1410:     }
 1411: </script>
 1412: INNERJS
 1413: 
 1414:     my $start_page_msg_central = 
 1415:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1416: 				       {'js_ready'  => 1,
 1417: 					'only_body' => 1,
 1418: 					'bgcolor'   =>'#FFFFFF',});
 1419:     my $end_page_msg_central = 
 1420: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1421: 
 1422: 
 1423:     my $start_page_highlight_central = 
 1424:         &Apache::loncommon::start_page('Highlight Central',
 1425: 				       $inner_js_highlight_central,
 1426: 				       {'js_ready'  => 1,
 1427: 					'only_body' => 1,
 1428: 					'bgcolor'   =>'#FFFFFF',});
 1429:     my $end_page_highlight_central = 
 1430: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1431: 
 1432:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1433:     $docopen=~s/^document\.//;
 1434:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1435:     $request->print(<<SUBJAVASCRIPT);
 1436: <script type="text/javascript" language="javascript">
 1437: 
 1438: //===================== Show list of keywords ====================
 1439:   function keywords(formname) {
 1440:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1441:     if (nret==null) return;
 1442:     formname.keywords.value = nret;
 1443: 
 1444:     if (formname.keywords.value != "") {
 1445: 	formname.refresh.value = "on";
 1446: 	formname.submit();
 1447:     }
 1448:     return;
 1449:   }
 1450: 
 1451: //===================== Script to view submitted by ==================
 1452:   function viewSubmitter(submitter) {
 1453:     document.SCORE.refresh.value = "on";
 1454:     document.SCORE.NCT.value = "1";
 1455:     document.SCORE.unamedom0.value = submitter;
 1456:     document.SCORE.submit();
 1457:     return;
 1458:   }
 1459: 
 1460: //===================== Script to add keyword(s) ==================
 1461:   function getSel() {
 1462:     if (document.getSelection) txt = document.getSelection();
 1463:     else if (document.selection) txt = document.selection.createRange().text;
 1464:     else return;
 1465:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1466:     if (cleantxt=="") {
 1467: 	alert("$alertmsg");
 1468: 	return;
 1469:     }
 1470:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1471:     if (nret==null) return;
 1472:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1473:     if (document.SCORE.keywords.value != "") {
 1474: 	document.SCORE.refresh.value = "on";
 1475: 	document.SCORE.submit();
 1476:     }
 1477:     return;
 1478:   }
 1479: 
 1480: //====================== Script for composing message ==============
 1481:    // preload images
 1482:    img1 = new Image();
 1483:    img1.src = "$iconpath/mailbkgrd.gif";
 1484:    img2 = new Image();
 1485:    img2.src = "$iconpath/mailto.gif";
 1486: 
 1487:   function msgCenter(msgform,usrctr,fullname) {
 1488:     var Nmsg  = msgform.savemsgN.value;
 1489:     savedMsgHeader(Nmsg,usrctr,fullname);
 1490:     var subject = msgform.msgsub.value;
 1491:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1492:     re = /msgsub/;
 1493:     var shwsel = "";
 1494:     if (re.test(msgchk)) { shwsel = "checked" }
 1495:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1496:     displaySubject(checkEntities(subject),shwsel);
 1497:     for (var i=1; i<=Nmsg; i++) {
 1498: 	var testmsg = "savemsg"+i+",";
 1499: 	re = new RegExp(testmsg,"g");
 1500: 	shwsel = "";
 1501: 	if (re.test(msgchk)) { shwsel = "checked" }
 1502: 	var message = document.SCORE["savemsg"+i].value;
 1503: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1504: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1505: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1506:     }
 1507:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1508:     shwsel = "";
 1509:     re = /newmsg/;
 1510:     if (re.test(msgchk)) { shwsel = "checked" }
 1511:     newMsg(newmsg,shwsel);
 1512:     msgTail(); 
 1513:     return;
 1514:   }
 1515: 
 1516:   function checkEntities(strx) {
 1517:     if (strx.length == 0) return strx;
 1518:     var orgStr = ["&", "<", ">", '"']; 
 1519:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1520:     var counter = 0;
 1521:     while (counter < 4) {
 1522: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1523: 	counter++;
 1524:     }
 1525:     return strx;
 1526:   }
 1527: 
 1528:   function strReplace(strx, orgStr, newStr) {
 1529:     return strx.split(orgStr).join(newStr);
 1530:   }
 1531: 
 1532:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1533:     var height = 70*Nmsg+250;
 1534:     var scrollbar = "no";
 1535:     if (height > 600) {
 1536: 	height = 600;
 1537: 	scrollbar = "yes";
 1538:     }
 1539:     var xpos = (screen.width-600)/2;
 1540:     xpos = (xpos < 0) ? '0' : xpos;
 1541:     var ypos = (screen.height-height)/2-30;
 1542:     ypos = (ypos < 0) ? '0' : ypos;
 1543: 
 1544:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1545:     pWin.focus();
 1546:     pDoc = pWin.document;
 1547:     pDoc.$docopen;
 1548:     pDoc.write('$start_page_msg_central');
 1549: 
 1550:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1551:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1552:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1553: 
 1554:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1555:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1556:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1557: }
 1558:     function displaySubject(msg,shwsel) {
 1559:     pDoc = pWin.document;
 1560:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1561:     pDoc.write("<td>Subject<\\/td>");
 1562:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1563:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1564: }
 1565: 
 1566:   function displaySavedMsg(ctr,msg,shwsel) {
 1567:     pDoc = pWin.document;
 1568:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1569:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1570:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1571:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1572: }
 1573: 
 1574:   function newMsg(newmsg,shwsel) {
 1575:     pDoc = pWin.document;
 1576:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1577:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1578:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1579:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1580: }
 1581: 
 1582:   function msgTail() {
 1583:     pDoc = pWin.document;
 1584:     pDoc.write("<\\/table>");
 1585:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1586:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1587:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1588:     pDoc.write("<\\/form>");
 1589:     pDoc.write('$end_page_msg_central');
 1590:     pDoc.close();
 1591: }
 1592: 
 1593: //====================== Script for keyword highlight options ==============
 1594:   function kwhighlight() {
 1595:     var kwclr    = document.SCORE.kwclr.value;
 1596:     var kwsize   = document.SCORE.kwsize.value;
 1597:     var kwstyle  = document.SCORE.kwstyle.value;
 1598:     var redsel = "";
 1599:     var grnsel = "";
 1600:     var blusel = "";
 1601:     if (kwclr=="red")   {var redsel="checked"};
 1602:     if (kwclr=="green") {var grnsel="checked"};
 1603:     if (kwclr=="blue")  {var blusel="checked"};
 1604:     var sznsel = "";
 1605:     var sz1sel = "";
 1606:     var sz2sel = "";
 1607:     if (kwsize=="0")  {var sznsel="checked"};
 1608:     if (kwsize=="+1") {var sz1sel="checked"};
 1609:     if (kwsize=="+2") {var sz2sel="checked"};
 1610:     var synsel = "";
 1611:     var syisel = "";
 1612:     var sybsel = "";
 1613:     if (kwstyle=="")    {var synsel="checked"};
 1614:     if (kwstyle=="<i>") {var syisel="checked"};
 1615:     if (kwstyle=="<b>") {var sybsel="checked"};
 1616:     highlightCentral();
 1617:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1618:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1619:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1620:     highlightend();
 1621:     return;
 1622:   }
 1623: 
 1624:   function highlightCentral() {
 1625: //    if (window.hwdWin) window.hwdWin.close();
 1626:     var xpos = (screen.width-400)/2;
 1627:     xpos = (xpos < 0) ? '0' : xpos;
 1628:     var ypos = (screen.height-330)/2-30;
 1629:     ypos = (ypos < 0) ? '0' : ypos;
 1630: 
 1631:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1632:     hwdWin.focus();
 1633:     var hDoc = hwdWin.document;
 1634:     hDoc.$docopen;
 1635:     hDoc.write('$start_page_highlight_central');
 1636:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1637:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1638: 
 1639:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1640:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1641:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1642:   }
 1643: 
 1644:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1645:     var hDoc = hwdWin.document;
 1646:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1647:     hDoc.write("<td align=\\"left\\">");
 1648:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1649:     hDoc.write("<td align=\\"left\\">");
 1650:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1651:     hDoc.write("<td align=\\"left\\">");
 1652:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1653:     hDoc.write("<\\/tr>");
 1654:   }
 1655: 
 1656:   function highlightend() { 
 1657:     var hDoc = hwdWin.document;
 1658:     hDoc.write("<\\/table>");
 1659:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1660:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1661:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1662:     hDoc.write("<\\/form>");
 1663:     hDoc.write('$end_page_highlight_central');
 1664:     hDoc.close();
 1665:   }
 1666: 
 1667: </script>
 1668: SUBJAVASCRIPT
 1669: }
 1670: 
 1671: sub get_increment {
 1672:     my $increment = $env{'form.increment'};
 1673:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1674:         $increment != .1) {
 1675:         $increment = 1;
 1676:     }
 1677:     return $increment;
 1678: }
 1679: 
 1680: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1681: sub gradeBox {
 1682:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1683:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1684: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1685:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1686:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1687:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1688:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1689:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1690: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1691:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1692:     my $display_part= &get_display_part($partid,$symb);
 1693:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1694: 				       [$partid]);
 1695:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1696:     if ($last_resets{$partid}) {
 1697:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1698:     }
 1699:     $result.='<table border="0"><tr>';
 1700:     my $ctr = 0;
 1701:     my $thisweight = 0;
 1702:     my $increment = &get_increment();
 1703: 
 1704:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1705:     while ($thisweight<=$wgt) {
 1706: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1707: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1708: 	    $thisweight.')" value="'.$thisweight.'" '.
 1709: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1710: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1711:         $thisweight += $increment;
 1712: 	$ctr++;
 1713:     }
 1714:     $radio.='</tr></table>';
 1715: 
 1716:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1717: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1718: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1719: 	$wgt.')" /></td>'."\n";
 1720:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1721: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1722: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1723:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1724: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1725:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1726: 	$line.='<option></option>'.
 1727: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1728:     } else {
 1729: 	$line.='<option selected="selected"></option>'.
 1730: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1731:     }
 1732:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1733: 
 1734: 
 1735: 	#&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);
 1736:     $result .= 
 1737: 	    '<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>'.
 1738:     
 1739:     $result.='</tr></table>'."\n";
 1740:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1741: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1742: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1743: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1744:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1745:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1746:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1747:         $aggtries.'" />'."\n";
 1748:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1749:     return $result;
 1750: }
 1751: 
 1752: sub handback_box {
 1753:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1754:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1755:     my (@respids);
 1756:      my @part_response_id = &flatten_responseType($responseType);
 1757:     foreach my $part_response_id (@part_response_id) {
 1758:     	my ($part,$resp) = @{ $part_response_id };
 1759:         if ($part eq $partid) {
 1760:             push(@respids,$resp);
 1761:         }
 1762:     }
 1763:     my $result;
 1764:     foreach my $respid (@respids) {
 1765: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1766: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1767: 	next if (!@$files);
 1768: 	my $file_counter = 1;
 1769: 	foreach my $file (@$files) {
 1770: 	    if ($file =~ /\/portfolio\//) {
 1771:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1772:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1773:     	        $file_disp = "$name.$ext";
 1774:     	        $file = $file_path.$file_disp;
 1775:     	        $result.=&mt('Return commented version of [_1] to student.',
 1776:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1777:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1778:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1779:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1780:     	        $file_counter++;
 1781: 	    }
 1782: 	}
 1783:     }
 1784:     return $result;    
 1785: }
 1786: 
 1787: sub show_problem {
 1788:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1789:     my $rendered;
 1790:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1791:     &Apache::lonxml::remember_problem_counter();
 1792:     if ($mode eq 'both' or $mode eq 'text') {
 1793: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1794: 						       $env{'request.course.id'},
 1795: 						       undef,\%form);
 1796:     }
 1797:     if ($removeform) {
 1798: 	$rendered=~s|<form(.*?)>||g;
 1799: 	$rendered=~s|</form>||g;
 1800: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1801:     }
 1802:     my $companswer;
 1803:     if ($mode eq 'both' or $mode eq 'answer') {
 1804: 	&Apache::lonxml::restore_problem_counter();
 1805: 	$companswer=
 1806: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1807: 						    $env{'request.course.id'},
 1808: 						    %form);
 1809:     }
 1810:     if ($removeform) {
 1811: 	$companswer=~s|<form(.*?)>||g;
 1812: 	$companswer=~s|</form>||g;
 1813: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1814:     }
 1815:     $rendered=
 1816: 	'<div class="LC_grade_show_problem_header">'.
 1817: 	&mt('View of the problem').
 1818: 	'</div><div class="LC_grade_show_problem_problem">'.
 1819: 	$rendered.
 1820: 	'</div>';
 1821:     $companswer=
 1822: 	'<div class="LC_grade_show_problem_header">'.
 1823: 	&mt('Correct answer').
 1824: 	'</div><div class="LC_grade_show_problem_problem">'.
 1825: 	$companswer.
 1826: 	'</div>';
 1827:     my $result;
 1828:     if ($mode eq 'both') {
 1829: 	$result=$rendered.$companswer;
 1830:     } elsif ($mode eq 'text') {
 1831: 	$result=$rendered;
 1832:     } elsif ($mode eq 'answer') {
 1833: 	$result=$companswer;
 1834:     }
 1835:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1836:     return $result;
 1837: }
 1838: 
 1839: sub files_exist {
 1840:     my ($r, $symb) = @_;
 1841:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1842: 
 1843:     foreach my $student (@students) {
 1844:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1845:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1846: 					      $udom,$uname);
 1847:         my ($string,$timestamp)= &get_last_submission(\%record);
 1848:         foreach my $submission (@$string) {
 1849:             my ($partid,$respid) =
 1850: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1851:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1852: 					   \%record);
 1853:             return 1 if (@$files);
 1854:         }
 1855:     }
 1856:     return 0;
 1857: }
 1858: 
 1859: sub download_all_link {
 1860:     my ($r,$symb) = @_;
 1861:     my $all_students = 
 1862: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1863: 
 1864:     my $parts =
 1865: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1866: 
 1867:     my $identifier = &Apache::loncommon::get_cgi_id();
 1868:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1869:                              'cgi.'.$identifier.'.symb' => $symb,
 1870:                              'cgi.'.$identifier.'.parts' => $parts,});
 1871:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1872: 	      &mt('Download All Submitted Documents').'</a>');
 1873:     return
 1874: }
 1875: 
 1876: sub build_section_inputs {
 1877:     my $section_inputs;
 1878:     if ($env{'form.section'} eq '') {
 1879:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1880:     } else {
 1881:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1882:         foreach my $section (@sections) {
 1883:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1884:         }
 1885:     }
 1886:     return $section_inputs;
 1887: }
 1888: 
 1889: # --------------------------- show submissions of a student, option to grade 
 1890: sub submission {
 1891:     my ($request,$counter,$total) = @_;
 1892:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1893:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1894:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1895:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1896:     my $symb = &get_symb($request); 
 1897:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1898: 
 1899:     if (!&canview($usec)) {
 1900: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1901: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1902: 			$env{'request.course.id'}.')</span>');
 1903: 	$request->print(&show_grading_menu_form($symb));
 1904: 	return;
 1905:     }
 1906: 
 1907:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1908:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1909:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1910:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1911:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1912: 	'" src="'.$request->dir_config('lonIconsURL').
 1913: 	'/check.gif" height="16" border="0" />';
 1914: 
 1915:     my %old_essays;
 1916:     # header info
 1917:     if ($counter == 0) {
 1918: 	&sub_page_js($request);
 1919: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1920: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1921: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1922: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1923: 	    &download_all_link($request, $symb);
 1924: 	}
 1925: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1926: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1927: 
 1928: 	# option to display problem, only once else it cause problems 
 1929:         # with the form later since the problem has a form.
 1930: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1931: 	    my $mode;
 1932: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1933: 		$mode='both';
 1934: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1935: 		$mode='text';
 1936: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1937: 		$mode='answer';
 1938: 	    }
 1939: 	    &Apache::lonxml::clear_problem_counter();
 1940: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1941: 	}
 1942: 
 1943: 	# kwclr is the only variable that is guaranteed to be non blank 
 1944:         # if this subroutine has been called once.
 1945: 	my %keyhash = ();
 1946: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1947: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1948: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1949: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1950: 
 1951: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1952: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1953: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1954: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1955: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1956: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1957: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1958: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1959: 	}
 1960: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1961: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1962: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1963: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1964: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1965: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1966: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1967: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1968: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1969: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1970: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1971: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1972: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1973: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1974: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1975: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1976: 			&build_section_inputs().
 1977: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1978: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1979: 			'<input type="hidden" name="NCT"'.
 1980: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1981: 	if ($env{'form.handgrade'} eq 'yes') {
 1982: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1983: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1984: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1985: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1986: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1987: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1988: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1989: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1990: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1991: 	    }
 1992: 	}
 1993: 	
 1994: 	my ($cts,$prnmsg) = (1,'');
 1995: 	while ($cts <= $env{'form.savemsgN'}) {
 1996: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1997: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1998: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1999: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2000: 		'" />'."\n".
 2001: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2002: 	    $cts++;
 2003: 	}
 2004: 	$request->print($prnmsg);
 2005: 
 2006: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2007: #
 2008: # Print out the keyword options line
 2009: #
 2010: 	    $request->print(<<KEYWORDS);
 2011: &nbsp;<b>Keyword Options:</b>&nbsp;
 2012: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2013: <a href="#" onMouseDown="javascript:getSel(); return false"
 2014:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2015: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2016: KEYWORDS
 2017: #
 2018: # Load the other essays for similarity check
 2019: #
 2020:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2021: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2022: 	    $apath=&escape($apath);
 2023: 	    $apath=~s/\W/\_/gs;
 2024: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2025:         }
 2026:     }
 2027: 
 2028: # This is where output for one specific student would start
 2029:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2030:     $request->print("\n\n".
 2031:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2032: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2033: 		    '<div class="LC_grade_show_user_body">'."\n");
 2034: 
 2035:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2036: 	my $mode;
 2037: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2038: 	    $mode='both';
 2039: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2040: 	    $mode='text';
 2041: 	} elsif ($env{'form.vAns'} eq 'all') {
 2042: 	    $mode='answer';
 2043: 	}
 2044: 	&Apache::lonxml::clear_problem_counter();
 2045: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2046:     }
 2047: 
 2048:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2050: 
 2051:     # Display student info
 2052:     $request->print(($counter == 0 ? '' : '<br />'));
 2053:     my $result='<div class="LC_grade_submissions">';
 2054:     
 2055:     $result.='<div class="LC_grade_submissions_header">';
 2056:     $result.= &mt('Submissions');
 2057:     $result.='<input type="hidden" name="name'.$counter.
 2058: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2059:     if ($env{'form.handgrade'} eq 'no') {
 2060: 	$result.='<span class="LC_grade_check_note">'.
 2061: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2062: 
 2063:     }
 2064: 
 2065: 
 2066: 
 2067:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2068:     my $fullname;
 2069:     my $col_fullnames = [];
 2070:     if ($env{'form.handgrade'} eq 'yes') {
 2071: 	(my $sub_result,$fullname,$col_fullnames)=
 2072: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2073: 				 $counter);
 2074: 	$result.=$sub_result;
 2075:     }
 2076:     $request->print($result."\n");
 2077:     $request->print('</div>'."\n");
 2078:     # print student answer/submission
 2079:     # Options are (1) Handgaded submission only
 2080:     #             (2) Last submission, includes submission that is not handgraded 
 2081:     #                  (for multi-response type part)
 2082:     #             (3) Last submission plus the parts info
 2083:     #             (4) The whole record for this student
 2084:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2085: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2086: 	
 2087: 	my $lastsubonly;
 2088: 
 2089: 	if ($$timestamp eq '') {
 2090: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2091: 	} else {
 2092: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2093: 
 2094: 	    my %seenparts;
 2095: 	    my @part_response_id = &flatten_responseType($responseType);
 2096: 	    foreach my $part (@part_response_id) {
 2097: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2098: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2099: 
 2100: 		my ($partid,$respid) = @{ $part };
 2101: 		my $display_part=&get_display_part($partid,$symb);
 2102: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2103: 		    if (exists($seenparts{$partid})) { next; }
 2104: 		    $seenparts{$partid}=1;
 2105: 		    my $submitby='<b>Part:</b> '.$display_part.
 2106: 			' <b>Collaborative submission by:</b> '.
 2107: 			'<a href="javascript:viewSubmitter(\''.
 2108: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2109: 			'\');" target="_self">'.
 2110: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2111: 		    $request->print($submitby);
 2112: 		    next;
 2113: 		}
 2114: 		my $responsetype = $responseType->{$partid}->{$respid};
 2115: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2116: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2117: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2118: 			' )</span>&nbsp; &nbsp;'.
 2119: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2120: 		    next;
 2121: 		}
 2122: 		foreach my $submission (@$string) {
 2123: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2124: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2125: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2126: 		    # Similarity check
 2127: 		    my $similar='';
 2128: 		    if($env{'form.checkPlag'}){
 2129: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2130: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2131: 			if ($osim) {
 2132: 			    $osim=int($osim*100.0);
 2133: 			    my %old_course_desc = 
 2134: 				&Apache::lonnet::coursedescription($ocrsid,
 2135: 								   {'one_time' => 1});
 2136: 
 2137: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2138: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2139: 				    $osim,
 2140: 				    &Apache::loncommon::plainname($oname,$odom),
 2141: 				    $oname,$odom,
 2142: 				    $old_course_desc{'description'},
 2143: 				    $old_course_desc{'num'},
 2144: 				    $old_course_desc{'domain'}).
 2145: 				'</span></h3><blockquote><i>'.
 2146: 				&keywords_highlight($oessay).
 2147: 				'</i></blockquote><hr />';
 2148: 			}
 2149: 		    }
 2150: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2151: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2152: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2153: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2154: 			my $display_part=&get_display_part($partid,$symb);
 2155: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2156: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2157: 			    ' )</span>&nbsp; &nbsp;';
 2158: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2159: 			if (@$files) {
 2160: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2161: 			    my $file_counter = 0;
 2162: 			    foreach my $file (@$files) {
 2163: 			        $file_counter++;
 2164: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2165: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2166: 			    }
 2167: 			    $lastsubonly.='<br />';
 2168: 			}
 2169: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2170: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2171: 					 $respid,\%record,$order,undef,$uname,$udom);
 2172: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2173: 			$lastsubonly.='</div>';
 2174: 		    }
 2175: 		}
 2176: 	    }
 2177: 	    $lastsubonly.='</div>'."\n";
 2178: 	}
 2179: 	$request->print($lastsubonly);
 2180:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2181: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2182: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2183:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2184: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2185: 								 $env{'request.course.id'},
 2186: 								 $last,'.submission',
 2187: 								 'Apache::grades::keywords_highlight'));
 2188:     }
 2189: 
 2190:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2191: 	.$udom.'" />'."\n");
 2192:     # return if view submission with no grading option
 2193:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2194: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2195: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2196: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2197: 	$toGrade.='</div>'."\n";
 2198: 	if (($env{'form.command'} eq 'submission') || 
 2199: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2200: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2201: 	}
 2202: 	$request->print($toGrade);
 2203: 	return;
 2204:     } else {
 2205: 	$request->print('</div>'."\n");
 2206:     }
 2207: 
 2208:     # essay grading message center
 2209:     if ($env{'form.handgrade'} eq 'yes') {
 2210: 	my $result='<div class="LC_grade_message_center">';
 2211:     
 2212: 	$result.='<div class="LC_grade_message_center_header">'.
 2213: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2214: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2215: 	my $msgfor = $givenn.' '.$lastname;
 2216: 	if (scalar(@$col_fullnames) > 0) {
 2217: 	    my $lastone = pop(@$col_fullnames);
 2218: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2219: 	}
 2220: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2221: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2222: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2223: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2224: 	    ',\''.$msgfor.'\');" target="_self">'.
 2225: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2226: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2227: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2228: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2229: 	    '<br />&nbsp;('.
 2230: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2231: 	$result.='</div></div>';
 2232: 	$request->print($result);
 2233:     }
 2234: 
 2235:     my %seen = ();
 2236:     my @partlist;
 2237:     my @gradePartRespid;
 2238:     my @part_response_id = &flatten_responseType($responseType);
 2239:     $request->print('<div class="LC_grade_assign">'.
 2240: 		    
 2241: 		    '<div class="LC_grade_assign_header">'.
 2242: 		    &mt('Assign Grades').'</div>'.
 2243: 		    '<div class="LC_grade_assign_body">');
 2244:     foreach my $part_response_id (@part_response_id) {
 2245:     	my ($partid,$respid) = @{ $part_response_id };
 2246: 	my $part_resp = join('_',@{ $part_response_id });
 2247: 	next if ($seen{$partid} > 0);
 2248: 	$seen{$partid}++;
 2249: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2250: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2251: 	push(@partlist,$partid);
 2252: 	push(@gradePartRespid,$partid.'.'.$respid);
 2253: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2254:     }
 2255:     $request->print('</div></div>');
 2256: 
 2257:     $request->print('<div class="LC_grade_info_links">');
 2258:     if ($perm{'vgr'}) {
 2259: 	$request->print(
 2260: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2261: 						   $uname,$udom,'check'));
 2262:     }
 2263:     if ($perm{'opa'}) {
 2264: 	$request->print(
 2265: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2266: 					 $uname,$udom,$symb,'check'));
 2267:     }
 2268:     $request->print('</div>');
 2269: 
 2270:     $result='<input type="hidden" name="partlist'.$counter.
 2271: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2272:     $result.='<input type="hidden" name="gradePartRespid'.
 2273: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2274:     my $ctr = 0;
 2275:     while ($ctr < scalar(@partlist)) {
 2276: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2277: 	    $partlist[$ctr].'" />'."\n";
 2278: 	$ctr++;
 2279:     }
 2280:     $request->print($result.''."\n");
 2281: 
 2282: # Done with printing info for one student
 2283: 
 2284:     $request->print('</div>');#LC_grade_show_user_body
 2285:     $request->print('</div>');#LC_grade_show_user
 2286: 
 2287: 
 2288:     # print end of form
 2289:     if ($counter == $total) {
 2290: 	my $endform='<table border="0"><tr><td>'."\n";
 2291: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2292: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2293: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2294: 	my $ntstu ='<select name="NTSTU">'.
 2295: 	    '<option>1</option><option>2</option>'.
 2296: 	    '<option>3</option><option>5</option>'.
 2297: 	    '<option>7</option><option>10</option></select>'."\n";
 2298: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2299: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2300: 	$endform.=&mt('[quant,_1,student]',$ntstu);
 2301: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2302: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2303: 	    '<input type="button" value="'.&mt('Next').'" '.
 2304: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2305: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2306:         $endform.="<input type='hidden' value='".&get_increment().
 2307:             "' name='increment' />";
 2308: 	$endform.='</td></tr></table></form>';
 2309: 	$endform.=&show_grading_menu_form($symb);
 2310: 	$request->print($endform);
 2311:     }
 2312:     return '';
 2313: }
 2314: 
 2315: sub check_collaborators {
 2316:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2317:     my ($result,@col_fullnames);
 2318:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2319:     foreach my $part (keys(%$handgrade)) {
 2320: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2321: 					'.maxcollaborators',
 2322: 					$symb,$udom,$uname);
 2323: 	next if ($ncol <= 0);
 2324: 	$part =~ s/\_/\./g;
 2325: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2326: 	my (@good_collaborators, @bad_collaborators);
 2327: 	foreach my $possible_collaborator
 2328: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2329: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2330: 	    next if ($possible_collaborator eq '');
 2331: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2332: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2333: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2334: 	    # Doing this grep allows 'fuzzy' specification
 2335: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2336: 			       keys(%$classlist));
 2337: 	    if (! scalar(@matches)) {
 2338: 		push(@bad_collaborators, $possible_collaborator);
 2339: 	    } else {
 2340: 		push(@good_collaborators, @matches);
 2341: 	    }
 2342: 	}
 2343: 	if (scalar(@good_collaborators) != 0) {
 2344: 	    $result.='<br />'.&mt('Collaborators: ');
 2345: 	    foreach my $name (@good_collaborators) {
 2346: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2347: 		push(@col_fullnames, $givenn.' '.$lastname);
 2348: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2349: 	    }
 2350: 	    $result.='<br />'."\n";
 2351: 	    my ($part)=split(/\./,$part);
 2352: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2353: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2354: 		"\n";
 2355: 	}
 2356: 	if (scalar(@bad_collaborators) > 0) {
 2357: 	    $result.='<div class="LC_warning">';
 2358: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2359: 	    $result .= '</div>';
 2360: 	}         
 2361: 	if (scalar(@bad_collaborators > $ncol)) {
 2362: 	    $result .= '<div class="LC_warning">';
 2363: 	    $result .= &mt('This student has submitted too many '.
 2364: 		'collaborators.  Maximum is [_1].',$ncol);
 2365: 	    $result .= '</div>';
 2366: 	}
 2367:     }
 2368:     return ($result,$fullname,\@col_fullnames);
 2369: }
 2370: 
 2371: #--- Retrieve the last submission for all the parts
 2372: sub get_last_submission {
 2373:     my ($returnhash)=@_;
 2374:     my (@string,$timestamp);
 2375:     if ($$returnhash{'version'}) {
 2376: 	my %lasthash=();
 2377: 	my ($version);
 2378: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2379: 	    foreach my $key (sort(split(/\:/,
 2380: 					$$returnhash{$version.':keys'}))) {
 2381: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2382: 		$timestamp = 
 2383: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2384: 	    }
 2385: 	}
 2386: 	foreach my $key (keys(%lasthash)) {
 2387: 	    next if ($key !~ /\.submission$/);
 2388: 
 2389: 	    my ($partid,$foo) = split(/submission$/,$key);
 2390: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2391: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2392: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2393: 	}
 2394:     }
 2395:     if (!@string) {
 2396: 	$string[0] =
 2397: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2398:     }
 2399:     return (\@string,\$timestamp);
 2400: }
 2401: 
 2402: #--- High light keywords, with style choosen by user.
 2403: sub keywords_highlight {
 2404:     my $string    = shift;
 2405:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2406:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2407:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2408:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2409:     foreach my $keyword (@keylist) {
 2410: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2411:     }
 2412:     return $string;
 2413: }
 2414: 
 2415: #--- Called from submission routine
 2416: sub processHandGrade {
 2417:     my ($request) = shift;
 2418:     my $symb   = &get_symb($request);
 2419:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2420:     my $button = $env{'form.gradeOpt'};
 2421:     my $ngrade = $env{'form.NCT'};
 2422:     my $ntstu  = $env{'form.NTSTU'};
 2423:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2424:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2425: 
 2426:     if ($button eq 'Save & Next') {
 2427: 	my $ctr = 0;
 2428: 	while ($ctr < $ngrade) {
 2429: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2430: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2431: 	    if ($errorflag eq 'no_score') {
 2432: 		$ctr++;
 2433: 		next;
 2434: 	    }
 2435: 	    if ($errorflag eq 'not_allowed') {
 2436: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2437: 		$ctr++;
 2438: 		next;
 2439: 	    }
 2440: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2441: 	    my ($subject,$message,$msgstatus) = ('','','');
 2442: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2443:             my ($feedurl,$showsymb) =
 2444: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2445: 	    my $messagetail;
 2446: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2447: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2448: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2449: 		$subject.=' ['.$restitle.']';
 2450: 		my (@msgnum) = split(/,/,$includemsg);
 2451: 		foreach (@msgnum) {
 2452: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2453: 		}
 2454: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2455: 		if ($env{'form.withgrades'.$ctr}) {
 2456: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2457: 		    $messagetail = " for <a href=\"".
 2458: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2459: 		}
 2460: 		$msgstatus = 
 2461:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2462: 						     $message.$messagetail,
 2463:                                                      undef,$feedurl,undef,
 2464:                                                      undef,undef,$showsymb,
 2465:                                                      $restitle);
 2466: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2467: 				$msgstatus);
 2468: 	    }
 2469: 	    if ($env{'form.collaborator'.$ctr}) {
 2470: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2471: 		foreach my $collabstr (@collabstrs) {
 2472: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2473: 		    foreach my $collaborator (@collaborators) {
 2474: 			my ($errorflag,$pts,$wgt) = 
 2475: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2476: 					   $env{'form.unamedom'.$ctr},$part);
 2477: 			if ($errorflag eq 'not_allowed') {
 2478: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2479: 			    next;
 2480: 			} elsif ($message ne '') {
 2481: 			    my ($baseurl,$showsymb) = 
 2482: 				&get_feedurl_and_symb($symb,$collaborator,
 2483: 						      $udom);
 2484: 			    if ($env{'form.withgrades'.$ctr}) {
 2485: 				$messagetail = " for <a href=\"".
 2486:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2487: 			    }
 2488: 			    $msgstatus = 
 2489: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2490: 			}
 2491: 		    }
 2492: 		}
 2493: 	    }
 2494: 	    $ctr++;
 2495: 	}
 2496:     }
 2497: 
 2498:     if ($env{'form.handgrade'} eq 'yes') {
 2499: 	# Keywords sorted in alphabatical order
 2500: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2501: 	my %keyhash = ();
 2502: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2503: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2504: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2505: 	$env{'form.keywords'} = join(' ',@keywords);
 2506: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2507: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2508: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2509: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2510: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2511: 
 2512: 	# message center - Order of message gets changed. Blank line is eliminated.
 2513: 	# New messages are saved in env for the next student.
 2514: 	# All messages are saved in nohist_handgrade.db
 2515: 	my ($ctr,$idx) = (1,1);
 2516: 	while ($ctr <= $env{'form.savemsgN'}) {
 2517: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2518: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2519: 		$idx++;
 2520: 	    }
 2521: 	    $ctr++;
 2522: 	}
 2523: 	$ctr = 0;
 2524: 	while ($ctr < $ngrade) {
 2525: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2526: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2527: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2528: 		$idx++;
 2529: 	    }
 2530: 	    $ctr++;
 2531: 	}
 2532: 	$env{'form.savemsgN'} = --$idx;
 2533: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2534: 	my $putresult = &Apache::lonnet::put
 2535: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2536:     }
 2537:     # Called by Save & Refresh from Highlight Attribute Window
 2538:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2539:     if ($env{'form.refresh'} eq 'on') {
 2540: 	my ($ctr,$total) = (0,0);
 2541: 	while ($ctr < $ngrade) {
 2542: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2543: 	    $ctr++;
 2544: 	}
 2545: 	$env{'form.NTSTU'}=$ngrade;
 2546: 	$ctr = 0;
 2547: 	while ($ctr < $total) {
 2548: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2549: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2550: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2551: 	    &submission($request,$ctr,$total-1);
 2552: 	    $ctr++;
 2553: 	}
 2554: 	return '';
 2555:     }
 2556: 
 2557: # Go directly to grade student - from submission or link from chart page
 2558:     if ($button eq 'Grade Student') {
 2559: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2560: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2561: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2562: 	$env{'form.fullname'} = $$fullname{$processUser};
 2563: 	&submission($request,0,0);
 2564: 	return '';
 2565:     }
 2566: 
 2567:     # Get the next/previous one or group of students
 2568:     my $firststu = $env{'form.unamedom0'};
 2569:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2570:     my $ctr = 2;
 2571:     while ($laststu eq '') {
 2572: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2573: 	$ctr++;
 2574: 	$laststu = $firststu if ($ctr > $ngrade);
 2575:     }
 2576: 
 2577:     my (@parsedlist,@nextlist);
 2578:     my ($nextflg) = 0;
 2579:     foreach my $item (sort 
 2580: 	     {
 2581: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2582: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2583: 		 }
 2584: 		 return $a cmp $b;
 2585: 	     } (keys(%$fullname))) {
 2586: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2587: 	    push(@parsedlist,$item);
 2588: 	}
 2589: 	$nextflg = 1 if ($item eq $laststu);
 2590: 	if ($button eq 'Previous') {
 2591: 	    last if ($item eq $firststu);
 2592: 	    push(@parsedlist,$item);
 2593: 	}
 2594:     }
 2595:     $ctr = 0;
 2596:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2597:     my ($partlist) = &response_type($symb);
 2598:     foreach my $student (@parsedlist) {
 2599: 	my $submitonly=$env{'form.submitonly'};
 2600: 	my ($uname,$udom) = split(/:/,$student);
 2601: 	
 2602: 	if ($submitonly eq 'queued') {
 2603: 	    my %queue_status = 
 2604: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2605: 							$udom,$uname);
 2606: 	    next if (!defined($queue_status{'gradingqueue'}));
 2607: 	}
 2608: 
 2609: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2610: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2611: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2612: 	    my $submitted = 0;
 2613: 	    my $ungraded = 0;
 2614: 	    my $incorrect = 0;
 2615: 	    foreach my $item (keys(%status)) {
 2616: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2617: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2618: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2619: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2620: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2621: 		    $submitted = 0;
 2622: 		}
 2623: 	    }
 2624: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2625: 				     $submitonly eq 'incorrect' ||
 2626: 				     $submitonly eq 'graded'));
 2627: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2628: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2629: 	}
 2630: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2631: 	last if ($ctr == $ntstu);
 2632: 	$ctr++;
 2633:     }
 2634: 
 2635:     $ctr = 0;
 2636:     my $total = scalar(@nextlist)-1;
 2637: 
 2638:     foreach (sort(@nextlist)) {
 2639: 	my ($uname,$udom,$submitter) = split(/:/);
 2640: 	$env{'form.student'}  = $uname;
 2641: 	$env{'form.userdom'}  = $udom;
 2642: 	$env{'form.fullname'} = $$fullname{$_};
 2643: 	&submission($request,$ctr,$total);
 2644: 	$ctr++;
 2645:     }
 2646:     if ($total < 0) {
 2647: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2648: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2649: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2650: 	$the_end.=&show_grading_menu_form($symb);
 2651: 	$request->print($the_end);
 2652:     }
 2653:     return '';
 2654: }
 2655: 
 2656: #---- Save the score and award for each student, if changed
 2657: sub saveHandGrade {
 2658:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2659:     my @version_parts;
 2660:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2661: 					   $env{'request.course.id'});
 2662:     if (!&canmodify($usec)) { return('not_allowed'); }
 2663:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2664:     my @parts_graded;
 2665:     my %newrecord  = ();
 2666:     my ($pts,$wgt) = ('','');
 2667:     my %aggregate = ();
 2668:     my $aggregateflag = 0;
 2669:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2670:     foreach my $new_part (@parts) {
 2671: 	#collaborator ($submi may vary for different parts
 2672: 	if ($submitter && $new_part ne $part) { next; }
 2673: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2674: 	if ($dropMenu eq 'excused') {
 2675: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2676: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2677: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2678: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2679: 		}
 2680: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2681: 	    }
 2682: 	} elsif ($dropMenu eq 'reset status'
 2683: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2684: 	    foreach my $key (keys(%record)) {
 2685: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2686: 	    }
 2687: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2688: 		"$env{'user.name'}:$env{'user.domain'}";
 2689:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2690: 
 2691:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2692: 					       [$new_part]);
 2693:             my $aggtries =$totaltries;
 2694:             if ($last_resets{$new_part}) {
 2695:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2696: 					   $new_part);
 2697:             }
 2698: 
 2699:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2700:             if ($aggtries > 0) {
 2701:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2702:                 $aggregateflag = 1;
 2703:             }
 2704: 	} elsif ($dropMenu eq '') {
 2705: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2706: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2707: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2708: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2709: 		next;
 2710: 	    }
 2711: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2712: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2713: 	    my $partial= $pts/$wgt;
 2714: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2715: 		#do not update score for part if not changed.
 2716:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2717: 		next;
 2718: 	    } else {
 2719: 	        push(@parts_graded,$new_part);
 2720: 	    }
 2721: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2722: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2723: 	    }
 2724: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2725: 	    if ($partial == 0) {
 2726: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2727: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2728: 		}
 2729: 	    } else {
 2730: 		if ($record{$reckey} ne 'correct_by_override') {
 2731: 		    $newrecord{$reckey} = 'correct_by_override';
 2732: 		}
 2733: 	    }	    
 2734: 	    if ($submitter && 
 2735: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2736: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2737: 	    }
 2738: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2739: 		"$env{'user.name'}:$env{'user.domain'}";
 2740: 	}
 2741: 	# unless problem has been graded, set flag to version the submitted files
 2742: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2743: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2744: 	        $dropMenu eq 'reset status')
 2745: 	   {
 2746: 	    push(@version_parts,$new_part);
 2747: 	}
 2748:     }
 2749:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2750:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2751: 
 2752:     if (%newrecord) {
 2753:         if (@version_parts) {
 2754:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2755:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2756: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2757: 	    foreach my $new_part (@version_parts) {
 2758: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2759: 				$new_part,\%newrecord);
 2760: 	    }
 2761:         }
 2762: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2763: 				$env{'request.course.id'},$domain,$stuname);
 2764: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2765: 				     $cdom,$cnum,$domain,$stuname);
 2766:     }
 2767:     if ($aggregateflag) {
 2768:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2769: 			      $cdom,$cnum);
 2770:     }
 2771:     return ('',$pts,$wgt);
 2772: }
 2773: 
 2774: sub check_and_remove_from_queue {
 2775:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2776:     my @ungraded_parts;
 2777:     foreach my $part (@{$parts}) {
 2778: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2779: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2780: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2781: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2782: 		) {
 2783: 	    push(@ungraded_parts, $part);
 2784: 	}
 2785:     }
 2786:     if ( !@ungraded_parts ) {
 2787: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2788: 					       $cnum,$domain,$stuname);
 2789:     }
 2790: }
 2791: 
 2792: sub handback_files {
 2793:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2794:     my $portfolio_root = '/userfiles/portfolio';
 2795:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2796: 
 2797:     my @part_response_id = &flatten_responseType($responseType);
 2798:     foreach my $part_response_id (@part_response_id) {
 2799:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2800: 	my $part_resp = join('_',@{ $part_response_id });
 2801:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2802:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2803:                 my $file_counter = 1;
 2804: 		my $file_msg;
 2805:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2806:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2807:                     my ($directory,$answer_file) = 
 2808:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2809:                     my ($answer_name,$answer_ver,$answer_ext) =
 2810: 		        &file_name_version_ext($answer_file);
 2811: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2812:                     my $getpropath = 1;
 2813: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2814: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2815:                     # fix file name
 2816:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2817:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2818:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2819:             	                                $save_file_name);
 2820:                     if ($result !~ m|^/uploaded/|) {
 2821:                         $request->print('<br /><span class="LC_error">'.
 2822:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2823:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2824:                                         '</span>');
 2825:                     } else {
 2826:                         # mark the file as read only
 2827:                         my @files = ($save_file_name);
 2828:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2829:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2830: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2831: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2832: 			}
 2833:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2834: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2835: 
 2836:                     }
 2837:                     $request->print("<br />".$fname." will be the uploaded file name");
 2838:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2839:                     $file_counter++;
 2840:                 }
 2841: 		my $subject = "File Handed Back by Instructor ";
 2842: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2843: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2844: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2845: 		$message .= " and can be found in your portfolio space.";
 2846: 		my ($feedurl,$showsymb) = 
 2847: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2848:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2849: 		my $msgstatus = 
 2850:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2851: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2852:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2853:             }
 2854:         }
 2855:     return;
 2856: }
 2857: 
 2858: sub get_feedurl_and_symb {
 2859:     my ($symb,$uname,$udom) = @_;
 2860:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2861:     $url = &Apache::lonnet::clutter($url);
 2862:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2863: 					$symb,$udom,$uname);
 2864:     if ($encrypturl =~ /^yes$/i) {
 2865: 	&Apache::lonenc::encrypted(\$url,1);
 2866: 	&Apache::lonenc::encrypted(\$symb,1);
 2867:     }
 2868:     return ($url,$symb);
 2869: }
 2870: 
 2871: sub get_submitted_files {
 2872:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2873:     my @files;
 2874:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2875:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2876:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2877:     	    push(@files,$file_url.$file);
 2878:         }
 2879:     }
 2880:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2881:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2882:     }
 2883:     return (\@files);
 2884: }
 2885: 
 2886: # ----------- Provides number of tries since last reset.
 2887: sub get_num_tries {
 2888:     my ($record,$last_reset,$part) = @_;
 2889:     my $timestamp = '';
 2890:     my $num_tries = 0;
 2891:     if ($$record{'version'}) {
 2892:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2893:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2894:                 $timestamp = $$record{$version.':timestamp'};
 2895:                 if ($timestamp > $last_reset) {
 2896:                     $num_tries ++;
 2897:                 } else {
 2898:                     last;
 2899:                 }
 2900:             }
 2901:         }
 2902:     }
 2903:     return $num_tries;
 2904: }
 2905: 
 2906: # ----------- Determine decrements required in aggregate totals 
 2907: sub decrement_aggs {
 2908:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2909:     my %decrement = (
 2910:                         attempts => 0,
 2911:                         users => 0,
 2912:                         correct => 0
 2913:                     );
 2914:     $decrement{'attempts'} = $aggtries;
 2915:     if ($solvedstatus =~ /^correct/) {
 2916:         $decrement{'correct'} = 1;
 2917:     }
 2918:     if ($aggtries == $totaltries) {
 2919:         $decrement{'users'} = 1;
 2920:     }
 2921:     foreach my $type (keys(%decrement)) {
 2922:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2923:     }
 2924:     return;
 2925: }
 2926: 
 2927: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2928: sub get_last_resets {
 2929:     my ($symb,$courseid,$partids) =@_;
 2930:     my %last_resets;
 2931:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2932:     my $cname = $env{'course.'.$courseid.'.num'};
 2933:     my @keys;
 2934:     foreach my $part (@{$partids}) {
 2935: 	push(@keys,"$symb\0$part\0resettime");
 2936:     }
 2937:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2938: 				     $cdom,$cname);
 2939:     foreach my $part (@{$partids}) {
 2940: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2941:     }
 2942:     return %last_resets;
 2943: }
 2944: 
 2945: # ----------- Handles creating versions for portfolio files as answers
 2946: sub version_portfiles {
 2947:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2948:     my $version_parts = join('|',@$v_flag);
 2949:     my @returned_keys;
 2950:     my $parts = join('|', @$parts_graded);
 2951:     my $portfolio_root = '/userfiles/portfolio';
 2952:     foreach my $key (keys(%$record)) {
 2953:         my $new_portfiles;
 2954:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2955:             my @versioned_portfiles;
 2956:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2957:             foreach my $file (@portfiles) {
 2958:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2959:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2960: 		my ($answer_name,$answer_ver,$answer_ext) =
 2961: 		    &file_name_version_ext($answer_file);
 2962:                 my $getpropath = 1;    
 2963:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2964:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2965:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2966:                 if ($new_answer ne 'problem getting file') {
 2967:                     push(@versioned_portfiles, $directory.$new_answer);
 2968:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2969:                         [$directory.$new_answer],
 2970:                         [$symb,$env{'request.course.id'},'graded']);
 2971:                 }
 2972:             }
 2973:             $$record{$key} = join(',',@versioned_portfiles);
 2974:             push(@returned_keys,$key);
 2975:         }
 2976:     } 
 2977:     return (@returned_keys);   
 2978: }
 2979: 
 2980: sub get_next_version {
 2981:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2982:     my $version;
 2983:     foreach my $row (@$dir_list) {
 2984:         my ($file) = split(/\&/,$row,2);
 2985:         my ($file_name,$file_version,$file_ext) =
 2986: 	    &file_name_version_ext($file);
 2987:         if (($file_name eq $answer_name) && 
 2988: 	    ($file_ext eq $answer_ext)) {
 2989:                 # gets here if filename and extension match, regardless of version
 2990:                 if ($file_version ne '') {
 2991:                 # a versioned file is found  so save it for later
 2992:                 if ($file_version > $version) {
 2993: 		    $version = $file_version;
 2994: 	        }
 2995:             }
 2996:         }
 2997:     } 
 2998:     $version ++;
 2999:     return($version);
 3000: }
 3001: 
 3002: sub version_selected_portfile {
 3003:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3004:     my ($answer_name,$answer_ver,$answer_ext) =
 3005:         &file_name_version_ext($file_name);
 3006:     my $new_answer;
 3007:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3008:     if($env{'form.copy'} eq '-1') {
 3009:         $new_answer = 'problem getting file';
 3010:     } else {
 3011:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3012:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3013:                             $stu_name,$domain,'copy',
 3014: 		        '/portfolio'.$directory.$new_answer);
 3015:     }    
 3016:     return ($new_answer);
 3017: }
 3018: 
 3019: sub file_name_version_ext {
 3020:     my ($file)=@_;
 3021:     my @file_parts = split(/\./, $file);
 3022:     my ($name,$version,$ext);
 3023:     if (@file_parts > 1) {
 3024: 	$ext=pop(@file_parts);
 3025: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3026: 	    $version=pop(@file_parts);
 3027: 	}
 3028: 	$name=join('.',@file_parts);
 3029:     } else {
 3030: 	$name=join('.',@file_parts);
 3031:     }
 3032:     return($name,$version,$ext);
 3033: }
 3034: 
 3035: #--------------------------------------------------------------------------------------
 3036: #
 3037: #-------------------------- Next few routines handles grading by section or whole class
 3038: #
 3039: #--- Javascript to handle grading by section or whole class
 3040: sub viewgrades_js {
 3041:     my ($request) = shift;
 3042: 
 3043:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3044:     $request->print(<<VIEWJAVASCRIPT);
 3045: <script type="text/javascript" language="javascript">
 3046:    function writePoint(partid,weight,point) {
 3047: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3048: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3049: 	if (point == "textval") {
 3050: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3051: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3052: 		alert("$alertmsg"+parseFloat(point));
 3053: 		var resetbox = false;
 3054: 		for (var i=0; i<radioButton.length; i++) {
 3055: 		    if (radioButton[i].checked) {
 3056: 			textbox.value = i;
 3057: 			resetbox = true;
 3058: 		    }
 3059: 		}
 3060: 		if (!resetbox) {
 3061: 		    textbox.value = "";
 3062: 		}
 3063: 		return;
 3064: 	    }
 3065: 	    if (parseFloat(point) > parseFloat(weight)) {
 3066: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3067: 				   ") greater than the weight for the part. Accept?");
 3068: 		if (resp == false) {
 3069: 		    textbox.value = "";
 3070: 		    return;
 3071: 		}
 3072: 	    }
 3073: 	    for (var i=0; i<radioButton.length; i++) {
 3074: 		radioButton[i].checked=false;
 3075: 		if (parseFloat(point) == i) {
 3076: 		    radioButton[i].checked=true;
 3077: 		}
 3078: 	    }
 3079: 
 3080: 	} else {
 3081: 	    textbox.value = parseFloat(point);
 3082: 	}
 3083: 	for (i=0;i<document.classgrade.total.value;i++) {
 3084: 	    var user = document.classgrade["ctr"+i].value;
 3085: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3086: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3087: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3088: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3089: 	    if (saveval != "correct") {
 3090: 		scorename.value = point;
 3091: 		if (selname[0].selected != true) {
 3092: 		    selname[0].selected = true;
 3093: 		}
 3094: 	    }
 3095: 	}
 3096: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3097:     }
 3098: 
 3099:     function writeRadText(partid,weight) {
 3100: 	var selval   = document.classgrade["SELVAL_"+partid];
 3101: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3102:         var override = document.classgrade["FORCE_"+partid].checked;
 3103: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3104: 	if (selval[1].selected || selval[2].selected) {
 3105: 	    for (var i=0; i<radioButton.length; i++) {
 3106: 		radioButton[i].checked=false;
 3107: 
 3108: 	    }
 3109: 	    textbox.value = "";
 3110: 
 3111: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3112: 		var user = document.classgrade["ctr"+i].value;
 3113: 		user = user.replace(new RegExp(':', 'g'),"_");
 3114: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3115: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3116: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3117: 		if ((saveval != "correct") || override) {
 3118: 		    scorename.value = "";
 3119: 		    if (selval[1].selected) {
 3120: 			selname[1].selected = true;
 3121: 		    } else {
 3122: 			selname[2].selected = true;
 3123: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3124: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3125: 		    }
 3126: 		}
 3127: 	    }
 3128: 	} else {
 3129: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3130: 		var user = document.classgrade["ctr"+i].value;
 3131: 		user = user.replace(new RegExp(':', 'g'),"_");
 3132: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3133: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3134: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3135: 		if ((saveval != "correct") || override) {
 3136: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3137: 		    selname[0].selected = true;
 3138: 		}
 3139: 	    }
 3140: 	}	    
 3141:     }
 3142: 
 3143:     function changeSelect(partid,user) {
 3144: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3145: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3146: 	var point  = textbox.value;
 3147: 	var weight = document.classgrade["weight_"+partid].value;
 3148: 
 3149: 	if (isNaN(point) || parseFloat(point) < 0) {
 3150: 	    alert("$alertmsg"+parseFloat(point));
 3151: 	    textbox.value = "";
 3152: 	    return;
 3153: 	}
 3154: 	if (parseFloat(point) > parseFloat(weight)) {
 3155: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3156: 			       ") greater than the weight of the part. Accept?");
 3157: 	    if (resp == false) {
 3158: 		textbox.value = "";
 3159: 		return;
 3160: 	    }
 3161: 	}
 3162: 	selval[0].selected = true;
 3163:     }
 3164: 
 3165:     function changeOneScore(partid,user) {
 3166: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3167: 	if (selval[1].selected || selval[2].selected) {
 3168: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3169: 	    if (selval[2].selected) {
 3170: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3171: 	    }
 3172:         }
 3173:     }
 3174: 
 3175:     function resetEntry(numpart) {
 3176: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3177: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3178: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3179: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3180: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3181: 	    for (var i=0; i<radioButton.length; i++) {
 3182: 		radioButton[i].checked=false;
 3183: 
 3184: 	    }
 3185: 	    textbox.value = "";
 3186: 	    selval[0].selected = true;
 3187: 
 3188: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3189: 		var user = document.classgrade["ctr"+i].value;
 3190: 		user = user.replace(new RegExp(':', 'g'),"_");
 3191: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3192: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3193: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3194: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3195: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3196: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3197: 		if (saveselval == "excused") {
 3198: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3199: 		} else {
 3200: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3201: 		}
 3202: 	    }
 3203: 	}
 3204:     }
 3205: 
 3206: </script>
 3207: VIEWJAVASCRIPT
 3208: }
 3209: 
 3210: #--- show scores for a section or whole class w/ option to change/update a score
 3211: sub viewgrades {
 3212:     my ($request) = shift;
 3213:     &viewgrades_js($request);
 3214: 
 3215:     my ($symb) = &get_symb($request);
 3216:     #need to make sure we have the correct data for later EXT calls, 
 3217:     #thus invalidate the cache
 3218:     &Apache::lonnet::devalidatecourseresdata(
 3219:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3220:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3221:     &Apache::lonnet::clear_EXT_cache_status();
 3222: 
 3223:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3224:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3225: 
 3226:     #view individual student submission form - called using Javascript viewOneStudent
 3227:     $result.=&jscriptNform($symb);
 3228: 
 3229:     #beginning of class grading form
 3230:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3231:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3232: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3233: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3234: 	&build_section_inputs().
 3235: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3236: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3237: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3238: 
 3239:     my ($common_header,$specific_header);
 3240:     if ($env{'form.section'} eq 'all') {
 3241: 	$common_header = &mt('Assign Common Grade to Class');
 3242:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3243:     } elsif ($env{'form.section'} eq 'none') {
 3244:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3245: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3246:     } else {
 3247:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3248:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3249: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3250:     }
 3251:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3252:     #radio buttons/text box for assigning points for a section or class.
 3253:     #handles different parts of a problem
 3254:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3255:     my %weight = ();
 3256:     my $ctsparts = 0;
 3257:     my %seen = ();
 3258:     my @part_response_id = &flatten_responseType($responseType);
 3259:     foreach my $part_response_id (@part_response_id) {
 3260:     	my ($partid,$respid) = @{ $part_response_id };
 3261: 	my $part_resp = join('_',@{ $part_response_id });
 3262: 	next if $seen{$partid};
 3263: 	$seen{$partid}++;
 3264: 	my $handgrade=$$handgrade{$part_resp};
 3265: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3266: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3267: 
 3268: 	my $display_part=&get_display_part($partid,$symb);
 3269: 	my $radio.='<table border="0"><tr>';  
 3270: 	my $ctr = 0;
 3271: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3272: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3273: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3274: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3275: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3276: 	    $ctr++;
 3277: 	}
 3278: 	$radio.='</tr></table>';
 3279: 	my $line = '<input type="text" name="TEXTVAL_'.
 3280: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3281: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3282: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3283: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3284: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3285: 		$weight{$partid}.')"> '.
 3286: 	    '<option selected="selected"> </option>'.
 3287: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3288: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3289: 	    '</select></td>'.
 3290:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3291: 	$line.='<input type="hidden" name="partid_'.
 3292: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3293: 	$line.='<input type="hidden" name="weight_'.
 3294: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3295: 
 3296: 	$result.=
 3297: 	    &Apache::loncommon::start_data_table_row()."\n".
 3298: 	    '<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>'.
 3299: 	    &Apache::loncommon::end_data_table_row()."\n";
 3300: 	$ctsparts++;
 3301:     }
 3302:     $result.=&Apache::loncommon::end_data_table()."\n".
 3303: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3304:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3305: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3306: 
 3307:     #table listing all the students in a section/class
 3308:     #header of table
 3309:     $result.= '<h3>'.$specific_header.'</h3>'.
 3310:               &Apache::loncommon::start_data_table().
 3311: 	      &Apache::loncommon::start_data_table_header_row().
 3312: 	      '<th>'.&mt('No.').'</th>'.
 3313: 	      '<th>'.&nameUserString('header')."</th>\n";
 3314:     my (@parts) = sort(&getpartlist($symb));
 3315:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3316:     my @partids = ();
 3317:     foreach my $part (@parts) {
 3318: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3319:         my $narrowtext = &mt('Tries');
 3320: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3321: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3322: 	my ($partid) = &split_part_type($part);
 3323:         push(@partids,$partid);
 3324: 	my $display_part=&get_display_part($partid,$symb);
 3325: 	if ($display =~ /^Partial Credit Factor/) {
 3326: 	    $result.='<th>'.
 3327: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3328: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3329: 	    next;
 3330: 	    
 3331: 	} else {
 3332: 	    if ($display =~ /Problem Status/) {
 3333: 		my $grade_status_mt = &mt('Grade Status');
 3334: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3335: 	    }
 3336: 	    my $part_mt = &mt('Part:');
 3337: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3338: 	}
 3339: 
 3340: 	$result.='<th>'.$display.'</th>'."\n";
 3341:     }
 3342:     $result.=&Apache::loncommon::end_data_table_header_row();
 3343: 
 3344:     my %last_resets = 
 3345: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3346: 
 3347:     #get info for each student
 3348:     #list all the students - with points and grade status
 3349:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3350:     my $ctr = 0;
 3351:     foreach (sort 
 3352: 	     {
 3353: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3354: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3355: 		 }
 3356: 		 return $a cmp $b;
 3357: 	     } (keys(%$fullname))) {
 3358: 	$ctr++;
 3359: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3360: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3361:     }
 3362:     $result.=&Apache::loncommon::end_data_table();
 3363:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3364:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3365: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3366:     if (scalar(%$fullname) eq 0) {
 3367: 	my $colspan=3+scalar(@parts);
 3368: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3369:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3370: 	$result='<span class="LC_warning">'.
 3371: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3372: 	        $section_display, $stu_status).
 3373: 	    '</span>';
 3374:     }
 3375:     $result.=&show_grading_menu_form($symb);
 3376:     return $result;
 3377: }
 3378: 
 3379: #--- call by previous routine to display each student
 3380: sub viewstudentgrade {
 3381:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3382:     my ($uname,$udom) = split(/:/,$student);
 3383:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3384:     my %aggregates = (); 
 3385:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3386: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3387: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3388: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3389: 	'\');" target="_self">'.$fullname.'</a> '.
 3390: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3391:     $student=~s/:/_/; # colon doen't work in javascript for names
 3392:     foreach my $apart (@$parts) {
 3393: 	my ($part,$type) = &split_part_type($apart);
 3394: 	my $score=$record{"resource.$part.$type"};
 3395:         $result.='<td align="center">';
 3396:         my ($aggtries,$totaltries);
 3397:         unless (exists($aggregates{$part})) {
 3398: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3399: 
 3400: 	    $aggtries = $totaltries;
 3401:             if ($$last_resets{$part}) {  
 3402:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3403: 					   $part);
 3404:             }
 3405:             $result.='<input type="hidden" name="'.
 3406:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3407:             $result.='<input type="hidden" name="'.
 3408:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3409:             $aggregates{$part} = 1;
 3410:         }
 3411: 	if ($type eq 'awarded') {
 3412: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3413: 	    $result.='<input type="hidden" name="'.
 3414: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3415: 	    $result.='<input type="text" name="'.
 3416: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3417: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3418: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3419: 	} elsif ($type eq 'solved') {
 3420: 	    my ($status,$foo)=split(/_/,$score,2);
 3421: 	    $status = 'nothing' if ($status eq '');
 3422: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3423: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3424: 	    $result.='&nbsp;<select name="'.
 3425: 		'GD_'.$student.'_'.$part.'_solved" '.
 3426: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3427: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3428: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3429: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3430: 	    $result.="</select>&nbsp;</td>\n";
 3431: 	} else {
 3432: 	    $result.='<input type="hidden" name="'.
 3433: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3434: 		    "\n";
 3435: 	    $result.='<input type="text" name="'.
 3436: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3437: 		'value="'.$score.'" size="4" /></td>'."\n";
 3438: 	}
 3439:     }
 3440:     $result.=&Apache::loncommon::end_data_table_row();
 3441:     return $result;
 3442: }
 3443: 
 3444: #--- change scores for all the students in a section/class
 3445: #    record does not get update if unchanged
 3446: sub editgrades {
 3447:     my ($request) = @_;
 3448: 
 3449:     my $symb=&get_symb($request);
 3450:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3451:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3452:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3453:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3454: 
 3455:     my $result= &Apache::loncommon::start_data_table().
 3456: 	&Apache::loncommon::start_data_table_header_row().
 3457: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3458: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3459:     my %scoreptr = (
 3460: 		    'correct'  =>'correct_by_override',
 3461: 		    'incorrect'=>'incorrect_by_override',
 3462: 		    'excused'  =>'excused',
 3463: 		    'ungraded' =>'ungraded_attempted',
 3464: 		    'nothing'  => '',
 3465: 		    );
 3466:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3467: 
 3468:     my (@partid);
 3469:     my %weight = ();
 3470:     my %columns = ();
 3471:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3472: 
 3473:     my (@parts) = sort(&getpartlist($symb));
 3474:     my $header;
 3475:     while ($ctr < $env{'form.totalparts'}) {
 3476: 	my $partid = $env{'form.partid_'.$ctr};
 3477: 	push(@partid,$partid);
 3478: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3479: 	$ctr++;
 3480:     }
 3481:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3482:     foreach my $partid (@partid) {
 3483: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3484: 	    '<th align="center">'.&mt('New Score').'</th>';
 3485: 	$columns{$partid}=2;
 3486: 	foreach my $stores (@parts) {
 3487: 	    my ($part,$type) = &split_part_type($stores);
 3488: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3489: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3490: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3491: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3492:             my $narrowtext = &mt('Tries');
 3493: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3494: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3495: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3496: 	    $columns{$partid}+=2;
 3497: 	}
 3498:     }
 3499:     foreach my $partid (@partid) {
 3500: 	my $display_part=&get_display_part($partid,$symb);
 3501: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3502: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3503: 	    '</th>';
 3504: 
 3505:     }
 3506:     $result .= &Apache::loncommon::end_data_table_header_row().
 3507: 	&Apache::loncommon::start_data_table_header_row().
 3508: 	$header.
 3509: 	&Apache::loncommon::end_data_table_header_row();
 3510:     my @noupdate;
 3511:     my ($updateCtr,$noupdateCtr) = (1,1);
 3512:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3513: 	my $line;
 3514: 	my $user = $env{'form.ctr'.$i};
 3515: 	my ($uname,$udom)=split(/:/,$user);
 3516: 	my %newrecord;
 3517: 	my $updateflag = 0;
 3518: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3519: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3520: 	if (!&canmodify($usec)) {
 3521: 	    my $numcols=scalar(@partid)*4+2;
 3522: 	    push(@noupdate,
 3523: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3524: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3525: 	    next;
 3526: 	}
 3527:         my %aggregate = ();
 3528:         my $aggregateflag = 0;
 3529: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3530: 	foreach (@partid) {
 3531: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3532: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3533: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3534: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3535: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3536: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3537: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3538: 	    my $score;
 3539: 	    if ($partial eq '') {
 3540: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3541: 	    } elsif ($partial > 0) {
 3542: 		$score = 'correct_by_override';
 3543: 	    } elsif ($partial == 0) {
 3544: 		$score = 'incorrect_by_override';
 3545: 	    }
 3546: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3547: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3548: 
 3549: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3550: 		"$env{'user.name'}:$env{'user.domain'}";
 3551: 	    if ($dropMenu eq 'reset status' &&
 3552: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3553: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3554: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3555: 		$newrecord{'resource.'.$_.'.award'} = '';
 3556: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3557: 		$updateflag = 1;
 3558:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3559:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3560:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3561:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3562:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3563:                     $aggregateflag = 1;
 3564:                 }
 3565: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3566: 		$updateflag = 1;
 3567: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3568: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3569: 		$rec_update++;
 3570: 	    }
 3571: 
 3572: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3573: 		'<td align="center">'.$awarded.
 3574: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3575: 
 3576: 
 3577: 	    my $partid=$_;
 3578: 	    foreach my $stores (@parts) {
 3579: 		my ($part,$type) = &split_part_type($stores);
 3580: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3581: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3582: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3583: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3584: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3585: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3586: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3587: 		    $updateflag=1;
 3588: 		}
 3589: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3590: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3591: 	    }
 3592: 	}
 3593: 	$line.="\n";
 3594: 
 3595: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3596: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3597: 
 3598: 	if ($updateflag) {
 3599: 	    $count++;
 3600: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3601: 				    $udom,$uname);
 3602: 
 3603: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3604: 					      $cnum,$udom,$uname)) {
 3605: 		# need to figure out if should be in queue.
 3606: 		my %record =  
 3607: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3608: 					     $udom,$uname);
 3609: 		my $all_graded = 1;
 3610: 		my $none_graded = 1;
 3611: 		foreach my $part (@parts) {
 3612: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3613: 			$all_graded = 0;
 3614: 		    } else {
 3615: 			$none_graded = 0;
 3616: 		    }
 3617: 		}
 3618: 
 3619: 		if ($all_graded || $none_graded) {
 3620: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3621: 							   $symb,$cdom,$cnum,
 3622: 							   $udom,$uname);
 3623: 		}
 3624: 	    }
 3625: 
 3626: 	    $result.=&Apache::loncommon::start_data_table_row().
 3627: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3628: 		&Apache::loncommon::end_data_table_row();
 3629: 	    $updateCtr++;
 3630: 	} else {
 3631: 	    push(@noupdate,
 3632: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3633: 	    $noupdateCtr++;
 3634: 	}
 3635:         if ($aggregateflag) {
 3636:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3637: 				  $cdom,$cnum);
 3638:         }
 3639:     }
 3640:     if (@noupdate) {
 3641: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3642: 	my $numcols=scalar(@partid)*4+2;
 3643: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3644: 	    '<td align="center" colspan="'.$numcols.'">'.
 3645: 	    &mt('No Changes Occurred For the Students Below').
 3646: 	    '</td>'.
 3647: 	    &Apache::loncommon::end_data_table_row();
 3648: 	foreach my $line (@noupdate) {
 3649: 	    $result.=
 3650: 		&Apache::loncommon::start_data_table_row().
 3651: 		$line.
 3652: 		&Apache::loncommon::end_data_table_row();
 3653: 	}
 3654:     }
 3655:     $result .= &Apache::loncommon::end_data_table().
 3656: 	&show_grading_menu_form($symb);
 3657:     my $msg = '<p><b>'.
 3658: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3659: 	    $rec_update,$count).'</b><br />'.
 3660: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3661: 	'</b></p>';
 3662:     return $title.$msg.$result;
 3663: }
 3664: 
 3665: sub split_part_type {
 3666:     my ($partstr) = @_;
 3667:     my ($temp,@allparts)=split(/_/,$partstr);
 3668:     my $type=pop(@allparts);
 3669:     my $part=join('_',@allparts);
 3670:     return ($part,$type);
 3671: }
 3672: 
 3673: #------------- end of section for handling grading by section/class ---------
 3674: #
 3675: #----------------------------------------------------------------------------
 3676: 
 3677: 
 3678: #----------------------------------------------------------------------------
 3679: #
 3680: #-------------------------- Next few routines handles grading by csv upload
 3681: #
 3682: #--- Javascript to handle csv upload
 3683: sub csvupload_javascript_reverse_associate {
 3684:     my $error1=&mt('You need to specify the username or ID');
 3685:     my $error2=&mt('You need to specify at least one grading field');
 3686:   return(<<ENDPICK);
 3687:   function verify(vf) {
 3688:     var foundsomething=0;
 3689:     var founduname=0;
 3690:     var foundID=0;
 3691:     for (i=0;i<=vf.nfields.value;i++) {
 3692:       tw=eval('vf.f'+i+'.selectedIndex');
 3693:       if (i==0 && tw!=0) { foundID=1; }
 3694:       if (i==1 && tw!=0) { founduname=1; }
 3695:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3696:     }
 3697:     if (founduname==0 && foundID==0) {
 3698: 	alert('$error1');
 3699: 	return;
 3700:     }
 3701:     if (foundsomething==0) {
 3702: 	alert('$error2');
 3703: 	return;
 3704:     }
 3705:     vf.submit();
 3706:   }
 3707:   function flip(vf,tf) {
 3708:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3709:     var i;
 3710:     for (i=0;i<=vf.nfields.value;i++) {
 3711:       //can not pick the same destination field for both name and domain
 3712:       if (((i ==0)||(i ==1)) && 
 3713:           ((tf==0)||(tf==1)) && 
 3714:           (i!=tf) &&
 3715:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3716:         eval('vf.f'+i+'.selectedIndex=0;')
 3717:       }
 3718:     }
 3719:   }
 3720: ENDPICK
 3721: }
 3722: 
 3723: sub csvupload_javascript_forward_associate {
 3724:     my $error1=&mt('You need to specify the username or ID');
 3725:     my $error2=&mt('You need to specify at least one grading field');
 3726:   return(<<ENDPICK);
 3727:   function verify(vf) {
 3728:     var foundsomething=0;
 3729:     var founduname=0;
 3730:     var foundID=0;
 3731:     for (i=0;i<=vf.nfields.value;i++) {
 3732:       tw=eval('vf.f'+i+'.selectedIndex');
 3733:       if (tw==1) { foundID=1; }
 3734:       if (tw==2) { founduname=1; }
 3735:       if (tw>3) { foundsomething=1; }
 3736:     }
 3737:     if (founduname==0 && foundID==0) {
 3738: 	alert('$error1');
 3739: 	return;
 3740:     }
 3741:     if (foundsomething==0) {
 3742: 	alert('$error2');
 3743: 	return;
 3744:     }
 3745:     vf.submit();
 3746:   }
 3747:   function flip(vf,tf) {
 3748:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3749:     var i;
 3750:     //can not pick the same destination field twice
 3751:     for (i=0;i<=vf.nfields.value;i++) {
 3752:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3753:         eval('vf.f'+i+'.selectedIndex=0;')
 3754:       }
 3755:     }
 3756:   }
 3757: ENDPICK
 3758: }
 3759: 
 3760: sub csvuploadmap_header {
 3761:     my ($request,$symb,$datatoken,$distotal)= @_;
 3762:     my $javascript;
 3763:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3764: 	$javascript=&csvupload_javascript_reverse_associate();
 3765:     } else {
 3766: 	$javascript=&csvupload_javascript_forward_associate();
 3767:     }
 3768: 
 3769:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3770:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3771:     my $ignore=&mt('Ignore First Line');
 3772:     $symb = &Apache::lonenc::check_encrypt($symb);
 3773:     $request->print(<<ENDPICK);
 3774: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3775: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3776: $result
 3777: <hr />
 3778: <h3>Identify fields</h3>
 3779: Total number of records found in file: $distotal <hr />
 3780: Enter as many fields as you can. The system will inform you and bring you back
 3781: to this page if the data selected is insufficient to run your class.<hr />
 3782: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3783: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3784: <input type="hidden" name="associate"  value="" />
 3785: <input type="hidden" name="phase"      value="three" />
 3786: <input type="hidden" name="datatoken"  value="$datatoken" />
 3787: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3788: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3789: <input type="hidden" name="upfile_associate" 
 3790:                                        value="$env{'form.upfile_associate'}" />
 3791: <input type="hidden" name="symb"       value="$symb" />
 3792: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3793: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3794: <input type="hidden" name="command"    value="csvuploadoptions" />
 3795: <hr />
 3796: <script type="text/javascript" language="Javascript">
 3797: $javascript
 3798: </script>
 3799: ENDPICK
 3800:     return '';
 3801: 
 3802: }
 3803: 
 3804: sub csvupload_fields {
 3805:     my ($symb) = @_;
 3806:     my (@parts) = &getpartlist($symb);
 3807:     my @fields=(['ID','Student/Employee ID'],
 3808: 		['username','Student Username'],
 3809: 		['domain','Student Domain']);
 3810:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3811:     foreach my $part (sort(@parts)) {
 3812: 	my @datum;
 3813: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3814: 	my $name=$part;
 3815: 	if  (!$display) { $display = $name; }
 3816: 	@datum=($name,$display);
 3817: 	if ($name=~/^stores_(.*)_awarded/) {
 3818: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3819: 	}
 3820: 	push(@fields,\@datum);
 3821:     }
 3822:     return (@fields);
 3823: }
 3824: 
 3825: sub csvuploadmap_footer {
 3826:     my ($request,$i,$keyfields) =@_;
 3827:     $request->print(<<ENDPICK);
 3828: </table>
 3829: <input type="hidden" name="nfields" value="$i" />
 3830: <input type="hidden" name="keyfields" value="$keyfields" />
 3831: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3832: </form>
 3833: ENDPICK
 3834: }
 3835: 
 3836: sub checkforfile_js {
 3837:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3838:     my $result =<<CSVFORMJS;
 3839: <script type="text/javascript" language="javascript">
 3840:     function checkUpload(formname) {
 3841: 	if (formname.upfile.value == "") {
 3842: 	    alert("$alertmsg");
 3843: 	    return false;
 3844: 	}
 3845: 	formname.submit();
 3846:     }
 3847:     </script>
 3848: CSVFORMJS
 3849:     return $result;
 3850: }
 3851: 
 3852: sub upcsvScores_form {
 3853:     my ($request) = shift;
 3854:     my ($symb)=&get_symb($request);
 3855:     if (!$symb) {return '';}
 3856:     my $result=&checkforfile_js();
 3857:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3858:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3859:     $result.=$table;
 3860:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3861:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3862:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3863: 	'</b></td></tr>'."\n";
 3864:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3865:     my $upload=&mt("Upload Scores");
 3866:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3867:     my $ignore=&mt('Ignore First Line');
 3868:     $symb = &Apache::lonenc::check_encrypt($symb);
 3869:     $result.=<<ENDUPFORM;
 3870: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3871: <input type="hidden" name="symb" value="$symb" />
 3872: <input type="hidden" name="command" value="csvuploadmap" />
 3873: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3874: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3875: $upfile_select
 3876: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3877: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3878: </form>
 3879: ENDUPFORM
 3880:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3881:                            &mt("How do I create a CSV file from a spreadsheet"))
 3882:     .'</td></tr></table>'."\n";
 3883:     $result.='</td></tr></table><br /><br />'."\n";
 3884:     $result.=&show_grading_menu_form($symb);
 3885:     return $result;
 3886: }
 3887: 
 3888: 
 3889: sub csvuploadmap {
 3890:     my ($request)= @_;
 3891:     my ($symb)=&get_symb($request);
 3892:     if (!$symb) {return '';}
 3893: 
 3894:     my $datatoken;
 3895:     if (!$env{'form.datatoken'}) {
 3896: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3897:     } else {
 3898: 	$datatoken=$env{'form.datatoken'};
 3899: 	&Apache::loncommon::load_tmp_file($request);
 3900:     }
 3901:     my @records=&Apache::loncommon::upfile_record_sep();
 3902:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3903:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3904:     my ($i,$keyfields);
 3905:     if (@records) {
 3906: 	my @fields=&csvupload_fields($symb);
 3907: 
 3908: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3909: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3910: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3911: 							  \@fields);
 3912: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3913: 	    chop($keyfields);
 3914: 	} else {
 3915: 	    unshift(@fields,['none','']);
 3916: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3917: 							    \@fields);
 3918:             foreach my $rec (@records) {
 3919:                 my %temp = &Apache::loncommon::record_sep($rec);
 3920:                 if (%temp) {
 3921:                     $keyfields=join(',',sort(keys(%temp)));
 3922:                     last;
 3923:                 }
 3924:             }
 3925: 	}
 3926:     }
 3927:     &csvuploadmap_footer($request,$i,$keyfields);
 3928:     $request->print(&show_grading_menu_form($symb));
 3929: 
 3930:     return '';
 3931: }
 3932: 
 3933: sub csvuploadoptions {
 3934:     my ($request)= @_;
 3935:     my ($symb)=&get_symb($request);
 3936:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3937:     my $ignore=&mt('Ignore First Line');
 3938:     $request->print(<<ENDPICK);
 3939: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3940: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3941: <input type="hidden" name="command"    value="csvuploadassign" />
 3942: <!--
 3943: <p>
 3944: <label>
 3945:    <input type="checkbox" name="show_full_results" />
 3946:    Show a table of all changes
 3947: </label>
 3948: </p>
 3949: -->
 3950: <p>
 3951: <label>
 3952:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3953:    Overwrite any existing score
 3954: </label>
 3955: </p>
 3956: ENDPICK
 3957:     my %fields=&get_fields();
 3958:     if (!defined($fields{'domain'})) {
 3959: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3960: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3961:     }
 3962:     foreach my $key (sort(keys(%env))) {
 3963: 	if ($key !~ /^form\.(.*)$/) { next; }
 3964: 	my $cleankey=$1;
 3965: 	if ($cleankey eq 'command') { next; }
 3966: 	$request->print('<input type="hidden" name="'.$cleankey.
 3967: 			'"  value="'.$env{$key}.'" />'."\n");
 3968:     }
 3969:     # FIXME do a check for any duplicated user ids...
 3970:     # FIXME do a check for any invalid user ids?...
 3971:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3972: <hr /></form>'."\n");
 3973:     $request->print(&show_grading_menu_form($symb));
 3974:     return '';
 3975: }
 3976: 
 3977: sub get_fields {
 3978:     my %fields;
 3979:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3980:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3981: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3982: 	    if ($env{'form.f'.$i} ne 'none') {
 3983: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3984: 	    }
 3985: 	} else {
 3986: 	    if ($env{'form.f'.$i} ne 'none') {
 3987: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3988: 	    }
 3989: 	}
 3990:     }
 3991:     return %fields;
 3992: }
 3993: 
 3994: sub csvuploadassign {
 3995:     my ($request)= @_;
 3996:     my ($symb)=&get_symb($request);
 3997:     if (!$symb) {return '';}
 3998:     my $error_msg = '';
 3999:     &Apache::loncommon::load_tmp_file($request);
 4000:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4001:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4002:     my %fields=&get_fields();
 4003:     $request->print('<h3>Assigning Grades</h3>');
 4004:     my $courseid=$env{'request.course.id'};
 4005:     my ($classlist) = &getclasslist('all',0);
 4006:     my @notallowed;
 4007:     my @skipped;
 4008:     my $countdone=0;
 4009:     foreach my $grade (@gradedata) {
 4010: 	my %entries=&Apache::loncommon::record_sep($grade);
 4011: 	my $domain;
 4012: 	if ($entries{$fields{'domain'}}) {
 4013: 	    $domain=$entries{$fields{'domain'}};
 4014: 	} else {
 4015: 	    $domain=$env{'form.default_domain'};
 4016: 	}
 4017: 	$domain=~s/\s//g;
 4018: 	my $username=$entries{$fields{'username'}};
 4019: 	$username=~s/\s//g;
 4020: 	if (!$username) {
 4021: 	    my $id=$entries{$fields{'ID'}};
 4022: 	    $id=~s/\s//g;
 4023: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4024: 	    $username=$ids{$id};
 4025: 	}
 4026: 	if (!exists($$classlist{"$username:$domain"})) {
 4027: 	    my $id=$entries{$fields{'ID'}};
 4028: 	    $id=~s/\s//g;
 4029: 	    if ($id) {
 4030: 		push(@skipped,"$id:$domain");
 4031: 	    } else {
 4032: 		push(@skipped,"$username:$domain");
 4033: 	    }
 4034: 	    next;
 4035: 	}
 4036: 	my $usec=$classlist->{"$username:$domain"}[5];
 4037: 	if (!&canmodify($usec)) {
 4038: 	    push(@notallowed,"$username:$domain");
 4039: 	    next;
 4040: 	}
 4041: 	my %points;
 4042: 	my %grades;
 4043: 	foreach my $dest (keys(%fields)) {
 4044: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4045: 		$dest eq 'domain') { next; }
 4046: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4047: 	    if ($dest=~/stores_(.*)_points/) {
 4048: 		my $part=$1;
 4049: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4050: 					      $symb,$domain,$username);
 4051:                 if ($wgt) {
 4052:                     $entries{$fields{$dest}}=~s/\s//g;
 4053:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4054:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4055:                                           : 'correct_by_override';
 4056:                     $grades{"resource.$part.awarded"}=$pcr;
 4057:                     $grades{"resource.$part.solved"}=$award;
 4058:                     $points{$part}=1;
 4059:                 } else {
 4060:                     $error_msg = "<br />" .
 4061:                         &mt("Some point values were assigned"
 4062:                             ." for problems with a weight "
 4063:                             ."of zero. These values were "
 4064:                             ."ignored.");
 4065:                 }
 4066: 	    } else {
 4067: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4068: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4069: 		my $store_key=$dest;
 4070: 		$store_key=~s/^stores/resource/;
 4071: 		$store_key=~s/_/\./g;
 4072: 		$grades{$store_key}=$entries{$fields{$dest}};
 4073: 	    }
 4074: 	}
 4075: 	if (! %grades) { 
 4076:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4077:         } else {
 4078: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4079: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4080: 					   $env{'request.course.id'},
 4081: 					   $domain,$username);
 4082: 	   if ($result eq 'ok') {
 4083: 	      $request->print('.');
 4084: 	   } else {
 4085: 	      $request->print("<p><span class=\"LC_error\">".
 4086:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4087:                                   "$username:$domain",$result)."</span></p>");
 4088: 	   }
 4089: 	   $request->rflush();
 4090: 	   $countdone++;
 4091:         }
 4092:     }
 4093:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4094:     if (@skipped) {
 4095: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4096: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4097:     }
 4098:     if (@notallowed) {
 4099: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4100: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4101:     }
 4102:     $request->print("<br />\n");
 4103:     $request->print(&show_grading_menu_form($symb));
 4104:     return $error_msg;
 4105: }
 4106: #------------- end of section for handling csv file upload ---------
 4107: #
 4108: #-------------------------------------------------------------------
 4109: #
 4110: #-------------- Next few routines handle grading by page/sequence
 4111: #
 4112: #--- Select a page/sequence and a student to grade
 4113: sub pickStudentPage {
 4114:     my ($request) = shift;
 4115: 
 4116:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4117:     $request->print(<<LISTJAVASCRIPT);
 4118: <script type="text/javascript" language="javascript">
 4119: 
 4120: function checkPickOne(formname) {
 4121:     if (radioSelection(formname.student) == null) {
 4122: 	alert("$alertmsg");
 4123: 	return;
 4124:     }
 4125:     ptr = pullDownSelection(formname.selectpage);
 4126:     formname.page.value = formname["page"+ptr].value;
 4127:     formname.title.value = formname["title"+ptr].value;
 4128:     formname.submit();
 4129: }
 4130: 
 4131: </script>
 4132: LISTJAVASCRIPT
 4133:     &commonJSfunctions($request);
 4134:     my ($symb) = &get_symb($request);
 4135:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4136:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4137:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4138: 
 4139:     my $result='<h3><span class="LC_info">&nbsp;'.
 4140: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4141: 
 4142:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4143:     my ($titles,$symbx) = &getSymbMap();
 4144:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4145: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4146: #    my $type=($curpage =~ /\.(page|sequence)/);
 4147:     my $select = '<select name="selectpage">'."\n";
 4148:     my $ctr=0;
 4149:     foreach (@$titles) {
 4150: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4151: 	$select.='<option value="'.$ctr.'" '.
 4152: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4153: 	    '>'.$showtitle.'</option>'."\n";
 4154: 	$ctr++;
 4155:     }
 4156:     $select.= '</select>';
 4157:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4158: 
 4159:     $ctr=0;
 4160:     foreach (@$titles) {
 4161: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4162: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4163: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4164: 	$ctr++;
 4165:     }
 4166:     $result.='<input type="hidden" name="page" />'."\n".
 4167: 	'<input type="hidden" name="title" />'."\n";
 4168: 
 4169:     my $options =
 4170: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4171: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4172:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4173: 
 4174:     $options =
 4175: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4176: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4177: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4178:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4179:     
 4180:     $result.=&build_section_inputs();
 4181:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4182:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4183: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4184: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4185: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4186: 
 4187:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4188: 
 4189:     $result.='&nbsp;<input type="button" '.
 4190: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4191: 
 4192:     $request->print($result);
 4193: 
 4194:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4195: 	&Apache::loncommon::start_data_table().
 4196: 	&Apache::loncommon::start_data_table_header_row().
 4197: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4198: 	'<th>'.&nameUserString('header').'</th>'.
 4199: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4200: 	'<th>'.&nameUserString('header').'</th>'.
 4201: 	&Apache::loncommon::end_data_table_header_row();
 4202:  
 4203:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4204:     my $ptr = 1;
 4205:     foreach my $student (sort 
 4206: 			 {
 4207: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4208: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4209: 			     }
 4210: 			     return $a cmp $b;
 4211: 			 } (keys(%$fullname))) {
 4212: 	my ($uname,$udom) = split(/:/,$student);
 4213: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4214:                                   : '</td>');
 4215: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4216: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4217: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4218: 	$studentTable.=
 4219: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4220:                          : '');
 4221: 	$ptr++;
 4222:     }
 4223:     if ($ptr%2 == 0) {
 4224: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4225: 	    &Apache::loncommon::end_data_table_row();
 4226:     }
 4227:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4228:     $studentTable.='<input type="button" '.
 4229: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4230: 
 4231:     $studentTable.=&show_grading_menu_form($symb);
 4232:     $request->print($studentTable);
 4233: 
 4234:     return '';
 4235: }
 4236: 
 4237: sub getSymbMap {
 4238:     my $navmap = Apache::lonnavmaps::navmap->new();
 4239: 
 4240:     my %symbx = ();
 4241:     my @titles = ();
 4242:     my $minder = 0;
 4243: 
 4244:     # Gather every sequence that has problems.
 4245:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4246: 					       1,0,1);
 4247:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4248: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4249: 	    my $title = $minder.'.'.
 4250: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4251: 	    push(@titles, $title); # minder in case two titles are identical
 4252: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4253: 	    $minder++;
 4254: 	}
 4255:     }
 4256:     return \@titles,\%symbx;
 4257: }
 4258: 
 4259: #
 4260: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4261: sub displayPage {
 4262:     my ($request) = shift;
 4263: 
 4264:     my ($symb) = &get_symb($request);
 4265:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4266:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4267:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4268:     my $pageTitle = $env{'form.page'};
 4269:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4270:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4271:     my $usec=$classlist->{$env{'form.student'}}[5];
 4272: 
 4273:     #need to make sure we have the correct data for later EXT calls, 
 4274:     #thus invalidate the cache
 4275:     &Apache::lonnet::devalidatecourseresdata(
 4276:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4277:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4278:     &Apache::lonnet::clear_EXT_cache_status();
 4279: 
 4280:     if (!&canview($usec)) {
 4281: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4282: 	$request->print(&show_grading_menu_form($symb));
 4283: 	return;
 4284:     }
 4285:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4286:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4287: 	'</h3>'."\n";
 4288:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4289:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4290: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4291:     } else {
 4292: 	delete($env{'form.CODE'});
 4293:     }
 4294:     &sub_page_js($request);
 4295:     $request->print($result);
 4296: 
 4297:     my $navmap = Apache::lonnavmaps::navmap->new();
 4298:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4299:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4300:     if (!$map) {
 4301: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4302: 	$request->print(&show_grading_menu_form($symb));
 4303: 	return; 
 4304:     }
 4305:     my $iterator = $navmap->getIterator($map->map_start(),
 4306: 					$map->map_finish());
 4307: 
 4308:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4309: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4310: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4311: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4312: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4313: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4314: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4315: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4316: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4317: 
 4318:     if (defined($env{'form.CODE'})) {
 4319: 	$studentTable.=
 4320: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4321:     }
 4322:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4323: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4324: 
 4325:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4326: 	&Apache::loncommon::start_data_table().
 4327: 	&Apache::loncommon::start_data_table_header_row().
 4328: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4329: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4330: 	&Apache::loncommon::end_data_table_header_row();
 4331: 
 4332:     &Apache::lonxml::clear_problem_counter();
 4333:     my ($depth,$question,$prob) = (1,1,1);
 4334:     $iterator->next(); # skip the first BEGIN_MAP
 4335:     my $curRes = $iterator->next(); # for "current resource"
 4336:     while ($depth > 0) {
 4337:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4338:         if($curRes == $iterator->END_MAP) { $depth--; }
 4339: 
 4340:         if (ref($curRes) && $curRes->is_problem()) {
 4341: 	    my $parts = $curRes->parts();
 4342:             my $title = $curRes->compTitle();
 4343: 	    my $symbx = $curRes->symb();
 4344: 	    $studentTable.=
 4345: 		&Apache::loncommon::start_data_table_row().
 4346: 		'<td align="center" valign="top" >'.$prob.
 4347: 		(scalar(@{$parts}) == 1 ? '' 
 4348: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4349: 							scalar(@{$parts}))
 4350: 		 ).
 4351: 		 '</td>';
 4352: 	    $studentTable.='<td valign="top">';
 4353: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4354: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4355: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4356: 					     undef,'both',\%form);
 4357: 	    } else {
 4358: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4359: 		$companswer =~ s|<form(.*?)>||g;
 4360: 		$companswer =~ s|</form>||g;
 4361: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4362: #		    $companswer =~ s/$1/ /ms;
 4363: #		    $request->print('match='.$1."<br />\n");
 4364: #		}
 4365: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4366: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4367: 	    }
 4368: 
 4369: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4370: 
 4371: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4372: 		if ($record{'version'} eq '') {
 4373: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4374: 		} else {
 4375: 		    my %responseType = ();
 4376: 		    foreach my $partid (@{$parts}) {
 4377: 			my @responseIds =$curRes->responseIds($partid);
 4378: 			my @responseType =$curRes->responseType($partid);
 4379: 			my %responseIds;
 4380: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4381: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4382: 			}
 4383: 			$responseType{$partid} = \%responseIds;
 4384: 		    }
 4385: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4386: 
 4387: 		}
 4388: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4389: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4390: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4391: 									$env{'request.course.id'},
 4392: 									'','.submission');
 4393:  
 4394: 	    }
 4395: 	    if (&canmodify($usec)) {
 4396: 		foreach my $partid (@{$parts}) {
 4397: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4398: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4399: 		    $question++;
 4400: 		}
 4401: 		$prob++;
 4402: 	    }
 4403: 	    $studentTable.='</td></tr>';
 4404: 
 4405: 	}
 4406:         $curRes = $iterator->next();
 4407:     }
 4408: 
 4409:     $studentTable.='</table>'."\n".
 4410: 	'<input type="button" value="'.&mt('Save').'" '.
 4411: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4412: 	'</form>'."\n";
 4413:     $studentTable.=&show_grading_menu_form($symb);
 4414:     $request->print($studentTable);
 4415: 
 4416:     return '';
 4417: }
 4418: 
 4419: sub displaySubByDates {
 4420:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4421:     my $isCODE=0;
 4422:     my $isTask = ($symb =~/\.task$/);
 4423:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4424:     my $studentTable=&Apache::loncommon::start_data_table().
 4425: 	&Apache::loncommon::start_data_table_header_row().
 4426: 	'<th>'.&mt('Date/Time').'</th>'.
 4427: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4428: 	'<th>'.&mt('Submission').'</th>'.
 4429: 	'<th>'.&mt('Status').'</th>'.
 4430: 	&Apache::loncommon::end_data_table_header_row();
 4431:     my ($version);
 4432:     my %mark;
 4433:     my %orders;
 4434:     $mark{'correct_by_student'} = $checkIcon;
 4435:     if (!exists($$record{'1:timestamp'})) {
 4436: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4437:     }
 4438: 
 4439:     my $interaction;
 4440:     my $no_increment = 1;
 4441:     for ($version=1;$version<=$$record{'version'};$version++) {
 4442: 	my $timestamp = 
 4443: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4444: 	if (exists($$record{$version.':resource.0.version'})) {
 4445: 	    $interaction = $$record{$version.':resource.0.version'};
 4446: 	}
 4447: 
 4448: 	my $where = ($isTask ? "$version:resource.$interaction"
 4449: 		             : "$version:resource");
 4450: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4451: 	    '<td>'.$timestamp.'</td>';
 4452: 	if ($isCODE) {
 4453: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4454: 	}
 4455: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4456: 	my @displaySub = ();
 4457: 	foreach my $partid (@{$parts}) {
 4458: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4459: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4460: 	    
 4461: 
 4462: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4463: 	    my $display_part=&get_display_part($partid,$symb);
 4464: 	    foreach my $matchKey (@matchKey) {
 4465: 		if (exists($$record{$version.':'.$matchKey}) &&
 4466: 		    $$record{$version.':'.$matchKey} ne '') {
 4467: 
 4468: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4469: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4470: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4471: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4472: 			$responseId.')</span>&nbsp;<b>';
 4473: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4474: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4475: 		    } else {
 4476: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4477: 					    $$record{"$where.$partid.tries"});
 4478: 		    }
 4479: 		    my $responseType=($isTask ? 'Task'
 4480:                                               : $responseType->{$partid}->{$responseId});
 4481: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4482: 		    if (!exists($orders{$partid}->{$responseId})) {
 4483: 			$orders{$partid}->{$responseId}=
 4484: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4485:                                        $no_increment);
 4486: 		    }
 4487: 		    $displaySub[0].='</b>&nbsp; '.
 4488: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4489: 		}
 4490: 	    }
 4491: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4492: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4493: 				    $$record{"$where.$partid.checkedin"},
 4494: 				    $$record{"$where.$partid.checkedin.slot"}).
 4495: 					'<br />';
 4496: 	    }
 4497: 	    if (exists $$record{"$where.$partid.award"}) {
 4498: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4499: 		    lc($$record{"$where.$partid.award"}).' '.
 4500: 		    $mark{$$record{"$where.$partid.solved"}}.
 4501: 		    '<br />';
 4502: 	    }
 4503: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4504: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4505: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4506: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4507: 		$displaySub[2].=
 4508: 		    $$record{"$version:resource.$partid.regrader"}.
 4509: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4510: 	    }
 4511: 	}
 4512: 	# needed because old essay regrader has not parts info
 4513: 	if (exists $$record{"$version:resource.regrader"}) {
 4514: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4515: 	}
 4516: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4517: 	if ($displaySub[2]) {
 4518: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4519: 	}
 4520: 	$studentTable.='&nbsp;</td>'.
 4521: 	    &Apache::loncommon::end_data_table_row();
 4522:     }
 4523:     $studentTable.=&Apache::loncommon::end_data_table();
 4524:     return $studentTable;
 4525: }
 4526: 
 4527: sub updateGradeByPage {
 4528:     my ($request) = shift;
 4529: 
 4530:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4531:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4532:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4533:     my $pageTitle = $env{'form.page'};
 4534:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4535:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4536:     my $usec=$classlist->{$env{'form.student'}}[5];
 4537:     if (!&canmodify($usec)) {
 4538: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4539: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4540: 	return;
 4541:     }
 4542:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4543:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4544: 	'</h3>'."\n";
 4545: 
 4546:     $request->print($result);
 4547: 
 4548:     my $navmap = Apache::lonnavmaps::navmap->new();
 4549:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4550:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4551:     if (!$map) {
 4552: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4553: 	my ($symb)=&get_symb($request);
 4554: 	$request->print(&show_grading_menu_form($symb));
 4555: 	return; 
 4556:     }
 4557:     my $iterator = $navmap->getIterator($map->map_start(),
 4558: 					$map->map_finish());
 4559: 
 4560:     my $studentTable=
 4561: 	&Apache::loncommon::start_data_table().
 4562: 	&Apache::loncommon::start_data_table_header_row().
 4563: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4564: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4565: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4566: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4567: 	&Apache::loncommon::end_data_table_header_row();
 4568: 
 4569:     $iterator->next(); # skip the first BEGIN_MAP
 4570:     my $curRes = $iterator->next(); # for "current resource"
 4571:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4572:     while ($depth > 0) {
 4573:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4574:         if($curRes == $iterator->END_MAP) { $depth--; }
 4575: 
 4576:         if (ref($curRes) && $curRes->is_problem()) {
 4577: 	    my $parts = $curRes->parts();
 4578:             my $title = $curRes->compTitle();
 4579: 	    my $symbx = $curRes->symb();
 4580: 	    $studentTable.=
 4581: 		&Apache::loncommon::start_data_table_row().
 4582: 		'<td align="center" valign="top" >'.$prob.
 4583: 		(scalar(@{$parts}) == 1 ? '' 
 4584:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4585: 		.')').'</td>';
 4586: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4587: 
 4588: 	    my %newrecord=();
 4589: 	    my @displayPts=();
 4590:             my %aggregate = ();
 4591:             my $aggregateflag = 0;
 4592: 	    foreach my $partid (@{$parts}) {
 4593: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4594: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4595: 
 4596: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4597: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4598: 		my $partial = $newpts/$wgt;
 4599: 		my $score;
 4600: 		if ($partial > 0) {
 4601: 		    $score = 'correct_by_override';
 4602: 		} elsif ($newpts ne '') { #empty is taken as 0
 4603: 		    $score = 'incorrect_by_override';
 4604: 		}
 4605: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4606: 		if ($dropMenu eq 'excused') {
 4607: 		    $partial = '';
 4608: 		    $score = 'excused';
 4609: 		} elsif ($dropMenu eq 'reset status'
 4610: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4611: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4612: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4613: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4614: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4615: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4616: 		    $changeflag++;
 4617: 		    $newpts = '';
 4618:                     
 4619:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4620:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4621:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4622:                     if ($aggtries > 0) {
 4623:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4624:                         $aggregateflag = 1;
 4625:                     }
 4626: 		}
 4627: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4628: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4629: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4630: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4631: 		    '&nbsp;<br />';
 4632: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4633: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4634: 		    '&nbsp;<br />';
 4635: 		$question++;
 4636: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4637: 
 4638: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4639: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4640: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4641: 		    if (scalar(keys(%newrecord)) > 0);
 4642: 
 4643: 		$changeflag++;
 4644: 	    }
 4645: 	    if (scalar(keys(%newrecord)) > 0) {
 4646: 		my %record = 
 4647: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4648: 					     $udom,$uname);
 4649: 
 4650: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4651: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4652: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4653: 		    $newrecord{'resource.CODE'} = '';
 4654: 		}
 4655: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4656: 					$udom,$uname);
 4657: 		%record = &Apache::lonnet::restore($symbx,
 4658: 						   $env{'request.course.id'},
 4659: 						   $udom,$uname);
 4660: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4661: 					     $cdom,$cnum,$udom,$uname);
 4662: 	    }
 4663: 	    
 4664:             if ($aggregateflag) {
 4665:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4666:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4667:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4668:             }
 4669: 
 4670: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4671: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4672: 		&Apache::loncommon::end_data_table_row();
 4673: 
 4674: 	    $prob++;
 4675: 	}
 4676:         $curRes = $iterator->next();
 4677:     }
 4678: 
 4679:     $studentTable.=&Apache::loncommon::end_data_table();
 4680:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4681:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4682: 		  &mt('The scores were changed for [quant,_1,problem].',
 4683: 		  $changeflag));
 4684:     $request->print($grademsg.$studentTable);
 4685: 
 4686:     return '';
 4687: }
 4688: 
 4689: #-------- end of section for handling grading by page/sequence ---------
 4690: #
 4691: #-------------------------------------------------------------------
 4692: 
 4693: #--------------------Scantron Grading-----------------------------------
 4694: #
 4695: #------ start of section for handling grading by page/sequence ---------
 4696: 
 4697: =pod
 4698: 
 4699: =head1 Bubble sheet grading routines
 4700: 
 4701:   For this documentation:
 4702: 
 4703:    'scanline' refers to the full line of characters
 4704:    from the file that we are parsing that represents one entire sheet
 4705: 
 4706:    'bubble line' refers to the data
 4707:    representing the line of bubbles that are on the physical bubble sheet
 4708: 
 4709: 
 4710: The overall process is that a scanned in bubble sheet data is uploaded
 4711: into a course. When a user wants to grade, they select a
 4712: sequence/folder of resources, a file of bubble sheet info, and pick
 4713: one of the predefined configurations for what each scanline looks
 4714: like.
 4715: 
 4716: Next each scanline is checked for any errors of either 'missing
 4717: bubbles' (it's an error because it may have been mis-scanned
 4718: because too light bubbling), 'double bubble' (each bubble line should
 4719: have no more that one letter picked), invalid or duplicated CODE,
 4720: invalid student/employee ID
 4721: 
 4722: If the CODE option is used that determines the randomization of the
 4723: homework problems, either way the student/employee ID is looked up into a
 4724: username:domain.
 4725: 
 4726: During the validation phase the instructor can choose to skip scanlines. 
 4727: 
 4728: After the validation phase, there are now 3 bubble sheet files
 4729: 
 4730:   scantron_original_filename (unmodified original file)
 4731:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4732:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4733: 
 4734: Also there is a separate hash nohist_scantrondata that contains extra
 4735: correction information that isn't representable in the bubble sheet
 4736: file (see &scantron_getfile() for more information)
 4737: 
 4738: After all scanlines are either valid, marked as valid or skipped, then
 4739: foreach line foreach problem in the picked sequence, an ssi request is
 4740: made that simulates a user submitting their selected letter(s) against
 4741: the homework problem.
 4742: 
 4743: =over 4
 4744: 
 4745: 
 4746: 
 4747: =item defaultFormData
 4748: 
 4749:   Returns html hidden inputs used to hold context/default values.
 4750: 
 4751:  Arguments:
 4752:   $symb - $symb of the current resource 
 4753: 
 4754: =cut
 4755: 
 4756: sub defaultFormData {
 4757:     my ($symb)=@_;
 4758:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4759:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4760:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4761: }
 4762: 
 4763: 
 4764: =pod 
 4765: 
 4766: =item getSequenceDropDown
 4767: 
 4768:    Return html dropdown of possible sequences to grade
 4769:  
 4770:  Arguments:
 4771:    $symb - $symb of the current resource 
 4772: 
 4773: =cut
 4774: 
 4775: sub getSequenceDropDown {
 4776:     my ($symb)=@_;
 4777:     my $result='<select name="selectpage">'."\n";
 4778:     my ($titles,$symbx) = &getSymbMap();
 4779:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4780:     my $ctr=0;
 4781:     foreach (@$titles) {
 4782: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4783: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4784: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4785: 	    '>'.$showtitle.'</option>'."\n";
 4786: 	$ctr++;
 4787:     }
 4788:     $result.= '</select>';
 4789:     return $result;
 4790: }
 4791: 
 4792: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4793:                                    # key is zero-based index - 0, 1, 2 ...
 4794: 
 4795: my %first_bubble_line;             # First bubble line no. for each bubble.
 4796: 
 4797: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4798:                                    # matchresponse or rankresponse, where 
 4799:                                    # an individual response can have multiple 
 4800:                                    # lines
 4801: 
 4802: my %responsetype_per_response;     # responsetype for each response
 4803: 
 4804: # Save and restore the bubble lines array to the form env.
 4805: 
 4806: 
 4807: sub save_bubble_lines {
 4808:     foreach my $line (keys(%bubble_lines_per_response)) {
 4809: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4810: 	$env{"form.scantron.first_bubble_line.$line"} =
 4811: 	    $first_bubble_line{$line};
 4812:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4813:             $subdivided_bubble_lines{$line};
 4814:         $env{"form.scantron.responsetype.$line"} =
 4815:             $responsetype_per_response{$line};
 4816:     }
 4817: }
 4818: 
 4819: 
 4820: sub restore_bubble_lines {
 4821:     my $line = 0;
 4822:     %bubble_lines_per_response = ();
 4823:     while ($env{"form.scantron.bubblelines.$line"}) {
 4824: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4825: 	$bubble_lines_per_response{$line} = $value;
 4826: 	$first_bubble_line{$line}  =
 4827: 	    $env{"form.scantron.first_bubble_line.$line"};
 4828:         $subdivided_bubble_lines{$line} =
 4829:             $env{"form.scantron.sub_bubblelines.$line"};
 4830:         $responsetype_per_response{$line} =
 4831:             $env{"form.scantron.responsetype.$line"};
 4832: 	$line++;
 4833:     }
 4834: }
 4835: 
 4836: #  Given the parsed scanline, get the response for 
 4837: #  'answer' number n:
 4838: 
 4839: sub get_response_bubbles {
 4840:     my ($parsed_line, $response)  = @_;
 4841: 
 4842:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4843:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4844:     
 4845:     my $selected = "";
 4846: 
 4847:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4848: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4849: 	$bubble_line++;
 4850:     }
 4851:     return $selected;
 4852: }
 4853: 
 4854: =pod 
 4855: 
 4856: =item scantron_filenames
 4857: 
 4858:    Returns a list of the scantron files in the current course 
 4859: 
 4860: =cut
 4861: 
 4862: sub scantron_filenames {
 4863:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4864:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4865:     my $getpropath = 1;
 4866:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4867:                                        $getpropath);
 4868:     my @possiblenames;
 4869:     foreach my $filename (sort(@files)) {
 4870: 	($filename)=split(/&/,$filename);
 4871: 	if ($filename!~/^scantron_orig_/) { next ; }
 4872: 	$filename=~s/^scantron_orig_//;
 4873: 	push(@possiblenames,$filename);
 4874:     }
 4875:     return @possiblenames;
 4876: }
 4877: 
 4878: =pod 
 4879: 
 4880: =item scantron_uploads
 4881: 
 4882:    Returns  html drop-down list of scantron files in current course.
 4883: 
 4884:  Arguments:
 4885:    $file2grade - filename to set as selected in the dropdown
 4886: 
 4887: =cut
 4888: 
 4889: sub scantron_uploads {
 4890:     my ($file2grade) = @_;
 4891:     my $result=	'<select name="scantron_selectfile">';
 4892:     $result.="<option></option>";
 4893:     foreach my $filename (sort(&scantron_filenames())) {
 4894: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4895:     }
 4896:     $result.="</select>";
 4897:     return $result;
 4898: }
 4899: 
 4900: =pod 
 4901: 
 4902: =item scantron_scantab
 4903: 
 4904:   Returns html drop down of the scantron formats in the scantronformat.tab
 4905:   file.
 4906: 
 4907: =cut
 4908: 
 4909: sub scantron_scantab {
 4910:     my $result='<select name="scantron_format">'."\n";
 4911:     $result.='<option></option>'."\n";
 4912:     my @lines = &get_scantronformat_file();
 4913:     if (@lines > 0) {
 4914:         foreach my $line (@lines) {
 4915:             next if (($line =~ /^\#/) || ($line eq ''));
 4916: 	    my ($name,$descrip)=split(/:/,$line);
 4917: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4918:         }
 4919:     }
 4920:     $result.='</select>'."\n";
 4921:     return $result;
 4922: }
 4923: 
 4924: =pod
 4925: 
 4926: =item get_scantronformat_file
 4927: 
 4928:   Returns an array containing lines from the scantron format file for
 4929:   the domain of the course.
 4930: 
 4931:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4932:   lines are from this file.
 4933: 
 4934:   Otherwise, if a default.tab has been published in RES space by the 
 4935:   domainconfig user, lines are from this file.
 4936: 
 4937:   Otherwise, fall back to getting lines from the legacy file on the
 4938:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4939: 
 4940: =cut
 4941: 
 4942: sub get_scantronformat_file {
 4943:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4944:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4945:     my $gottab = 0;
 4946:     my @lines;
 4947:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4948:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4949:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4950:             if ($formatfile ne '-1') {
 4951:                 @lines = split("\n",$formatfile,-1);
 4952:                 $gottab = 1;
 4953:             }
 4954:         }
 4955:     }
 4956:     if (!$gottab) {
 4957:         my $confname = $cdom.'-domainconfig';
 4958:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4959:         my $formatfile =  &Apache::lonnet::getfile($default);
 4960:         if ($formatfile ne '-1') {
 4961:             @lines = split("\n",$formatfile,-1);
 4962:             $gottab = 1;
 4963:         }
 4964:     }
 4965:     if (!$gottab) {
 4966:         my @domains = &Apache::lonnet::current_machine_domains();
 4967:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4968:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4969:             @lines = <$fh>;
 4970:             close($fh);
 4971:         } else {
 4972:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4973:             @lines = <$fh>;
 4974:             close($fh);
 4975:         }
 4976:     }
 4977:     return @lines;
 4978: }
 4979: 
 4980: =pod 
 4981: 
 4982: =item scantron_CODElist
 4983: 
 4984:   Returns html drop down of the saved CODE lists from current course,
 4985:   generated from earlier printings.
 4986: 
 4987: =cut
 4988: 
 4989: sub scantron_CODElist {
 4990:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4991:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4992:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4993:     my $namechoice='<option></option>';
 4994:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4995: 	if ($name =~ /^error: 2 /) { next; }
 4996: 	if ($name =~ /^type\0/) { next; }
 4997: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4998:     }
 4999:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5000:     return $namechoice;
 5001: }
 5002: 
 5003: =pod 
 5004: 
 5005: =item scantron_CODEunique
 5006: 
 5007:   Returns the html for "Each CODE to be used once" radio.
 5008: 
 5009: =cut
 5010: 
 5011: sub scantron_CODEunique {
 5012:     my $result='<span class="LC_nobreak">
 5013:                  <label><input type="radio" name="scantron_CODEunique"
 5014:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5015:                 </span>
 5016:                 <span class="LC_nobreak">
 5017:                  <label><input type="radio" name="scantron_CODEunique"
 5018:                         value="no" />'.&mt('No').' </label>
 5019:                 </span>';
 5020:     return $result;
 5021: }
 5022: 
 5023: =pod 
 5024: 
 5025: =item scantron_selectphase
 5026: 
 5027:   Generates the initial screen to start the bubble sheet process.
 5028:   Allows for - starting a grading run.
 5029:              - downloading existing scan data (original, corrected
 5030:                                                 or skipped info)
 5031: 
 5032:              - uploading new scan data
 5033: 
 5034:  Arguments:
 5035:   $r          - The Apache request object
 5036:   $file2grade - name of the file that contain the scanned data to score
 5037: 
 5038: =cut
 5039: 
 5040: sub scantron_selectphase {
 5041:     my ($r,$file2grade) = @_;
 5042:     my ($symb)=&get_symb($r);
 5043:     if (!$symb) {return '';}
 5044:     my $sequence_selector=&getSequenceDropDown($symb);
 5045:     my $default_form_data=&defaultFormData($symb);
 5046:     my $grading_menu_button=&show_grading_menu_form($symb);
 5047:     my $file_selector=&scantron_uploads($file2grade);
 5048:     my $format_selector=&scantron_scantab();
 5049:     my $CODE_selector=&scantron_CODElist();
 5050:     my $CODE_unique=&scantron_CODEunique();
 5051:     my $result;
 5052: 
 5053:     $ssi_error = 0;
 5054: 
 5055:     # Chunk of form to prompt for a file to grade and how:
 5056: 
 5057:     $result.= '
 5058:     <br />
 5059:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5060:     <input type="hidden" name="command" value="scantron_warning" />
 5061:     '.$default_form_data.'
 5062:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5063:        '.&Apache::loncommon::start_data_table_header_row().'
 5064:             <th colspan="2">
 5065:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5066:             </th>
 5067:        '.&Apache::loncommon::end_data_table_header_row().'
 5068:        '.&Apache::loncommon::start_data_table_row().'
 5069:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5070:        '.&Apache::loncommon::end_data_table_row().'
 5071:        '.&Apache::loncommon::start_data_table_row().'
 5072:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5073:        '.&Apache::loncommon::end_data_table_row().'
 5074:        '.&Apache::loncommon::start_data_table_row().'
 5075:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5076:        '.&Apache::loncommon::end_data_table_row().'
 5077:        '.&Apache::loncommon::start_data_table_row().'
 5078:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5079:        '.&Apache::loncommon::end_data_table_row().'
 5080:        '.&Apache::loncommon::start_data_table_row().'
 5081:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5082:        '.&Apache::loncommon::end_data_table_row().'
 5083:        '.&Apache::loncommon::start_data_table_row().'
 5084: 	    <td> '.&mt('Options:').' </td>
 5085:             <td>
 5086: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5087:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5088:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5089: 	    </td>
 5090:        '.&Apache::loncommon::end_data_table_row().'
 5091:        '.&Apache::loncommon::start_data_table_row().'
 5092:             <td colspan="2">
 5093:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5094:             </td>
 5095:        '.&Apache::loncommon::end_data_table_row().'
 5096:     '.&Apache::loncommon::end_data_table().'
 5097:     </form>
 5098: ';
 5099:    
 5100:     $r->print($result);
 5101: 
 5102:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5103:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5104: 
 5105: 	# Chunk of form to prompt for a scantron file upload.
 5106: 
 5107:         $r->print('
 5108:     <br />
 5109:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5110:        '.&Apache::loncommon::start_data_table_header_row().'
 5111:             <th>
 5112:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5113:             </th>
 5114:        '.&Apache::loncommon::end_data_table_header_row().'
 5115:        '.&Apache::loncommon::start_data_table_row().'
 5116:             <td>
 5117: ');
 5118:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5119:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5120:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5121:     $r->print('
 5122:               <script type="text/javascript" language="javascript">
 5123:     function checkUpload(formname) {
 5124: 	if (formname.upfile.value == "") {
 5125: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5126: 	    return false;
 5127: 	}
 5128: 	formname.submit();
 5129:     }
 5130:               </script>
 5131: 
 5132:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5133:                 '.$default_form_data.'
 5134:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5135:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5136:                 <input name="command" value="scantronupload_save" type="hidden" />
 5137:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5138:                 <br />
 5139:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5140:               </form>
 5141: ');
 5142: 
 5143:         $r->print('
 5144:             </td>
 5145:        '.&Apache::loncommon::end_data_table_row().'
 5146:        '.&Apache::loncommon::end_data_table().'
 5147: ');
 5148:     }
 5149: 
 5150:     # Chunk of the form that prompts to view a scoring office file,
 5151:     # corrected file, skipped records in a file.
 5152: 
 5153:     $r->print('
 5154:    <br />
 5155:    <form action="/adm/grades" name="scantron_download">
 5156:      '.$default_form_data.'
 5157:      <input type="hidden" name="command" value="scantron_download" />
 5158:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5159:        '.&Apache::loncommon::start_data_table_header_row().'
 5160:               <th>
 5161:                 &nbsp;'.&mt('Download a scoring office file').'
 5162:               </th>
 5163:        '.&Apache::loncommon::end_data_table_header_row().'
 5164:        '.&Apache::loncommon::start_data_table_row().'
 5165:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5166:                 <br />
 5167:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5168:        '.&Apache::loncommon::end_data_table_row().'
 5169:      '.&Apache::loncommon::end_data_table().'
 5170:    </form>
 5171:    <br />
 5172: ');
 5173: 
 5174:     &Apache::lonpickcode::code_list($r,2);
 5175: 
 5176:     $r->print('<br /><form method="post" name="checkscantron">'.
 5177:              $default_form_data."\n".
 5178:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5179:              &Apache::loncommon::start_data_table_header_row()."\n".
 5180:              '<th colspan="2">
 5181:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5182:              '</th>'."\n".
 5183:               &Apache::loncommon::end_data_table_header_row()."\n".
 5184:               &Apache::loncommon::start_data_table_row()."\n".
 5185:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5186:               '<td> '.$sequence_selector.' </td>'.
 5187:               &Apache::loncommon::end_data_table_row()."\n".
 5188:               &Apache::loncommon::start_data_table_row()."\n".
 5189:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5190:               '<td> '.$file_selector.' </td>'."\n".
 5191:               &Apache::loncommon::end_data_table_row()."\n".
 5192:               &Apache::loncommon::start_data_table_row()."\n".
 5193:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5194:               '<td> '.$format_selector.' </td>'."\n".
 5195:               &Apache::loncommon::end_data_table_row()."\n".
 5196:               &Apache::loncommon::start_data_table_row()."\n".
 5197:               '<td> '.&mt('Options').' </td>'."\n".
 5198:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5199:               &Apache::loncommon::end_data_table_row()."\n".
 5200:               &Apache::loncommon::start_data_table_row()."\n".
 5201:               '<td colspan="2">'."\n".
 5202:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5203:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5204:               '</td>'."\n".
 5205:               &Apache::loncommon::end_data_table_row()."\n".
 5206:               &Apache::loncommon::end_data_table()."\n".
 5207:               '</form><br />');
 5208:     $r->print($grading_menu_button);
 5209:     return;
 5210: }
 5211: 
 5212: =pod
 5213: 
 5214: =item get_scantron_config
 5215: 
 5216:    Parse and return the scantron configuration line selected as a
 5217:    hash of configuration file fields.
 5218: 
 5219:  Arguments:
 5220:     which - the name of the configuration to parse from the file.
 5221: 
 5222: 
 5223:  Returns:
 5224:             If the named configuration is not in the file, an empty
 5225:             hash is returned.
 5226:     a hash with the fields
 5227:       name         - internal name for the this configuration setup
 5228:       description  - text to display to operator that describes this config
 5229:       CODElocation - if 0 or the string 'none'
 5230:                           - no CODE exists for this config
 5231:                      if -1 || the string 'letter'
 5232:                           - a CODE exists for this config and is
 5233:                             a string of letters
 5234:                      Unsupported value (but planned for future support)
 5235:                           if a positive integer
 5236:                                - The CODE exists as the first n items from
 5237:                                  the question section of the form
 5238:                           if the string 'number'
 5239:                                - The CODE exists for this config and is
 5240:                                  a string of numbers
 5241:       CODEstart   - (only matter if a CODE exists) column in the line where
 5242:                      the CODE starts
 5243:       CODElength  - length of the CODE
 5244:       IDstart     - column where the student/employee ID number starts
 5245:       IDlength    - length of the student/employee ID info
 5246:       Qstart      - column where the information from the bubbled
 5247:                     'questions' start
 5248:       Qlength     - number of columns comprising a single bubble line from
 5249:                     the sheet. (usually either 1 or 10)
 5250:       Qon         - either a single character representing the character used
 5251:                     to signal a bubble was chosen in the positional setup, or
 5252:                     the string 'letter' if the letter of the chosen bubble is
 5253:                     in the final, or 'number' if a number representing the
 5254:                     chosen bubble is in the file (1->A 0->J)
 5255:       Qoff        - the character used to represent that a bubble was
 5256:                     left blank
 5257:       PaperID     - if the scanning process generates a unique number for each
 5258:                     sheet scanned the column that this ID number starts in
 5259:       PaperIDlength - number of columns that comprise the unique ID number
 5260:                       for the sheet of paper
 5261:       FirstName   - column that the first name starts in
 5262:       FirstNameLength - number of columns that the first name spans
 5263:  
 5264:       LastName    - column that the last name starts in
 5265:       LastNameLength - number of columns that the last name spans
 5266: 
 5267: =cut
 5268: 
 5269: sub get_scantron_config {
 5270:     my ($which) = @_;
 5271:     my @lines = &get_scantronformat_file();
 5272:     my %config;
 5273:     #FIXME probably should move to XML it has already gotten a bit much now
 5274:     foreach my $line (@lines) {
 5275: 	my ($name,$descrip)=split(/:/,$line);
 5276: 	if ($name ne $which ) { next; }
 5277: 	chomp($line);
 5278: 	my @config=split(/:/,$line);
 5279: 	$config{'name'}=$config[0];
 5280: 	$config{'description'}=$config[1];
 5281: 	$config{'CODElocation'}=$config[2];
 5282: 	$config{'CODEstart'}=$config[3];
 5283: 	$config{'CODElength'}=$config[4];
 5284: 	$config{'IDstart'}=$config[5];
 5285: 	$config{'IDlength'}=$config[6];
 5286: 	$config{'Qstart'}=$config[7];
 5287:  	$config{'Qlength'}=$config[8];
 5288: 	$config{'Qoff'}=$config[9];
 5289: 	$config{'Qon'}=$config[10];
 5290: 	$config{'PaperID'}=$config[11];
 5291: 	$config{'PaperIDlength'}=$config[12];
 5292: 	$config{'FirstName'}=$config[13];
 5293: 	$config{'FirstNamelength'}=$config[14];
 5294: 	$config{'LastName'}=$config[15];
 5295: 	$config{'LastNamelength'}=$config[16];
 5296: 	last;
 5297:     }
 5298:     return %config;
 5299: }
 5300: 
 5301: =pod 
 5302: 
 5303: =item username_to_idmap
 5304: 
 5305:     creates a hash keyed by student/employee ID with values of the corresponding
 5306:     student username:domain.
 5307: 
 5308:   Arguments:
 5309: 
 5310:     $classlist - reference to the class list hash. This is a hash
 5311:                  keyed by student name:domain  whose elements are references
 5312:                  to arrays containing various chunks of information
 5313:                  about the student. (See loncoursedata for more info).
 5314: 
 5315:   Returns
 5316:     %idmap - the constructed hash
 5317: 
 5318: =cut
 5319: 
 5320: sub username_to_idmap {
 5321:     my ($classlist)= @_;
 5322:     my %idmap;
 5323:     foreach my $student (keys(%$classlist)) {
 5324: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5325: 	    $student;
 5326:     }
 5327:     return %idmap;
 5328: }
 5329: 
 5330: =pod
 5331: 
 5332: =item scantron_fixup_scanline
 5333: 
 5334:    Process a requested correction to a scanline.
 5335: 
 5336:   Arguments:
 5337:     $scantron_config   - hash from &get_scantron_config()
 5338:     $scan_data         - hash of correction information 
 5339:                           (see &scantron_getfile())
 5340:     $line              - existing scanline
 5341:     $whichline         - line number of the passed in scanline
 5342:     $field             - type of change to process 
 5343:                          (either 
 5344:                           'ID'     -> correct the student/employee ID number
 5345:                           'CODE'   -> correct the CODE
 5346:                           'answer' -> fixup the submitted answers)
 5347:     
 5348:    $args               - hash of additional info,
 5349:                           - 'ID' 
 5350:                                'newid' -> studentID to use in replacement
 5351:                                           of existing one
 5352:                           - 'CODE' 
 5353:                                'CODE_ignore_dup' - set to true if duplicates
 5354:                                                    should be ignored.
 5355: 	                       'CODE' - is new code or 'use_unfound'
 5356:                                         if the existing unfound code should
 5357:                                         be used as is
 5358:                           - 'answer'
 5359:                                'response' - new answer or 'none' if blank
 5360:                                'question' - the bubble line to change
 5361:                                'questionnum' - the question identifier,
 5362:                                                may include subquestion. 
 5363: 
 5364:   Returns:
 5365:     $line - the modified scanline
 5366: 
 5367:   Side effects: 
 5368:     $scan_data - may be updated
 5369: 
 5370: =cut
 5371: 
 5372: 
 5373: sub scantron_fixup_scanline {
 5374:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5375:     if ($field eq 'ID') {
 5376: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5377: 	    return ($line,1,'New value too large');
 5378: 	}
 5379: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5380: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5381: 				     $args->{'newid'});
 5382: 	}
 5383: 	substr($line,$$scantron_config{'IDstart'}-1,
 5384: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5385: 	if ($args->{'newid'}=~/^\s*$/) {
 5386: 	    &scan_data($scan_data,"$whichline.user",
 5387: 		       $args->{'username'}.':'.$args->{'domain'});
 5388: 	}
 5389:     } elsif ($field eq 'CODE') {
 5390: 	if ($args->{'CODE_ignore_dup'}) {
 5391: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5392: 	}
 5393: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5394: 	if ($args->{'CODE'} ne 'use_unfound') {
 5395: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5396: 		return ($line,1,'New CODE value too large');
 5397: 	    }
 5398: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5399: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5400: 	    }
 5401: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5402: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5403: 	}
 5404:     } elsif ($field eq 'answer') {
 5405: 	my $length=$scantron_config->{'Qlength'};
 5406: 	my $off=$scantron_config->{'Qoff'};
 5407: 	my $on=$scantron_config->{'Qon'};
 5408: 	my $answer=${off}x$length;
 5409: 	if ($args->{'response'} eq 'none') {
 5410: 	    &scan_data($scan_data,
 5411: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5412: 	} else {
 5413: 	    if ($on eq 'letter') {
 5414: 		my @alphabet=('A'..'Z');
 5415: 		$answer=$alphabet[$args->{'response'}];
 5416: 	    } elsif ($on eq 'number') {
 5417: 		$answer=$args->{'response'}+1;
 5418: 		if ($answer == 10) { $answer = '0'; }
 5419: 	    } else {
 5420: 		substr($answer,$args->{'response'},1)=$on;
 5421: 	    }
 5422: 	    &scan_data($scan_data,
 5423: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5424: 	}
 5425: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5426: 	substr($line,$where-1,$length)=$answer;
 5427:     }
 5428:     return $line;
 5429: }
 5430: 
 5431: =pod
 5432: 
 5433: =item scan_data
 5434: 
 5435:     Edit or look up  an item in the scan_data hash.
 5436: 
 5437:   Arguments:
 5438:     $scan_data  - The hash (see scantron_getfile)
 5439:     $key        - shorthand of the key to edit (actual key is
 5440:                   scantronfilename_key).
 5441:     $data        - New value of the hash entry.
 5442:     $delete      - If true, the entry is removed from the hash.
 5443: 
 5444:   Returns:
 5445:     The new value of the hash table field (undefined if deleted).
 5446: 
 5447: =cut
 5448: 
 5449: 
 5450: sub scan_data {
 5451:     my ($scan_data,$key,$value,$delete)=@_;
 5452:     my $filename=$env{'form.scantron_selectfile'};
 5453:     if (defined($value)) {
 5454: 	$scan_data->{$filename.'_'.$key} = $value;
 5455:     }
 5456:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5457:     return $scan_data->{$filename.'_'.$key};
 5458: }
 5459: 
 5460: # ----- These first few routines are general use routines.----
 5461: 
 5462: # Return the number of occurences of a pattern in a string.
 5463: 
 5464: sub occurence_count {
 5465:     my ($string, $pattern) = @_;
 5466: 
 5467:     my @matches = ($string =~ /$pattern/g);
 5468: 
 5469:     return scalar(@matches);
 5470: }
 5471: 
 5472: 
 5473: # Take a string known to have digits and convert all the
 5474: # digits into letters in the range J,A..I.
 5475: 
 5476: sub digits_to_letters {
 5477:     my ($input) = @_;
 5478: 
 5479:     my @alphabet = ('J', 'A'..'I');
 5480: 
 5481:     my @input    = split(//, $input);
 5482:     my $output ='';
 5483:     for (my $i = 0; $i < scalar(@input); $i++) {
 5484: 	if ($input[$i] =~ /\d/) {
 5485: 	    $output .= $alphabet[$input[$i]];
 5486: 	} else {
 5487: 	    $output .= $input[$i];
 5488: 	}
 5489:     }
 5490:     return $output;
 5491: }
 5492: 
 5493: =pod 
 5494: 
 5495: =item scantron_parse_scanline
 5496: 
 5497:   Decodes a scanline from the selected scantron file
 5498: 
 5499:  Arguments:
 5500:     line             - The text of the scantron file line to process
 5501:     whichline        - Line number
 5502:     scantron_config  - Hash describing the format of the scantron lines.
 5503:     scan_data        - Hash of extra information about the scanline
 5504:                        (see scantron_getfile for more information)
 5505:     just_header      - True if should not process question answers but only
 5506:                        the stuff to the left of the answers.
 5507:  Returns:
 5508:    Hash containing the result of parsing the scanline
 5509: 
 5510:    Keys are all proceeded by the string 'scantron.'
 5511: 
 5512:        CODE    - the CODE in use for this scanline
 5513:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5514:                  by the operator
 5515:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5516:                             CODEs were selected, but the usage has been
 5517:                             forced by the operator
 5518:        ID  - student/employee ID
 5519:        PaperID - if used, the ID number printed on the sheet when the 
 5520:                  paper was scanned
 5521:        FirstName - first name from the sheet
 5522:        LastName  - last name from the sheet
 5523: 
 5524:      if just_header was not true these key may also exist
 5525: 
 5526:        missingerror - a list of bubble ranges that are considered to be answers
 5527:                       to a single question that don't have any bubbles filled in.
 5528:                       Of the form questionnumber:firstbubblenumber:count.
 5529:        doubleerror  - a list of bubble ranges that are considered to be answers
 5530:                       to a single question that have more than one bubble filled in.
 5531:                       Of the form questionnumber::firstbubblenumber:count
 5532:    
 5533:                 In the above, count is the number of bubble responses in the
 5534:                 input line needed to represent the possible answers to the question.
 5535:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5536:                 per line would have count = 2.
 5537: 
 5538:        maxquest     - the number of the last bubble line that was parsed
 5539: 
 5540:        (<number> starts at 1)
 5541:        <number>.answer - zero or more letters representing the selected
 5542:                          letters from the scanline for the bubble line 
 5543:                          <number>.
 5544:                          if blank there was either no bubble or there where
 5545:                          multiple bubbles, (consult the keys missingerror and
 5546:                          doubleerror if this is an error condition)
 5547: 
 5548: =cut
 5549: 
 5550: sub scantron_parse_scanline {
 5551:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5552: 
 5553:     my %record;
 5554:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5555:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5556:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5557:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5558: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5559: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5560: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5561: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5562: 	    $record{'scantron.CODE'}=substr($data,
 5563: 					    $$scantron_config{'CODEstart'}-1,
 5564: 					    $$scantron_config{'CODElength'});
 5565: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5566: 		$record{'scantron.useCODE'}=1;
 5567: 	    }
 5568: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5569: 		$record{'scantron.CODE_ignore_dup'}=1;
 5570: 	    }
 5571: 	} else {
 5572: 	    #FIXME interpret first N questions
 5573: 	}
 5574:     }
 5575:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5576: 				  $$scantron_config{'IDlength'});
 5577:     $record{'scantron.PaperID'}=
 5578: 	substr($data,$$scantron_config{'PaperID'}-1,
 5579: 	       $$scantron_config{'PaperIDlength'});
 5580:     $record{'scantron.FirstName'}=
 5581: 	substr($data,$$scantron_config{'FirstName'}-1,
 5582: 	       $$scantron_config{'FirstNamelength'});
 5583:     $record{'scantron.LastName'}=
 5584: 	substr($data,$$scantron_config{'LastName'}-1,
 5585: 	       $$scantron_config{'LastNamelength'});
 5586:     if ($just_header) { return \%record; }
 5587: 
 5588:     my @alphabet=('A'..'Z');
 5589:     my $questnum=0;
 5590:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5591: 
 5592:     chomp($questions);		# Get rid of any trailing \n.
 5593:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5594:     while (length($questions)) {
 5595: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5596:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5597:                              || 1;
 5598:         $questnum++;
 5599:         my $quest_id = $questnum;
 5600:         my $currentquest = substr($questions,0,$answer_length);
 5601:         $questions       = substr($questions,$answer_length);
 5602:         if (length($currentquest) < $answer_length) { next; }
 5603: 
 5604:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5605:             my $subquestnum = 1;
 5606:             my $subquestions = $currentquest;
 5607:             my @subanswers_needed = 
 5608:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5609:             foreach my $subans (@subanswers_needed) {
 5610:                 my $subans_length =
 5611:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5612:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5613:                 $subquestions   = substr($subquestions,$subans_length);
 5614:                 $quest_id = "$questnum.$subquestnum";
 5615:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5616:                     ($$scantron_config{'Qon'} eq 'number')) {
 5617:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5618:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5619:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5620:                 } else {
 5621:                     $ansnum = &scantron_validator_positional($ansnum,
 5622:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5623:                 }
 5624:                 $subquestnum ++;
 5625:             }
 5626:         } else {
 5627:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5628:                 ($$scantron_config{'Qon'} eq 'number')) {
 5629:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5630:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5631:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5632:             } else {
 5633:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5634:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5635:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5636:             }
 5637:         }
 5638:     }
 5639:     $record{'scantron.maxquest'}=$questnum;
 5640:     return \%record;
 5641: }
 5642: 
 5643: sub scantron_validator_lettnum {
 5644:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5645:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5646: 
 5647:     # Qon 'letter' implies for each slot in currquest we have:
 5648:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5649:     #    about anything else (esp. a value of Qoff) for missing
 5650:     #    bubbles.
 5651:     #
 5652:     # Qon 'number' implies each slot gives a digit that indexes the
 5653:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5654:     #    and * or ? for double bubbles on a single line.
 5655:     #
 5656: 
 5657:     my $matchon;
 5658:     if ($$scantron_config{'Qon'} eq 'letter') {
 5659:         $matchon = '[A-Z]';
 5660:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5661:         $matchon = '\d';
 5662:     }
 5663:     my $occurrences = 0;
 5664:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5665:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5666:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5667:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5668:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5669:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5670:         my @singlelines = split('',$currquest);
 5671:         foreach my $entry (@singlelines) {
 5672:             $occurrences = &occurence_count($entry,$matchon);
 5673:             if ($occurrences > 1) {
 5674:                 last;
 5675:             }
 5676:         } 
 5677:     } else {
 5678:         $occurrences = &occurence_count($currquest,$matchon); 
 5679:     }
 5680:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5681:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5682:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5683:             my $bubble = substr($currquest,$ans,1);
 5684:             if ($bubble =~ /$matchon/ ) {
 5685:                 if ($$scantron_config{'Qon'} eq 'number') {
 5686:                     if ($bubble == 0) {
 5687:                         $bubble = 10; 
 5688:                     }
 5689:                     $record->{"scantron.$ansnum.answer"} = 
 5690:                         $alphabet->[$bubble-1];
 5691:                 } else {
 5692:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5693:                 }
 5694:             } else {
 5695:                 $record->{"scantron.$ansnum.answer"}='';
 5696:             }
 5697:             $ansnum++;
 5698:         }
 5699:     } elsif (!defined($currquest)
 5700:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5701:             || (&occurence_count($currquest,$matchon) == 0)) {
 5702:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5703:             $record->{"scantron.$ansnum.answer"}='';
 5704:             $ansnum++;
 5705:         }
 5706:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5707:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5708:         }
 5709:     } else {
 5710:         if ($$scantron_config{'Qon'} eq 'number') {
 5711:             $currquest = &digits_to_letters($currquest);            
 5712:         }
 5713:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5714:             my $bubble = substr($currquest,$ans,1);
 5715:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5716:             $ansnum++;
 5717:         }
 5718:     }
 5719:     return $ansnum;
 5720: }
 5721: 
 5722: sub scantron_validator_positional {
 5723:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5724:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5725: 
 5726:     # Otherwise there's a positional notation;
 5727:     # each bubble line requires Qlength items, and there are filled in
 5728:     # bubbles for each case where there 'Qon' characters.
 5729:     #
 5730: 
 5731:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5732: 
 5733:     # If the split only gives us one element.. the full length of the
 5734:     # answer string, no bubbles are filled in:
 5735: 
 5736:     if ($answers_needed eq '') {
 5737:         return;
 5738:     }
 5739: 
 5740:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5741:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5742:             $record->{"scantron.$ansnum.answer"}='';
 5743:             $ansnum++;
 5744:         }
 5745:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5746:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5747:         }
 5748:     } elsif (scalar(@array) == 2) {
 5749:         my $location = length($array[0]);
 5750:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5751:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5752:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5753:             if ($ans eq $line_num) {
 5754:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5755:             } else {
 5756:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5757:             }
 5758:             $ansnum++;
 5759:          }
 5760:     } else {
 5761:         #  If there's more than one instance of a bubble character
 5762:         #  That's a double bubble; with positional notation we can
 5763:         #  record all the bubbles filled in as well as the
 5764:         #  fact this response consists of multiple bubbles.
 5765:         #
 5766:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5767:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5768:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5769:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5770:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5771:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5772:             my $doubleerror = 0;
 5773:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5774:                    (!$doubleerror)) {
 5775:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5776:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5777:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5778:                if (length(@currarray) > 2) {
 5779:                    $doubleerror = 1;
 5780:                } 
 5781:             }
 5782:             if ($doubleerror) {
 5783:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5784:             }
 5785:         } else {
 5786:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5787:         }
 5788:         my $item = $ansnum;
 5789:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5790:             $record->{"scantron.$item.answer"} = '';
 5791:             $item ++;
 5792:         }
 5793: 
 5794:         my @ans=@array;
 5795:         my $i=0;
 5796:         my $increment = 0;
 5797:         while ($#ans) {
 5798:             $i+=length($ans[0]) + $increment;
 5799:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5800:             my $bubble = $i%$$scantron_config{'Qlength'};
 5801:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5802:             shift(@ans);
 5803:             $increment = 1;
 5804:         }
 5805:         $ansnum += $answers_needed;
 5806:     }
 5807:     return $ansnum;
 5808: }
 5809: 
 5810: =pod
 5811: 
 5812: =item scantron_add_delay
 5813: 
 5814:    Adds an error message that occurred during the grading phase to a
 5815:    queue of messages to be shown after grading pass is complete
 5816: 
 5817:  Arguments:
 5818:    $delayqueue  - arrary ref of hash ref of error messages
 5819:    $scanline    - the scanline that caused the error
 5820:    $errormesage - the error message
 5821:    $errorcode   - a numeric code for the error
 5822: 
 5823:  Side Effects:
 5824:    updates the $delayqueue to have a new hash ref of the error
 5825: 
 5826: =cut
 5827: 
 5828: sub scantron_add_delay {
 5829:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5830:     push(@$delayqueue,
 5831: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5832: 	  'ecode' => $errorcode }
 5833: 	 );
 5834: }
 5835: 
 5836: =pod
 5837: 
 5838: =item scantron_find_student
 5839: 
 5840:    Finds the username for the current scanline
 5841: 
 5842:   Arguments:
 5843:    $scantron_record - hash result from scantron_parse_scanline
 5844:    $scan_data       - hash of correction information 
 5845:                       (see &scantron_getfile() form more information)
 5846:    $idmap           - hash from &username_to_idmap()
 5847:    $line            - number of current scanline
 5848:  
 5849:   Returns:
 5850:    Either 'username:domain' or undef if unknown
 5851: 
 5852: =cut
 5853: 
 5854: sub scantron_find_student {
 5855:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5856:     my $scanID=$$scantron_record{'scantron.ID'};
 5857:     if ($scanID =~ /^\s*$/) {
 5858:  	return &scan_data($scan_data,"$line.user");
 5859:     }
 5860:     foreach my $id (keys(%$idmap)) {
 5861:  	if (lc($id) eq lc($scanID)) {
 5862:  	    return $$idmap{$id};
 5863:  	}
 5864:     }
 5865:     return undef;
 5866: }
 5867: 
 5868: =pod
 5869: 
 5870: =item scantron_filter
 5871: 
 5872:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5873:    hidden resources was selected
 5874: 
 5875: =cut
 5876: 
 5877: sub scantron_filter {
 5878:     my ($curres)=@_;
 5879: 
 5880:     if (ref($curres) && $curres->is_problem()) {
 5881: 	# if the user has asked to not have either hidden
 5882: 	# or 'randomout' controlled resources to be graded
 5883: 	# don't include them
 5884: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5885: 	    && $curres->randomout) {
 5886: 	    return 0;
 5887: 	}
 5888: 	return 1;
 5889:     }
 5890:     return 0;
 5891: }
 5892: 
 5893: =pod
 5894: 
 5895: =item scantron_process_corrections
 5896: 
 5897:    Gets correction information out of submitted form data and corrects
 5898:    the scanline
 5899: 
 5900: =cut
 5901: 
 5902: sub scantron_process_corrections {
 5903:     my ($r) = @_;
 5904:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5905:     my ($scanlines,$scan_data)=&scantron_getfile();
 5906:     my $classlist=&Apache::loncoursedata::get_classlist();
 5907:     my $which=$env{'form.scantron_line'};
 5908:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5909:     my ($skip,$err,$errmsg);
 5910:     if ($env{'form.scantron_skip_record'}) {
 5911: 	$skip=1;
 5912:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5913: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5914: 	    $env{'form.scantron_domain'};
 5915: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5916: 	($line,$err,$errmsg)=
 5917: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5918: 				     'ID',{'newid'=>$newid,
 5919: 				    'username'=>$env{'form.scantron_username'},
 5920: 				    'domain'=>$env{'form.scantron_domain'}});
 5921:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5922: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5923: 	my $newCODE;
 5924: 	my %args;
 5925: 	if      ($resolution eq 'use_unfound') {
 5926: 	    $newCODE='use_unfound';
 5927: 	} elsif ($resolution eq 'use_found') {
 5928: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5929: 	} elsif ($resolution eq 'use_typed') {
 5930: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5931: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5932: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5933: 	}
 5934: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5935: 	    $args{'CODE_ignore_dup'}=1;
 5936: 	}
 5937: 	$args{'CODE'}=$newCODE;
 5938: 	($line,$err,$errmsg)=
 5939: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5940: 				     'CODE',\%args);
 5941:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5942: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5943: 	    ($line,$err,$errmsg)=
 5944: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5945: 					 $which,'answer',
 5946: 					 { 'question'=>$question,
 5947: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5948:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5949: 	    if ($err) { last; }
 5950: 	}
 5951:     }
 5952:     if ($err) {
 5953: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5954:     } else {
 5955: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5956: 	&scantron_putfile($scanlines,$scan_data);
 5957:     }
 5958: }
 5959: 
 5960: =pod
 5961: 
 5962: =item reset_skipping_status
 5963: 
 5964:    Forgets the current set of remember skipped scanlines (and thus
 5965:    reverts back to considering all lines in the
 5966:    scantron_skipped_<filename> file)
 5967: 
 5968: =cut
 5969: 
 5970: sub reset_skipping_status {
 5971:     my ($scanlines,$scan_data)=&scantron_getfile();
 5972:     &scan_data($scan_data,'remember_skipping',undef,1);
 5973:     &scantron_putfile(undef,$scan_data);
 5974: }
 5975: 
 5976: =pod
 5977: 
 5978: =item start_skipping
 5979: 
 5980:    Marks a scanline to be skipped. 
 5981: 
 5982: =cut
 5983: 
 5984: sub start_skipping {
 5985:     my ($scan_data,$i)=@_;
 5986:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5987:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5988: 	$remembered{$i}=2;
 5989:     } else {
 5990: 	$remembered{$i}=1;
 5991:     }
 5992:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5993: }
 5994: 
 5995: =pod
 5996: 
 5997: =item should_be_skipped
 5998: 
 5999:    Checks whether a scanline should be skipped.
 6000: 
 6001: =cut
 6002: 
 6003: sub should_be_skipped {
 6004:     my ($scanlines,$scan_data,$i)=@_;
 6005:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6006: 	# not redoing old skips
 6007: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6008: 	return 0;
 6009:     }
 6010:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6011: 
 6012:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6013: 	return 0;
 6014:     }
 6015:     return 1;
 6016: }
 6017: 
 6018: =pod
 6019: 
 6020: =item remember_current_skipped
 6021: 
 6022:    Discovers what scanlines are in the scantron_skipped_<filename>
 6023:    file and remembers them into scan_data for later use.
 6024: 
 6025: =cut
 6026: 
 6027: sub remember_current_skipped {
 6028:     my ($scanlines,$scan_data)=&scantron_getfile();
 6029:     my %to_remember;
 6030:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6031: 	if ($scanlines->{'skipped'}[$i]) {
 6032: 	    $to_remember{$i}=1;
 6033: 	}
 6034:     }
 6035: 
 6036:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6037:     &scantron_putfile(undef,$scan_data);
 6038: }
 6039: 
 6040: =pod
 6041: 
 6042: =item check_for_error
 6043: 
 6044:     Checks if there was an error when attempting to remove a specific
 6045:     scantron_.. bubble sheet data file. Prints out an error if
 6046:     something went wrong.
 6047: 
 6048: =cut
 6049: 
 6050: sub check_for_error {
 6051:     my ($r,$result)=@_;
 6052:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6053: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6054:     }
 6055: }
 6056: 
 6057: =pod
 6058: 
 6059: =item scantron_warning_screen
 6060: 
 6061:    Interstitial screen to make sure the operator has selected the
 6062:    correct options before we start the validation phase.
 6063: 
 6064: =cut
 6065: 
 6066: sub scantron_warning_screen {
 6067:     my ($button_text)=@_;
 6068:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6069:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6070:     my $CODElist;
 6071:     if ($scantron_config{'CODElocation'} &&
 6072: 	$scantron_config{'CODEstart'} &&
 6073: 	$scantron_config{'CODElength'}) {
 6074: 	$CODElist=$env{'form.scantron_CODElist'};
 6075: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6076: 	$CODElist=
 6077: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6078: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6079:     }
 6080:     return ('
 6081: <p>
 6082: <span class="LC_warning">
 6083: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6084: </p>
 6085: <table>
 6086: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6087: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6088: '.$CODElist.'
 6089: </table>
 6090: <br />
 6091: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6092: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6093: 
 6094: <br />
 6095: ');
 6096: }
 6097: 
 6098: =pod
 6099: 
 6100: =item scantron_do_warning
 6101: 
 6102:    Check if the operator has picked something for all required
 6103:    fields. Error out if something is missing.
 6104: 
 6105: =cut
 6106: 
 6107: sub scantron_do_warning {
 6108:     my ($r)=@_;
 6109:     my ($symb)=&get_symb($r);
 6110:     if (!$symb) {return '';}
 6111:     my $default_form_data=&defaultFormData($symb);
 6112:     $r->print(&scantron_form_start().$default_form_data);
 6113:     if ( $env{'form.selectpage'} eq '' ||
 6114: 	 $env{'form.scantron_selectfile'} eq '' ||
 6115: 	 $env{'form.scantron_format'} eq '' ) {
 6116: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6117: 	if ( $env{'form.selectpage'} eq '') {
 6118: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6119: 	} 
 6120: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6121: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6122: 	} 
 6123: 	if ( $env{'form.scantron_format'} eq '') {
 6124: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6125: 	} 
 6126:     } else {
 6127: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6128: 	$r->print('
 6129: '.$warning.'
 6130: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6131: <input type="hidden" name="command" value="scantron_validate" />
 6132: ');
 6133:     }
 6134:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6135:     return '';
 6136: }
 6137: 
 6138: =pod
 6139: 
 6140: =item scantron_form_start
 6141: 
 6142:     html hidden input for remembering all selected grading options
 6143: 
 6144: =cut
 6145: 
 6146: sub scantron_form_start {
 6147:     my ($max_bubble)=@_;
 6148:     my $result= <<SCANTRONFORM;
 6149: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6150:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6151:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6152:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6153:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6154:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6155:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6156:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6157:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6158:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6159: SCANTRONFORM
 6160: 
 6161:   my $line = 0;
 6162:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6163:        my $chunk =
 6164: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6165:        $chunk .=
 6166: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6167:        $chunk .= 
 6168:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6169:        $chunk .=
 6170:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6171:        $result .= $chunk;
 6172:        $line++;
 6173:    }
 6174:     return $result;
 6175: }
 6176: 
 6177: =pod
 6178: 
 6179: =item scantron_validate_file
 6180: 
 6181:     Dispatch routine for doing validation of a bubble sheet data file.
 6182: 
 6183:     Also processes any necessary information resets that need to
 6184:     occur before validation begins (ignore previous corrections,
 6185:     restarting the skipped records processing)
 6186: 
 6187: =cut
 6188: 
 6189: sub scantron_validate_file {
 6190:     my ($r) = @_;
 6191:     my ($symb)=&get_symb($r);
 6192:     if (!$symb) {return '';}
 6193:     my $default_form_data=&defaultFormData($symb);
 6194:     
 6195:     # do the detection of only doing skipped records first befroe we delete
 6196:     # them when doing the corrections reset
 6197:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6198: 	&reset_skipping_status();
 6199:     }
 6200:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6201: 	&remember_current_skipped();
 6202: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6203:     }
 6204: 
 6205:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6206: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6207: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6208: 	&check_for_error($r,&scantron_remove_scan_data());
 6209: 	$env{'form.scantron_options_ignore'}='done';
 6210:     }
 6211: 
 6212:     if ($env{'form.scantron_corrections'}) {
 6213: 	&scantron_process_corrections($r);
 6214:     }
 6215:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6216:     #get the student pick code ready
 6217:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6218:     my $max_bubble=&scantron_get_maxbubble();
 6219:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6220:     $r->print($result);
 6221:     
 6222:     my @validate_phases=( 'sequence',
 6223: 			  'ID',
 6224: 			  'CODE',
 6225: 			  'doublebubble',
 6226: 			  'missingbubbles');
 6227:     if (!$env{'form.validatepass'}) {
 6228: 	$env{'form.validatepass'} = 0;
 6229:     }
 6230:     my $currentphase=$env{'form.validatepass'};
 6231: 
 6232: 
 6233:     my $stop=0;
 6234:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6235: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6236: 	$r->rflush();
 6237: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6238: 	{
 6239: 	    no strict 'refs';
 6240: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6241: 	}
 6242:     }
 6243:     if (!$stop) {
 6244: 	my $warning=&scantron_warning_screen('Start Grading');
 6245: 	$r->print(&mt('Validation process complete.').'<br />'.
 6246:                   $warning.
 6247:                   &mt('Perform verification for each student after storage of submissions?').
 6248:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6249:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6250:                   ('&nbsp;'x3).'<label>'.
 6251:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6252:                   '</label></span><br />'.
 6253:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6254:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6255:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6256:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6257:     } else {
 6258: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6259: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6260:     }
 6261:     if ($stop) {
 6262: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6263: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6264: 	    $r->print(' '.&mt('this error').' <br />');
 6265: 
 6266: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6267: 	} else {
 6268:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6269: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6270:             } else {
 6271:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6272:             }
 6273: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6274: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6275: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6276: 	}
 6277:     }
 6278:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6279:     return '';
 6280: }
 6281: 
 6282: 
 6283: =pod
 6284: 
 6285: =item scantron_remove_file
 6286: 
 6287:    Removes the requested bubble sheet data file, makes sure that
 6288:    scantron_original_<filename> is never removed
 6289: 
 6290: 
 6291: =cut
 6292: 
 6293: sub scantron_remove_file {
 6294:     my ($which)=@_;
 6295:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6296:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6297:     my $file='scantron_';
 6298:     if ($which eq 'corrected' || $which eq 'skipped') {
 6299: 	$file.=$which.'_';
 6300:     } else {
 6301: 	return 'refused';
 6302:     }
 6303:     $file.=$env{'form.scantron_selectfile'};
 6304:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6305: }
 6306: 
 6307: 
 6308: =pod
 6309: 
 6310: =item scantron_remove_scan_data
 6311: 
 6312:    Removes all scan_data correction for the requested bubble sheet
 6313:    data file.  (In the case that both the are doing skipped records we need
 6314:    to remember the old skipped lines for the time being so that element
 6315:    persists for a while.)
 6316: 
 6317: =cut
 6318: 
 6319: sub scantron_remove_scan_data {
 6320:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6321:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6322:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6323:     my @todelete;
 6324:     my $filename=$env{'form.scantron_selectfile'};
 6325:     foreach my $key (@keys) {
 6326: 	if ($key=~/^\Q$filename\E_/) {
 6327: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6328: 		$key=~/remember_skipping/) {
 6329: 		next;
 6330: 	    }
 6331: 	    push(@todelete,$key);
 6332: 	}
 6333:     }
 6334:     my $result;
 6335:     if (@todelete) {
 6336: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6337: 				       \@todelete,$cdom,$cname);
 6338:     } else {
 6339: 	$result = 'ok';
 6340:     }
 6341:     return $result;
 6342: }
 6343: 
 6344: 
 6345: =pod
 6346: 
 6347: =item scantron_getfile
 6348: 
 6349:     Fetches the requested bubble sheet data file (all 3 versions), and
 6350:     the scan_data hash
 6351:   
 6352:   Arguments:
 6353:     None
 6354: 
 6355:   Returns:
 6356:     2 hash references
 6357: 
 6358:      - first one has 
 6359:          orig      -
 6360:          corrected -
 6361:          skipped   -  each of which points to an array ref of the specified
 6362:                       file broken up into individual lines
 6363:          count     - number of scanlines
 6364:  
 6365:      - second is the scan_data hash possible keys are
 6366:        ($number refers to scanline numbered $number and thus the key affects
 6367:         only that scanline
 6368:         $bubline refers to the specific bubble line element and the aspects
 6369:         refers to that specific bubble line element)
 6370: 
 6371:        $number.user - username:domain to use
 6372:        $number.CODE_ignore_dup 
 6373:                     - ignore the duplicate CODE error 
 6374:        $number.useCODE
 6375:                     - use the CODE in the scanline as is
 6376:        $number.no_bubble.$bubline
 6377:                     - it is valid that there is no bubbled in bubble
 6378:                       at $number $bubline
 6379:        remember_skipping
 6380:                     - a frozen hash containing keys of $number and values
 6381:                       of either 
 6382:                         1 - we are on a 'do skipped records pass' and plan
 6383:                             on processing this line
 6384:                         2 - we are on a 'do skipped records pass' and this
 6385:                             scanline has been marked to skip yet again
 6386: 
 6387: =cut
 6388: 
 6389: sub scantron_getfile {
 6390:     #FIXME really would prefer a scantron directory
 6391:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6392:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6393:     my $lines;
 6394:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6395: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6396:     my %scanlines;
 6397:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6398:     my $temp=$scanlines{'orig'};
 6399:     $scanlines{'count'}=$#$temp;
 6400: 
 6401:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6402: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6403:     if ($lines eq '-1') {
 6404: 	$scanlines{'corrected'}=[];
 6405:     } else {
 6406: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6407:     }
 6408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6409: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6410:     if ($lines eq '-1') {
 6411: 	$scanlines{'skipped'}=[];
 6412:     } else {
 6413: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6414:     }
 6415:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6416:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6417:     my %scan_data = @tmp;
 6418:     return (\%scanlines,\%scan_data);
 6419: }
 6420: 
 6421: =pod
 6422: 
 6423: =item lonnet_putfile
 6424: 
 6425:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6426: 
 6427:  Arguments:
 6428:    $contents - data to store
 6429:    $filename - filename to store $contents into
 6430: 
 6431:  Returns:
 6432:    result value from &Apache::lonnet::finishuserfileupload
 6433: 
 6434: =cut
 6435: 
 6436: sub lonnet_putfile {
 6437:     my ($contents,$filename)=@_;
 6438:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6439:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6440:     $env{'form.sillywaytopassafilearound'}=$contents;
 6441:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6442: 
 6443: }
 6444: 
 6445: =pod
 6446: 
 6447: =item scantron_putfile
 6448: 
 6449:     Stores the current version of the bubble sheet data files, and the
 6450:     scan_data hash. (Does not modify the original version only the
 6451:     corrected and skipped versions.
 6452: 
 6453:  Arguments:
 6454:     $scanlines - hash ref that looks like the first return value from
 6455:                  &scantron_getfile()
 6456:     $scan_data - hash ref that looks like the second return value from
 6457:                  &scantron_getfile()
 6458: 
 6459: =cut
 6460: 
 6461: sub scantron_putfile {
 6462:     my ($scanlines,$scan_data) = @_;
 6463:     #FIXME really would prefer a scantron directory
 6464:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6465:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6466:     if ($scanlines) {
 6467: 	my $prefix='scantron_';
 6468: # no need to update orig, shouldn't change
 6469: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6470: #		    $env{'form.scantron_selectfile'});
 6471: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6472: 			$prefix.'corrected_'.
 6473: 			$env{'form.scantron_selectfile'});
 6474: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6475: 			$prefix.'skipped_'.
 6476: 			$env{'form.scantron_selectfile'});
 6477:     }
 6478:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6479: }
 6480: 
 6481: =pod
 6482: 
 6483: =item scantron_get_line
 6484: 
 6485:    Returns the correct version of the scanline
 6486: 
 6487:  Arguments:
 6488:     $scanlines - hash ref that looks like the first return value from
 6489:                  &scantron_getfile()
 6490:     $scan_data - hash ref that looks like the second return value from
 6491:                  &scantron_getfile()
 6492:     $i         - number of the requested line (starts at 0)
 6493: 
 6494:  Returns:
 6495:    A scanline, (either the original or the corrected one if it
 6496:    exists), or undef if the requested scanline should be
 6497:    skipped. (Either because it's an skipped scanline, or it's an
 6498:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6499:    pass.
 6500: 
 6501: =cut
 6502: 
 6503: sub scantron_get_line {
 6504:     my ($scanlines,$scan_data,$i)=@_;
 6505:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6506:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6507:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6508:     return $scanlines->{'orig'}[$i]; 
 6509: }
 6510: 
 6511: =pod
 6512: 
 6513: =item scantron_todo_count
 6514: 
 6515:     Counts the number of scanlines that need processing.
 6516: 
 6517:  Arguments:
 6518:     $scanlines - hash ref that looks like the first return value from
 6519:                  &scantron_getfile()
 6520:     $scan_data - hash ref that looks like the second return value from
 6521:                  &scantron_getfile()
 6522: 
 6523:  Returns:
 6524:     $count - number of scanlines to process
 6525: 
 6526: =cut
 6527: 
 6528: sub get_todo_count {
 6529:     my ($scanlines,$scan_data)=@_;
 6530:     my $count=0;
 6531:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6532: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6533: 	if ($line=~/^[\s\cz]*$/) { next; }
 6534: 	$count++;
 6535:     }
 6536:     return $count;
 6537: }
 6538: 
 6539: =pod
 6540: 
 6541: =item scantron_put_line
 6542: 
 6543:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6544:     data file.
 6545: 
 6546:  Arguments:
 6547:     $scanlines - hash ref that looks like the first return value from
 6548:                  &scantron_getfile()
 6549:     $scan_data - hash ref that looks like the second return value from
 6550:                  &scantron_getfile()
 6551:     $i         - line number to update
 6552:     $newline   - contents of the updated scanline
 6553:     $skip      - if true make the line for skipping and update the
 6554:                  'skipped' file
 6555: 
 6556: =cut
 6557: 
 6558: sub scantron_put_line {
 6559:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6560:     if ($skip) {
 6561: 	$scanlines->{'skipped'}[$i]=$newline;
 6562: 	&start_skipping($scan_data,$i);
 6563: 	return;
 6564:     }
 6565:     $scanlines->{'corrected'}[$i]=$newline;
 6566: }
 6567: 
 6568: =pod
 6569: 
 6570: =item scantron_clear_skip
 6571: 
 6572:    Remove a line from the 'skipped' file
 6573: 
 6574:  Arguments:
 6575:     $scanlines - hash ref that looks like the first return value from
 6576:                  &scantron_getfile()
 6577:     $scan_data - hash ref that looks like the second return value from
 6578:                  &scantron_getfile()
 6579:     $i         - line number to update
 6580: 
 6581: =cut
 6582: 
 6583: sub scantron_clear_skip {
 6584:     my ($scanlines,$scan_data,$i)=@_;
 6585:     if (exists($scanlines->{'skipped'}[$i])) {
 6586: 	undef($scanlines->{'skipped'}[$i]);
 6587: 	return 1;
 6588:     }
 6589:     return 0;
 6590: }
 6591: 
 6592: =pod
 6593: 
 6594: =item scantron_filter_not_exam
 6595: 
 6596:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6597:    filter out resources that are not marked as 'exam' mode
 6598: 
 6599: =cut
 6600: 
 6601: sub scantron_filter_not_exam {
 6602:     my ($curres)=@_;
 6603:     
 6604:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6605: 	# if the user has asked to not have either hidden
 6606: 	# or 'randomout' controlled resources to be graded
 6607: 	# don't include them
 6608: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6609: 	    && $curres->randomout) {
 6610: 	    return 0;
 6611: 	}
 6612: 	return 1;
 6613:     }
 6614:     return 0;
 6615: }
 6616: 
 6617: =pod
 6618: 
 6619: =item scantron_validate_sequence
 6620: 
 6621:     Validates the selected sequence, checking for resource that are
 6622:     not set to exam mode.
 6623: 
 6624: =cut
 6625: 
 6626: sub scantron_validate_sequence {
 6627:     my ($r,$currentphase) = @_;
 6628: 
 6629:     my $navmap=Apache::lonnavmaps::navmap->new();
 6630:     my (undef,undef,$sequence)=
 6631: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6632: 
 6633:     my $map=$navmap->getResourceByUrl($sequence);
 6634: 
 6635:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6636:                                     value="ignore" />');
 6637:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6638: 	my @resources=
 6639: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6640: 	if (@resources) {
 6641: 	    $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>");
 6642: 	    return (1,$currentphase);
 6643: 	}
 6644:     }
 6645: 
 6646:     return (0,$currentphase+1);
 6647: }
 6648: 
 6649: 
 6650: 
 6651: sub scantron_validate_ID {
 6652:     my ($r,$currentphase) = @_;
 6653:     
 6654:     #get student info
 6655:     my $classlist=&Apache::loncoursedata::get_classlist();
 6656:     my %idmap=&username_to_idmap($classlist);
 6657: 
 6658:     #get scantron line setup
 6659:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6660:     my ($scanlines,$scan_data)=&scantron_getfile();
 6661:     
 6662:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6663: 
 6664:     my %found=('ids'=>{},'usernames'=>{});
 6665:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6666: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6667: 	if ($line=~/^[\s\cz]*$/) { next; }
 6668: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6669: 						 $scan_data);
 6670: 	my $id=$$scan_record{'scantron.ID'};
 6671: 	my $found;
 6672: 	foreach my $checkid (keys(%idmap)) {
 6673: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6674: 	}
 6675: 	if ($found) {
 6676: 	    my $username=$idmap{$found};
 6677: 	    if ($found{'ids'}{$found}) {
 6678: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6679: 					 $line,'duplicateID',$found);
 6680: 		return(1,$currentphase);
 6681: 	    } elsif ($found{'usernames'}{$username}) {
 6682: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6683: 					 $line,'duplicateID',$username);
 6684: 		return(1,$currentphase);
 6685: 	    }
 6686: 	    #FIXME store away line we previously saw the ID on to use above
 6687: 	    $found{'ids'}{$found}++;
 6688: 	    $found{'usernames'}{$username}++;
 6689: 	} else {
 6690: 	    if ($id =~ /^\s*$/) {
 6691: 		my $username=&scan_data($scan_data,"$i.user");
 6692: 		if (defined($username) && $found{'usernames'}{$username}) {
 6693: 		    &scantron_get_correction($r,$i,$scan_record,
 6694: 					     \%scantron_config,
 6695: 					     $line,'duplicateID',$username);
 6696: 		    return(1,$currentphase);
 6697: 		} elsif (!defined($username)) {
 6698: 		    &scantron_get_correction($r,$i,$scan_record,
 6699: 					     \%scantron_config,
 6700: 					     $line,'incorrectID');
 6701: 		    return(1,$currentphase);
 6702: 		}
 6703: 		$found{'usernames'}{$username}++;
 6704: 	    } else {
 6705: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6706: 					 $line,'incorrectID');
 6707: 		return(1,$currentphase);
 6708: 	    }
 6709: 	}
 6710:     }
 6711: 
 6712:     return (0,$currentphase+1);
 6713: }
 6714: 
 6715: 
 6716: sub scantron_get_correction {
 6717:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6718: #FIXME in the case of a duplicated ID the previous line, probably need
 6719: #to show both the current line and the previous one and allow skipping
 6720: #the previous one or the current one
 6721: 
 6722:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6723: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6724: 			    " for PaperID <tt>[_1]</tt>",
 6725: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6726:     } else {
 6727: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6728: 			    " in scanline [_1] <pre>[_2]</pre>",
 6729: 			    $i,$line)."</p> \n");
 6730:     }
 6731:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6732: 			  "The name on the paper is [_2],[_3]",
 6733: 			  $$scan_record{'scantron.ID'},
 6734: 			  $$scan_record{'scantron.LastName'},
 6735: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6736: 
 6737:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6738:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6739:                            # Array populated for doublebubble or
 6740:     my @lines_to_correct;  # missingbubble errors to build javascript
 6741:                            # to validate radio button checking   
 6742: 
 6743:     if ($error =~ /ID$/) {
 6744: 	if ($error eq 'incorrectID') {
 6745: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6746: 		      "</p>\n");
 6747: 	} elsif ($error eq 'duplicateID') {
 6748: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6749: 	}
 6750: 	$r->print($message);
 6751: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6752: 	$r->print("\n<ul><li> ");
 6753: 	#FIXME it would be nice if this sent back the user ID and
 6754: 	#could do partial userID matches
 6755: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6756: 				       'scantron_username','scantron_domain'));
 6757: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6758: 	$r->print("\n@".
 6759: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6760: 
 6761: 	$r->print('</li>');
 6762:     } elsif ($error =~ /CODE$/) {
 6763: 	if ($error eq 'incorrectCODE') {
 6764: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6765: 	} elsif ($error eq 'duplicateCODE') {
 6766: 	    $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");
 6767: 	}
 6768: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6769: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6770: 	$r->print($message);
 6771: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6772: 	$r->print("\n<br /> ");
 6773: 	my $i=0;
 6774: 	if ($error eq 'incorrectCODE' 
 6775: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6776: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6777: 	    if ($closest > 0) {
 6778: 		foreach my $testcode (@{$closest}) {
 6779: 		    my $checked='';
 6780: 		    if (!$i) { $checked=' checked="checked"'; }
 6781: 		    $r->print("
 6782:    <label>
 6783:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6784:        ".&mt("Use the similar CODE [_1] instead.",
 6785: 	    "<b><tt>".$testcode."</tt></b>")."
 6786:     </label>
 6787:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6788: 		    $r->print("\n<br />");
 6789: 		    $i++;
 6790: 		}
 6791: 	    }
 6792: 	}
 6793: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6794: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6795: 	    $r->print("
 6796:     <label>
 6797:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6798:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6799: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6800:     </label>");
 6801: 	    $r->print("\n<br />");
 6802: 	}
 6803: 
 6804: 	$r->print(<<ENDSCRIPT);
 6805: <script type="text/javascript">
 6806: function change_radio(field) {
 6807:     var slct=document.scantronupload.scantron_CODE_resolution;
 6808:     var i;
 6809:     for (i=0;i<slct.length;i++) {
 6810:         if (slct[i].value==field) { slct[i].checked=true; }
 6811:     }
 6812: }
 6813: </script>
 6814: ENDSCRIPT
 6815: 	my $href="/adm/pickcode?".
 6816: 	   "form=".&escape("scantronupload").
 6817: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6818: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6819: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6820: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6821: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6822: 	    $r->print("
 6823:     <label>
 6824:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6825:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6826: 	     "<a target='_blank' href='$href'>","</a>")."
 6827:     </label> 
 6828:     ".&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\')" />'));
 6829: 	    $r->print("\n<br />");
 6830: 	}
 6831: 	$r->print("
 6832:     <label>
 6833:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6834:        ".&mt("Use [_1] as the CODE.",
 6835: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6836: 	$r->print("\n<br /><br />");
 6837:     } elsif ($error eq 'doublebubble') {
 6838: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6839: 
 6840: 	# The form field scantron_questions is acutally a list of line numbers.
 6841: 	# represented by this form so:
 6842: 
 6843: 	my $line_list = &questions_to_line_list($arg);
 6844: 
 6845: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6846: 		  $line_list.'" />');
 6847: 	$r->print($message);
 6848: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6849: 	foreach my $question (@{$arg}) {
 6850: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6851:                                                    $scan_record, $error);
 6852:             push(@lines_to_correct,@linenums);
 6853: 	}
 6854:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6855:     } elsif ($error eq 'missingbubble') {
 6856: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6857: 	$r->print($message);
 6858: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6859: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6860: 
 6861: 	# The form field scantron_questions is actually a list of line numbers not
 6862: 	# a list of question numbers. Therefore:
 6863: 	#
 6864: 	
 6865: 	my $line_list = &questions_to_line_list($arg);
 6866: 
 6867: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6868: 		  $line_list.'" />');
 6869: 	foreach my $question (@{$arg}) {
 6870: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6871:                                                    $scan_record, $error);
 6872:             push(@lines_to_correct,@linenums);
 6873: 	}
 6874:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6875:     } else {
 6876: 	$r->print("\n<ul>");
 6877:     }
 6878:     $r->print("\n</li></ul>");
 6879: }
 6880: 
 6881: sub verify_bubbles_checked {
 6882:     my (@ansnums) = @_;
 6883:     my $ansnumstr = join('","',@ansnums);
 6884:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6885:     my $output = (<<ENDSCRIPT);
 6886: <script type="text/javascript">
 6887: function verify_bubble_radio(form) {
 6888:     var ansnumArray = new Array ("$ansnumstr");
 6889:     var need_bubble_count = 0;
 6890:     for (var i=0; i<ansnumArray.length; i++) {
 6891:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6892:             var bubble_picked = 0; 
 6893:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6894:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6895:                     bubble_picked = 1;
 6896:                 }
 6897:             }
 6898:             if (bubble_picked == 0) {
 6899:                 need_bubble_count ++;
 6900:             }
 6901:         }
 6902:     }
 6903:     if (need_bubble_count) {
 6904:         alert("$warning");
 6905:         return;
 6906:     }
 6907:     form.submit(); 
 6908: }
 6909: </script>
 6910: ENDSCRIPT
 6911:     return $output;
 6912: }
 6913: 
 6914: =pod
 6915: 
 6916: =item  questions_to_line_list
 6917: 
 6918: Converts a list of questions into a string of comma separated
 6919: line numbers in the answer sheet used by the questions.  This is
 6920: used to fill in the scantron_questions form field.
 6921: 
 6922:   Arguments:
 6923:      questions    - Reference to an array of questions.
 6924: 
 6925: =cut
 6926: 
 6927: 
 6928: sub questions_to_line_list {
 6929:     my ($questions) = @_;
 6930:     my @lines;
 6931: 
 6932:     foreach my $item (@{$questions}) {
 6933:         my $question = $item;
 6934:         my ($first,$count,$last);
 6935:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6936:             $question = $1;
 6937:             my $subquestion = $2;
 6938:             $first = $first_bubble_line{$question-1} + 1;
 6939:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6940:             my $subcount = 1;
 6941:             while ($subcount<$subquestion) {
 6942:                 $first += $subans[$subcount-1];
 6943:                 $subcount ++;
 6944:             }
 6945:             $count = $subans[$subquestion-1];
 6946:         } else {
 6947: 	    $first   = $first_bubble_line{$question-1} + 1;
 6948: 	    $count   = $bubble_lines_per_response{$question-1};
 6949:         }
 6950:         $last = $first+$count-1;
 6951:         push(@lines, ($first..$last));
 6952:     }
 6953:     return join(',', @lines);
 6954: }
 6955: 
 6956: =pod 
 6957: 
 6958: =item prompt_for_corrections
 6959: 
 6960: Prompts for a potentially multiline correction to the
 6961: user's bubbling (factors out common code from scantron_get_correction
 6962: for multi and missing bubble cases).
 6963: 
 6964:  Arguments:
 6965:    $r           - Apache request object.
 6966:    $question    - The question number to prompt for.
 6967:    $scan_config - The scantron file configuration hash.
 6968:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6969:    $error       - Type of error
 6970: 
 6971:  Implicit inputs:
 6972:    %bubble_lines_per_response   - Starting line numbers for each question.
 6973:                                   Numbered from 0 (but question numbers are from
 6974:                                   1.
 6975:    %first_bubble_line           - Starting bubble line for each question.
 6976:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6977:                                   type problems render as separate sub-questions, 
 6978:                                   in exam mode. This hash contains a 
 6979:                                   comma-separated list of the lines per 
 6980:                                   sub-question.
 6981:    %responsetype_per_response   - essayresponse, formularesponse,
 6982:                                   stringresponse, imageresponse, reactionresponse,
 6983:                                   and organicresponse type problem parts can have
 6984:                                   multiple lines per response if the weight
 6985:                                   assigned exceeds 10.  In this case, only
 6986:                                   one bubble per line is permitted, but more 
 6987:                                   than one line might contain bubbles, e.g.
 6988:                                   bubbling of: line 1 - J, line 2 - J, 
 6989:                                   line 3 - B would assign 22 points.  
 6990: 
 6991: =cut
 6992: 
 6993: sub prompt_for_corrections {
 6994:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6995:     my ($current_line,$lines);
 6996:     my @linenums;
 6997:     my $questionnum = $question;
 6998:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6999:         $question = $1;
 7000:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7001:         my $subquestion = $2;
 7002:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7003:         my $subcount = 1;
 7004:         while ($subcount<$subquestion) {
 7005:             $current_line += $subans[$subcount-1];
 7006:             $subcount ++;
 7007:         }
 7008:         $lines = $subans[$subquestion-1];
 7009:     } else {
 7010:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7011:         $lines        = $bubble_lines_per_response{$question-1};
 7012:     }
 7013:     if ($lines > 1) {
 7014:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7015:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7016:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7017:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7018:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7019:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7020:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7021:             $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 scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron 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 />');
 7022:         } else {
 7023:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7024:         }
 7025:     }
 7026:     for (my $i =0; $i < $lines; $i++) {
 7027:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7028: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7029: 	        		  $questionnum,$error,split('', $selected));
 7030:         push(@linenums,$current_line);
 7031: 	$current_line++;
 7032:     }
 7033:     if ($lines > 1) {
 7034: 	$r->print("<hr /><br />");
 7035:     }
 7036:     return @linenums;
 7037: }
 7038: 
 7039: =pod
 7040: 
 7041: =item scantron_bubble_selector
 7042:   
 7043:    Generates the html radiobuttons to correct a single bubble line
 7044:    possibly showing the existing the selected bubbles if known
 7045: 
 7046:  Arguments:
 7047:     $r           - Apache request object
 7048:     $scan_config - hash from &get_scantron_config()
 7049:     $line        - Number of the line being displayed.
 7050:     $questionnum - Question number (may include subquestion)
 7051:     $error       - Type of error.
 7052:     @selected    - Array of bubbles picked on this line.
 7053: 
 7054: =cut
 7055: 
 7056: sub scantron_bubble_selector {
 7057:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7058:     my $max=$$scan_config{'Qlength'};
 7059: 
 7060:     my $scmode=$$scan_config{'Qon'};
 7061:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7062: 
 7063:     my @alphabet=('A'..'Z');
 7064:     $r->print(&Apache::loncommon::start_data_table().
 7065:               &Apache::loncommon::start_data_table_row());
 7066:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7067:     for (my $i=0;$i<$max+1;$i++) {
 7068: 	$r->print("\n".'<td align="center">');
 7069: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7070: 	else { $r->print('&nbsp;'); }
 7071: 	$r->print('</td>');
 7072:     }
 7073:     $r->print(&Apache::loncommon::end_data_table_row().
 7074:               &Apache::loncommon::start_data_table_row());
 7075:     for (my $i=0;$i<$max;$i++) {
 7076: 	$r->print("\n".
 7077: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7078: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7079:     }
 7080:     my $nobub_checked = ' ';
 7081:     if ($error eq 'missingbubble') {
 7082:         $nobub_checked = ' checked = "checked" ';
 7083:     }
 7084:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7085: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7086:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7087:               $line.'" value="'.$questionnum.'" /></td>');
 7088:     $r->print(&Apache::loncommon::end_data_table_row().
 7089:               &Apache::loncommon::end_data_table());
 7090: }
 7091: 
 7092: =pod
 7093: 
 7094: =item num_matches
 7095: 
 7096:    Counts the number of characters that are the same between the two arguments.
 7097: 
 7098:  Arguments:
 7099:    $orig - CODE from the scanline
 7100:    $code - CODE to match against
 7101: 
 7102:  Returns:
 7103:    $count - integer count of the number of same characters between the
 7104:             two arguments
 7105: 
 7106: =cut
 7107: 
 7108: sub num_matches {
 7109:     my ($orig,$code) = @_;
 7110:     my @code=split(//,$code);
 7111:     my @orig=split(//,$orig);
 7112:     my $same=0;
 7113:     for (my $i=0;$i<scalar(@code);$i++) {
 7114: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7115:     }
 7116:     return $same;
 7117: }
 7118: 
 7119: =pod
 7120: 
 7121: =item scantron_get_closely_matching_CODEs
 7122: 
 7123:    Cycles through all CODEs and finds the set that has the greatest
 7124:    number of same characters as the provided CODE
 7125: 
 7126:  Arguments:
 7127:    $allcodes - hash ref returned by &get_codes()
 7128:    $CODE     - CODE from the current scanline
 7129: 
 7130:  Returns:
 7131:    2 element list
 7132:     - first elements is number of how closely matching the best fit is 
 7133:       (5 means best set has 5 matching characters)
 7134:     - second element is an arrary ref containing the set of valid CODEs
 7135:       that best fit the passed in CODE
 7136: 
 7137: =cut
 7138: 
 7139: sub scantron_get_closely_matching_CODEs {
 7140:     my ($allcodes,$CODE)=@_;
 7141:     my @CODEs;
 7142:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7143: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7144:     }
 7145: 
 7146:     return ($#CODEs,$CODEs[-1]);
 7147: }
 7148: 
 7149: =pod
 7150: 
 7151: =item get_codes
 7152: 
 7153:    Builds a hash which has keys of all of the valid CODEs from the selected
 7154:    set of remembered CODEs.
 7155: 
 7156:  Arguments:
 7157:   $old_name - name of the set of remembered CODEs
 7158:   $cdom     - domain of the course
 7159:   $cnum     - internal course name
 7160: 
 7161:  Returns:
 7162:   %allcodes - keys are the valid CODEs, values are all 1
 7163: 
 7164: =cut
 7165: 
 7166: sub get_codes {
 7167:     my ($old_name, $cdom, $cnum) = @_;
 7168:     if (!$old_name) {
 7169: 	$old_name=$env{'form.scantron_CODElist'};
 7170:     }
 7171:     if (!$cdom) {
 7172: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7173:     }
 7174:     if (!$cnum) {
 7175: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7176:     }
 7177:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7178: 				    $cdom,$cnum);
 7179:     my %allcodes;
 7180:     if ($result{"type\0$old_name"} eq 'number') {
 7181: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7182:     } else {
 7183: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7184:     }
 7185:     return %allcodes;
 7186: }
 7187: 
 7188: =pod
 7189: 
 7190: =item scantron_validate_CODE
 7191: 
 7192:    Validates all scanlines in the selected file to not have any
 7193:    invalid or underspecified CODEs and that none of the codes are
 7194:    duplicated if this was requested.
 7195: 
 7196: =cut
 7197: 
 7198: sub scantron_validate_CODE {
 7199:     my ($r,$currentphase) = @_;
 7200:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7201:     if ($scantron_config{'CODElocation'} &&
 7202: 	$scantron_config{'CODEstart'} &&
 7203: 	$scantron_config{'CODElength'}) {
 7204: 	if (!defined($env{'form.scantron_CODElist'})) {
 7205: 	    &FIXME_blow_up()
 7206: 	}
 7207:     } else {
 7208: 	return (0,$currentphase+1);
 7209:     }
 7210:     
 7211:     my %usedCODEs;
 7212: 
 7213:     my %allcodes=&get_codes();
 7214: 
 7215:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7216: 
 7217:     my ($scanlines,$scan_data)=&scantron_getfile();
 7218:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7219: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7220: 	if ($line=~/^[\s\cz]*$/) { next; }
 7221: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7222: 						 $scan_data);
 7223: 	my $CODE=$$scan_record{'scantron.CODE'};
 7224: 	my $error=0;
 7225: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7226: 	    &scantron_get_correction($r,$i,$scan_record,
 7227: 				     \%scantron_config,
 7228: 				     $line,'incorrectCODE',\%allcodes);
 7229: 	    return(1,$currentphase);
 7230: 	}
 7231: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7232: 	    && !$$scan_record{'scantron.useCODE'}) {
 7233: 	    &scantron_get_correction($r,$i,$scan_record,
 7234: 				     \%scantron_config,
 7235: 				     $line,'incorrectCODE',\%allcodes);
 7236: 	    return(1,$currentphase);
 7237: 	}
 7238: 	if (exists($usedCODEs{$CODE}) 
 7239: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7240: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7241: 	    &scantron_get_correction($r,$i,$scan_record,
 7242: 				     \%scantron_config,
 7243: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7244: 	    return(1,$currentphase);
 7245: 	}
 7246: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7247:     }
 7248:     return (0,$currentphase+1);
 7249: }
 7250: 
 7251: =pod
 7252: 
 7253: =item scantron_validate_doublebubble
 7254: 
 7255:    Validates all scanlines in the selected file to not have any
 7256:    bubble lines with multiple bubbles marked.
 7257: 
 7258: =cut
 7259: 
 7260: sub scantron_validate_doublebubble {
 7261:     my ($r,$currentphase) = @_;
 7262:     #get student info
 7263:     my $classlist=&Apache::loncoursedata::get_classlist();
 7264:     my %idmap=&username_to_idmap($classlist);
 7265: 
 7266:     #get scantron line setup
 7267:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7268:     my ($scanlines,$scan_data)=&scantron_getfile();
 7269:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7270: 
 7271:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7272: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7273: 	if ($line=~/^[\s\cz]*$/) { next; }
 7274: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7275: 						 $scan_data);
 7276: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7277: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7278: 				 'doublebubble',
 7279: 				 $$scan_record{'scantron.doubleerror'});
 7280:     	return (1,$currentphase);
 7281:     }
 7282:     return (0,$currentphase+1);
 7283: }
 7284: 
 7285: 
 7286: sub scantron_get_maxbubble {
 7287:     if (defined($env{'form.scantron_maxbubble'}) &&
 7288: 	$env{'form.scantron_maxbubble'}) {
 7289: 	&restore_bubble_lines();
 7290: 	return $env{'form.scantron_maxbubble'};
 7291:     }
 7292: 
 7293:     my (undef, undef, $sequence) =
 7294: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7295: 
 7296:     my $navmap=Apache::lonnavmaps::navmap->new();
 7297:     my $map=$navmap->getResourceByUrl($sequence);
 7298:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7299: 
 7300:     &Apache::lonxml::clear_problem_counter();
 7301: 
 7302:     my $uname       = $env{'user.name'};
 7303:     my $udom        = $env{'user.domain'};
 7304:     my $cid         = $env{'request.course.id'};
 7305:     my $total_lines = 0;
 7306:     %bubble_lines_per_response = ();
 7307:     %first_bubble_line         = ();
 7308:     %subdivided_bubble_lines   = ();
 7309:     %responsetype_per_response = ();
 7310: 
 7311:     my $response_number = 0;
 7312:     my $bubble_line     = 0;
 7313:     foreach my $resource (@resources) {
 7314:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7315:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7316: 	    foreach my $part_id (@{$parts}) {
 7317:                 my $lines;
 7318: 
 7319: 	        # TODO - make this a persistent hash not an array.
 7320: 
 7321:                 # optionresponse, matchresponse and rankresponse type items 
 7322:                 # render as separate sub-questions in exam mode.
 7323:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7324:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7325:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7326:                     my ($numbub,$numshown);
 7327:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7328:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7329:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7330:                         }
 7331:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7332:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7333:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7334:                         }
 7335:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7336:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7337:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7338:                         }
 7339:                     }
 7340:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7341:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7342:                     }
 7343:                     my $bubbles_per_line = 10;
 7344:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7345:                     if (($numbub % $bubbles_per_line) != 0) {
 7346:                         $inner_bubble_lines++;
 7347:                     }
 7348:                     for (my $i=0; $i<$numshown; $i++) {
 7349:                         $subdivided_bubble_lines{$response_number} .= 
 7350:                             $inner_bubble_lines.',';
 7351:                     }
 7352:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7353:                     $lines = $numshown * $inner_bubble_lines;
 7354:                 } else {
 7355:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7356:                 } 
 7357: 
 7358:                 $first_bubble_line{$response_number} = $bubble_line;
 7359: 	        $bubble_lines_per_response{$response_number} = $lines;
 7360:                 $responsetype_per_response{$response_number} = 
 7361:                     $analysis->{$part_id.'.type'};
 7362: 	        $response_number++;
 7363: 
 7364: 	        $bubble_line +=  $lines;
 7365: 	        $total_lines +=  $lines;
 7366: 	    }
 7367:         }
 7368:     }
 7369:     &Apache::lonnet::delenv('scantron.');
 7370: 
 7371:     &save_bubble_lines();
 7372:     $env{'form.scantron_maxbubble'} =
 7373: 	$total_lines;
 7374:     return $env{'form.scantron_maxbubble'};
 7375: }
 7376: 
 7377: sub scantron_validate_missingbubbles {
 7378:     my ($r,$currentphase) = @_;
 7379:     #get student info
 7380:     my $classlist=&Apache::loncoursedata::get_classlist();
 7381:     my %idmap=&username_to_idmap($classlist);
 7382: 
 7383:     #get scantron line setup
 7384:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7385:     my ($scanlines,$scan_data)=&scantron_getfile();
 7386:     my $max_bubble=&scantron_get_maxbubble();
 7387:     if (!$max_bubble) { $max_bubble=2**31; }
 7388:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7389: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7390: 	if ($line=~/^[\s\cz]*$/) { next; }
 7391: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7392: 						 $scan_data);
 7393: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7394: 	my @to_correct;
 7395: 	
 7396: 	# Probably here's where the error is...
 7397: 
 7398: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7399:             my $lastbubble;
 7400:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7401:                my $question = $1;
 7402:                my $subquestion = $2;
 7403:                if (!defined($first_bubble_line{$question -1})) { next; }
 7404:                my $first = $first_bubble_line{$question-1};
 7405:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7406:                my $subcount = 1;
 7407:                while ($subcount<$subquestion) {
 7408:                    $first += $subans[$subcount-1];
 7409:                    $subcount ++;
 7410:                }
 7411:                my $count = $subans[$subquestion-1];
 7412:                $lastbubble = $first + $count;
 7413:             } else {
 7414:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7415:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7416:             }
 7417:             if ($lastbubble > $max_bubble) { next; }
 7418: 	    push(@to_correct,$missing);
 7419: 	}
 7420: 	if (@to_correct) {
 7421: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7422: 				     $line,'missingbubble',\@to_correct);
 7423: 	    return (1,$currentphase);
 7424: 	}
 7425: 
 7426:     }
 7427:     return (0,$currentphase+1);
 7428: }
 7429: 
 7430: 
 7431: sub scantron_process_students {
 7432:     my ($r) = @_;
 7433: 
 7434:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7435:     my ($symb)=&get_symb($r);
 7436:     if (!$symb) {
 7437: 	return '';
 7438:     }
 7439:     my $default_form_data=&defaultFormData($symb);
 7440: 
 7441:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7442:     my ($scanlines,$scan_data)=&scantron_getfile();
 7443:     my $classlist=&Apache::loncoursedata::get_classlist();
 7444:     my %idmap=&username_to_idmap($classlist);
 7445:     my $navmap=Apache::lonnavmaps::navmap->new();
 7446:     my $map=$navmap->getResourceByUrl($sequence);
 7447:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7448:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7449:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7450:                             \%grader_randomlists_by_symb);
 7451:     foreach my $resource (@resources) {
 7452:         my $ressymb = $resource->symb();
 7453:         my ($analysis,$parts) =
 7454:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7455:                                       $env{'user.name'},$env{'user.domain'},1);
 7456:         $grader_partids_by_symb{$ressymb} = $parts;
 7457:         if (ref($analysis) eq 'HASH') {
 7458:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7459:                 $grader_randomlists_by_symb{$ressymb} = 
 7460:                     $analysis->{'parts_withrandomlist'};
 7461:             }
 7462:         }
 7463:     }
 7464: 
 7465:     my ($uname,$udom);
 7466:     my $result= <<SCANTRONFORM;
 7467: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7468:   <input type="hidden" name="command" value="scantron_configphase" />
 7469:   $default_form_data
 7470: SCANTRONFORM
 7471:     $r->print($result);
 7472: 
 7473:     my @delayqueue;
 7474:     my (%completedstudents,%scandata);
 7475:     
 7476:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7477:     my $count=&get_todo_count($scanlines,$scan_data);
 7478:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7479:  				    'Scantron Progress',$count,
 7480: 				    'inline',undef,'scantronupload');
 7481:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7482: 					  'Processing first student');
 7483:     $r->print('<br />');
 7484:     my $start=&Time::HiRes::time();
 7485:     my $i=-1;
 7486:     my $started;
 7487: 
 7488:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7489: 
 7490:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7491:     # the user and return.
 7492: 
 7493:     if ($ssi_error) {
 7494: 	$r->print("</form>");
 7495: 	&ssi_print_error($r);
 7496: 	$r->print(&show_grading_menu_form($symb));
 7497:         &Apache::lonnet::remove_lock($lock);
 7498: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7499:     }
 7500: 
 7501:     my %lettdig = &letter_to_digits();
 7502:     my $numletts = scalar(keys(%lettdig));
 7503: 
 7504:     while ($i<$scanlines->{'count'}) {
 7505:  	($uname,$udom)=('','');
 7506:  	$i++;
 7507:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7508:  	if ($line=~/^[\s\cz]*$/) { next; }
 7509: 	if ($started) {
 7510: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7511: 						     'last student');
 7512: 	}
 7513: 	$started=1;
 7514:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7515:  						 $scan_data);
 7516:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7517:  					      \%idmap,$i)) {
 7518:   	    &scantron_add_delay(\@delayqueue,$line,
 7519:  				'Unable to find a student that matches',1);
 7520:  	    next;
 7521:   	}
 7522:  	if (exists $completedstudents{$uname}) {
 7523:  	    &scantron_add_delay(\@delayqueue,$line,
 7524:  				'Student '.$uname.' has multiple sheets',2);
 7525:  	    next;
 7526:  	}
 7527:   	($uname,$udom)=split(/:/,$uname);
 7528: 
 7529:         my %partids_by_symb;
 7530:         foreach my $resource (@resources) {
 7531:             my $ressymb = $resource->symb();
 7532:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7533:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7534:                 my ($analysis,$parts) =
 7535:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7536:                 $partids_by_symb{$ressymb} = $parts;
 7537:             } else {
 7538:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7539:             }
 7540:         }
 7541: 
 7542: 	&Apache::lonxml::clear_problem_counter();
 7543:   	&Apache::lonnet::appenv($scan_record);
 7544: 
 7545: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7546: 	    &scantron_putfile($scanlines,$scan_data);
 7547: 	}
 7548: 	
 7549:         my $scancode;
 7550:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7551:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7552:             $scancode = $scan_record->{'scantron.CODE'};
 7553:         } else {
 7554:             $scancode = '';
 7555:         }
 7556: 
 7557:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7558:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7559:             $ssi_error = 0; # So end of handler error message does not trigger.
 7560:             $r->print("</form>");
 7561:             &ssi_print_error($r);
 7562:             $r->print(&show_grading_menu_form($symb));
 7563:             &Apache::lonnet::remove_lock($lock);
 7564:             return '';      # Why return ''?  Beats me.
 7565:         }
 7566: 
 7567: 	$completedstudents{$uname}={'line'=>$line};
 7568:         if ($env{'form.verifyrecord'}) {
 7569:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7570:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7571:             chomp($studentdata);
 7572:             $studentdata =~ s/\r$//;
 7573:             my $studentrecord = '';
 7574:             my $counter = -1;
 7575:             foreach my $resource (@resources) {
 7576:                 my $ressymb = $resource->symb();
 7577:                 ($counter,my $recording) =
 7578:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7579:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7580:                                              \%scantron_config,\%lettdig,$numletts);
 7581:                 $studentrecord .= $recording;
 7582:             }
 7583:             if ($studentrecord ne $studentdata) {
 7584:                 &Apache::lonxml::clear_problem_counter();
 7585:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7586:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7587:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7588:                     $r->print("</form>");
 7589:                     &ssi_print_error($r);
 7590:                     $r->print(&show_grading_menu_form($symb));
 7591:                     &Apache::lonnet::remove_lock($lock);
 7592:                     delete($completedstudents{$uname});
 7593:                     return '';
 7594:                 }
 7595:                 $counter = -1;
 7596:                 $studentrecord = '';
 7597:                 foreach my $resource (@resources) {
 7598:                     my $ressymb = $resource->symb();
 7599:                     ($counter,my $recording) =
 7600:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7601:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7602:                                                  \%scantron_config,\%lettdig,$numletts);
 7603:                     $studentrecord .= $recording;
 7604:                 }
 7605:                 if ($studentrecord ne $studentdata) {
 7606:                     $r->print('<p><span class="LC_error">');
 7607:                     if ($scancode eq '') {
 7608:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7609:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7610:                     } else {
 7611:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7612:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7613:                     }
 7614:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7615:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7616:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7617:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7618:                               &Apache::loncommon::start_data_table_row().
 7619:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7620:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7621:                               &Apache::loncommon::end_data_table_row().
 7622:                               &Apache::loncommon::start_data_table_row().
 7623:                               '<td>Stored submissions</td>'.
 7624:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7625:                               &Apache::loncommon::end_data_table_row().
 7626:                               &Apache::loncommon::end_data_table().'</p>');
 7627:                 } else {
 7628:                     $r->print('<br /><span class="LC_warning">'.
 7629:                              &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 />'.
 7630:                              &mt("As a consequence, this user's submission history records two tries.").
 7631:                                  '</span><br />');
 7632:                 }
 7633:             }
 7634:         }
 7635:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7636:     } continue {
 7637: 	&Apache::lonxml::clear_problem_counter();
 7638: 	&Apache::lonnet::delenv('scantron.');
 7639:     }
 7640:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7641:     &Apache::lonnet::remove_lock($lock);
 7642: #    my $lasttime = &Time::HiRes::time()-$start;
 7643: #    $r->print("<p>took $lasttime</p>");
 7644: 
 7645:     $r->print("</form>");
 7646:     $r->print(&show_grading_menu_form($symb));
 7647:     return '';
 7648: }
 7649: 
 7650: sub graders_resources_pass {
 7651:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7652:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7653:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7654:         foreach my $resource (@{$resources}) {
 7655:             my $ressymb = $resource->symb();
 7656:             my ($analysis,$parts) =
 7657:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7658:                                           $env{'user.name'},$env{'user.domain'},1);
 7659:             $grader_partids_by_symb->{$ressymb} = $parts;
 7660:             if (ref($analysis) eq 'HASH') {
 7661:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7662:                     $grader_randomlists_by_symb->{$ressymb} =
 7663:                         $analysis->{'parts_withrandomlist'};
 7664:                 }
 7665:             }
 7666:         }
 7667:     }
 7668:     return;
 7669: }
 7670: 
 7671: sub grade_student_bubbles {
 7672:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7673:     if (ref($resources) eq 'ARRAY') {
 7674:         my $count = 0;
 7675:         foreach my $resource (@{$resources}) {
 7676:             my $ressymb = $resource->symb();
 7677:             my %form = ('submitted'      => 'scantron',
 7678:                         'grade_target'   => 'grade',
 7679:                         'grade_username' => $uname,
 7680:                         'grade_domain'   => $udom,
 7681:                         'grade_courseid' => $env{'request.course.id'},
 7682:                         'grade_symb'     => $ressymb,
 7683:                         'CODE'           => $scancode
 7684:                        );
 7685:             if (ref($parts) eq 'HASH') {
 7686:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7687:                     foreach my $part (@{$parts->{$ressymb}}) {
 7688:                         $form{'scantron_questnum_start.'.$part} =
 7689:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7690:                         $count++;
 7691:                     }
 7692:                 }
 7693:             }
 7694:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7695:             return 'ssi_error' if ($ssi_error);
 7696:             last if (&Apache::loncommon::connection_aborted($r));
 7697:         }
 7698:     }
 7699:     return;
 7700: }
 7701: 
 7702: sub scantron_upload_scantron_data {
 7703:     my ($r)=@_;
 7704:     my $dom = $env{'request.role.domain'};
 7705:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7706:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7707:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7708: 							  'domainid',
 7709: 							  'coursename',$dom);
 7710:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7711:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7712:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7713:     $r->print('
 7714: <script type="text/javascript" language="javascript">
 7715:     function checkUpload(formname) {
 7716: 	if (formname.upfile.value == "") {
 7717: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 7718: 	    return false;
 7719: 	}
 7720:         if (formname.courseid.value == "") {
 7721:             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.').'");
 7722:             return false;
 7723:         }
 7724: 	formname.submit();
 7725:     }
 7726: 
 7727:     function ToSyllabus() {
 7728:         var cdom = '."'$dom'".';
 7729:         var cnum = document.rules.courseid.value;
 7730:         if (cdom == "" || cdom == null) {
 7731:             return;
 7732:         }
 7733:         if (cnum == "" || cnum == null) {
 7734:            return;
 7735:         }
 7736:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7737:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7738:         return;
 7739:     }
 7740: 
 7741: </script>
 7742: 
 7743: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7744: 
 7745: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7746: '.$default_form_data.
 7747:   &Apache::lonhtmlcommon::start_pick_box().
 7748:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7749:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7750:   &Apache::lonhtmlcommon::row_closure().
 7751:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7752:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7753:   &Apache::lonhtmlcommon::row_closure().
 7754:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7755:   '<input name="domainid" type="hidden" />'.$domdesc.
 7756:   &Apache::lonhtmlcommon::row_closure().
 7757:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7758:   '<input type="file" name="upfile" size="50" />'.
 7759:   &Apache::lonhtmlcommon::row_closure(1).
 7760:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7761: 
 7762: <input name="command" value="scantronupload_save" type="hidden" />
 7763: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7764: </form>
 7765: ');
 7766:     return '';
 7767: }
 7768: 
 7769: 
 7770: sub scantron_upload_scantron_data_save {
 7771:     my($r)=@_;
 7772:     my ($symb)=&get_symb($r,1);
 7773:     my $doanotherupload=
 7774: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7775: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7776: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7777: 	'</form>'."\n";
 7778:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7779: 	!&Apache::lonnet::allowed('usc',
 7780: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7781: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7782: 	if ($symb) {
 7783: 	    $r->print(&show_grading_menu_form($symb));
 7784: 	} else {
 7785: 	    $r->print($doanotherupload);
 7786: 	}
 7787: 	return '';
 7788:     }
 7789:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7790:     my $uploadedfile;
 7791:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7792:     if (length($env{'form.upfile'}) < 2) {
 7793:         $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>'));
 7794:     } else {
 7795:         my $result = 
 7796:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7797:                                             $env{'form.courseid'},$env{'form.domainid'});
 7798: 	if ($result =~ m{^/uploaded/}) {
 7799: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7800:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7801: 			  '<span class="LC_filename">'.$result.'</span>'));
 7802:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7803:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7804:                                                        $env{'form.courseid'},$uploadedfile));
 7805: 	} else {
 7806: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7807:                           '<span class="LC_error">','</span>',$result,
 7808: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7809: 	}
 7810:     }
 7811:     if ($symb) {
 7812: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7813:     } else {
 7814: 	$r->print($doanotherupload);
 7815:     }
 7816:     return '';
 7817: }
 7818: 
 7819: sub validate_uploaded_scantron_file {
 7820:     my ($cdom,$cname,$fname) = @_;
 7821:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7822:     my @lines;
 7823:     if ($scanlines ne '-1') {
 7824:         @lines=split("\n",$scanlines,-1);
 7825:     }
 7826:     my $output;
 7827:     if (@lines) {
 7828:         my (%counts,$max_match_format);
 7829:         my ($max_match_count,$max_match_pct) = (0,0);
 7830:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7831:         my %idmap = &username_to_idmap($classlist);
 7832:         foreach my $key (keys(%idmap)) {
 7833:             my $lckey = lc($key);
 7834:             $idmap{$lckey} = $idmap{$key};
 7835:         }
 7836:         my %unique_formats;
 7837:         my @formatlines = &get_scantronformat_file();
 7838:         foreach my $line (@formatlines) {
 7839:             chomp($line);
 7840:             my @config = split(/:/,$line);
 7841:             my $idstart = $config[5];
 7842:             my $idlength = $config[6];
 7843:             if (($idstart ne '') && ($idlength > 0)) {
 7844:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7845:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7846:                 } else {
 7847:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7848:                 }
 7849:             }
 7850:         }
 7851:         foreach my $key (keys(%unique_formats)) {
 7852:             my ($idstart,$idlength) = split(':',$key);
 7853:             %{$counts{$key}} = (
 7854:                                'found'   => 0,
 7855:                                'total'   => 0,
 7856:                               );
 7857:             foreach my $line (@lines) {
 7858:                 next if ($line =~ /^#/);
 7859:                 next if ($line =~ /^[\s\cz]*$/);
 7860:                 my $id = substr($line,$idstart-1,$idlength);
 7861:                 $id = lc($id);
 7862:                 if (exists($idmap{$id})) {
 7863:                     $counts{$key}{'found'} ++;
 7864:                 }
 7865:                 $counts{$key}{'total'} ++;
 7866:             }
 7867:             if ($counts{$key}{'total'}) {
 7868:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7869:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7870:                     $max_match_pct = $percent_match;
 7871:                     $max_match_format = $key;
 7872:                     $max_match_count = $counts{$key}{'total'};
 7873:                 }
 7874:             }
 7875:         }
 7876:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 7877:             my $format_descs;
 7878:             my $numwithformat = @{$unique_formats{$max_match_format}};
 7879:             for (my $i=0; $i<$numwithformat; $i++) {
 7880:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 7881:                 if ($i<$numwithformat-2) {
 7882:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 7883:                 } elsif ($i==$numwithformat-2) {
 7884:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 7885:                 } elsif ($i==$numwithformat-1) {
 7886:                     $format_descs .= '"<i>'.$desc.'</i>"';
 7887:                 }
 7888:             }
 7889:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 7890:             $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).
 7891:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 7892:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 7893:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 7894:                                   '<i>'.$cdom.'</i>').'</li>'.
 7895:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 7896:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 7897:                        '</ul>';
 7898:         }
 7899:     } else {
 7900:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 7901:     }
 7902:     return $output;
 7903: }
 7904: 
 7905: sub valid_file {
 7906:     my ($requested_file)=@_;
 7907:     foreach my $filename (sort(&scantron_filenames())) {
 7908: 	if ($requested_file eq $filename) { return 1; }
 7909:     }
 7910:     return 0;
 7911: }
 7912: 
 7913: sub scantron_download_scantron_data {
 7914:     my ($r)=@_;
 7915:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7916:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7917:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7918:     my $file=$env{'form.scantron_selectfile'};
 7919:     if (! &valid_file($file)) {
 7920: 	$r->print('
 7921: 	<p>
 7922: 	    '.&mt('The requested file name was invalid.').'
 7923:         </p>
 7924: ');
 7925: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7926: 	return;
 7927:     }
 7928:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7929:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7930:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7931:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7932:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7933:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7934:     $r->print('
 7935:     <p>
 7936: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7937: 	      '<a href="'.$orig.'">','</a>').'
 7938:     </p>
 7939:     <p>
 7940: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7941: 	      '<a href="'.$corrected.'">','</a>').'
 7942:     </p>
 7943:     <p>
 7944: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7945: 	      '<a href="'.$skipped.'">','</a>').'
 7946:     </p>
 7947: ');
 7948:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7949:     return '';
 7950: }
 7951: 
 7952: sub checkscantron_results {
 7953:     my ($r) = @_;
 7954:     my ($symb)=&get_symb($r);
 7955:     if (!$symb) {return '';}
 7956:     my $grading_menu_button=&show_grading_menu_form($symb);
 7957:     my $cid = $env{'request.course.id'};
 7958:     my %lettdig = &letter_to_digits();
 7959:     my $numletts = scalar(keys(%lettdig));
 7960:     my $cnum = $env{'course.'.$cid.'.num'};
 7961:     my $cdom = $env{'course.'.$cid.'.domain'};
 7962:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7963:     my %record;
 7964:     my %scantron_config =
 7965:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7966:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7967:     my $classlist=&Apache::loncoursedata::get_classlist();
 7968:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7969:     my $navmap=Apache::lonnavmaps::navmap->new();
 7970:     my $map=$navmap->getResourceByUrl($sequence);
 7971:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7972:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7973:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 7974: 
 7975:     my ($uname,$udom);
 7976:     my (%scandata,%lastname,%bylast);
 7977:     $r->print('
 7978: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7979: 
 7980:     my @delayqueue;
 7981:     my %completedstudents;
 7982: 
 7983:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7984:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7985:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7986:                                     'inline',undef,'checkscantron');
 7987:     my ($username,$domain,$started);
 7988: 
 7989:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7990: 
 7991:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7992:                                           'Processing first student');
 7993:     my $start=&Time::HiRes::time();
 7994:     my $i=-1;
 7995: 
 7996:     while ($i<$scanlines->{'count'}) {
 7997:         ($username,$domain,$uname)=('','','');
 7998:         $i++;
 7999:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8000:         if ($line=~/^[\s\cz]*$/) { next; }
 8001:         if ($started) {
 8002:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8003:                                                      'last student');
 8004:         }
 8005:         $started=1;
 8006:         my $scan_record=
 8007:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8008:                                                      $scan_data);
 8009:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8010:                                                               \%idmap,$i)) {
 8011:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8012:                                 'Unable to find a student that matches',1);
 8013:             next;
 8014:         }
 8015:         if (exists $completedstudents{$uname}) {
 8016:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8017:                                 'Student '.$uname.' has multiple sheets',2);
 8018:             next;
 8019:         }
 8020:         my $pid = $scan_record->{'scantron.ID'};
 8021:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8022:         push(@{$bylast{$lastname{$pid}}},$pid);
 8023:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8024:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8025:         chomp($scandata{$pid});
 8026:         $scandata{$pid} =~ s/\r$//;
 8027:         ($username,$domain)=split(/:/,$uname);
 8028:         my $counter = -1;
 8029:         foreach my $resource (@resources) {
 8030:             my $parts;
 8031:             my $ressymb = $resource->symb();
 8032:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8033:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8034:                 (my $analysis,$parts) =
 8035:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8036:             } else {
 8037:                 $parts = $grader_partids_by_symb{$ressymb};
 8038:             }
 8039:             ($counter,my $recording) =
 8040:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8041:                                          $scandata{$pid},$parts,
 8042:                                          \%scantron_config,\%lettdig,$numletts);
 8043:             $record{$pid} .= $recording;
 8044:         }
 8045:     }
 8046:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8047:     $r->print('<br />');
 8048:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8049:     $passed = 0;
 8050:     $failed = 0;
 8051:     $numstudents = 0;
 8052:     foreach my $last (sort(keys(%bylast))) {
 8053:         if (ref($bylast{$last}) eq 'ARRAY') {
 8054:             foreach my $pid (sort(@{$bylast{$last}})) {
 8055:                 my $showscandata = $scandata{$pid};
 8056:                 my $showrecord = $record{$pid};
 8057:                 $showscandata =~ s/\s/&nbsp;/g;
 8058:                 $showrecord =~ s/\s/&nbsp;/g;
 8059:                 if ($scandata{$pid} eq $record{$pid}) {
 8060:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8061:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8062: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8063: '</tr>'."\n".
 8064: '<tr class="'.$css_class.'">'."\n".
 8065: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8066:                     $passed ++;
 8067:                 } else {
 8068:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8069:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8070: '</tr>'."\n".
 8071: '<tr class="'.$css_class.'">'."\n".
 8072: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8073: '</tr>'."\n";
 8074:                     $failed ++;
 8075:                 }
 8076:                 $numstudents ++;
 8077:             }
 8078:         }
 8079:     }
 8080:     $r->print('<p>'.&mt('Comparison of scantron 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>');
 8081:     $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>');
 8082:     if ($passed) {
 8083:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 8084:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8085:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8086:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8087:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8088:                  $okstudents."\n".
 8089:                  &Apache::loncommon::end_data_table().'<br />');
 8090:     }
 8091:     if ($failed) {
 8092:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 8093:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8094:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8095:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8096:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8097:                  $badstudents."\n".
 8098:                  &Apache::loncommon::end_data_table()).'<br />'.
 8099:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
 8100:     }
 8101:     $r->print('</form><br />'.$grading_menu_button);
 8102:     return;
 8103: }
 8104: 
 8105: sub verify_scantron_grading {
 8106:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8107:         $scantron_config,$lettdig,$numletts) = @_;
 8108:     my ($record,%expected,%startpos);
 8109:     return ($counter,$record) if (!ref($resource));
 8110:     return ($counter,$record) if (!$resource->is_problem());
 8111:     my $symb = $resource->symb();
 8112:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8113:     foreach my $part_id (@{$partids}) {
 8114:         $counter ++;
 8115:         $expected{$part_id} = 0;
 8116:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8117:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8118:             foreach my $item (@sub_lines) {
 8119:                 $expected{$part_id} += $item;
 8120:             }
 8121:         } else {
 8122:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8123:         }
 8124:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8125:     }
 8126:     if ($symb) {
 8127:         my %recorded;
 8128:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8129:         if ($returnhash{'version'}) {
 8130:             my %lasthash=();
 8131:             my $version;
 8132:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8133:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8134:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8135:                 }
 8136:             }
 8137:             foreach my $key (keys(%lasthash)) {
 8138:                 if ($key =~ /\.scantron$/) {
 8139:                     my $value = &unescape($lasthash{$key});
 8140:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8141:                     if ($value eq '') {
 8142:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8143:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8144:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8145:                             }
 8146:                         }
 8147:                     } else {
 8148:                         my @tocheck;
 8149:                         my @items = split(//,$value);
 8150:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8151:                             ($scantron_config->{'Qon'} eq 'number')) {
 8152:                             if (@items < $expected{$part_id}) {
 8153:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8154:                                 my @singles = split(//,$fragment);
 8155:                                 foreach my $pos (@singles) {
 8156:                                     if ($pos eq ' ') {
 8157:                                         push(@tocheck,$pos);
 8158:                                     } else {
 8159:                                         my $next = shift(@items);
 8160:                                         push(@tocheck,$next);
 8161:                                     }
 8162:                                 }
 8163:                             } else {
 8164:                                 @tocheck = @items;
 8165:                             }
 8166:                             foreach my $letter (@tocheck) {
 8167:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8168:                                     if ($letter !~ /^[A-J]$/) {
 8169:                                         $letter = $scantron_config->{'Qoff'};
 8170:                                     }
 8171:                                     $recorded{$part_id} .= $letter;
 8172:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8173:                                     my $digit;
 8174:                                     if ($letter !~ /^[A-J]$/) {
 8175:                                         $digit = $scantron_config->{'Qoff'};
 8176:                                     } else {
 8177:                                         $digit = $lettdig->{$letter};
 8178:                                     }
 8179:                                     $recorded{$part_id} .= $digit;
 8180:                                 }
 8181:                             }
 8182:                         } else {
 8183:                             @tocheck = @items;
 8184:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8185:                                 my $curr_sub = shift(@tocheck);
 8186:                                 my $digit;
 8187:                                 if ($curr_sub =~ /^[A-J]$/) {
 8188:                                     $digit = $lettdig->{$curr_sub}-1;
 8189:                                 }
 8190:                                 if ($curr_sub eq 'J') {
 8191:                                     $digit += scalar($numletts);
 8192:                                 }
 8193:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8194:                                     if ($j == $digit) {
 8195:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8196:                                     } else {
 8197:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8198:                                     }
 8199:                                 }
 8200:                             }
 8201:                         }
 8202:                     }
 8203:                 }
 8204:             }
 8205:         }
 8206:         foreach my $part_id (@{$partids}) {
 8207:             if ($recorded{$part_id} eq '') {
 8208:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8209:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8210:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8211:                     }
 8212:                 }
 8213:             }
 8214:             $record .= $recorded{$part_id};
 8215:         }
 8216:     }
 8217:     return ($counter,$record);
 8218: }
 8219: 
 8220: sub letter_to_digits { 
 8221:     my %lettdig = (
 8222:                     A => 1,
 8223:                     B => 2,
 8224:                     C => 3,
 8225:                     D => 4,
 8226:                     E => 5,
 8227:                     F => 6,
 8228:                     G => 7,
 8229:                     H => 8,
 8230:                     I => 9,
 8231:                     J => 0,
 8232:                   );
 8233:     return %lettdig;
 8234: }
 8235: 
 8236: 
 8237: #-------- end of section for handling grading scantron forms -------
 8238: #
 8239: #-------------------------------------------------------------------
 8240: 
 8241: #-------------------------- Menu interface -------------------------
 8242: #
 8243: #--- Show a Grading Menu button - Calls the next routine ---
 8244: sub show_grading_menu_form {
 8245:     my ($symb)=@_;
 8246:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8247: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8248: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8249: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8250: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8251: 	'</form>'."\n";
 8252:     return $result;
 8253: }
 8254: 
 8255: # -- Retrieve choices for grading form
 8256: sub savedState {
 8257:     my %savedState = ();
 8258:     if ($env{'form.saveState'}) {
 8259: 	foreach (split(/:/,$env{'form.saveState'})) {
 8260: 	    my ($key,$value) = split(/=/,$_,2);
 8261: 	    $savedState{$key} = $value;
 8262: 	}
 8263:     }
 8264:     return \%savedState;
 8265: }
 8266: 
 8267: sub grading_menu {
 8268:     my ($request) = @_;
 8269:     my ($symb)=&get_symb($request);
 8270:     if (!$symb) {return '';}
 8271:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8272:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8273: 
 8274:     $request->print($table);
 8275:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8276:                   'handgrade'=>$hdgrade,
 8277:                   'probTitle'=>$probTitle,
 8278:                   'command'=>'submit_options',
 8279:                   'saveState'=>"",
 8280:                   'gradingMenu'=>1,
 8281:                   'showgrading'=>"yes");
 8282:     
 8283:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8284:     
 8285:     $fields{'command'} = 'csvform';
 8286:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8287:     
 8288:     $fields{'command'} = 'processclicker';
 8289:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8290:     
 8291:     $fields{'command'} = 'scantron_selectphase';
 8292:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8293:     
 8294:     my @menu = ({	categorytitle=>'Course Grading',
 8295:             items =>[
 8296:                         {	linktext => 'Manual Grading/View Submissions',
 8297:                     		url => $url1,
 8298:                     		permission => 'F',
 8299:                     		icon => 'edit-find-replace.png',
 8300:                     		linktitle => 'Start the process of hand grading submissions.'
 8301:                         },
 8302:                 	    {	linktext => 'Upload Scores',
 8303:                     		url => $url2,
 8304:                     		permission => 'F',
 8305:                     		icon => 'uploadscores.png',
 8306:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8307:                 	    },
 8308:                 	    {	linktext => 'Process Clicker',
 8309:                     		url => $url3,
 8310:                     		permission => 'F',
 8311:                     		icon => 'addClickerInfoFile.png',
 8312:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8313:                 	    },
 8314:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
 8315:                     		url => $url4,
 8316:                     		permission => 'F',
 8317:                     		icon => 'stat.png',
 8318:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8319:                 	    }
 8320:                     ]
 8321:             });
 8322: 
 8323:     #$fields{'command'} = 'verify';
 8324:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8325:     #
 8326:     # Create the menu
 8327:     my $Str;
 8328:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8329:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8330:     $Str .= '<input type="hidden" name="command" value="" />'.
 8331:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8332: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8333: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8334: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8335: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8336: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8337: 
 8338:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8339:     #$menudata->{'jscript'}
 8340:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8341:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8342:         ' /> '.
 8343:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8344:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8345: 
 8346:     $Str .="</form>\n";
 8347:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8348:     $request->print(<<GRADINGMENUJS);
 8349: <script type="text/javascript" language="javascript">
 8350:     function checkChoice(formname,val,cmdx) {
 8351: 	if (val <= 2) {
 8352: 	    var cmd = radioSelection(formname.radioChoice);
 8353: 	    var cmdsave = cmd;
 8354: 	} else {
 8355: 	    cmd = cmdx;
 8356: 	    cmdsave = 'submission';
 8357: 	}
 8358: 	formname.command.value = cmd;
 8359: 	if (val < 5) formname.submit();
 8360: 	if (val == 5) {
 8361: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8362: 	        return false;
 8363: 	    } else {
 8364: 	        formname.submit();
 8365: 	    }
 8366: 	}
 8367:     }
 8368: 
 8369:     function checkReceiptNo(formname,nospace) {
 8370: 	var receiptNo = formname.receipt.value;
 8371: 	var checkOpt = false;
 8372: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8373: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8374: 	if (checkOpt) {
 8375: 	    alert("$receiptalert");
 8376: 	    formname.receipt.value = "";
 8377: 	    formname.receipt.focus();
 8378: 	    return false;
 8379: 	}
 8380: 	return true;
 8381:     }
 8382: </script>
 8383: GRADINGMENUJS
 8384:     &commonJSfunctions($request);
 8385:     return $Str;    
 8386: }
 8387: 
 8388: 
 8389: #--- Displays the submissions first page -------
 8390: sub submit_options {
 8391:     my ($request) = @_;
 8392:     my ($symb)=&get_symb($request);
 8393:     if (!$symb) {return '';}
 8394:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8395: 
 8396:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8397:     $request->print(<<GRADINGMENUJS);
 8398: <script type="text/javascript" language="javascript">
 8399:     function checkChoice(formname,val,cmdx) {
 8400: 	if (val <= 2) {
 8401: 	    var cmd = radioSelection(formname.radioChoice);
 8402: 	    var cmdsave = cmd;
 8403: 	} else {
 8404: 	    cmd = cmdx;
 8405: 	    cmdsave = 'submission';
 8406: 	}
 8407: 	formname.command.value = cmd;
 8408: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8409: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8410: 	if (val < 5) formname.submit();
 8411: 	if (val == 5) {
 8412: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8413: 	    formname.submit();
 8414: 	}
 8415: 	if (val < 7) formname.submit();
 8416:     }
 8417: 
 8418:     function checkReceiptNo(formname,nospace) {
 8419: 	var receiptNo = formname.receipt.value;
 8420: 	var checkOpt = false;
 8421: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8422: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8423: 	if (checkOpt) {
 8424: 	    alert("$receiptalert");
 8425: 	    formname.receipt.value = "";
 8426: 	    formname.receipt.focus();
 8427: 	    return false;
 8428: 	}
 8429: 	return true;
 8430:     }
 8431: </script>
 8432: GRADINGMENUJS
 8433:     &commonJSfunctions($request);
 8434:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8435:     my $result;
 8436:     my (undef,$sections) = &getclasslist('all','0');
 8437:     my $savedState = &savedState();
 8438:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8439:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8440:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8441:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8442: 
 8443:     # Preselect sections
 8444:     my $selsec="";
 8445:     if (ref($sections)) {
 8446:         foreach my $section (sort(@$sections)) {
 8447:             $selsec.='<option value="'.$section.'" '.
 8448:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8449:         }
 8450:     }
 8451: 
 8452:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8453: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8454: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8455: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8456: 	'<input type="hidden" name="command"     value="" />'."\n".
 8457: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8458: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8459: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8460: 
 8461:     $result.='
 8462: <h2>
 8463:   '.&mt('Grade Current Resource').'
 8464: </h2>
 8465: <div>
 8466:   '.$table.'
 8467: </div>
 8468: 
 8469: <div class="LC_columnSection">
 8470:   
 8471:     <fieldset>
 8472:       <legend>
 8473:        '.&mt('Sections').'
 8474:       </legend>
 8475:       <select name="section" multiple="multiple" size="5">'."\n";
 8476:     $result.= $selsec;
 8477:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8478:     $result.='
 8479:     </fieldset>
 8480:   
 8481:     <fieldset>
 8482:       <legend>
 8483:         '.&mt('Groups').'
 8484:       </legend>
 8485:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8486:     </fieldset>
 8487:   
 8488:     <fieldset>
 8489:       <legend>
 8490:         '.&mt('Access Status').'
 8491:       </legend>
 8492:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8493:     </fieldset>
 8494:   
 8495:     <fieldset>
 8496:       <legend>
 8497:         '.&mt('Submission Status').'
 8498:       </legend>
 8499:       <select name="submitonly" size="5">
 8500: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8501: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8502: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8503: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8504:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8505:       </select>
 8506:     </fieldset>
 8507:   
 8508: </div>
 8509: 
 8510: <br />
 8511:           <div>
 8512:             <div>
 8513:               <label>
 8514:                 <input type="radio" name="radioChoice" value="submission" '.
 8515:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8516:              &mt('Select individual students to grade and view submissions.').'
 8517: 	      </label> 
 8518:             </div>
 8519:             <div>
 8520: 	      <label>
 8521:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8522:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8523:                     &mt('Grade all selected students in a grading table.').'
 8524:               </label>
 8525:             </div>
 8526:             <div>
 8527: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8528:             </div>
 8529:           </div>
 8530: 
 8531: 
 8532:         <h2>
 8533:          '.&mt('Grade Complete Folder for One Student').'
 8534:         </h2>
 8535:         <div>
 8536:             <div>
 8537:               <label>
 8538:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8539: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8540:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8541:               </label>
 8542:             </div>
 8543:             <div>
 8544: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8545:             </div>
 8546:         </div>
 8547:   </form>';
 8548:     $result .= &show_grading_menu_form($symb);
 8549:     return $result;
 8550: }
 8551: 
 8552: sub reset_perm {
 8553:     undef(%perm);
 8554: }
 8555: 
 8556: sub init_perm {
 8557:     &reset_perm();
 8558:     foreach my $test_perm ('vgr','mgr','opa') {
 8559: 
 8560: 	my $scope = $env{'request.course.id'};
 8561: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8562: 
 8563: 	    $scope .= '/'.$env{'request.course.sec'};
 8564: 	    if ( $perm{$test_perm}=
 8565: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8566: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8567: 	    } else {
 8568: 		delete($perm{$test_perm});
 8569: 	    }
 8570: 	}
 8571:     }
 8572: }
 8573: 
 8574: sub gather_clicker_ids {
 8575:     my %clicker_ids;
 8576: 
 8577:     my $classlist = &Apache::loncoursedata::get_classlist();
 8578: 
 8579:     # Set up a couple variables.
 8580:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8581:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8582:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8583: 
 8584:     foreach my $student (keys(%$classlist)) {
 8585:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8586:         my $username = $classlist->{$student}->[$username_idx];
 8587:         my $domain   = $classlist->{$student}->[$domain_idx];
 8588:         my $clickers =
 8589: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8590:         foreach my $id (split(/\,/,$clickers)) {
 8591:             $id=~s/^[\#0]+//;
 8592:             $id=~s/[\-\:]//g;
 8593:             if (exists($clicker_ids{$id})) {
 8594: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8595:             } else {
 8596: 		$clicker_ids{$id}=$username.':'.$domain;
 8597:             }
 8598:         }
 8599:     }
 8600:     return %clicker_ids;
 8601: }
 8602: 
 8603: sub gather_adv_clicker_ids {
 8604:     my %clicker_ids;
 8605:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8606:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8607:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8608:     foreach my $element (sort(keys(%coursepersonnel))) {
 8609:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8610:             my ($puname,$pudom)=split(/\:/,$person);
 8611:             my $clickers =
 8612: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8613:             foreach my $id (split(/\,/,$clickers)) {
 8614: 		$id=~s/^[\#0]+//;
 8615:                 $id=~s/[\-\:]//g;
 8616: 		if (exists($clicker_ids{$id})) {
 8617: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8618: 		} else {
 8619: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8620: 		}
 8621:             }
 8622:         }
 8623:     }
 8624:     return %clicker_ids;
 8625: }
 8626: 
 8627: sub clicker_grading_parameters {
 8628:     return ('gradingmechanism' => 'scalar',
 8629:             'upfiletype' => 'scalar',
 8630:             'specificid' => 'scalar',
 8631:             'pcorrect' => 'scalar',
 8632:             'pincorrect' => 'scalar');
 8633: }
 8634: 
 8635: sub process_clicker {
 8636:     my ($r)=@_;
 8637:     my ($symb)=&get_symb($r);
 8638:     if (!$symb) {return '';}
 8639:     my $result=&checkforfile_js();
 8640:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8641:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8642:     $result.=$table;
 8643:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8644:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8645:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8646:         '</b></td></tr>'."\n";
 8647:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8648: # Attempt to restore parameters from last session, set defaults if not present
 8649:     my %Saveable_Parameters=&clicker_grading_parameters();
 8650:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8651:                                                  \%Saveable_Parameters);
 8652:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8653:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8654:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8655:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8656: 
 8657:     my %checked;
 8658:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8659:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8660:           $checked{$gradingmechanism}=' checked="checked"';
 8661:        }
 8662:     }
 8663: 
 8664:     my $upload=&mt("Upload File");
 8665:     my $type=&mt("Type");
 8666:     my $attendance=&mt("Award points just for participation");
 8667:     my $personnel=&mt("Correctness determined from response by course personnel");
 8668:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8669:     my $given=&mt("Correctness determined from given list of answers").' '.
 8670:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8671:     my $pcorrect=&mt("Percentage points for correct solution");
 8672:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8673:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8674: 						   ('iclicker' => 'i>clicker',
 8675:                                                     'interwrite' => 'interwrite PRS'));
 8676:     $symb = &Apache::lonenc::check_encrypt($symb);
 8677:     $result.=<<ENDUPFORM;
 8678: <script type="text/javascript">
 8679: function sanitycheck() {
 8680: // Accept only integer percentages
 8681:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8682:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8683: // Find out grading choice
 8684:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8685:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8686:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8687:       }
 8688:    }
 8689: // By default, new choice equals user selection
 8690:    newgradingchoice=gradingchoice;
 8691: // Not good to give more points for false answers than correct ones
 8692:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8693:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8694:    }
 8695: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8696:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8697:       document.forms.gradesupload.pcorrect.value=100;
 8698:       document.forms.gradesupload.pincorrect.value=100;
 8699:    }
 8700: // If the values are different, cannot be attendance only
 8701:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8702:        (gradingchoice=='attendance')) {
 8703:        newgradingchoice='personnel';
 8704:    }
 8705: // Change grading choice to new one
 8706:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8707:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8708:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8709:       } else {
 8710:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8711:       }
 8712:    }
 8713: // Remember the old state
 8714:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8715: }
 8716: </script>
 8717: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8718: <input type="hidden" name="symb" value="$symb" />
 8719: <input type="hidden" name="command" value="processclickerfile" />
 8720: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8721: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8722: <input type="file" name="upfile" size="50" />
 8723: <br /><label>$type: $selectform</label>
 8724: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8725: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8726: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8727: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8728: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
 8729: <br />&nbsp;&nbsp;&nbsp;
 8730: <input type="text" name="givenanswer" size="50" />
 8731: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8732: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8733: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8734: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8735: </form>
 8736: ENDUPFORM
 8737:     $result.='</td></tr></table>'."\n".
 8738:              '</td></tr></table><br /><br />'."\n";
 8739:     $result.=&show_grading_menu_form($symb);
 8740:     return $result;
 8741: }
 8742: 
 8743: sub process_clicker_file {
 8744:     my ($r)=@_;
 8745:     my ($symb)=&get_symb($r);
 8746:     if (!$symb) {return '';}
 8747: 
 8748:     my %Saveable_Parameters=&clicker_grading_parameters();
 8749:     &Apache::loncommon::store_course_settings('grades_clicker',
 8750:                                               \%Saveable_Parameters);
 8751: 
 8752:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8753:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8754: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8755: 	return $result.&show_grading_menu_form($symb);
 8756:     }
 8757:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8758:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8759:         return $result.&show_grading_menu_form($symb);
 8760:     }
 8761:     my $foundgiven=0;
 8762:     if ($env{'form.gradingmechanism'} eq 'given') {
 8763:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8764:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8765:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8766:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8767:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8768:         $foundgiven=$#answers+1;
 8769:     }
 8770:     my %clicker_ids=&gather_clicker_ids();
 8771:     my %correct_ids;
 8772:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8773: 	%correct_ids=&gather_adv_clicker_ids();
 8774:     }
 8775:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8776: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8777: 	   $correct_id=~tr/a-z/A-Z/;
 8778: 	   $correct_id=~s/\s//gs;
 8779: 	   $correct_id=~s/^[\#0]+//;
 8780:            $correct_id=~s/[\-\:]//g;
 8781:            if ($correct_id) {
 8782: 	      $correct_ids{$correct_id}='specified';
 8783:            }
 8784:         }
 8785:     }
 8786:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8787: 	$result.=&mt('Score based on attendance only');
 8788:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8789:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8790:     } else {
 8791: 	my $number=0;
 8792: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8793: 	foreach my $id (sort(keys(%correct_ids))) {
 8794: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8795: 	    if ($correct_ids{$id} eq 'specified') {
 8796: 		$result.=&mt('specified');
 8797: 	    } else {
 8798: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8799: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8800: 	    }
 8801: 	    $number++;
 8802: 	}
 8803:         $result.="</p>\n";
 8804: 	if ($number==0) {
 8805: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8806: 	    return $result.&show_grading_menu_form($symb);
 8807: 	}
 8808:     }
 8809:     if (length($env{'form.upfile'}) < 2) {
 8810:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8811: 		     '<span class="LC_error">',
 8812: 		     '</span>',
 8813: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8814:         return $result.&show_grading_menu_form($symb);
 8815:     }
 8816: 
 8817: # Were able to get all the info needed, now analyze the file
 8818: 
 8819:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8820:     $symb = &Apache::lonenc::check_encrypt($symb);
 8821:     my $heading=&mt('Scanning clicker file');
 8822:     $result.=(<<ENDHEADER);
 8823: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8824: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8825: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8826: <form method="post" action="/adm/grades" name="clickeranalysis">
 8827: <input type="hidden" name="symb" value="$symb" />
 8828: <input type="hidden" name="command" value="assignclickergrades" />
 8829: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8830: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8831: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8832: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8833: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8834: ENDHEADER
 8835:     if ($env{'form.gradingmechanism'} eq 'given') {
 8836:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8837:     } 
 8838:     my %responses;
 8839:     my @questiontitles;
 8840:     my $errormsg='';
 8841:     my $number=0;
 8842:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8843: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8844:     }
 8845:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8846:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8847:     }
 8848:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8849:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8850:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8851:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8852:              '<br />';
 8853:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8854:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8855:        return $result.&show_grading_menu_form($symb);
 8856:     } 
 8857: # Remember Question Titles
 8858: # FIXME: Possibly need delimiter other than ":"
 8859:     for (my $i=0;$i<$number;$i++) {
 8860:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8861:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8862:     }
 8863:     my $correct_count=0;
 8864:     my $student_count=0;
 8865:     my $unknown_count=0;
 8866: # Match answers with usernames
 8867: # FIXME: Possibly need delimiter other than ":"
 8868:     foreach my $id (keys(%responses)) {
 8869:        if ($correct_ids{$id}) {
 8870:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8871:           $correct_count++;
 8872:        } elsif ($clicker_ids{$id}) {
 8873:           if ($clicker_ids{$id}=~/\,/) {
 8874: # More than one user with the same clicker!
 8875:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8876:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8877:                            "<select name='multi".$id."'>";
 8878:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8879:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8880:              }
 8881:              $result.='</select>';
 8882:              $unknown_count++;
 8883:           } else {
 8884: # Good: found one and only one user with the right clicker
 8885:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8886:              $student_count++;
 8887:           }
 8888:        } else {
 8889:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8890:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8891:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8892:                    "\n".&mt("Domain").": ".
 8893:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8894:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8895:           $unknown_count++;
 8896:        }
 8897:     }
 8898:     $result.='<hr />'.
 8899:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8900:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8901:        if ($correct_count==0) {
 8902:           $errormsg.="Found no correct answers answers for grading!";
 8903:        } elsif ($correct_count>1) {
 8904:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8905:        }
 8906:     }
 8907:     if ($number<1) {
 8908:        $errormsg.="Found no questions.";
 8909:     }
 8910:     if ($errormsg) {
 8911:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8912:     } else {
 8913:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8914:     }
 8915:     $result.='</form></td></tr></table>'."\n".
 8916:              '</td></tr></table><br /><br />'."\n";
 8917:     return $result.&show_grading_menu_form($symb);
 8918: }
 8919: 
 8920: sub iclicker_eval {
 8921:     my ($questiontitles,$responses)=@_;
 8922:     my $number=0;
 8923:     my $errormsg='';
 8924:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8925:         my %components=&Apache::loncommon::record_sep($line);
 8926:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8927: 	if ($entries[0] eq 'Question') {
 8928: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8929: 		$$questiontitles[$number]=$entries[$i];
 8930: 		$number++;
 8931: 	    }
 8932: 	}
 8933: 	if ($entries[0]=~/^\#/) {
 8934: 	    my $id=$entries[0];
 8935: 	    my @idresponses;
 8936: 	    $id=~s/^[\#0]+//;
 8937: 	    for (my $i=0;$i<$number;$i++) {
 8938: 		my $idx=3+$i*6;
 8939: 		push(@idresponses,$entries[$idx]);
 8940: 	    }
 8941: 	    $$responses{$id}=join(',',@idresponses);
 8942: 	}
 8943:     }
 8944:     return ($errormsg,$number);
 8945: }
 8946: 
 8947: sub interwrite_eval {
 8948:     my ($questiontitles,$responses)=@_;
 8949:     my $number=0;
 8950:     my $errormsg='';
 8951:     my $skipline=1;
 8952:     my $questionnumber=0;
 8953:     my %idresponses=();
 8954:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8955:         my %components=&Apache::loncommon::record_sep($line);
 8956:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8957:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8958:         if ($entries[1] eq 'Response') { $skipline=1; }
 8959:         next if $skipline;
 8960:         if ($entries[0]!=$questionnumber) {
 8961:            $questionnumber=$entries[0];
 8962:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8963:            $number++;
 8964:         }
 8965:         my $id=$entries[4];
 8966:         $id=~s/^[\#0]+//;
 8967:         $id=~s/^v\d*\://i;
 8968:         $id=~s/[\-\:]//g;
 8969:         $idresponses{$id}[$number]=$entries[6];
 8970:     }
 8971:     foreach my $id (keys(%idresponses)) {
 8972:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8973:        $$responses{$id}=~s/^\s*\,//;
 8974:     }
 8975:     return ($errormsg,$number);
 8976: }
 8977: 
 8978: sub assign_clicker_grades {
 8979:     my ($r)=@_;
 8980:     my ($symb)=&get_symb($r);
 8981:     if (!$symb) {return '';}
 8982: # See which part we are saving to
 8983:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8984: # FIXME: This should probably look for the first handgradeable part
 8985:     my $part=$$partlist[0];
 8986: # Start screen output
 8987:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8988: 
 8989:     my $heading=&mt('Assigning grades based on clicker file');
 8990:     $result.=(<<ENDHEADER);
 8991: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8992: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8993: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8994: ENDHEADER
 8995: # Get correct result
 8996: # FIXME: Possibly need delimiter other than ":"
 8997:     my @correct=();
 8998:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8999:     my $number=$env{'form.number'};
 9000:     if ($gradingmechanism ne 'attendance') {
 9001:        foreach my $key (keys(%env)) {
 9002:           if ($key=~/^form\.correct\:/) {
 9003:              my @input=split(/\,/,$env{$key});
 9004:              for (my $i=0;$i<=$#input;$i++) {
 9005:                  if (($correct[$i]) && ($input[$i]) &&
 9006:                      ($correct[$i] ne $input[$i])) {
 9007:                     $result.='<br /><span class="LC_warning">'.
 9008:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9009:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9010:                  } elsif ($input[$i]) {
 9011:                     $correct[$i]=$input[$i];
 9012:                  }
 9013:              }
 9014:           }
 9015:        }
 9016:        for (my $i=0;$i<$number;$i++) {
 9017:           if (!$correct[$i]) {
 9018:              $result.='<br /><span class="LC_error">'.
 9019:                       &mt('No correct result given for question "[_1]"!',
 9020:                           $env{'form.question:'.$i}).'</span>';
 9021:           }
 9022:        }
 9023:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9024:     }
 9025: # Start grading
 9026:     my $pcorrect=$env{'form.pcorrect'};
 9027:     my $pincorrect=$env{'form.pincorrect'};
 9028:     my $storecount=0;
 9029:     foreach my $key (keys(%env)) {
 9030:        my $user='';
 9031:        if ($key=~/^form\.student\:(.*)$/) {
 9032:           $user=$1;
 9033:        }
 9034:        if ($key=~/^form\.unknown\:(.*)$/) {
 9035:           my $id=$1;
 9036:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9037:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9038:           } elsif ($env{'form.multi'.$id}) {
 9039:              $user=$env{'form.multi'.$id};
 9040:           }
 9041:        }
 9042:        if ($user) { 
 9043:           my @answer=split(/\,/,$env{$key});
 9044:           my $sum=0;
 9045:           my $realnumber=$number;
 9046:           for (my $i=0;$i<$number;$i++) {
 9047:              if ($answer[$i]) {
 9048:                 if ($gradingmechanism eq 'attendance') {
 9049:                    $sum+=$pcorrect;
 9050:                 } elsif ($answer[$i] eq '*') {
 9051:                    $sum+=$pcorrect;
 9052:                 } elsif ($answer[$i] eq '-') {
 9053:                    $realnumber--;
 9054:                 } else {
 9055:                    if ($answer[$i] eq $correct[$i]) {
 9056:                       $sum+=$pcorrect;
 9057:                    } else {
 9058:                       $sum+=$pincorrect;
 9059:                    }
 9060:                 }
 9061:              }
 9062:           }
 9063:           my $ave=$sum/(100*$realnumber);
 9064: # Store
 9065:           my ($username,$domain)=split(/\:/,$user);
 9066:           my %grades=();
 9067:           $grades{"resource.$part.solved"}='correct_by_override';
 9068:           $grades{"resource.$part.awarded"}=$ave;
 9069:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9070:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9071:                                                  $env{'request.course.id'},
 9072:                                                  $domain,$username);
 9073:           if ($returncode ne 'ok') {
 9074:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9075:           } else {
 9076:              $storecount++;
 9077:           }
 9078:        }
 9079:     }
 9080: # We are done
 9081:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9082:              '</td></tr></table>'."\n".
 9083:              '</td></tr></table><br /><br />'."\n";
 9084:     return $result.&show_grading_menu_form($symb);
 9085: }
 9086: 
 9087: sub handler {
 9088:     my $request=$_[0];
 9089:     &reset_caches();
 9090:     if ($env{'browser.mathml'}) {
 9091: 	&Apache::loncommon::content_type($request,'text/xml');
 9092:     } else {
 9093: 	&Apache::loncommon::content_type($request,'text/html');
 9094:     }
 9095:     $request->send_http_header;
 9096:     return '' if $request->header_only;
 9097:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9098:     my $symb=&get_symb($request,1);
 9099:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9100:     my $command=$commands[0];
 9101: 
 9102:     if ($#commands > 0) {
 9103: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9104:     }
 9105: 
 9106:     $ssi_error = 0;
 9107:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9108:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9109:                                           {'bread_crumbs' => $brcrum}));
 9110:     if ($symb eq '' && $command eq '') {
 9111: 	if ($env{'user.adv'}) {
 9112: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9113: 		($env{'form.codethree'})) {
 9114: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9115: 		    $env{'form.codethree'};
 9116: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9117: 		    &Apache::lonnet::checkin($token);
 9118: 		if ($tsymb) {
 9119: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9120: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9121: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9122: 					  ('grade_username' => $tuname,
 9123: 					   'grade_domain' => $tudom,
 9124: 					   'grade_courseid' => $tcrsid,
 9125: 					   'grade_symb' => $tsymb)));
 9126: 		    } else {
 9127: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9128: 		    }
 9129: 		} else {
 9130: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9131: 		}
 9132: 	    } else {
 9133: 		$request->print(&Apache::lonxml::tokeninputfield());
 9134: 	    }
 9135: 	}
 9136:     } else {
 9137: 	&init_perm();
 9138: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9139: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9140: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9141: 	    &pickStudentPage($request);
 9142: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9143: 	    &displayPage($request);
 9144: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9145: 	    &updateGradeByPage($request);
 9146: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9147: 	    &processGroup($request);
 9148: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9149: 	    $request->print(&grading_menu($request));
 9150: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9151: 	    $request->print(&submit_options($request));
 9152: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9153: 	    $request->print(&viewgrades($request));
 9154: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9155: 	    $request->print(&processHandGrade($request));
 9156: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9157: 	    $request->print(&editgrades($request));
 9158: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9159: 	    $request->print(&verifyreceipt($request));
 9160:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9161:             $request->print(&process_clicker($request));
 9162:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9163:             $request->print(&process_clicker_file($request));
 9164:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9165:             $request->print(&assign_clicker_grades($request));
 9166: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9167: 	    $request->print(&upcsvScores_form($request));
 9168: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9169: 	    $request->print(&csvupload($request));
 9170: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9171: 	    $request->print(&csvuploadmap($request));
 9172: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9173: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9174: 		$request->print(&csvuploadoptions($request));
 9175: 	    } else {
 9176: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9177: 		    $env{'form.upfile_associate'} = 'reverse';
 9178: 		} else {
 9179: 		    $env{'form.upfile_associate'} = 'forward';
 9180: 		}
 9181: 		$request->print(&csvuploadmap($request));
 9182: 	    }
 9183: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9184: 	    $request->print(&csvuploadassign($request));
 9185: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9186: 	    $request->print(&scantron_selectphase($request));
 9187:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9188:  	    $request->print(&scantron_do_warning($request));
 9189: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9190: 	    $request->print(&scantron_validate_file($request));
 9191: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9192: 	    $request->print(&scantron_process_students($request));
 9193:  	} elsif ($command eq 'scantronupload' && 
 9194:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9195: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9196:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9197:  	} elsif ($command eq 'scantronupload_save' &&
 9198:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9199: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9200:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9201:  	} elsif ($command eq 'scantron_download' &&
 9202: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9203:  	    $request->print(&scantron_download_scantron_data($request));
 9204:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9205:             $request->print(&checkscantron_results($request));     
 9206: 	} elsif ($command) {
 9207: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9208: 	}
 9209:     }
 9210:     if ($ssi_error) {
 9211: 	&ssi_print_error($request);
 9212:     }
 9213:     $request->print(&Apache::loncommon::end_page());
 9214:     &reset_caches();
 9215:     return '';
 9216: }
 9217: 
 9218: 1;
 9219: 
 9220: __END__;
 9221: 
 9222: 
 9223: =head1 NAME
 9224: 
 9225: Apache::grades
 9226: 
 9227: =head1 SYNOPSIS
 9228: 
 9229: Handles the viewing of grades.
 9230: 
 9231: This is part of the LearningOnline Network with CAPA project
 9232: described at http://www.lon-capa.org.
 9233: 
 9234: =head1 OVERVIEW
 9235: 
 9236: Do an ssi with retries:
 9237: While I'd love to factor out this with the vesrion in lonprintout,
 9238: 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
 9239: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9240: 
 9241: At least the logic that drives this has been pulled out into loncommon.
 9242: 
 9243: 
 9244: 
 9245: ssi_with_retries - Does the server side include of a resource.
 9246:                      if the ssi call returns an error we'll retry it up to
 9247:                      the number of times requested by the caller.
 9248:                      If we still have a proble, no text is appended to the
 9249:                      output and we set some global variables.
 9250:                      to indicate to the caller an SSI error occurred.  
 9251:                      All of this is supposed to deal with the issues described
 9252:                      in LonCAPA BZ 5631 see:
 9253:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9254:                      by informing the user that this happened.
 9255: 
 9256: Parameters:
 9257:   resource   - The resource to include.  This is passed directly, without
 9258:                interpretation to lonnet::ssi.
 9259:   form       - The form hash parameters that guide the interpretation of the resource
 9260:                
 9261:   retries    - Number of retries allowed before giving up completely.
 9262: Returns:
 9263:   On success, returns the rendered resource identified by the resource parameter.
 9264: Side Effects:
 9265:   The following global variables can be set:
 9266:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9267:                               It is up to the caller to initialize this to false
 9268:                               if desired.
 9269:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9270:                               of the resource that could not be rendered by the ssi
 9271:                               call.
 9272:    ssi_error_message   - The error string fetched from the ssi response
 9273:                               in the event of an error.
 9274: 
 9275: 
 9276: =head1 HANDLER SUBROUTINE
 9277: 
 9278: ssi_with_retries()
 9279: 
 9280: =head1 SUBROUTINES
 9281: 
 9282: =over
 9283: 
 9284: =item scantron_get_correction() : 
 9285: 
 9286:    Builds the interface screen to interact with the operator to fix a
 9287:    specific error condition in a specific scanline
 9288: 
 9289:  Arguments:
 9290:     $r           - Apache request object
 9291:     $i           - number of the current scanline
 9292:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9293:     $scan_config - hash ref as returned from &get_scantron_config()
 9294:     $line        - full contents of the current scanline
 9295:     $error       - error condition, valid values are
 9296:                    'incorrectCODE', 'duplicateCODE',
 9297:                    'doublebubble', 'missingbubble',
 9298:                    'duplicateID', 'incorrectID'
 9299:     $arg         - extra information needed
 9300:        For errors:
 9301:          - duplicateID   - paper number that this studentID was seen before on
 9302:          - duplicateCODE - array ref of the paper numbers this CODE was
 9303:                            seen on before
 9304:          - incorrectCODE - current incorrect CODE 
 9305:          - doublebubble  - array ref of the bubble lines that have double
 9306:                            bubble errors
 9307:          - missingbubble - array ref of the bubble lines that have missing
 9308:                            bubble errors
 9309: 
 9310: =item  scantron_get_maxbubble() : 
 9311: 
 9312:    Returns the maximum number of bubble lines that are expected to
 9313:    occur. Does this by walking the selected sequence rendering the
 9314:    resource and then checking &Apache::lonxml::get_problem_counter()
 9315:    for what the current value of the problem counter is.
 9316: 
 9317:    Caches the results to $env{'form.scantron_maxbubble'},
 9318:    $env{'form.scantron.bubble_lines.n'}, 
 9319:    $env{'form.scantron.first_bubble_line.n'} and
 9320:    $env{"form.scantron.sub_bubblelines.n"}
 9321:    which are the total number of bubble, lines, the number of bubble
 9322:    lines for response n and number of the first bubble line for response n,
 9323:    and a comma separated list of numbers of bubble lines for sub-questions
 9324:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9325: 
 9326: 
 9327: =item  scantron_validate_missingbubbles() : 
 9328: 
 9329:    Validates all scanlines in the selected file to not have any
 9330:     answers that don't have bubbles that have not been verified
 9331:     to be bubble free.
 9332: 
 9333: =item  scantron_process_students() : 
 9334: 
 9335:    Routine that does the actual grading of the bubble sheet information.
 9336: 
 9337:    The parsed scanline hash is added to %env 
 9338: 
 9339:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9340:    foreach resource , with the form data of
 9341: 
 9342: 	'submitted'     =>'scantron' 
 9343: 	'grade_target'  =>'grade',
 9344: 	'grade_username'=> username of student
 9345: 	'grade_domain'  => domain of student
 9346: 	'grade_courseid'=> of course
 9347: 	'grade_symb'    => symb of resource to grade
 9348: 
 9349:     This triggers a grading pass. The problem grading code takes care
 9350:     of converting the bubbled letter information (now in %env) into a
 9351:     valid submission.
 9352: 
 9353: =item  scantron_upload_scantron_data() :
 9354: 
 9355:     Creates the screen for adding a new bubble sheet data file to a course.
 9356: 
 9357: =item  scantron_upload_scantron_data_save() : 
 9358: 
 9359:    Adds a provided bubble information data file to the course if user
 9360:    has the correct privileges to do so. 
 9361: 
 9362: =item  valid_file() :
 9363: 
 9364:    Validates that the requested bubble data file exists in the course.
 9365: 
 9366: =item  scantron_download_scantron_data() : 
 9367: 
 9368:    Shows a list of the three internal files (original, corrected,
 9369:    skipped) for a specific bubble sheet data file that exists in the
 9370:    course.
 9371: 
 9372: =item  scantron_validate_ID() : 
 9373: 
 9374:    Validates all scanlines in the selected file to not have any
 9375:    invalid or underspecified student/employee IDs
 9376: 
 9377: =back
 9378: 
 9379: =cut

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