File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.559: download - view: text, annotated - select for diffs
Thu Mar 19 19:09:47 2009 UTC (15 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Revert part of rev. 1.539. &mt() not required (Apache::lonlocal::texthash() already in use).

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.559 2009/03/19 19:09:47 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   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 .= 
  893: 	'&nbsp;<b>'.&mt('View Problem Text').': </b>'.
  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:     $gradeTable .= 
  898: 	'&nbsp;<b>'.&mt('View Answer').': </b>'.
  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: 
  903:     my $submission_options;
  904:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  905: 	$submission_options.=
  906: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  907:     }
  908:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  909:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  910:     $env{'form.Status'} = $saveStatus;
  911:     $submission_options.=
  912: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  913: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  914: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  915: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  916:     $gradeTable .= 
  917: 	'&nbsp;<b>'.&mt('Submissions').': </b>'.$submission_options.'<br />'."\n";
  918: 
  919:     $gradeTable .= 
  920:         '&nbsp;<b>'.&mt('Grading Increments').': </b>'.
  921: 	    '<select name="increment">'.
  922: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  923: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  924: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  925: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  926: 	    '</select>';
  927:     
  928:     $gradeTable .= 
  929:         &build_section_inputs().
  930: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  931: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  932: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  933: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  934: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  935: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  936: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  937: 
  938:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  939: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  940:     } else {
  941: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  942: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  943:     }
  944: 
  945:     $gradeTable.=&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.").'<br />'."\n".
  946: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  947: 
  948: # checkall buttons
  949:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  950:     $gradeTable.='<input type="button" '."\n".
  951: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  952: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  953:     $gradeTable.=&check_buttons();
  954:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  955:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  956:     $gradeTable.= &Apache::loncommon::start_data_table().
  957: 	&Apache::loncommon::start_data_table_header_row();
  958:     my $loop = 0;
  959:     while ($loop < 2) {
  960: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  961: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  962: 	if ($env{'form.showgrading'} eq 'yes' 
  963: 	    && $submitonly ne 'queued'
  964: 	    && $submitonly ne 'all') {
  965: 	    foreach my $part (sort(@$partlist)) {
  966: 		my $display_part=
  967: 		    &get_display_part((split(/_/,$part))[0],$symb);
  968: 		$gradeTable.=
  969: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  970: 	    }
  971: 	} elsif ($submitonly eq 'queued') {
  972: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  973: 	}
  974: 	$loop++;
  975: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  976:     }
  977:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  978: 
  979:     my $ctr = 0;
  980:     foreach my $student (sort 
  981: 			 {
  982: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  983: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  984: 			     }
  985: 			     return $a cmp $b;
  986: 			 }
  987: 			 (keys(%$fullname))) {
  988: 	my ($uname,$udom) = split(/:/,$student);
  989: 
  990: 	my %status = ();
  991: 
  992: 	if ($submitonly eq 'queued') {
  993: 	    my %queue_status = 
  994: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  995: 							$udom,$uname);
  996: 	    next if (!defined($queue_status{'gradingqueue'}));
  997: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  998: 	}
  999: 
 1000: 	if ($env{'form.showgrading'} eq 'yes' 
 1001: 	    && $submitonly ne 'queued'
 1002: 	    && $submitonly ne 'all') {
 1003: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1004: 	    my $submitted = 0;
 1005: 	    my $graded = 0;
 1006: 	    my $incorrect = 0;
 1007: 	    foreach (keys(%status)) {
 1008: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1009: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1010: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1011: 		
 1012: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1013: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1014: 		    $submitted = 0;
 1015: 		    my ($part)=split(/\./,$partid);
 1016: 		    $gradeTable.='<input type="hidden" name="'.
 1017: 			$student.':'.$part.':submitted_by" value="'.
 1018: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1019: 		}
 1020: 	    }
 1021: 	    
 1022: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1023: 				     $submitonly eq 'incorrect' ||
 1024: 				     $submitonly eq 'graded'));
 1025: 	    next if (!$graded && ($submitonly eq 'graded'));
 1026: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1027: 	}
 1028: 
 1029: 	$ctr++;
 1030: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1031:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1032: 	if ( $perm{'vgr'} eq 'F' ) {
 1033: 	    if ($ctr%2 ==1) {
 1034: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1035: 	    }
 1036: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1037:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1038:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1039: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1040: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1041: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1042: 
 1043: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1044: 		foreach (sort(keys(%status))) {
 1045: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1046: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1047: 		}
 1048: 	    }
 1049: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1050: 	    if ($ctr%2 ==0) {
 1051: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1052: 	    }
 1053: 	}
 1054:     }
 1055:     if ($ctr%2 ==1) {
 1056: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1057: 	    if ($env{'form.showgrading'} eq 'yes' 
 1058: 		&& $submitonly ne 'queued'
 1059: 		&& $submitonly ne 'all') {
 1060: 		foreach (@$partlist) {
 1061: 		    $gradeTable.='<td>&nbsp;</td>';
 1062: 		}
 1063: 	    } elsif ($submitonly eq 'queued') {
 1064: 		$gradeTable.='<td>&nbsp;</td>';
 1065: 	    }
 1066: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1067:     }
 1068: 
 1069:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1070: 	'<input type="button" '.
 1071: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1072: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1073:     if ($ctr == 0) {
 1074: 	my $num_students=(scalar(keys(%$fullname)));
 1075: 	if ($num_students eq 0) {
 1076: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1077: 	} else {
 1078: 	    my $submissions='submissions';
 1079: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1080: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1081: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1082: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1083: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1084: 		    $num_students).
 1085: 		'</span><br />';
 1086: 	}
 1087:     } elsif ($ctr == 1) {
 1088: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1089:     }
 1090:     $gradeTable.=&show_grading_menu_form($symb);
 1091:     $request->print($gradeTable);
 1092:     return '';
 1093: }
 1094: 
 1095: #---- Called from the listStudents routine
 1096: 
 1097: sub check_script {
 1098:     my ($form, $type)=@_;
 1099:     my $chkallscript='<script type="text/javascript">
 1100:     function checkall() {
 1101:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1102:             ele = document.forms.'.$form.'.elements[i];
 1103:             if (ele.name == "'.$type.'") {
 1104:             document.forms.'.$form.'.elements[i].checked=true;
 1105:                                        }
 1106:         }
 1107:     }
 1108: 
 1109:     function checksec() {
 1110:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1111:             ele = document.forms.'.$form.'.elements[i];
 1112:            string = document.forms.'.$form.'.chksec.value;
 1113:            if
 1114:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1115:               document.forms.'.$form.'.elements[i].checked=true;
 1116:             }
 1117:         }
 1118:     }
 1119: 
 1120: 
 1121:     function uncheckall() {
 1122:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1123:             ele = document.forms.'.$form.'.elements[i];
 1124:             if (ele.name == "'.$type.'") {
 1125:             document.forms.'.$form.'.elements[i].checked=false;
 1126:                                        }
 1127:         }
 1128:     }
 1129: 
 1130: </script>'."\n";
 1131:     return $chkallscript;
 1132: }
 1133: 
 1134: sub check_buttons {
 1135:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1136:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1137:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1138:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1139:     return $buttons;
 1140: }
 1141: 
 1142: #     Displays the submissions for one student or a group of students
 1143: sub processGroup {
 1144:     my ($request)  = shift;
 1145:     my $ctr        = 0;
 1146:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1147:     my $total      = scalar(@stuchecked)-1;
 1148: 
 1149:     foreach my $student (@stuchecked) {
 1150: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1151: 	$env{'form.student'}        = $uname;
 1152: 	$env{'form.userdom'}        = $udom;
 1153: 	$env{'form.fullname'}       = $fullname;
 1154: 	&submission($request,$ctr,$total);
 1155: 	$ctr++;
 1156:     }
 1157:     return '';
 1158: }
 1159: 
 1160: #------------------------------------------------------------------------------------
 1161: #
 1162: #-------------------------- Next few routines handles grading by student, essentially
 1163: #                           handles essay response type problem/part
 1164: #
 1165: #--- Javascript to handle the submission page functionality ---
 1166: sub sub_page_js {
 1167:     my $request = shift;
 1168: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1169:     $request->print(<<SUBJAVASCRIPT);
 1170: <script type="text/javascript" language="javascript">
 1171:     function updateRadio(formname,id,weight) {
 1172: 	var gradeBox = formname["GD_BOX"+id];
 1173: 	var radioButton = formname["RADVAL"+id];
 1174: 	var oldpts = formname["oldpts"+id].value;
 1175: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1176: 	gradeBox.value = pts;
 1177: 	var resetbox = false;
 1178: 	if (isNaN(pts) || pts < 0) {
 1179: 	    alert("$alertmsg"+pts);
 1180: 	    for (var i=0; i<radioButton.length; i++) {
 1181: 		if (radioButton[i].checked) {
 1182: 		    gradeBox.value = i;
 1183: 		    resetbox = true;
 1184: 		}
 1185: 	    }
 1186: 	    if (!resetbox) {
 1187: 		formtextbox.value = "";
 1188: 	    }
 1189: 	    return;
 1190: 	}
 1191: 
 1192: 	if (pts > weight) {
 1193: 	    var resp = confirm("You entered a value ("+pts+
 1194: 			       ") greater than the weight for the part. Accept?");
 1195: 	    if (resp == false) {
 1196: 		gradeBox.value = oldpts;
 1197: 		return;
 1198: 	    }
 1199: 	}
 1200: 
 1201: 	for (var i=0; i<radioButton.length; i++) {
 1202: 	    radioButton[i].checked=false;
 1203: 	    if (pts == i && pts != "") {
 1204: 		radioButton[i].checked=true;
 1205: 	    }
 1206: 	}
 1207: 	updateSelect(formname,id);
 1208: 	formname["stores"+id].value = "0";
 1209:     }
 1210: 
 1211:     function writeBox(formname,id,pts) {
 1212: 	var gradeBox = formname["GD_BOX"+id];
 1213: 	if (checkSolved(formname,id) == 'update') {
 1214: 	    gradeBox.value = pts;
 1215: 	} else {
 1216: 	    var oldpts = formname["oldpts"+id].value;
 1217: 	    gradeBox.value = oldpts;
 1218: 	    var radioButton = formname["RADVAL"+id];
 1219: 	    for (var i=0; i<radioButton.length; i++) {
 1220: 		radioButton[i].checked=false;
 1221: 		if (i == oldpts) {
 1222: 		    radioButton[i].checked=true;
 1223: 		}
 1224: 	    }
 1225: 	}
 1226: 	formname["stores"+id].value = "0";
 1227: 	updateSelect(formname,id);
 1228: 	return;
 1229:     }
 1230: 
 1231:     function clearRadBox(formname,id) {
 1232: 	if (checkSolved(formname,id) == 'noupdate') {
 1233: 	    updateSelect(formname,id);
 1234: 	    return;
 1235: 	}
 1236: 	gradeSelect = formname["GD_SEL"+id];
 1237: 	for (var i=0; i<gradeSelect.length; i++) {
 1238: 	    if (gradeSelect[i].selected) {
 1239: 		var selectx=i;
 1240: 	    }
 1241: 	}
 1242: 	var stores = formname["stores"+id];
 1243: 	if (selectx == stores.value) { return };
 1244: 	var gradeBox = formname["GD_BOX"+id];
 1245: 	gradeBox.value = "";
 1246: 	var radioButton = formname["RADVAL"+id];
 1247: 	for (var i=0; i<radioButton.length; i++) {
 1248: 	    radioButton[i].checked=false;
 1249: 	}
 1250: 	stores.value = selectx;
 1251:     }
 1252: 
 1253:     function checkSolved(formname,id) {
 1254: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1255: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1256: 	    if (!reply) {return "noupdate";}
 1257: 	    formname.overRideScore.value = 'yes';
 1258: 	}
 1259: 	return "update";
 1260:     }
 1261: 
 1262:     function updateSelect(formname,id) {
 1263: 	formname["GD_SEL"+id][0].selected = true;
 1264: 	return;
 1265:     }
 1266: 
 1267: //=========== Check that a point is assigned for all the parts  ============
 1268:     function checksubmit(formname,val,total,parttot) {
 1269: 	formname.gradeOpt.value = val;
 1270: 	if (val == "Save & Next") {
 1271: 	    for (i=0;i<=total;i++) {
 1272: 		for (j=0;j<parttot;j++) {
 1273: 		    var partid = formname["partid"+i+"_"+j].value;
 1274: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1275: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1276: 			if (points == "") {
 1277: 			    var name = formname["name"+i].value;
 1278: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1279: 			    var resp = confirm("You did not assign a score for "+studentID+
 1280: 					       ", part "+partid+". Continue?");
 1281: 			    if (resp == false) {
 1282: 				formname["GD_BOX"+i+"_"+partid].focus();
 1283: 				return false;
 1284: 			    }
 1285: 			}
 1286: 		    }
 1287: 		    
 1288: 		}
 1289: 	    }
 1290: 	    
 1291: 	}
 1292: 	if (val == "Grade Student") {
 1293: 	    formname.showgrading.value = "yes";
 1294: 	    if (formname.Status.value == "") {
 1295: 		formname.Status.value = "Active";
 1296: 	    }
 1297: 	    formname.studentNo.value = total;
 1298: 	}
 1299: 	formname.submit();
 1300:     }
 1301: 
 1302: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1303:     function checkSubmitPage(formname,total) {
 1304: 	noscore = new Array(100);
 1305: 	var ptr = 0;
 1306: 	for (i=1;i<total;i++) {
 1307: 	    var partid = formname["q_"+i].value;
 1308: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1309: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1310: 		var status = formname["solved"+i+"_"+partid].value;
 1311: 		if (points == "" && status != "correct_by_student") {
 1312: 		    noscore[ptr] = i;
 1313: 		    ptr++;
 1314: 		}
 1315: 	    }
 1316: 	}
 1317: 	if (ptr != 0) {
 1318: 	    var sense = ptr == 1 ? ": " : "s: ";
 1319: 	    var prolist = "";
 1320: 	    if (ptr == 1) {
 1321: 		prolist = noscore[0];
 1322: 	    } else {
 1323: 		var i = 0;
 1324: 		while (i < ptr-1) {
 1325: 		    prolist += noscore[i]+", ";
 1326: 		    i++;
 1327: 		}
 1328: 		prolist += "and "+noscore[i];
 1329: 	    }
 1330: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1331: 	    if (resp == false) {
 1332: 		return false;
 1333: 	    }
 1334: 	}
 1335: 
 1336: 	formname.submit();
 1337:     }
 1338: </script>
 1339: SUBJAVASCRIPT
 1340: }
 1341: 
 1342: #--- javascript for essay type problem --
 1343: sub sub_page_kw_js {
 1344:     my $request = shift;
 1345:     my $iconpath = $request->dir_config('lonIconsURL');
 1346:     &commonJSfunctions($request);
 1347: 
 1348:     my $inner_js_msg_central=<<INNERJS;
 1349:     <script text="text/javascript">
 1350:     function checkInput() {
 1351:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1352:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1353:       var usrctr = document.msgcenter.usrctr.value;
 1354:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1355:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1356: 
 1357:       var msgchk = "";
 1358:       if (document.msgcenter.subchk.checked) {
 1359:          msgchk = "msgsub,";
 1360:       }
 1361:       var includemsg = 0;
 1362:       for (var i=1; i<=nmsg; i++) {
 1363:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1364:           var frmmsg = document.msgcenter["msg"+i];
 1365:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1366:           var showflg = opener.document.SCORE["shownOnce"+i];
 1367:           showflg.value = "1";
 1368:           var chkbox = document.msgcenter["msgn"+i];
 1369:           if (chkbox.checked) {
 1370:              msgchk += "savemsg"+i+",";
 1371:              includemsg = 1;
 1372:           }
 1373:       }
 1374:       if (document.msgcenter.newmsgchk.checked) {
 1375:          msgchk += "newmsg"+usrctr;
 1376:          includemsg = 1;
 1377:       }
 1378:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1379:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1380:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1381:       includemsg.value = msgchk;
 1382: 
 1383:       self.close()
 1384: 
 1385:     }
 1386:     </script>
 1387: INNERJS
 1388: 
 1389:     my $inner_js_highlight_central=<<INNERJS;
 1390:  <script type="text/javascript">
 1391:     function updateChoice(flag) {
 1392:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1393:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1394:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1395:       opener.document.SCORE.refresh.value = "on";
 1396:       if (opener.document.SCORE.keywords.value!=""){
 1397:          opener.document.SCORE.submit();
 1398:       }
 1399:       self.close()
 1400:     }
 1401: </script>
 1402: INNERJS
 1403: 
 1404:     my $start_page_msg_central = 
 1405:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1406: 				       {'js_ready'  => 1,
 1407: 					'only_body' => 1,
 1408: 					'bgcolor'   =>'#FFFFFF',});
 1409:     my $end_page_msg_central = 
 1410: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1411: 
 1412: 
 1413:     my $start_page_highlight_central = 
 1414:         &Apache::loncommon::start_page('Highlight Central',
 1415: 				       $inner_js_highlight_central,
 1416: 				       {'js_ready'  => 1,
 1417: 					'only_body' => 1,
 1418: 					'bgcolor'   =>'#FFFFFF',});
 1419:     my $end_page_highlight_central = 
 1420: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1421: 
 1422:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1423:     $docopen=~s/^document\.//;
 1424:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1425:     $request->print(<<SUBJAVASCRIPT);
 1426: <script type="text/javascript" language="javascript">
 1427: 
 1428: //===================== Show list of keywords ====================
 1429:   function keywords(formname) {
 1430:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1431:     if (nret==null) return;
 1432:     formname.keywords.value = nret;
 1433: 
 1434:     if (formname.keywords.value != "") {
 1435: 	formname.refresh.value = "on";
 1436: 	formname.submit();
 1437:     }
 1438:     return;
 1439:   }
 1440: 
 1441: //===================== Script to view submitted by ==================
 1442:   function viewSubmitter(submitter) {
 1443:     document.SCORE.refresh.value = "on";
 1444:     document.SCORE.NCT.value = "1";
 1445:     document.SCORE.unamedom0.value = submitter;
 1446:     document.SCORE.submit();
 1447:     return;
 1448:   }
 1449: 
 1450: //===================== Script to add keyword(s) ==================
 1451:   function getSel() {
 1452:     if (document.getSelection) txt = document.getSelection();
 1453:     else if (document.selection) txt = document.selection.createRange().text;
 1454:     else return;
 1455:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1456:     if (cleantxt=="") {
 1457: 	alert("$alertmsg");
 1458: 	return;
 1459:     }
 1460:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1461:     if (nret==null) return;
 1462:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1463:     if (document.SCORE.keywords.value != "") {
 1464: 	document.SCORE.refresh.value = "on";
 1465: 	document.SCORE.submit();
 1466:     }
 1467:     return;
 1468:   }
 1469: 
 1470: //====================== Script for composing message ==============
 1471:    // preload images
 1472:    img1 = new Image();
 1473:    img1.src = "$iconpath/mailbkgrd.gif";
 1474:    img2 = new Image();
 1475:    img2.src = "$iconpath/mailto.gif";
 1476: 
 1477:   function msgCenter(msgform,usrctr,fullname) {
 1478:     var Nmsg  = msgform.savemsgN.value;
 1479:     savedMsgHeader(Nmsg,usrctr,fullname);
 1480:     var subject = msgform.msgsub.value;
 1481:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1482:     re = /msgsub/;
 1483:     var shwsel = "";
 1484:     if (re.test(msgchk)) { shwsel = "checked" }
 1485:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1486:     displaySubject(checkEntities(subject),shwsel);
 1487:     for (var i=1; i<=Nmsg; i++) {
 1488: 	var testmsg = "savemsg"+i+",";
 1489: 	re = new RegExp(testmsg,"g");
 1490: 	shwsel = "";
 1491: 	if (re.test(msgchk)) { shwsel = "checked" }
 1492: 	var message = document.SCORE["savemsg"+i].value;
 1493: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1494: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1495: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1496:     }
 1497:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1498:     shwsel = "";
 1499:     re = /newmsg/;
 1500:     if (re.test(msgchk)) { shwsel = "checked" }
 1501:     newMsg(newmsg,shwsel);
 1502:     msgTail(); 
 1503:     return;
 1504:   }
 1505: 
 1506:   function checkEntities(strx) {
 1507:     if (strx.length == 0) return strx;
 1508:     var orgStr = ["&", "<", ">", '"']; 
 1509:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1510:     var counter = 0;
 1511:     while (counter < 4) {
 1512: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1513: 	counter++;
 1514:     }
 1515:     return strx;
 1516:   }
 1517: 
 1518:   function strReplace(strx, orgStr, newStr) {
 1519:     return strx.split(orgStr).join(newStr);
 1520:   }
 1521: 
 1522:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1523:     var height = 70*Nmsg+250;
 1524:     var scrollbar = "no";
 1525:     if (height > 600) {
 1526: 	height = 600;
 1527: 	scrollbar = "yes";
 1528:     }
 1529:     var xpos = (screen.width-600)/2;
 1530:     xpos = (xpos < 0) ? '0' : xpos;
 1531:     var ypos = (screen.height-height)/2-30;
 1532:     ypos = (ypos < 0) ? '0' : ypos;
 1533: 
 1534:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1535:     pWin.focus();
 1536:     pDoc = pWin.document;
 1537:     pDoc.$docopen;
 1538:     pDoc.write('$start_page_msg_central');
 1539: 
 1540:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1541:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1542:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1543: 
 1544:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1545:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1546:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1547: }
 1548:     function displaySubject(msg,shwsel) {
 1549:     pDoc = pWin.document;
 1550:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1551:     pDoc.write("<td>Subject<\\/td>");
 1552:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1553:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1554: }
 1555: 
 1556:   function displaySavedMsg(ctr,msg,shwsel) {
 1557:     pDoc = pWin.document;
 1558:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1559:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1560:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1561:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1562: }
 1563: 
 1564:   function newMsg(newmsg,shwsel) {
 1565:     pDoc = pWin.document;
 1566:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1567:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1568:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1569:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1570: }
 1571: 
 1572:   function msgTail() {
 1573:     pDoc = pWin.document;
 1574:     pDoc.write("<\\/table>");
 1575:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1576:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1577:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1578:     pDoc.write("<\\/form>");
 1579:     pDoc.write('$end_page_msg_central');
 1580:     pDoc.close();
 1581: }
 1582: 
 1583: //====================== Script for keyword highlight options ==============
 1584:   function kwhighlight() {
 1585:     var kwclr    = document.SCORE.kwclr.value;
 1586:     var kwsize   = document.SCORE.kwsize.value;
 1587:     var kwstyle  = document.SCORE.kwstyle.value;
 1588:     var redsel = "";
 1589:     var grnsel = "";
 1590:     var blusel = "";
 1591:     if (kwclr=="red")   {var redsel="checked"};
 1592:     if (kwclr=="green") {var grnsel="checked"};
 1593:     if (kwclr=="blue")  {var blusel="checked"};
 1594:     var sznsel = "";
 1595:     var sz1sel = "";
 1596:     var sz2sel = "";
 1597:     if (kwsize=="0")  {var sznsel="checked"};
 1598:     if (kwsize=="+1") {var sz1sel="checked"};
 1599:     if (kwsize=="+2") {var sz2sel="checked"};
 1600:     var synsel = "";
 1601:     var syisel = "";
 1602:     var sybsel = "";
 1603:     if (kwstyle=="")    {var synsel="checked"};
 1604:     if (kwstyle=="<i>") {var syisel="checked"};
 1605:     if (kwstyle=="<b>") {var sybsel="checked"};
 1606:     highlightCentral();
 1607:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1608:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1609:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1610:     highlightend();
 1611:     return;
 1612:   }
 1613: 
 1614:   function highlightCentral() {
 1615: //    if (window.hwdWin) window.hwdWin.close();
 1616:     var xpos = (screen.width-400)/2;
 1617:     xpos = (xpos < 0) ? '0' : xpos;
 1618:     var ypos = (screen.height-330)/2-30;
 1619:     ypos = (ypos < 0) ? '0' : ypos;
 1620: 
 1621:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1622:     hwdWin.focus();
 1623:     var hDoc = hwdWin.document;
 1624:     hDoc.$docopen;
 1625:     hDoc.write('$start_page_highlight_central');
 1626:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1627:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1628: 
 1629:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1630:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1631:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1632:   }
 1633: 
 1634:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1635:     var hDoc = hwdWin.document;
 1636:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1637:     hDoc.write("<td align=\\"left\\">");
 1638:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1639:     hDoc.write("<td align=\\"left\\">");
 1640:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1641:     hDoc.write("<td align=\\"left\\">");
 1642:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1643:     hDoc.write("<\\/tr>");
 1644:   }
 1645: 
 1646:   function highlightend() { 
 1647:     var hDoc = hwdWin.document;
 1648:     hDoc.write("<\\/table>");
 1649:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1650:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1651:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1652:     hDoc.write("<\\/form>");
 1653:     hDoc.write('$end_page_highlight_central');
 1654:     hDoc.close();
 1655:   }
 1656: 
 1657: </script>
 1658: SUBJAVASCRIPT
 1659: }
 1660: 
 1661: sub get_increment {
 1662:     my $increment = $env{'form.increment'};
 1663:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1664:         $increment != .1) {
 1665:         $increment = 1;
 1666:     }
 1667:     return $increment;
 1668: }
 1669: 
 1670: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1671: sub gradeBox {
 1672:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1673:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1674: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1675:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1676:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1677:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1678:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1679:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1680: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1681:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1682:     my $display_part= &get_display_part($partid,$symb);
 1683:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1684: 				       [$partid]);
 1685:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1686:     if ($last_resets{$partid}) {
 1687:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1688:     }
 1689:     $result.='<table border="0"><tr>';
 1690:     my $ctr = 0;
 1691:     my $thisweight = 0;
 1692:     my $increment = &get_increment();
 1693: 
 1694:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1695:     while ($thisweight<=$wgt) {
 1696: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1697: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1698: 	    $thisweight.')" value="'.$thisweight.'" '.
 1699: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1700: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1701:         $thisweight += $increment;
 1702: 	$ctr++;
 1703:     }
 1704:     $radio.='</tr></table>';
 1705: 
 1706:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1707: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1708: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1709: 	$wgt.')" /></td>'."\n";
 1710:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1711: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1712: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1713:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1714: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1715:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1716: 	$line.='<option></option>'.
 1717: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1718:     } else {
 1719: 	$line.='<option selected="selected"></option>'.
 1720: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1721:     }
 1722:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1723: 
 1724: 
 1725: 	#&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);
 1726:     $result .= 
 1727: 	    '<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>'.
 1728:     
 1729:     $result.='</tr></table>'."\n";
 1730:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1731: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1732: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1733: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1734:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1735:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1736:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1737:         $aggtries.'" />'."\n";
 1738:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1739:     return $result;
 1740: }
 1741: 
 1742: sub handback_box {
 1743:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1744:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1745:     my (@respids);
 1746:      my @part_response_id = &flatten_responseType($responseType);
 1747:     foreach my $part_response_id (@part_response_id) {
 1748:     	my ($part,$resp) = @{ $part_response_id };
 1749:         if ($part eq $partid) {
 1750:             push(@respids,$resp);
 1751:         }
 1752:     }
 1753:     my $result;
 1754:     foreach my $respid (@respids) {
 1755: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1756: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1757: 	next if (!@$files);
 1758: 	my $file_counter = 1;
 1759: 	foreach my $file (@$files) {
 1760: 	    if ($file =~ /\/portfolio\//) {
 1761:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1762:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1763:     	        $file_disp = "$name.$ext";
 1764:     	        $file = $file_path.$file_disp;
 1765:     	        $result.=&mt('Return commented version of [_1] to student.',
 1766:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1767:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1768:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1769:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1770:     	        $file_counter++;
 1771: 	    }
 1772: 	}
 1773:     }
 1774:     return $result;    
 1775: }
 1776: 
 1777: sub show_problem {
 1778:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1779:     my $rendered;
 1780:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1781:     &Apache::lonxml::remember_problem_counter();
 1782:     if ($mode eq 'both' or $mode eq 'text') {
 1783: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1784: 						       $env{'request.course.id'},
 1785: 						       undef,\%form);
 1786:     }
 1787:     if ($removeform) {
 1788: 	$rendered=~s|<form(.*?)>||g;
 1789: 	$rendered=~s|</form>||g;
 1790: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1791:     }
 1792:     my $companswer;
 1793:     if ($mode eq 'both' or $mode eq 'answer') {
 1794: 	&Apache::lonxml::restore_problem_counter();
 1795: 	$companswer=
 1796: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1797: 						    $env{'request.course.id'},
 1798: 						    %form);
 1799:     }
 1800:     if ($removeform) {
 1801: 	$companswer=~s|<form(.*?)>||g;
 1802: 	$companswer=~s|</form>||g;
 1803: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1804:     }
 1805:     $rendered=
 1806: 	'<div class="LC_grade_show_problem_header">'.
 1807: 	&mt('View of the problem').
 1808: 	'</div><div class="LC_grade_show_problem_problem">'.
 1809: 	$rendered.
 1810: 	'</div>';
 1811:     $companswer=
 1812: 	'<div class="LC_grade_show_problem_header">'.
 1813: 	&mt('Correct answer').
 1814: 	'</div><div class="LC_grade_show_problem_problem">'.
 1815: 	$companswer.
 1816: 	'</div>';
 1817:     my $result;
 1818:     if ($mode eq 'both') {
 1819: 	$result=$rendered.$companswer;
 1820:     } elsif ($mode eq 'text') {
 1821: 	$result=$rendered;
 1822:     } elsif ($mode eq 'answer') {
 1823: 	$result=$companswer;
 1824:     }
 1825:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1826:     return $result;
 1827: }
 1828: 
 1829: sub files_exist {
 1830:     my ($r, $symb) = @_;
 1831:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1832: 
 1833:     foreach my $student (@students) {
 1834:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1835:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1836: 					      $udom,$uname);
 1837:         my ($string,$timestamp)= &get_last_submission(\%record);
 1838:         foreach my $submission (@$string) {
 1839:             my ($partid,$respid) =
 1840: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1841:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1842: 					   \%record);
 1843:             return 1 if (@$files);
 1844:         }
 1845:     }
 1846:     return 0;
 1847: }
 1848: 
 1849: sub download_all_link {
 1850:     my ($r,$symb) = @_;
 1851:     my $all_students = 
 1852: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1853: 
 1854:     my $parts =
 1855: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1856: 
 1857:     my $identifier = &Apache::loncommon::get_cgi_id();
 1858:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1859:                              'cgi.'.$identifier.'.symb' => $symb,
 1860:                              'cgi.'.$identifier.'.parts' => $parts,});
 1861:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1862: 	      &mt('Download All Submitted Documents').'</a>');
 1863:     return
 1864: }
 1865: 
 1866: sub build_section_inputs {
 1867:     my $section_inputs;
 1868:     if ($env{'form.section'} eq '') {
 1869:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1870:     } else {
 1871:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1872:         foreach my $section (@sections) {
 1873:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1874:         }
 1875:     }
 1876:     return $section_inputs;
 1877: }
 1878: 
 1879: # --------------------------- show submissions of a student, option to grade 
 1880: sub submission {
 1881:     my ($request,$counter,$total) = @_;
 1882:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1883:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1884:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1885:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1886:     my $symb = &get_symb($request); 
 1887:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1888: 
 1889:     if (!&canview($usec)) {
 1890: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1891: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1892: 			$env{'request.course.id'}.')</span>');
 1893: 	$request->print(&show_grading_menu_form($symb));
 1894: 	return;
 1895:     }
 1896: 
 1897:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1898:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1899:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1900:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1901:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1902: 	'" src="'.$request->dir_config('lonIconsURL').
 1903: 	'/check.gif" height="16" border="0" />';
 1904: 
 1905:     my %old_essays;
 1906:     # header info
 1907:     if ($counter == 0) {
 1908: 	&sub_page_js($request);
 1909: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1910: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1911: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1912: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1913: 	    &download_all_link($request, $symb);
 1914: 	}
 1915: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1916: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1917: 
 1918: 	# option to display problem, only once else it cause problems 
 1919:         # with the form later since the problem has a form.
 1920: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1921: 	    my $mode;
 1922: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1923: 		$mode='both';
 1924: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1925: 		$mode='text';
 1926: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1927: 		$mode='answer';
 1928: 	    }
 1929: 	    &Apache::lonxml::clear_problem_counter();
 1930: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1931: 	}
 1932: 
 1933: 	# kwclr is the only variable that is guaranteed to be non blank 
 1934:         # if this subroutine has been called once.
 1935: 	my %keyhash = ();
 1936: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1937: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1938: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1939: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1940: 
 1941: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1942: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1943: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1944: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1945: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1946: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1947: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1948: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1949: 	}
 1950: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1951: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1952: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1953: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1954: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1955: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1956: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1957: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1958: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1959: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1960: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1961: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1962: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1963: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1964: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1965: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1966: 			&build_section_inputs().
 1967: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1968: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1969: 			'<input type="hidden" name="NCT"'.
 1970: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1971: 	if ($env{'form.handgrade'} eq 'yes') {
 1972: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1973: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1974: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1975: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1976: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1977: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1978: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1979: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1980: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1981: 	    }
 1982: 	}
 1983: 	
 1984: 	my ($cts,$prnmsg) = (1,'');
 1985: 	while ($cts <= $env{'form.savemsgN'}) {
 1986: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1987: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1988: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1989: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1990: 		'" />'."\n".
 1991: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1992: 	    $cts++;
 1993: 	}
 1994: 	$request->print($prnmsg);
 1995: 
 1996: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1997: #
 1998: # Print out the keyword options line
 1999: #
 2000: 	    $request->print(<<KEYWORDS);
 2001: &nbsp;<b>Keyword Options:</b>&nbsp;
 2002: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2003: <a href="#" onMouseDown="javascript:getSel(); return false"
 2004:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2005: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2006: KEYWORDS
 2007: #
 2008: # Load the other essays for similarity check
 2009: #
 2010:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2011: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2012: 	    $apath=&escape($apath);
 2013: 	    $apath=~s/\W/\_/gs;
 2014: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2015:         }
 2016:     }
 2017: 
 2018: # This is where output for one specific student would start
 2019:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2020:     $request->print("\n\n".
 2021:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2022: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2023: 		    '<div class="LC_grade_show_user_body">'."\n");
 2024: 
 2025:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2026: 	my $mode;
 2027: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2028: 	    $mode='both';
 2029: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2030: 	    $mode='text';
 2031: 	} elsif ($env{'form.vAns'} eq 'all') {
 2032: 	    $mode='answer';
 2033: 	}
 2034: 	&Apache::lonxml::clear_problem_counter();
 2035: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2036:     }
 2037: 
 2038:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2039:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2040: 
 2041:     # Display student info
 2042:     $request->print(($counter == 0 ? '' : '<br />'));
 2043:     my $result='<div class="LC_grade_submissions">';
 2044:     
 2045:     $result.='<div class="LC_grade_submissions_header">';
 2046:     $result.= &mt('Submissions');
 2047:     $result.='<input type="hidden" name="name'.$counter.
 2048: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2049:     if ($env{'form.handgrade'} eq 'no') {
 2050: 	$result.='<span class="LC_grade_check_note">'.
 2051: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2052: 
 2053:     }
 2054: 
 2055: 
 2056: 
 2057:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2058:     my $fullname;
 2059:     my $col_fullnames = [];
 2060:     if ($env{'form.handgrade'} eq 'yes') {
 2061: 	(my $sub_result,$fullname,$col_fullnames)=
 2062: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2063: 				 $counter);
 2064: 	$result.=$sub_result;
 2065:     }
 2066:     $request->print($result."\n");
 2067:     $request->print('</div>'."\n");
 2068:     # print student answer/submission
 2069:     # Options are (1) Handgaded submission only
 2070:     #             (2) Last submission, includes submission that is not handgraded 
 2071:     #                  (for multi-response type part)
 2072:     #             (3) Last submission plus the parts info
 2073:     #             (4) The whole record for this student
 2074:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2075: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2076: 	
 2077: 	my $lastsubonly;
 2078: 
 2079: 	if ($$timestamp eq '') {
 2080: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2081: 	} else {
 2082: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2083: 
 2084: 	    my %seenparts;
 2085: 	    my @part_response_id = &flatten_responseType($responseType);
 2086: 	    foreach my $part (@part_response_id) {
 2087: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2088: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2089: 
 2090: 		my ($partid,$respid) = @{ $part };
 2091: 		my $display_part=&get_display_part($partid,$symb);
 2092: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2093: 		    if (exists($seenparts{$partid})) { next; }
 2094: 		    $seenparts{$partid}=1;
 2095: 		    my $submitby='<b>Part:</b> '.$display_part.
 2096: 			' <b>Collaborative submission by:</b> '.
 2097: 			'<a href="javascript:viewSubmitter(\''.
 2098: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2099: 			'\');" target="_self">'.
 2100: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2101: 		    $request->print($submitby);
 2102: 		    next;
 2103: 		}
 2104: 		my $responsetype = $responseType->{$partid}->{$respid};
 2105: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2106: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2107: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2108: 			' )</span>&nbsp; &nbsp;'.
 2109: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2110: 		    next;
 2111: 		}
 2112: 		foreach my $submission (@$string) {
 2113: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2114: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2115: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2116: 		    # Similarity check
 2117: 		    my $similar='';
 2118: 		    if($env{'form.checkPlag'}){
 2119: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2120: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2121: 			if ($osim) {
 2122: 			    $osim=int($osim*100.0);
 2123: 			    my %old_course_desc = 
 2124: 				&Apache::lonnet::coursedescription($ocrsid,
 2125: 								   {'one_time' => 1});
 2126: 
 2127: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2128: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2129: 				    $osim,
 2130: 				    &Apache::loncommon::plainname($oname,$odom),
 2131: 				    $oname,$odom,
 2132: 				    $old_course_desc{'description'},
 2133: 				    $old_course_desc{'num'},
 2134: 				    $old_course_desc{'domain'}).
 2135: 				'</span></h3><blockquote><i>'.
 2136: 				&keywords_highlight($oessay).
 2137: 				'</i></blockquote><hr />';
 2138: 			}
 2139: 		    }
 2140: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2141: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2142: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2143: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2144: 			my $display_part=&get_display_part($partid,$symb);
 2145: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2146: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2147: 			    ' )</span>&nbsp; &nbsp;';
 2148: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2149: 			if (@$files) {
 2150: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2151: 			    my $file_counter = 0;
 2152: 			    foreach my $file (@$files) {
 2153: 			        $file_counter++;
 2154: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2155: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2156: 			    }
 2157: 			    $lastsubonly.='<br />';
 2158: 			}
 2159: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2160: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2161: 					 $respid,\%record,$order,undef,$uname,$udom);
 2162: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2163: 			$lastsubonly.='</div>';
 2164: 		    }
 2165: 		}
 2166: 	    }
 2167: 	    $lastsubonly.='</div>'."\n";
 2168: 	}
 2169: 	$request->print($lastsubonly);
 2170:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2171: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2172: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2173:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2174: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2175: 								 $env{'request.course.id'},
 2176: 								 $last,'.submission',
 2177: 								 'Apache::grades::keywords_highlight'));
 2178:     }
 2179: 
 2180:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2181: 	.$udom.'" />'."\n");
 2182:     # return if view submission with no grading option
 2183:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2184: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2185: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2186: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2187: 	$toGrade.='</div>'."\n";
 2188: 	if (($env{'form.command'} eq 'submission') || 
 2189: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2190: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2191: 	}
 2192: 	$request->print($toGrade);
 2193: 	return;
 2194:     } else {
 2195: 	$request->print('</div>'."\n");
 2196:     }
 2197: 
 2198:     # essay grading message center
 2199:     if ($env{'form.handgrade'} eq 'yes') {
 2200: 	my $result='<div class="LC_grade_message_center">';
 2201:     
 2202: 	$result.='<div class="LC_grade_message_center_header">'.
 2203: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2204: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2205: 	my $msgfor = $givenn.' '.$lastname;
 2206: 	if (scalar(@$col_fullnames) > 0) {
 2207: 	    my $lastone = pop(@$col_fullnames);
 2208: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2209: 	}
 2210: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2211: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2212: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2213: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2214: 	    ',\''.$msgfor.'\');" target="_self">'.
 2215: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2216: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2217: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2218: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2219: 	    '<br />&nbsp;('.
 2220: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2221: 	$result.='</div></div>';
 2222: 	$request->print($result);
 2223:     }
 2224: 
 2225:     my %seen = ();
 2226:     my @partlist;
 2227:     my @gradePartRespid;
 2228:     my @part_response_id = &flatten_responseType($responseType);
 2229:     $request->print('<div class="LC_grade_assign">'.
 2230: 		    
 2231: 		    '<div class="LC_grade_assign_header">'.
 2232: 		    &mt('Assign Grades').'</div>'.
 2233: 		    '<div class="LC_grade_assign_body">');
 2234:     foreach my $part_response_id (@part_response_id) {
 2235:     	my ($partid,$respid) = @{ $part_response_id };
 2236: 	my $part_resp = join('_',@{ $part_response_id });
 2237: 	next if ($seen{$partid} > 0);
 2238: 	$seen{$partid}++;
 2239: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2240: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2241: 	push(@partlist,$partid);
 2242: 	push(@gradePartRespid,$partid.'.'.$respid);
 2243: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2244:     }
 2245:     $request->print('</div></div>');
 2246: 
 2247:     $request->print('<div class="LC_grade_info_links">');
 2248:     if ($perm{'vgr'}) {
 2249: 	$request->print(
 2250: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2251: 						   $uname,$udom,'check'));
 2252:     }
 2253:     if ($perm{'opa'}) {
 2254: 	$request->print(
 2255: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2256: 					 $uname,$udom,$symb,'check'));
 2257:     }
 2258:     $request->print('</div>');
 2259: 
 2260:     $result='<input type="hidden" name="partlist'.$counter.
 2261: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2262:     $result.='<input type="hidden" name="gradePartRespid'.
 2263: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2264:     my $ctr = 0;
 2265:     while ($ctr < scalar(@partlist)) {
 2266: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2267: 	    $partlist[$ctr].'" />'."\n";
 2268: 	$ctr++;
 2269:     }
 2270:     $request->print($result.''."\n");
 2271: 
 2272: # Done with printing info for one student
 2273: 
 2274:     $request->print('</div>');#LC_grade_show_user_body
 2275:     $request->print('</div>');#LC_grade_show_user
 2276: 
 2277: 
 2278:     # print end of form
 2279:     if ($counter == $total) {
 2280: 	my $endform='<table border="0"><tr><td>'."\n";
 2281: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2282: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2283: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2284: 	my $ntstu ='<select name="NTSTU">'.
 2285: 	    '<option>1</option><option>2</option>'.
 2286: 	    '<option>3</option><option>5</option>'.
 2287: 	    '<option>7</option><option>10</option></select>'."\n";
 2288: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2289: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2290: 	$endform.=&mt('[quant,_1,student]',$ntstu);
 2291: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2292: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2293: 	    '<input type="button" value="'.&mt('Next').'" '.
 2294: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2295: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2296:         $endform.="<input type='hidden' value='".&get_increment().
 2297:             "' name='increment' />";
 2298: 	$endform.='</td></tr></table></form>';
 2299: 	$endform.=&show_grading_menu_form($symb);
 2300: 	$request->print($endform);
 2301:     }
 2302:     return '';
 2303: }
 2304: 
 2305: sub check_collaborators {
 2306:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2307:     my ($result,@col_fullnames);
 2308:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2309:     foreach my $part (keys(%$handgrade)) {
 2310: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2311: 					'.maxcollaborators',
 2312: 					$symb,$udom,$uname);
 2313: 	next if ($ncol <= 0);
 2314: 	$part =~ s/\_/\./g;
 2315: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2316: 	my (@good_collaborators, @bad_collaborators);
 2317: 	foreach my $possible_collaborator
 2318: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2319: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2320: 	    next if ($possible_collaborator eq '');
 2321: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2322: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2323: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2324: 	    # Doing this grep allows 'fuzzy' specification
 2325: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2326: 			       keys(%$classlist));
 2327: 	    if (! scalar(@matches)) {
 2328: 		push(@bad_collaborators, $possible_collaborator);
 2329: 	    } else {
 2330: 		push(@good_collaborators, @matches);
 2331: 	    }
 2332: 	}
 2333: 	if (scalar(@good_collaborators) != 0) {
 2334: 	    $result.='<br />'.&mt('Collaborators: ');
 2335: 	    foreach my $name (@good_collaborators) {
 2336: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2337: 		push(@col_fullnames, $givenn.' '.$lastname);
 2338: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2339: 	    }
 2340: 	    $result.='<br />'."\n";
 2341: 	    my ($part)=split(/\./,$part);
 2342: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2343: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2344: 		"\n";
 2345: 	}
 2346: 	if (scalar(@bad_collaborators) > 0) {
 2347: 	    $result.='<div class="LC_warning">';
 2348: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2349: 	    $result .= '</div>';
 2350: 	}         
 2351: 	if (scalar(@bad_collaborators > $ncol)) {
 2352: 	    $result .= '<div class="LC_warning">';
 2353: 	    $result .= &mt('This student has submitted too many '.
 2354: 		'collaborators.  Maximum is [_1].',$ncol);
 2355: 	    $result .= '</div>';
 2356: 	}
 2357:     }
 2358:     return ($result,$fullname,\@col_fullnames);
 2359: }
 2360: 
 2361: #--- Retrieve the last submission for all the parts
 2362: sub get_last_submission {
 2363:     my ($returnhash)=@_;
 2364:     my (@string,$timestamp);
 2365:     if ($$returnhash{'version'}) {
 2366: 	my %lasthash=();
 2367: 	my ($version);
 2368: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2369: 	    foreach my $key (sort(split(/\:/,
 2370: 					$$returnhash{$version.':keys'}))) {
 2371: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2372: 		$timestamp = 
 2373: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2374: 	    }
 2375: 	}
 2376: 	foreach my $key (keys(%lasthash)) {
 2377: 	    next if ($key !~ /\.submission$/);
 2378: 
 2379: 	    my ($partid,$foo) = split(/submission$/,$key);
 2380: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2381: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2382: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2383: 	}
 2384:     }
 2385:     if (!@string) {
 2386: 	$string[0] =
 2387: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2388:     }
 2389:     return (\@string,\$timestamp);
 2390: }
 2391: 
 2392: #--- High light keywords, with style choosen by user.
 2393: sub keywords_highlight {
 2394:     my $string    = shift;
 2395:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2396:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2397:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2398:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2399:     foreach my $keyword (@keylist) {
 2400: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2401:     }
 2402:     return $string;
 2403: }
 2404: 
 2405: #--- Called from submission routine
 2406: sub processHandGrade {
 2407:     my ($request) = shift;
 2408:     my $symb   = &get_symb($request);
 2409:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2410:     my $button = $env{'form.gradeOpt'};
 2411:     my $ngrade = $env{'form.NCT'};
 2412:     my $ntstu  = $env{'form.NTSTU'};
 2413:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2414:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2415: 
 2416:     if ($button eq 'Save & Next') {
 2417: 	my $ctr = 0;
 2418: 	while ($ctr < $ngrade) {
 2419: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2420: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2421: 	    if ($errorflag eq 'no_score') {
 2422: 		$ctr++;
 2423: 		next;
 2424: 	    }
 2425: 	    if ($errorflag eq 'not_allowed') {
 2426: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2427: 		$ctr++;
 2428: 		next;
 2429: 	    }
 2430: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2431: 	    my ($subject,$message,$msgstatus) = ('','','');
 2432: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2433:             my ($feedurl,$showsymb) =
 2434: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2435: 	    my $messagetail;
 2436: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2437: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2438: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2439: 		$subject.=' ['.$restitle.']';
 2440: 		my (@msgnum) = split(/,/,$includemsg);
 2441: 		foreach (@msgnum) {
 2442: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2443: 		}
 2444: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2445: 		if ($env{'form.withgrades'.$ctr}) {
 2446: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2447: 		    $messagetail = " for <a href=\"".
 2448: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2449: 		}
 2450: 		$msgstatus = 
 2451:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2452: 						     $message.$messagetail,
 2453:                                                      undef,$feedurl,undef,
 2454:                                                      undef,undef,$showsymb,
 2455:                                                      $restitle);
 2456: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2457: 				$msgstatus);
 2458: 	    }
 2459: 	    if ($env{'form.collaborator'.$ctr}) {
 2460: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2461: 		foreach my $collabstr (@collabstrs) {
 2462: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2463: 		    foreach my $collaborator (@collaborators) {
 2464: 			my ($errorflag,$pts,$wgt) = 
 2465: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2466: 					   $env{'form.unamedom'.$ctr},$part);
 2467: 			if ($errorflag eq 'not_allowed') {
 2468: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2469: 			    next;
 2470: 			} elsif ($message ne '') {
 2471: 			    my ($baseurl,$showsymb) = 
 2472: 				&get_feedurl_and_symb($symb,$collaborator,
 2473: 						      $udom);
 2474: 			    if ($env{'form.withgrades'.$ctr}) {
 2475: 				$messagetail = " for <a href=\"".
 2476:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2477: 			    }
 2478: 			    $msgstatus = 
 2479: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2480: 			}
 2481: 		    }
 2482: 		}
 2483: 	    }
 2484: 	    $ctr++;
 2485: 	}
 2486:     }
 2487: 
 2488:     if ($env{'form.handgrade'} eq 'yes') {
 2489: 	# Keywords sorted in alphabatical order
 2490: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2491: 	my %keyhash = ();
 2492: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2493: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2494: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2495: 	$env{'form.keywords'} = join(' ',@keywords);
 2496: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2497: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2498: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2499: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2500: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2501: 
 2502: 	# message center - Order of message gets changed. Blank line is eliminated.
 2503: 	# New messages are saved in env for the next student.
 2504: 	# All messages are saved in nohist_handgrade.db
 2505: 	my ($ctr,$idx) = (1,1);
 2506: 	while ($ctr <= $env{'form.savemsgN'}) {
 2507: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2508: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2509: 		$idx++;
 2510: 	    }
 2511: 	    $ctr++;
 2512: 	}
 2513: 	$ctr = 0;
 2514: 	while ($ctr < $ngrade) {
 2515: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2516: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2517: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2518: 		$idx++;
 2519: 	    }
 2520: 	    $ctr++;
 2521: 	}
 2522: 	$env{'form.savemsgN'} = --$idx;
 2523: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2524: 	my $putresult = &Apache::lonnet::put
 2525: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2526:     }
 2527:     # Called by Save & Refresh from Highlight Attribute Window
 2528:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2529:     if ($env{'form.refresh'} eq 'on') {
 2530: 	my ($ctr,$total) = (0,0);
 2531: 	while ($ctr < $ngrade) {
 2532: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2533: 	    $ctr++;
 2534: 	}
 2535: 	$env{'form.NTSTU'}=$ngrade;
 2536: 	$ctr = 0;
 2537: 	while ($ctr < $total) {
 2538: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2539: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2540: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2541: 	    &submission($request,$ctr,$total-1);
 2542: 	    $ctr++;
 2543: 	}
 2544: 	return '';
 2545:     }
 2546: 
 2547: # Go directly to grade student - from submission or link from chart page
 2548:     if ($button eq 'Grade Student') {
 2549: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2550: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2551: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2552: 	$env{'form.fullname'} = $$fullname{$processUser};
 2553: 	&submission($request,0,0);
 2554: 	return '';
 2555:     }
 2556: 
 2557:     # Get the next/previous one or group of students
 2558:     my $firststu = $env{'form.unamedom0'};
 2559:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2560:     my $ctr = 2;
 2561:     while ($laststu eq '') {
 2562: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2563: 	$ctr++;
 2564: 	$laststu = $firststu if ($ctr > $ngrade);
 2565:     }
 2566: 
 2567:     my (@parsedlist,@nextlist);
 2568:     my ($nextflg) = 0;
 2569:     foreach my $item (sort 
 2570: 	     {
 2571: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2572: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2573: 		 }
 2574: 		 return $a cmp $b;
 2575: 	     } (keys(%$fullname))) {
 2576: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2577: 	    push(@parsedlist,$item);
 2578: 	}
 2579: 	$nextflg = 1 if ($item eq $laststu);
 2580: 	if ($button eq 'Previous') {
 2581: 	    last if ($item eq $firststu);
 2582: 	    push(@parsedlist,$item);
 2583: 	}
 2584:     }
 2585:     $ctr = 0;
 2586:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2587:     my ($partlist) = &response_type($symb);
 2588:     foreach my $student (@parsedlist) {
 2589: 	my $submitonly=$env{'form.submitonly'};
 2590: 	my ($uname,$udom) = split(/:/,$student);
 2591: 	
 2592: 	if ($submitonly eq 'queued') {
 2593: 	    my %queue_status = 
 2594: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2595: 							$udom,$uname);
 2596: 	    next if (!defined($queue_status{'gradingqueue'}));
 2597: 	}
 2598: 
 2599: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2600: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2601: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2602: 	    my $submitted = 0;
 2603: 	    my $ungraded = 0;
 2604: 	    my $incorrect = 0;
 2605: 	    foreach my $item (keys(%status)) {
 2606: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2607: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2608: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2609: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2610: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2611: 		    $submitted = 0;
 2612: 		}
 2613: 	    }
 2614: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2615: 				     $submitonly eq 'incorrect' ||
 2616: 				     $submitonly eq 'graded'));
 2617: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2618: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2619: 	}
 2620: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2621: 	last if ($ctr == $ntstu);
 2622: 	$ctr++;
 2623:     }
 2624: 
 2625:     $ctr = 0;
 2626:     my $total = scalar(@nextlist)-1;
 2627: 
 2628:     foreach (sort(@nextlist)) {
 2629: 	my ($uname,$udom,$submitter) = split(/:/);
 2630: 	$env{'form.student'}  = $uname;
 2631: 	$env{'form.userdom'}  = $udom;
 2632: 	$env{'form.fullname'} = $$fullname{$_};
 2633: 	&submission($request,$ctr,$total);
 2634: 	$ctr++;
 2635:     }
 2636:     if ($total < 0) {
 2637: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2638: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2639: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2640: 	$the_end.=&show_grading_menu_form($symb);
 2641: 	$request->print($the_end);
 2642:     }
 2643:     return '';
 2644: }
 2645: 
 2646: #---- Save the score and award for each student, if changed
 2647: sub saveHandGrade {
 2648:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2649:     my @version_parts;
 2650:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2651: 					   $env{'request.course.id'});
 2652:     if (!&canmodify($usec)) { return('not_allowed'); }
 2653:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2654:     my @parts_graded;
 2655:     my %newrecord  = ();
 2656:     my ($pts,$wgt) = ('','');
 2657:     my %aggregate = ();
 2658:     my $aggregateflag = 0;
 2659:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2660:     foreach my $new_part (@parts) {
 2661: 	#collaborator ($submi may vary for different parts
 2662: 	if ($submitter && $new_part ne $part) { next; }
 2663: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2664: 	if ($dropMenu eq 'excused') {
 2665: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2666: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2667: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2668: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2669: 		}
 2670: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2671: 	    }
 2672: 	} elsif ($dropMenu eq 'reset status'
 2673: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2674: 	    foreach my $key (keys(%record)) {
 2675: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2676: 	    }
 2677: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2678: 		"$env{'user.name'}:$env{'user.domain'}";
 2679:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2680: 
 2681:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2682: 					       [$new_part]);
 2683:             my $aggtries =$totaltries;
 2684:             if ($last_resets{$new_part}) {
 2685:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2686: 					   $new_part);
 2687:             }
 2688: 
 2689:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2690:             if ($aggtries > 0) {
 2691:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2692:                 $aggregateflag = 1;
 2693:             }
 2694: 	} elsif ($dropMenu eq '') {
 2695: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2696: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2697: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2698: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2699: 		next;
 2700: 	    }
 2701: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2702: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2703: 	    my $partial= $pts/$wgt;
 2704: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2705: 		#do not update score for part if not changed.
 2706:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2707: 		next;
 2708: 	    } else {
 2709: 	        push(@parts_graded,$new_part);
 2710: 	    }
 2711: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2712: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2713: 	    }
 2714: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2715: 	    if ($partial == 0) {
 2716: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2717: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2718: 		}
 2719: 	    } else {
 2720: 		if ($record{$reckey} ne 'correct_by_override') {
 2721: 		    $newrecord{$reckey} = 'correct_by_override';
 2722: 		}
 2723: 	    }	    
 2724: 	    if ($submitter && 
 2725: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2726: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2727: 	    }
 2728: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2729: 		"$env{'user.name'}:$env{'user.domain'}";
 2730: 	}
 2731: 	# unless problem has been graded, set flag to version the submitted files
 2732: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2733: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2734: 	        $dropMenu eq 'reset status')
 2735: 	   {
 2736: 	    push(@version_parts,$new_part);
 2737: 	}
 2738:     }
 2739:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2740:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2741: 
 2742:     if (%newrecord) {
 2743:         if (@version_parts) {
 2744:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2745:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2746: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2747: 	    foreach my $new_part (@version_parts) {
 2748: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2749: 				$new_part,\%newrecord);
 2750: 	    }
 2751:         }
 2752: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2753: 				$env{'request.course.id'},$domain,$stuname);
 2754: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2755: 				     $cdom,$cnum,$domain,$stuname);
 2756:     }
 2757:     if ($aggregateflag) {
 2758:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2759: 			      $cdom,$cnum);
 2760:     }
 2761:     return ('',$pts,$wgt);
 2762: }
 2763: 
 2764: sub check_and_remove_from_queue {
 2765:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2766:     my @ungraded_parts;
 2767:     foreach my $part (@{$parts}) {
 2768: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2769: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2770: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2771: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2772: 		) {
 2773: 	    push(@ungraded_parts, $part);
 2774: 	}
 2775:     }
 2776:     if ( !@ungraded_parts ) {
 2777: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2778: 					       $cnum,$domain,$stuname);
 2779:     }
 2780: }
 2781: 
 2782: sub handback_files {
 2783:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2784:     my $portfolio_root = '/userfiles/portfolio';
 2785:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2786: 
 2787:     my @part_response_id = &flatten_responseType($responseType);
 2788:     foreach my $part_response_id (@part_response_id) {
 2789:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2790: 	my $part_resp = join('_',@{ $part_response_id });
 2791:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2792:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2793:                 my $file_counter = 1;
 2794: 		my $file_msg;
 2795:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2796:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2797:                     my ($directory,$answer_file) = 
 2798:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2799:                     my ($answer_name,$answer_ver,$answer_ext) =
 2800: 		        &file_name_version_ext($answer_file);
 2801: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2802:                     my $getpropath = 1;
 2803: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2804: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2805:                     # fix file name
 2806:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2807:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2808:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2809:             	                                $save_file_name);
 2810:                     if ($result !~ m|^/uploaded/|) {
 2811:                         $request->print('<br /><span class="LC_error">'.
 2812:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2813:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2814:                                         '</span>');
 2815:                     } else {
 2816:                         # mark the file as read only
 2817:                         my @files = ($save_file_name);
 2818:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2819:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2820: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2821: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2822: 			}
 2823:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2824: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2825: 
 2826:                     }
 2827:                     $request->print("<br />".$fname." will be the uploaded file name");
 2828:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2829:                     $file_counter++;
 2830:                 }
 2831: 		my $subject = "File Handed Back by Instructor ";
 2832: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2833: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2834: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2835: 		$message .= " and can be found in your portfolio space.";
 2836: 		my ($feedurl,$showsymb) = 
 2837: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2838:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2839: 		my $msgstatus = 
 2840:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2841: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2842:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2843:             }
 2844:         }
 2845:     return;
 2846: }
 2847: 
 2848: sub get_feedurl_and_symb {
 2849:     my ($symb,$uname,$udom) = @_;
 2850:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2851:     $url = &Apache::lonnet::clutter($url);
 2852:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2853: 					$symb,$udom,$uname);
 2854:     if ($encrypturl =~ /^yes$/i) {
 2855: 	&Apache::lonenc::encrypted(\$url,1);
 2856: 	&Apache::lonenc::encrypted(\$symb,1);
 2857:     }
 2858:     return ($url,$symb);
 2859: }
 2860: 
 2861: sub get_submitted_files {
 2862:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2863:     my @files;
 2864:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2865:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2866:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2867:     	    push(@files,$file_url.$file);
 2868:         }
 2869:     }
 2870:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2871:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2872:     }
 2873:     return (\@files);
 2874: }
 2875: 
 2876: # ----------- Provides number of tries since last reset.
 2877: sub get_num_tries {
 2878:     my ($record,$last_reset,$part) = @_;
 2879:     my $timestamp = '';
 2880:     my $num_tries = 0;
 2881:     if ($$record{'version'}) {
 2882:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2883:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2884:                 $timestamp = $$record{$version.':timestamp'};
 2885:                 if ($timestamp > $last_reset) {
 2886:                     $num_tries ++;
 2887:                 } else {
 2888:                     last;
 2889:                 }
 2890:             }
 2891:         }
 2892:     }
 2893:     return $num_tries;
 2894: }
 2895: 
 2896: # ----------- Determine decrements required in aggregate totals 
 2897: sub decrement_aggs {
 2898:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2899:     my %decrement = (
 2900:                         attempts => 0,
 2901:                         users => 0,
 2902:                         correct => 0
 2903:                     );
 2904:     $decrement{'attempts'} = $aggtries;
 2905:     if ($solvedstatus =~ /^correct/) {
 2906:         $decrement{'correct'} = 1;
 2907:     }
 2908:     if ($aggtries == $totaltries) {
 2909:         $decrement{'users'} = 1;
 2910:     }
 2911:     foreach my $type (keys(%decrement)) {
 2912:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2913:     }
 2914:     return;
 2915: }
 2916: 
 2917: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2918: sub get_last_resets {
 2919:     my ($symb,$courseid,$partids) =@_;
 2920:     my %last_resets;
 2921:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2922:     my $cname = $env{'course.'.$courseid.'.num'};
 2923:     my @keys;
 2924:     foreach my $part (@{$partids}) {
 2925: 	push(@keys,"$symb\0$part\0resettime");
 2926:     }
 2927:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2928: 				     $cdom,$cname);
 2929:     foreach my $part (@{$partids}) {
 2930: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2931:     }
 2932:     return %last_resets;
 2933: }
 2934: 
 2935: # ----------- Handles creating versions for portfolio files as answers
 2936: sub version_portfiles {
 2937:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2938:     my $version_parts = join('|',@$v_flag);
 2939:     my @returned_keys;
 2940:     my $parts = join('|', @$parts_graded);
 2941:     my $portfolio_root = '/userfiles/portfolio';
 2942:     foreach my $key (keys(%$record)) {
 2943:         my $new_portfiles;
 2944:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2945:             my @versioned_portfiles;
 2946:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2947:             foreach my $file (@portfiles) {
 2948:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2949:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2950: 		my ($answer_name,$answer_ver,$answer_ext) =
 2951: 		    &file_name_version_ext($answer_file);
 2952:                 my $getpropath = 1;    
 2953:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2954:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2955:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2956:                 if ($new_answer ne 'problem getting file') {
 2957:                     push(@versioned_portfiles, $directory.$new_answer);
 2958:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2959:                         [$directory.$new_answer],
 2960:                         [$symb,$env{'request.course.id'},'graded']);
 2961:                 }
 2962:             }
 2963:             $$record{$key} = join(',',@versioned_portfiles);
 2964:             push(@returned_keys,$key);
 2965:         }
 2966:     } 
 2967:     return (@returned_keys);   
 2968: }
 2969: 
 2970: sub get_next_version {
 2971:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2972:     my $version;
 2973:     foreach my $row (@$dir_list) {
 2974:         my ($file) = split(/\&/,$row,2);
 2975:         my ($file_name,$file_version,$file_ext) =
 2976: 	    &file_name_version_ext($file);
 2977:         if (($file_name eq $answer_name) && 
 2978: 	    ($file_ext eq $answer_ext)) {
 2979:                 # gets here if filename and extension match, regardless of version
 2980:                 if ($file_version ne '') {
 2981:                 # a versioned file is found  so save it for later
 2982:                 if ($file_version > $version) {
 2983: 		    $version = $file_version;
 2984: 	        }
 2985:             }
 2986:         }
 2987:     } 
 2988:     $version ++;
 2989:     return($version);
 2990: }
 2991: 
 2992: sub version_selected_portfile {
 2993:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2994:     my ($answer_name,$answer_ver,$answer_ext) =
 2995:         &file_name_version_ext($file_name);
 2996:     my $new_answer;
 2997:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2998:     if($env{'form.copy'} eq '-1') {
 2999:         $new_answer = 'problem getting file';
 3000:     } else {
 3001:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3002:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3003:                             $stu_name,$domain,'copy',
 3004: 		        '/portfolio'.$directory.$new_answer);
 3005:     }    
 3006:     return ($new_answer);
 3007: }
 3008: 
 3009: sub file_name_version_ext {
 3010:     my ($file)=@_;
 3011:     my @file_parts = split(/\./, $file);
 3012:     my ($name,$version,$ext);
 3013:     if (@file_parts > 1) {
 3014: 	$ext=pop(@file_parts);
 3015: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3016: 	    $version=pop(@file_parts);
 3017: 	}
 3018: 	$name=join('.',@file_parts);
 3019:     } else {
 3020: 	$name=join('.',@file_parts);
 3021:     }
 3022:     return($name,$version,$ext);
 3023: }
 3024: 
 3025: #--------------------------------------------------------------------------------------
 3026: #
 3027: #-------------------------- Next few routines handles grading by section or whole class
 3028: #
 3029: #--- Javascript to handle grading by section or whole class
 3030: sub viewgrades_js {
 3031:     my ($request) = shift;
 3032: 
 3033:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3034:     $request->print(<<VIEWJAVASCRIPT);
 3035: <script type="text/javascript" language="javascript">
 3036:    function writePoint(partid,weight,point) {
 3037: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3038: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3039: 	if (point == "textval") {
 3040: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3041: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3042: 		alert("$alertmsg"+parseFloat(point));
 3043: 		var resetbox = false;
 3044: 		for (var i=0; i<radioButton.length; i++) {
 3045: 		    if (radioButton[i].checked) {
 3046: 			textbox.value = i;
 3047: 			resetbox = true;
 3048: 		    }
 3049: 		}
 3050: 		if (!resetbox) {
 3051: 		    textbox.value = "";
 3052: 		}
 3053: 		return;
 3054: 	    }
 3055: 	    if (parseFloat(point) > parseFloat(weight)) {
 3056: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3057: 				   ") greater than the weight for the part. Accept?");
 3058: 		if (resp == false) {
 3059: 		    textbox.value = "";
 3060: 		    return;
 3061: 		}
 3062: 	    }
 3063: 	    for (var i=0; i<radioButton.length; i++) {
 3064: 		radioButton[i].checked=false;
 3065: 		if (parseFloat(point) == i) {
 3066: 		    radioButton[i].checked=true;
 3067: 		}
 3068: 	    }
 3069: 
 3070: 	} else {
 3071: 	    textbox.value = parseFloat(point);
 3072: 	}
 3073: 	for (i=0;i<document.classgrade.total.value;i++) {
 3074: 	    var user = document.classgrade["ctr"+i].value;
 3075: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3076: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3077: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3078: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3079: 	    if (saveval != "correct") {
 3080: 		scorename.value = point;
 3081: 		if (selname[0].selected != true) {
 3082: 		    selname[0].selected = true;
 3083: 		}
 3084: 	    }
 3085: 	}
 3086: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3087:     }
 3088: 
 3089:     function writeRadText(partid,weight) {
 3090: 	var selval   = document.classgrade["SELVAL_"+partid];
 3091: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3092:         var override = document.classgrade["FORCE_"+partid].checked;
 3093: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3094: 	if (selval[1].selected || selval[2].selected) {
 3095: 	    for (var i=0; i<radioButton.length; i++) {
 3096: 		radioButton[i].checked=false;
 3097: 
 3098: 	    }
 3099: 	    textbox.value = "";
 3100: 
 3101: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3102: 		var user = document.classgrade["ctr"+i].value;
 3103: 		user = user.replace(new RegExp(':', 'g'),"_");
 3104: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3105: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3106: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3107: 		if ((saveval != "correct") || override) {
 3108: 		    scorename.value = "";
 3109: 		    if (selval[1].selected) {
 3110: 			selname[1].selected = true;
 3111: 		    } else {
 3112: 			selname[2].selected = true;
 3113: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3114: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3115: 		    }
 3116: 		}
 3117: 	    }
 3118: 	} else {
 3119: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3120: 		var user = document.classgrade["ctr"+i].value;
 3121: 		user = user.replace(new RegExp(':', 'g'),"_");
 3122: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3123: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3124: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3125: 		if ((saveval != "correct") || override) {
 3126: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3127: 		    selname[0].selected = true;
 3128: 		}
 3129: 	    }
 3130: 	}	    
 3131:     }
 3132: 
 3133:     function changeSelect(partid,user) {
 3134: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3135: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3136: 	var point  = textbox.value;
 3137: 	var weight = document.classgrade["weight_"+partid].value;
 3138: 
 3139: 	if (isNaN(point) || parseFloat(point) < 0) {
 3140: 	    alert("$alertmsg"+parseFloat(point));
 3141: 	    textbox.value = "";
 3142: 	    return;
 3143: 	}
 3144: 	if (parseFloat(point) > parseFloat(weight)) {
 3145: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3146: 			       ") greater than the weight of the part. Accept?");
 3147: 	    if (resp == false) {
 3148: 		textbox.value = "";
 3149: 		return;
 3150: 	    }
 3151: 	}
 3152: 	selval[0].selected = true;
 3153:     }
 3154: 
 3155:     function changeOneScore(partid,user) {
 3156: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3157: 	if (selval[1].selected || selval[2].selected) {
 3158: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3159: 	    if (selval[2].selected) {
 3160: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3161: 	    }
 3162:         }
 3163:     }
 3164: 
 3165:     function resetEntry(numpart) {
 3166: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3167: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3168: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3169: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3170: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3171: 	    for (var i=0; i<radioButton.length; i++) {
 3172: 		radioButton[i].checked=false;
 3173: 
 3174: 	    }
 3175: 	    textbox.value = "";
 3176: 	    selval[0].selected = true;
 3177: 
 3178: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3179: 		var user = document.classgrade["ctr"+i].value;
 3180: 		user = user.replace(new RegExp(':', 'g'),"_");
 3181: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3182: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3183: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3184: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3185: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3186: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3187: 		if (saveselval == "excused") {
 3188: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3189: 		} else {
 3190: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3191: 		}
 3192: 	    }
 3193: 	}
 3194:     }
 3195: 
 3196: </script>
 3197: VIEWJAVASCRIPT
 3198: }
 3199: 
 3200: #--- show scores for a section or whole class w/ option to change/update a score
 3201: sub viewgrades {
 3202:     my ($request) = shift;
 3203:     &viewgrades_js($request);
 3204: 
 3205:     my ($symb) = &get_symb($request);
 3206:     #need to make sure we have the correct data for later EXT calls, 
 3207:     #thus invalidate the cache
 3208:     &Apache::lonnet::devalidatecourseresdata(
 3209:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3210:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3211:     &Apache::lonnet::clear_EXT_cache_status();
 3212: 
 3213:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3214:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3215: 
 3216:     #view individual student submission form - called using Javascript viewOneStudent
 3217:     $result.=&jscriptNform($symb);
 3218: 
 3219:     #beginning of class grading form
 3220:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3221:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3222: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3223: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3224: 	&build_section_inputs().
 3225: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3226: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3227: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3228: 
 3229:     my $sectionClass;
 3230:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3231:     if ($env{'form.section'} eq 'all') {
 3232: 	$sectionClass=&mt('Class');
 3233:     } elsif ($env{'form.section'} eq 'none') {
 3234: 	$sectionClass=&mt('Students in no Section');
 3235:     } else {
 3236: 	$sectionClass=&mt('Students in Section(s) [_1]');
 3237:     }
 3238:     $result.=
 3239: 	'<h3>'.
 3240: 	&mt("Assign Common Grade to [_1]",$sectionClass,$section_display).'</h3>';
 3241:     $result.= &Apache::loncommon::start_data_table();
 3242:     #radio buttons/text box for assigning points for a section or class.
 3243:     #handles different parts of a problem
 3244:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3245:     my %weight = ();
 3246:     my $ctsparts = 0;
 3247:     my %seen = ();
 3248:     my @part_response_id = &flatten_responseType($responseType);
 3249:     foreach my $part_response_id (@part_response_id) {
 3250:     	my ($partid,$respid) = @{ $part_response_id };
 3251: 	my $part_resp = join('_',@{ $part_response_id });
 3252: 	next if $seen{$partid};
 3253: 	$seen{$partid}++;
 3254: 	my $handgrade=$$handgrade{$part_resp};
 3255: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3256: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3257: 
 3258: 	my $display_part=&get_display_part($partid,$symb);
 3259: 	my $radio.='<table border="0"><tr>';  
 3260: 	my $ctr = 0;
 3261: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3262: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3263: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3264: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3265: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3266: 	    $ctr++;
 3267: 	}
 3268: 	$radio.='</tr></table>';
 3269: 	my $line = '<input type="text" name="TEXTVAL_'.
 3270: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3271: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3272: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3273: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3274: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3275: 		$weight{$partid}.')"> '.
 3276: 	    '<option selected="selected"> </option>'.
 3277: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3278: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3279: 	    '</select></td>'.
 3280:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3281: 	$line.='<input type="hidden" name="partid_'.
 3282: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3283: 	$line.='<input type="hidden" name="weight_'.
 3284: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3285: 
 3286: 	$result.=
 3287: 	    &Apache::loncommon::start_data_table_row()."\n".
 3288: 	    '<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>'.
 3289: 	    &Apache::loncommon::end_data_table_row()."\n";
 3290: 	$ctsparts++;
 3291:     }
 3292:     $result.=&Apache::loncommon::end_data_table()."\n".
 3293: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3294:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3295: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3296: 
 3297:     #table listing all the students in a section/class
 3298:     #header of table
 3299:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in ').$sectionClass,
 3300: 			 $section_display.'</h3>';
 3301:     $result.= &Apache::loncommon::start_data_table().
 3302: 	&Apache::loncommon::start_data_table_header_row().
 3303: 	'<th>'.&mt('No.').'</th>'.
 3304: 	'<th>'.&nameUserString('header')."</th>\n";
 3305:     my (@parts) = sort(&getpartlist($symb));
 3306:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3307:     my @partids = ();
 3308:     foreach my $part (@parts) {
 3309: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3310:         my $narrowtext = &mt('Tries');
 3311: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3312: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3313: 	my ($partid) = &split_part_type($part);
 3314:         push(@partids,$partid);
 3315: 	my $display_part=&get_display_part($partid,$symb);
 3316: 	if ($display =~ /^Partial Credit Factor/) {
 3317: 	    $result.='<th>'.
 3318: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3319: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3320: 	    next;
 3321: 	    
 3322: 	} else {
 3323: 	    if ($display =~ /Problem Status/) {
 3324: 		my $grade_status_mt = &mt('Grade Status');
 3325: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3326: 	    }
 3327: 	    my $part_mt = &mt('Part:');
 3328: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3329: 	}
 3330: 
 3331: 	$result.='<th>'.$display.'</th>'."\n";
 3332:     }
 3333:     $result.=&Apache::loncommon::end_data_table_header_row();
 3334: 
 3335:     my %last_resets = 
 3336: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3337: 
 3338:     #get info for each student
 3339:     #list all the students - with points and grade status
 3340:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3341:     my $ctr = 0;
 3342:     foreach (sort 
 3343: 	     {
 3344: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3345: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3346: 		 }
 3347: 		 return $a cmp $b;
 3348: 	     } (keys(%$fullname))) {
 3349: 	$ctr++;
 3350: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3351: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3352:     }
 3353:     $result.=&Apache::loncommon::end_data_table();
 3354:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3355:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3356: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3357:     if (scalar(%$fullname) eq 0) {
 3358: 	my $colspan=3+scalar(@parts);
 3359: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3360:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3361: 	$result='<span class="LC_warning">'.
 3362: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3363: 	        $section_display, $stu_status).
 3364: 	    '</span>';
 3365:     }
 3366:     $result.=&show_grading_menu_form($symb);
 3367:     return $result;
 3368: }
 3369: 
 3370: #--- call by previous routine to display each student
 3371: sub viewstudentgrade {
 3372:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3373:     my ($uname,$udom) = split(/:/,$student);
 3374:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3375:     my %aggregates = (); 
 3376:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3377: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3378: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3379: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3380: 	'\');" target="_self">'.$fullname.'</a> '.
 3381: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3382:     $student=~s/:/_/; # colon doen't work in javascript for names
 3383:     foreach my $apart (@$parts) {
 3384: 	my ($part,$type) = &split_part_type($apart);
 3385: 	my $score=$record{"resource.$part.$type"};
 3386:         $result.='<td align="center">';
 3387:         my ($aggtries,$totaltries);
 3388:         unless (exists($aggregates{$part})) {
 3389: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3390: 
 3391: 	    $aggtries = $totaltries;
 3392:             if ($$last_resets{$part}) {  
 3393:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3394: 					   $part);
 3395:             }
 3396:             $result.='<input type="hidden" name="'.
 3397:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3398:             $result.='<input type="hidden" name="'.
 3399:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3400:             $aggregates{$part} = 1;
 3401:         }
 3402: 	if ($type eq 'awarded') {
 3403: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3404: 	    $result.='<input type="hidden" name="'.
 3405: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3406: 	    $result.='<input type="text" name="'.
 3407: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3408: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3409: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3410: 	} elsif ($type eq 'solved') {
 3411: 	    my ($status,$foo)=split(/_/,$score,2);
 3412: 	    $status = 'nothing' if ($status eq '');
 3413: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3414: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3415: 	    $result.='&nbsp;<select name="'.
 3416: 		'GD_'.$student.'_'.$part.'_solved" '.
 3417: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3418: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3419: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3420: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3421: 	    $result.="</select>&nbsp;</td>\n";
 3422: 	} else {
 3423: 	    $result.='<input type="hidden" name="'.
 3424: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3425: 		    "\n";
 3426: 	    $result.='<input type="text" name="'.
 3427: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3428: 		'value="'.$score.'" size="4" /></td>'."\n";
 3429: 	}
 3430:     }
 3431:     $result.=&Apache::loncommon::end_data_table_row();
 3432:     return $result;
 3433: }
 3434: 
 3435: #--- change scores for all the students in a section/class
 3436: #    record does not get update if unchanged
 3437: sub editgrades {
 3438:     my ($request) = @_;
 3439: 
 3440:     my $symb=&get_symb($request);
 3441:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3442:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3443:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3444:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3445: 
 3446:     my $result= &Apache::loncommon::start_data_table().
 3447: 	&Apache::loncommon::start_data_table_header_row().
 3448: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3449: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3450:     my %scoreptr = (
 3451: 		    'correct'  =>'correct_by_override',
 3452: 		    'incorrect'=>'incorrect_by_override',
 3453: 		    'excused'  =>'excused',
 3454: 		    'ungraded' =>'ungraded_attempted',
 3455: 		    'nothing'  => '',
 3456: 		    );
 3457:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3458: 
 3459:     my (@partid);
 3460:     my %weight = ();
 3461:     my %columns = ();
 3462:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3463: 
 3464:     my (@parts) = sort(&getpartlist($symb));
 3465:     my $header;
 3466:     while ($ctr < $env{'form.totalparts'}) {
 3467: 	my $partid = $env{'form.partid_'.$ctr};
 3468: 	push(@partid,$partid);
 3469: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3470: 	$ctr++;
 3471:     }
 3472:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3473:     foreach my $partid (@partid) {
 3474: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3475: 	    '<th align="center">'.&mt('New Score').'</th>';
 3476: 	$columns{$partid}=2;
 3477: 	foreach my $stores (@parts) {
 3478: 	    my ($part,$type) = &split_part_type($stores);
 3479: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3480: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3481: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3482: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3483:             my $narrowtext = &mt('Tries');
 3484: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3485: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3486: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3487: 	    $columns{$partid}+=2;
 3488: 	}
 3489:     }
 3490:     foreach my $partid (@partid) {
 3491: 	my $display_part=&get_display_part($partid,$symb);
 3492: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3493: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3494: 	    '</th>';
 3495: 
 3496:     }
 3497:     $result .= &Apache::loncommon::end_data_table_header_row().
 3498: 	&Apache::loncommon::start_data_table_header_row().
 3499: 	$header.
 3500: 	&Apache::loncommon::end_data_table_header_row();
 3501:     my @noupdate;
 3502:     my ($updateCtr,$noupdateCtr) = (1,1);
 3503:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3504: 	my $line;
 3505: 	my $user = $env{'form.ctr'.$i};
 3506: 	my ($uname,$udom)=split(/:/,$user);
 3507: 	my %newrecord;
 3508: 	my $updateflag = 0;
 3509: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3510: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3511: 	if (!&canmodify($usec)) {
 3512: 	    my $numcols=scalar(@partid)*4+2;
 3513: 	    push(@noupdate,
 3514: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3515: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3516: 	    next;
 3517: 	}
 3518:         my %aggregate = ();
 3519:         my $aggregateflag = 0;
 3520: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3521: 	foreach (@partid) {
 3522: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3523: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3524: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3525: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3526: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3527: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3528: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3529: 	    my $score;
 3530: 	    if ($partial eq '') {
 3531: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3532: 	    } elsif ($partial > 0) {
 3533: 		$score = 'correct_by_override';
 3534: 	    } elsif ($partial == 0) {
 3535: 		$score = 'incorrect_by_override';
 3536: 	    }
 3537: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3538: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3539: 
 3540: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3541: 		"$env{'user.name'}:$env{'user.domain'}";
 3542: 	    if ($dropMenu eq 'reset status' &&
 3543: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3544: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3545: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3546: 		$newrecord{'resource.'.$_.'.award'} = '';
 3547: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3548: 		$updateflag = 1;
 3549:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3550:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3551:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3552:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3553:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3554:                     $aggregateflag = 1;
 3555:                 }
 3556: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3557: 		$updateflag = 1;
 3558: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3559: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3560: 		$rec_update++;
 3561: 	    }
 3562: 
 3563: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3564: 		'<td align="center">'.$awarded.
 3565: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3566: 
 3567: 
 3568: 	    my $partid=$_;
 3569: 	    foreach my $stores (@parts) {
 3570: 		my ($part,$type) = &split_part_type($stores);
 3571: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3572: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3573: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3574: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3575: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3576: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3577: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3578: 		    $updateflag=1;
 3579: 		}
 3580: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3581: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3582: 	    }
 3583: 	}
 3584: 	$line.="\n";
 3585: 
 3586: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3587: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3588: 
 3589: 	if ($updateflag) {
 3590: 	    $count++;
 3591: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3592: 				    $udom,$uname);
 3593: 
 3594: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3595: 					      $cnum,$udom,$uname)) {
 3596: 		# need to figure out if should be in queue.
 3597: 		my %record =  
 3598: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3599: 					     $udom,$uname);
 3600: 		my $all_graded = 1;
 3601: 		my $none_graded = 1;
 3602: 		foreach my $part (@parts) {
 3603: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3604: 			$all_graded = 0;
 3605: 		    } else {
 3606: 			$none_graded = 0;
 3607: 		    }
 3608: 		}
 3609: 
 3610: 		if ($all_graded || $none_graded) {
 3611: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3612: 							   $symb,$cdom,$cnum,
 3613: 							   $udom,$uname);
 3614: 		}
 3615: 	    }
 3616: 
 3617: 	    $result.=&Apache::loncommon::start_data_table_row().
 3618: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3619: 		&Apache::loncommon::end_data_table_row();
 3620: 	    $updateCtr++;
 3621: 	} else {
 3622: 	    push(@noupdate,
 3623: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3624: 	    $noupdateCtr++;
 3625: 	}
 3626:         if ($aggregateflag) {
 3627:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3628: 				  $cdom,$cnum);
 3629:         }
 3630:     }
 3631:     if (@noupdate) {
 3632: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3633: 	my $numcols=scalar(@partid)*4+2;
 3634: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3635: 	    '<td align="center" colspan="'.$numcols.'">'.
 3636: 	    &mt('No Changes Occurred For the Students Below').
 3637: 	    '</td>'.
 3638: 	    &Apache::loncommon::end_data_table_row();
 3639: 	foreach my $line (@noupdate) {
 3640: 	    $result.=
 3641: 		&Apache::loncommon::start_data_table_row().
 3642: 		$line.
 3643: 		&Apache::loncommon::end_data_table_row();
 3644: 	}
 3645:     }
 3646:     $result .= &Apache::loncommon::end_data_table().
 3647: 	&show_grading_menu_form($symb);
 3648:     my $msg = '<p><b>'.
 3649: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3650: 	    $rec_update,$count).'</b><br />'.
 3651: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3652: 	'</b></p>';
 3653:     return $title.$msg.$result;
 3654: }
 3655: 
 3656: sub split_part_type {
 3657:     my ($partstr) = @_;
 3658:     my ($temp,@allparts)=split(/_/,$partstr);
 3659:     my $type=pop(@allparts);
 3660:     my $part=join('_',@allparts);
 3661:     return ($part,$type);
 3662: }
 3663: 
 3664: #------------- end of section for handling grading by section/class ---------
 3665: #
 3666: #----------------------------------------------------------------------------
 3667: 
 3668: 
 3669: #----------------------------------------------------------------------------
 3670: #
 3671: #-------------------------- Next few routines handles grading by csv upload
 3672: #
 3673: #--- Javascript to handle csv upload
 3674: sub csvupload_javascript_reverse_associate {
 3675:     my $error1=&mt('You need to specify the username or ID');
 3676:     my $error2=&mt('You need to specify at least one grading field');
 3677:   return(<<ENDPICK);
 3678:   function verify(vf) {
 3679:     var foundsomething=0;
 3680:     var founduname=0;
 3681:     var foundID=0;
 3682:     for (i=0;i<=vf.nfields.value;i++) {
 3683:       tw=eval('vf.f'+i+'.selectedIndex');
 3684:       if (i==0 && tw!=0) { foundID=1; }
 3685:       if (i==1 && tw!=0) { founduname=1; }
 3686:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3687:     }
 3688:     if (founduname==0 && foundID==0) {
 3689: 	alert('$error1');
 3690: 	return;
 3691:     }
 3692:     if (foundsomething==0) {
 3693: 	alert('$error2');
 3694: 	return;
 3695:     }
 3696:     vf.submit();
 3697:   }
 3698:   function flip(vf,tf) {
 3699:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3700:     var i;
 3701:     for (i=0;i<=vf.nfields.value;i++) {
 3702:       //can not pick the same destination field for both name and domain
 3703:       if (((i ==0)||(i ==1)) && 
 3704:           ((tf==0)||(tf==1)) && 
 3705:           (i!=tf) &&
 3706:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3707:         eval('vf.f'+i+'.selectedIndex=0;')
 3708:       }
 3709:     }
 3710:   }
 3711: ENDPICK
 3712: }
 3713: 
 3714: sub csvupload_javascript_forward_associate {
 3715:     my $error1=&mt('You need to specify the username or ID');
 3716:     my $error2=&mt('You need to specify at least one grading field');
 3717:   return(<<ENDPICK);
 3718:   function verify(vf) {
 3719:     var foundsomething=0;
 3720:     var founduname=0;
 3721:     var foundID=0;
 3722:     for (i=0;i<=vf.nfields.value;i++) {
 3723:       tw=eval('vf.f'+i+'.selectedIndex');
 3724:       if (tw==1) { foundID=1; }
 3725:       if (tw==2) { founduname=1; }
 3726:       if (tw>3) { foundsomething=1; }
 3727:     }
 3728:     if (founduname==0 && foundID==0) {
 3729: 	alert('$error1');
 3730: 	return;
 3731:     }
 3732:     if (foundsomething==0) {
 3733: 	alert('$error2');
 3734: 	return;
 3735:     }
 3736:     vf.submit();
 3737:   }
 3738:   function flip(vf,tf) {
 3739:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3740:     var i;
 3741:     //can not pick the same destination field twice
 3742:     for (i=0;i<=vf.nfields.value;i++) {
 3743:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3744:         eval('vf.f'+i+'.selectedIndex=0;')
 3745:       }
 3746:     }
 3747:   }
 3748: ENDPICK
 3749: }
 3750: 
 3751: sub csvuploadmap_header {
 3752:     my ($request,$symb,$datatoken,$distotal)= @_;
 3753:     my $javascript;
 3754:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3755: 	$javascript=&csvupload_javascript_reverse_associate();
 3756:     } else {
 3757: 	$javascript=&csvupload_javascript_forward_associate();
 3758:     }
 3759: 
 3760:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3761:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3762:     my $ignore=&mt('Ignore First Line');
 3763:     $symb = &Apache::lonenc::check_encrypt($symb);
 3764:     $request->print(<<ENDPICK);
 3765: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3766: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3767: $result
 3768: <hr />
 3769: <h3>Identify fields</h3>
 3770: Total number of records found in file: $distotal <hr />
 3771: Enter as many fields as you can. The system will inform you and bring you back
 3772: to this page if the data selected is insufficient to run your class.<hr />
 3773: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3774: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3775: <input type="hidden" name="associate"  value="" />
 3776: <input type="hidden" name="phase"      value="three" />
 3777: <input type="hidden" name="datatoken"  value="$datatoken" />
 3778: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3779: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3780: <input type="hidden" name="upfile_associate" 
 3781:                                        value="$env{'form.upfile_associate'}" />
 3782: <input type="hidden" name="symb"       value="$symb" />
 3783: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3784: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3785: <input type="hidden" name="command"    value="csvuploadoptions" />
 3786: <hr />
 3787: <script type="text/javascript" language="Javascript">
 3788: $javascript
 3789: </script>
 3790: ENDPICK
 3791:     return '';
 3792: 
 3793: }
 3794: 
 3795: sub csvupload_fields {
 3796:     my ($symb) = @_;
 3797:     my (@parts) = &getpartlist($symb);
 3798:     my @fields=(['ID','Student/Employee ID'],
 3799: 		['username','Student Username'],
 3800: 		['domain','Student Domain']);
 3801:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3802:     foreach my $part (sort(@parts)) {
 3803: 	my @datum;
 3804: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3805: 	my $name=$part;
 3806: 	if  (!$display) { $display = $name; }
 3807: 	@datum=($name,$display);
 3808: 	if ($name=~/^stores_(.*)_awarded/) {
 3809: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3810: 	}
 3811: 	push(@fields,\@datum);
 3812:     }
 3813:     return (@fields);
 3814: }
 3815: 
 3816: sub csvuploadmap_footer {
 3817:     my ($request,$i,$keyfields) =@_;
 3818:     $request->print(<<ENDPICK);
 3819: </table>
 3820: <input type="hidden" name="nfields" value="$i" />
 3821: <input type="hidden" name="keyfields" value="$keyfields" />
 3822: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3823: </form>
 3824: ENDPICK
 3825: }
 3826: 
 3827: sub checkforfile_js {
 3828:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3829:     my $result =<<CSVFORMJS;
 3830: <script type="text/javascript" language="javascript">
 3831:     function checkUpload(formname) {
 3832: 	if (formname.upfile.value == "") {
 3833: 	    alert("$alertmsg");
 3834: 	    return false;
 3835: 	}
 3836: 	formname.submit();
 3837:     }
 3838:     </script>
 3839: CSVFORMJS
 3840:     return $result;
 3841: }
 3842: 
 3843: sub upcsvScores_form {
 3844:     my ($request) = shift;
 3845:     my ($symb)=&get_symb($request);
 3846:     if (!$symb) {return '';}
 3847:     my $result=&checkforfile_js();
 3848:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3849:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3850:     $result.=$table;
 3851:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3852:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3853:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3854: 	'</b></td></tr>'."\n";
 3855:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3856:     my $upload=&mt("Upload Scores");
 3857:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3858:     my $ignore=&mt('Ignore First Line');
 3859:     $symb = &Apache::lonenc::check_encrypt($symb);
 3860:     $result.=<<ENDUPFORM;
 3861: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3862: <input type="hidden" name="symb" value="$symb" />
 3863: <input type="hidden" name="command" value="csvuploadmap" />
 3864: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3865: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3866: $upfile_select
 3867: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3868: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3869: </form>
 3870: ENDUPFORM
 3871:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3872:                            &mt("How do I create a CSV file from a spreadsheet"))
 3873:     .'</td></tr></table>'."\n";
 3874:     $result.='</td></tr></table><br /><br />'."\n";
 3875:     $result.=&show_grading_menu_form($symb);
 3876:     return $result;
 3877: }
 3878: 
 3879: 
 3880: sub csvuploadmap {
 3881:     my ($request)= @_;
 3882:     my ($symb)=&get_symb($request);
 3883:     if (!$symb) {return '';}
 3884: 
 3885:     my $datatoken;
 3886:     if (!$env{'form.datatoken'}) {
 3887: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3888:     } else {
 3889: 	$datatoken=$env{'form.datatoken'};
 3890: 	&Apache::loncommon::load_tmp_file($request);
 3891:     }
 3892:     my @records=&Apache::loncommon::upfile_record_sep();
 3893:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3894:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3895:     my ($i,$keyfields);
 3896:     if (@records) {
 3897: 	my @fields=&csvupload_fields($symb);
 3898: 
 3899: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3900: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3901: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3902: 							  \@fields);
 3903: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3904: 	    chop($keyfields);
 3905: 	} else {
 3906: 	    unshift(@fields,['none','']);
 3907: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3908: 							    \@fields);
 3909:             foreach my $rec (@records) {
 3910:                 my %temp = &Apache::loncommon::record_sep($rec);
 3911:                 if (%temp) {
 3912:                     $keyfields=join(',',sort(keys(%temp)));
 3913:                     last;
 3914:                 }
 3915:             }
 3916: 	}
 3917:     }
 3918:     &csvuploadmap_footer($request,$i,$keyfields);
 3919:     $request->print(&show_grading_menu_form($symb));
 3920: 
 3921:     return '';
 3922: }
 3923: 
 3924: sub csvuploadoptions {
 3925:     my ($request)= @_;
 3926:     my ($symb)=&get_symb($request);
 3927:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3928:     my $ignore=&mt('Ignore First Line');
 3929:     $request->print(<<ENDPICK);
 3930: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3931: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3932: <input type="hidden" name="command"    value="csvuploadassign" />
 3933: <!--
 3934: <p>
 3935: <label>
 3936:    <input type="checkbox" name="show_full_results" />
 3937:    Show a table of all changes
 3938: </label>
 3939: </p>
 3940: -->
 3941: <p>
 3942: <label>
 3943:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3944:    Overwrite any existing score
 3945: </label>
 3946: </p>
 3947: ENDPICK
 3948:     my %fields=&get_fields();
 3949:     if (!defined($fields{'domain'})) {
 3950: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3951: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3952:     }
 3953:     foreach my $key (sort(keys(%env))) {
 3954: 	if ($key !~ /^form\.(.*)$/) { next; }
 3955: 	my $cleankey=$1;
 3956: 	if ($cleankey eq 'command') { next; }
 3957: 	$request->print('<input type="hidden" name="'.$cleankey.
 3958: 			'"  value="'.$env{$key}.'" />'."\n");
 3959:     }
 3960:     # FIXME do a check for any duplicated user ids...
 3961:     # FIXME do a check for any invalid user ids?...
 3962:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3963: <hr /></form>'."\n");
 3964:     $request->print(&show_grading_menu_form($symb));
 3965:     return '';
 3966: }
 3967: 
 3968: sub get_fields {
 3969:     my %fields;
 3970:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3971:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3972: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3973: 	    if ($env{'form.f'.$i} ne 'none') {
 3974: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3975: 	    }
 3976: 	} else {
 3977: 	    if ($env{'form.f'.$i} ne 'none') {
 3978: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3979: 	    }
 3980: 	}
 3981:     }
 3982:     return %fields;
 3983: }
 3984: 
 3985: sub csvuploadassign {
 3986:     my ($request)= @_;
 3987:     my ($symb)=&get_symb($request);
 3988:     if (!$symb) {return '';}
 3989:     my $error_msg = '';
 3990:     &Apache::loncommon::load_tmp_file($request);
 3991:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3992:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3993:     my %fields=&get_fields();
 3994:     $request->print('<h3>Assigning Grades</h3>');
 3995:     my $courseid=$env{'request.course.id'};
 3996:     my ($classlist) = &getclasslist('all',0);
 3997:     my @notallowed;
 3998:     my @skipped;
 3999:     my $countdone=0;
 4000:     foreach my $grade (@gradedata) {
 4001: 	my %entries=&Apache::loncommon::record_sep($grade);
 4002: 	my $domain;
 4003: 	if ($entries{$fields{'domain'}}) {
 4004: 	    $domain=$entries{$fields{'domain'}};
 4005: 	} else {
 4006: 	    $domain=$env{'form.default_domain'};
 4007: 	}
 4008: 	$domain=~s/\s//g;
 4009: 	my $username=$entries{$fields{'username'}};
 4010: 	$username=~s/\s//g;
 4011: 	if (!$username) {
 4012: 	    my $id=$entries{$fields{'ID'}};
 4013: 	    $id=~s/\s//g;
 4014: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4015: 	    $username=$ids{$id};
 4016: 	}
 4017: 	if (!exists($$classlist{"$username:$domain"})) {
 4018: 	    my $id=$entries{$fields{'ID'}};
 4019: 	    $id=~s/\s//g;
 4020: 	    if ($id) {
 4021: 		push(@skipped,"$id:$domain");
 4022: 	    } else {
 4023: 		push(@skipped,"$username:$domain");
 4024: 	    }
 4025: 	    next;
 4026: 	}
 4027: 	my $usec=$classlist->{"$username:$domain"}[5];
 4028: 	if (!&canmodify($usec)) {
 4029: 	    push(@notallowed,"$username:$domain");
 4030: 	    next;
 4031: 	}
 4032: 	my %points;
 4033: 	my %grades;
 4034: 	foreach my $dest (keys(%fields)) {
 4035: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4036: 		$dest eq 'domain') { next; }
 4037: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4038: 	    if ($dest=~/stores_(.*)_points/) {
 4039: 		my $part=$1;
 4040: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4041: 					      $symb,$domain,$username);
 4042:                 if ($wgt) {
 4043:                     $entries{$fields{$dest}}=~s/\s//g;
 4044:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4045:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4046:                                           : 'correct_by_override';
 4047:                     $grades{"resource.$part.awarded"}=$pcr;
 4048:                     $grades{"resource.$part.solved"}=$award;
 4049:                     $points{$part}=1;
 4050:                 } else {
 4051:                     $error_msg = "<br />" .
 4052:                         &mt("Some point values were assigned"
 4053:                             ." for problems with a weight "
 4054:                             ."of zero. These values were "
 4055:                             ."ignored.");
 4056:                 }
 4057: 	    } else {
 4058: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4059: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4060: 		my $store_key=$dest;
 4061: 		$store_key=~s/^stores/resource/;
 4062: 		$store_key=~s/_/\./g;
 4063: 		$grades{$store_key}=$entries{$fields{$dest}};
 4064: 	    }
 4065: 	}
 4066: 	if (! %grades) { 
 4067:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4068:         } else {
 4069: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4070: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4071: 					   $env{'request.course.id'},
 4072: 					   $domain,$username);
 4073: 	   if ($result eq 'ok') {
 4074: 	      $request->print('.');
 4075: 	   } else {
 4076: 	      $request->print("<p><span class=\"LC_error\">".
 4077:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4078:                                   "$username:$domain",$result)."</span></p>");
 4079: 	   }
 4080: 	   $request->rflush();
 4081: 	   $countdone++;
 4082:         }
 4083:     }
 4084:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4085:     if (@skipped) {
 4086: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4087: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4088:     }
 4089:     if (@notallowed) {
 4090: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4091: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4092:     }
 4093:     $request->print("<br />\n");
 4094:     $request->print(&show_grading_menu_form($symb));
 4095:     return $error_msg;
 4096: }
 4097: #------------- end of section for handling csv file upload ---------
 4098: #
 4099: #-------------------------------------------------------------------
 4100: #
 4101: #-------------- Next few routines handle grading by page/sequence
 4102: #
 4103: #--- Select a page/sequence and a student to grade
 4104: sub pickStudentPage {
 4105:     my ($request) = shift;
 4106: 
 4107:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4108:     $request->print(<<LISTJAVASCRIPT);
 4109: <script type="text/javascript" language="javascript">
 4110: 
 4111: function checkPickOne(formname) {
 4112:     if (radioSelection(formname.student) == null) {
 4113: 	alert("$alertmsg");
 4114: 	return;
 4115:     }
 4116:     ptr = pullDownSelection(formname.selectpage);
 4117:     formname.page.value = formname["page"+ptr].value;
 4118:     formname.title.value = formname["title"+ptr].value;
 4119:     formname.submit();
 4120: }
 4121: 
 4122: </script>
 4123: LISTJAVASCRIPT
 4124:     &commonJSfunctions($request);
 4125:     my ($symb) = &get_symb($request);
 4126:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4127:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4128:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4129: 
 4130:     my $result='<h3><span class="LC_info">&nbsp;'.
 4131: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4132: 
 4133:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4134:     my ($titles,$symbx) = &getSymbMap();
 4135:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4136: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4137: #    my $type=($curpage =~ /\.(page|sequence)/);
 4138:     my $select = '<select name="selectpage">'."\n";
 4139:     my $ctr=0;
 4140:     foreach (@$titles) {
 4141: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4142: 	$select.='<option value="'.$ctr.'" '.
 4143: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4144: 	    '>'.$showtitle.'</option>'."\n";
 4145: 	$ctr++;
 4146:     }
 4147:     $select.= '</select>';
 4148:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4149: 
 4150:     $ctr=0;
 4151:     foreach (@$titles) {
 4152: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4153: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4154: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4155: 	$ctr++;
 4156:     }
 4157:     $result.='<input type="hidden" name="page" />'."\n".
 4158: 	'<input type="hidden" name="title" />'."\n";
 4159: 
 4160:     my $options =
 4161: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4162: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4163:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4164: 
 4165:     $options =
 4166: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4167: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4168: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4169:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4170:     
 4171:     $result.=&build_section_inputs();
 4172:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4173:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4174: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4175: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4176: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4177: 
 4178:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4179: 
 4180:     $result.='&nbsp;<input type="button" '.
 4181: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4182: 
 4183:     $request->print($result);
 4184: 
 4185:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4186: 	&Apache::loncommon::start_data_table().
 4187: 	&Apache::loncommon::start_data_table_header_row().
 4188: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4189: 	'<th>'.&nameUserString('header').'</th>'.
 4190: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4191: 	'<th>'.&nameUserString('header').'</th>'.
 4192: 	&Apache::loncommon::end_data_table_header_row();
 4193:  
 4194:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4195:     my $ptr = 1;
 4196:     foreach my $student (sort 
 4197: 			 {
 4198: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4199: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4200: 			     }
 4201: 			     return $a cmp $b;
 4202: 			 } (keys(%$fullname))) {
 4203: 	my ($uname,$udom) = split(/:/,$student);
 4204: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4205:                                   : '</td>');
 4206: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4207: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4208: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4209: 	$studentTable.=
 4210: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4211:                          : '');
 4212: 	$ptr++;
 4213:     }
 4214:     if ($ptr%2 == 0) {
 4215: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4216: 	    &Apache::loncommon::end_data_table_row();
 4217:     }
 4218:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4219:     $studentTable.='<input type="button" '.
 4220: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4221: 
 4222:     $studentTable.=&show_grading_menu_form($symb);
 4223:     $request->print($studentTable);
 4224: 
 4225:     return '';
 4226: }
 4227: 
 4228: sub getSymbMap {
 4229:     my $navmap = Apache::lonnavmaps::navmap->new();
 4230: 
 4231:     my %symbx = ();
 4232:     my @titles = ();
 4233:     my $minder = 0;
 4234: 
 4235:     # Gather every sequence that has problems.
 4236:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4237: 					       1,0,1);
 4238:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4239: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4240: 	    my $title = $minder.'.'.
 4241: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4242: 	    push(@titles, $title); # minder in case two titles are identical
 4243: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4244: 	    $minder++;
 4245: 	}
 4246:     }
 4247:     return \@titles,\%symbx;
 4248: }
 4249: 
 4250: #
 4251: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4252: sub displayPage {
 4253:     my ($request) = shift;
 4254: 
 4255:     my ($symb) = &get_symb($request);
 4256:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4257:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4258:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4259:     my $pageTitle = $env{'form.page'};
 4260:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4261:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4262:     my $usec=$classlist->{$env{'form.student'}}[5];
 4263: 
 4264:     #need to make sure we have the correct data for later EXT calls, 
 4265:     #thus invalidate the cache
 4266:     &Apache::lonnet::devalidatecourseresdata(
 4267:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4268:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4269:     &Apache::lonnet::clear_EXT_cache_status();
 4270: 
 4271:     if (!&canview($usec)) {
 4272: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4273: 	$request->print(&show_grading_menu_form($symb));
 4274: 	return;
 4275:     }
 4276:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4277:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4278: 	'</h3>'."\n";
 4279:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4280:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4281: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4282:     } else {
 4283: 	delete($env{'form.CODE'});
 4284:     }
 4285:     &sub_page_js($request);
 4286:     $request->print($result);
 4287: 
 4288:     my $navmap = Apache::lonnavmaps::navmap->new();
 4289:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4290:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4291:     if (!$map) {
 4292: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4293: 	$request->print(&show_grading_menu_form($symb));
 4294: 	return; 
 4295:     }
 4296:     my $iterator = $navmap->getIterator($map->map_start(),
 4297: 					$map->map_finish());
 4298: 
 4299:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4300: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4301: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4302: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4303: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4304: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4305: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4306: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4307: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4308: 
 4309:     if (defined($env{'form.CODE'})) {
 4310: 	$studentTable.=
 4311: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4312:     }
 4313:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4314: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4315: 
 4316:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4317: 	&Apache::loncommon::start_data_table().
 4318: 	&Apache::loncommon::start_data_table_header_row().
 4319: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4320: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4321: 	&Apache::loncommon::end_data_table_header_row();
 4322: 
 4323:     &Apache::lonxml::clear_problem_counter();
 4324:     my ($depth,$question,$prob) = (1,1,1);
 4325:     $iterator->next(); # skip the first BEGIN_MAP
 4326:     my $curRes = $iterator->next(); # for "current resource"
 4327:     while ($depth > 0) {
 4328:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4329:         if($curRes == $iterator->END_MAP) { $depth--; }
 4330: 
 4331:         if (ref($curRes) && $curRes->is_problem()) {
 4332: 	    my $parts = $curRes->parts();
 4333:             my $title = $curRes->compTitle();
 4334: 	    my $symbx = $curRes->symb();
 4335: 	    $studentTable.=
 4336: 		&Apache::loncommon::start_data_table_row().
 4337: 		'<td align="center" valign="top" >'.$prob.
 4338: 		(scalar(@{$parts}) == 1 ? '' 
 4339: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4340: 							scalar(@{$parts}))
 4341: 		 ).
 4342: 		 '</td>';
 4343: 	    $studentTable.='<td valign="top">';
 4344: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4345: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4346: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4347: 					     undef,'both',\%form);
 4348: 	    } else {
 4349: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4350: 		$companswer =~ s|<form(.*?)>||g;
 4351: 		$companswer =~ s|</form>||g;
 4352: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4353: #		    $companswer =~ s/$1/ /ms;
 4354: #		    $request->print('match='.$1."<br />\n");
 4355: #		}
 4356: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4357: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4358: 	    }
 4359: 
 4360: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4361: 
 4362: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4363: 		if ($record{'version'} eq '') {
 4364: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4365: 		} else {
 4366: 		    my %responseType = ();
 4367: 		    foreach my $partid (@{$parts}) {
 4368: 			my @responseIds =$curRes->responseIds($partid);
 4369: 			my @responseType =$curRes->responseType($partid);
 4370: 			my %responseIds;
 4371: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4372: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4373: 			}
 4374: 			$responseType{$partid} = \%responseIds;
 4375: 		    }
 4376: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4377: 
 4378: 		}
 4379: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4380: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4381: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4382: 									$env{'request.course.id'},
 4383: 									'','.submission');
 4384:  
 4385: 	    }
 4386: 	    if (&canmodify($usec)) {
 4387: 		foreach my $partid (@{$parts}) {
 4388: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4389: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4390: 		    $question++;
 4391: 		}
 4392: 		$prob++;
 4393: 	    }
 4394: 	    $studentTable.='</td></tr>';
 4395: 
 4396: 	}
 4397:         $curRes = $iterator->next();
 4398:     }
 4399: 
 4400:     $studentTable.='</table>'."\n".
 4401: 	'<input type="button" value="'.&mt('Save').'" '.
 4402: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4403: 	'</form>'."\n";
 4404:     $studentTable.=&show_grading_menu_form($symb);
 4405:     $request->print($studentTable);
 4406: 
 4407:     return '';
 4408: }
 4409: 
 4410: sub displaySubByDates {
 4411:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4412:     my $isCODE=0;
 4413:     my $isTask = ($symb =~/\.task$/);
 4414:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4415:     my $studentTable=&Apache::loncommon::start_data_table().
 4416: 	&Apache::loncommon::start_data_table_header_row().
 4417: 	'<th>'.&mt('Date/Time').'</th>'.
 4418: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4419: 	'<th>'.&mt('Submission').'</th>'.
 4420: 	'<th>'.&mt('Status').'</th>'.
 4421: 	&Apache::loncommon::end_data_table_header_row();
 4422:     my ($version);
 4423:     my %mark;
 4424:     my %orders;
 4425:     $mark{'correct_by_student'} = $checkIcon;
 4426:     if (!exists($$record{'1:timestamp'})) {
 4427: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4428:     }
 4429: 
 4430:     my $interaction;
 4431:     my $no_increment = 1;
 4432:     for ($version=1;$version<=$$record{'version'};$version++) {
 4433: 	my $timestamp = 
 4434: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4435: 	if (exists($$record{$version.':resource.0.version'})) {
 4436: 	    $interaction = $$record{$version.':resource.0.version'};
 4437: 	}
 4438: 
 4439: 	my $where = ($isTask ? "$version:resource.$interaction"
 4440: 		             : "$version:resource");
 4441: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4442: 	    '<td>'.$timestamp.'</td>';
 4443: 	if ($isCODE) {
 4444: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4445: 	}
 4446: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4447: 	my @displaySub = ();
 4448: 	foreach my $partid (@{$parts}) {
 4449: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4450: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4451: 	    
 4452: 
 4453: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4454: 	    my $display_part=&get_display_part($partid,$symb);
 4455: 	    foreach my $matchKey (@matchKey) {
 4456: 		if (exists($$record{$version.':'.$matchKey}) &&
 4457: 		    $$record{$version.':'.$matchKey} ne '') {
 4458: 
 4459: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4460: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4461: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4462: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4463: 			$responseId.')</span>&nbsp;<b>';
 4464: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4465: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4466: 		    } else {
 4467: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4468: 					    $$record{"$where.$partid.tries"});
 4469: 		    }
 4470: 		    my $responseType=($isTask ? 'Task'
 4471:                                               : $responseType->{$partid}->{$responseId});
 4472: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4473: 		    if (!exists($orders{$partid}->{$responseId})) {
 4474: 			$orders{$partid}->{$responseId}=
 4475: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4476:                                        $no_increment);
 4477: 		    }
 4478: 		    $displaySub[0].='</b>&nbsp; '.
 4479: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4480: 		}
 4481: 	    }
 4482: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4483: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4484: 				    $$record{"$where.$partid.checkedin"},
 4485: 				    $$record{"$where.$partid.checkedin.slot"}).
 4486: 					'<br />';
 4487: 	    }
 4488: 	    if (exists $$record{"$where.$partid.award"}) {
 4489: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4490: 		    lc($$record{"$where.$partid.award"}).' '.
 4491: 		    $mark{$$record{"$where.$partid.solved"}}.
 4492: 		    '<br />';
 4493: 	    }
 4494: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4495: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4496: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4497: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4498: 		$displaySub[2].=
 4499: 		    $$record{"$version:resource.$partid.regrader"}.
 4500: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4501: 	    }
 4502: 	}
 4503: 	# needed because old essay regrader has not parts info
 4504: 	if (exists $$record{"$version:resource.regrader"}) {
 4505: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4506: 	}
 4507: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4508: 	if ($displaySub[2]) {
 4509: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4510: 	}
 4511: 	$studentTable.='&nbsp;</td>'.
 4512: 	    &Apache::loncommon::end_data_table_row();
 4513:     }
 4514:     $studentTable.=&Apache::loncommon::end_data_table();
 4515:     return $studentTable;
 4516: }
 4517: 
 4518: sub updateGradeByPage {
 4519:     my ($request) = shift;
 4520: 
 4521:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4522:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4523:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4524:     my $pageTitle = $env{'form.page'};
 4525:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4526:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4527:     my $usec=$classlist->{$env{'form.student'}}[5];
 4528:     if (!&canmodify($usec)) {
 4529: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4530: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4531: 	return;
 4532:     }
 4533:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4534:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4535: 	'</h3>'."\n";
 4536: 
 4537:     $request->print($result);
 4538: 
 4539:     my $navmap = Apache::lonnavmaps::navmap->new();
 4540:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4541:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4542:     if (!$map) {
 4543: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4544: 	my ($symb)=&get_symb($request);
 4545: 	$request->print(&show_grading_menu_form($symb));
 4546: 	return; 
 4547:     }
 4548:     my $iterator = $navmap->getIterator($map->map_start(),
 4549: 					$map->map_finish());
 4550: 
 4551:     my $studentTable=
 4552: 	&Apache::loncommon::start_data_table().
 4553: 	&Apache::loncommon::start_data_table_header_row().
 4554: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4555: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4556: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4557: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4558: 	&Apache::loncommon::end_data_table_header_row();
 4559: 
 4560:     $iterator->next(); # skip the first BEGIN_MAP
 4561:     my $curRes = $iterator->next(); # for "current resource"
 4562:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4563:     while ($depth > 0) {
 4564:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4565:         if($curRes == $iterator->END_MAP) { $depth--; }
 4566: 
 4567:         if (ref($curRes) && $curRes->is_problem()) {
 4568: 	    my $parts = $curRes->parts();
 4569:             my $title = $curRes->compTitle();
 4570: 	    my $symbx = $curRes->symb();
 4571: 	    $studentTable.=
 4572: 		&Apache::loncommon::start_data_table_row().
 4573: 		'<td align="center" valign="top" >'.$prob.
 4574: 		(scalar(@{$parts}) == 1 ? '' 
 4575:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4576: 		.')').'</td>';
 4577: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4578: 
 4579: 	    my %newrecord=();
 4580: 	    my @displayPts=();
 4581:             my %aggregate = ();
 4582:             my $aggregateflag = 0;
 4583: 	    foreach my $partid (@{$parts}) {
 4584: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4585: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4586: 
 4587: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4588: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4589: 		my $partial = $newpts/$wgt;
 4590: 		my $score;
 4591: 		if ($partial > 0) {
 4592: 		    $score = 'correct_by_override';
 4593: 		} elsif ($newpts ne '') { #empty is taken as 0
 4594: 		    $score = 'incorrect_by_override';
 4595: 		}
 4596: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4597: 		if ($dropMenu eq 'excused') {
 4598: 		    $partial = '';
 4599: 		    $score = 'excused';
 4600: 		} elsif ($dropMenu eq 'reset status'
 4601: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4602: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4603: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4604: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4605: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4606: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4607: 		    $changeflag++;
 4608: 		    $newpts = '';
 4609:                     
 4610:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4611:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4612:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4613:                     if ($aggtries > 0) {
 4614:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4615:                         $aggregateflag = 1;
 4616:                     }
 4617: 		}
 4618: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4619: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4620: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4621: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4622: 		    '&nbsp;<br />';
 4623: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4624: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4625: 		    '&nbsp;<br />';
 4626: 		$question++;
 4627: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4628: 
 4629: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4630: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4631: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4632: 		    if (scalar(keys(%newrecord)) > 0);
 4633: 
 4634: 		$changeflag++;
 4635: 	    }
 4636: 	    if (scalar(keys(%newrecord)) > 0) {
 4637: 		my %record = 
 4638: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4639: 					     $udom,$uname);
 4640: 
 4641: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4642: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4643: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4644: 		    $newrecord{'resource.CODE'} = '';
 4645: 		}
 4646: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4647: 					$udom,$uname);
 4648: 		%record = &Apache::lonnet::restore($symbx,
 4649: 						   $env{'request.course.id'},
 4650: 						   $udom,$uname);
 4651: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4652: 					     $cdom,$cnum,$udom,$uname);
 4653: 	    }
 4654: 	    
 4655:             if ($aggregateflag) {
 4656:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4657:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4658:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4659:             }
 4660: 
 4661: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4662: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4663: 		&Apache::loncommon::end_data_table_row();
 4664: 
 4665: 	    $prob++;
 4666: 	}
 4667:         $curRes = $iterator->next();
 4668:     }
 4669: 
 4670:     $studentTable.=&Apache::loncommon::end_data_table();
 4671:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4672:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4673: 		  &mt('The scores were changed for [quant,_1,problem].',
 4674: 		  $changeflag));
 4675:     $request->print($grademsg.$studentTable);
 4676: 
 4677:     return '';
 4678: }
 4679: 
 4680: #-------- end of section for handling grading by page/sequence ---------
 4681: #
 4682: #-------------------------------------------------------------------
 4683: 
 4684: #--------------------Scantron Grading-----------------------------------
 4685: #
 4686: #------ start of section for handling grading by page/sequence ---------
 4687: 
 4688: =pod
 4689: 
 4690: =head1 Bubble sheet grading routines
 4691: 
 4692:   For this documentation:
 4693: 
 4694:    'scanline' refers to the full line of characters
 4695:    from the file that we are parsing that represents one entire sheet
 4696: 
 4697:    'bubble line' refers to the data
 4698:    representing the line of bubbles that are on the physical bubble sheet
 4699: 
 4700: 
 4701: The overall process is that a scanned in bubble sheet data is uploaded
 4702: into a course. When a user wants to grade, they select a
 4703: sequence/folder of resources, a file of bubble sheet info, and pick
 4704: one of the predefined configurations for what each scanline looks
 4705: like.
 4706: 
 4707: Next each scanline is checked for any errors of either 'missing
 4708: bubbles' (it's an error because it may have been mis-scanned
 4709: because too light bubbling), 'double bubble' (each bubble line should
 4710: have no more that one letter picked), invalid or duplicated CODE,
 4711: invalid student/employee ID
 4712: 
 4713: If the CODE option is used that determines the randomization of the
 4714: homework problems, either way the student/employee ID is looked up into a
 4715: username:domain.
 4716: 
 4717: During the validation phase the instructor can choose to skip scanlines. 
 4718: 
 4719: After the validation phase, there are now 3 bubble sheet files
 4720: 
 4721:   scantron_original_filename (unmodified original file)
 4722:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4723:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4724: 
 4725: Also there is a separate hash nohist_scantrondata that contains extra
 4726: correction information that isn't representable in the bubble sheet
 4727: file (see &scantron_getfile() for more information)
 4728: 
 4729: After all scanlines are either valid, marked as valid or skipped, then
 4730: foreach line foreach problem in the picked sequence, an ssi request is
 4731: made that simulates a user submitting their selected letter(s) against
 4732: the homework problem.
 4733: 
 4734: =over 4
 4735: 
 4736: 
 4737: 
 4738: =item defaultFormData
 4739: 
 4740:   Returns html hidden inputs used to hold context/default values.
 4741: 
 4742:  Arguments:
 4743:   $symb - $symb of the current resource 
 4744: 
 4745: =cut
 4746: 
 4747: sub defaultFormData {
 4748:     my ($symb)=@_;
 4749:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4750:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4751:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4752: }
 4753: 
 4754: 
 4755: =pod 
 4756: 
 4757: =item getSequenceDropDown
 4758: 
 4759:    Return html dropdown of possible sequences to grade
 4760:  
 4761:  Arguments:
 4762:    $symb - $symb of the current resource 
 4763: 
 4764: =cut
 4765: 
 4766: sub getSequenceDropDown {
 4767:     my ($symb)=@_;
 4768:     my $result='<select name="selectpage">'."\n";
 4769:     my ($titles,$symbx) = &getSymbMap();
 4770:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4771:     my $ctr=0;
 4772:     foreach (@$titles) {
 4773: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4774: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4775: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4776: 	    '>'.$showtitle.'</option>'."\n";
 4777: 	$ctr++;
 4778:     }
 4779:     $result.= '</select>';
 4780:     return $result;
 4781: }
 4782: 
 4783: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4784:                                    # key is zero-based index - 0, 1, 2 ...
 4785: 
 4786: my %first_bubble_line;             # First bubble line no. for each bubble.
 4787: 
 4788: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4789:                                    # matchresponse or rankresponse, where 
 4790:                                    # an individual response can have multiple 
 4791:                                    # lines
 4792: 
 4793: my %responsetype_per_response;     # responsetype for each response
 4794: 
 4795: # Save and restore the bubble lines array to the form env.
 4796: 
 4797: 
 4798: sub save_bubble_lines {
 4799:     foreach my $line (keys(%bubble_lines_per_response)) {
 4800: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4801: 	$env{"form.scantron.first_bubble_line.$line"} =
 4802: 	    $first_bubble_line{$line};
 4803:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4804:             $subdivided_bubble_lines{$line};
 4805:         $env{"form.scantron.responsetype.$line"} =
 4806:             $responsetype_per_response{$line};
 4807:     }
 4808: }
 4809: 
 4810: 
 4811: sub restore_bubble_lines {
 4812:     my $line = 0;
 4813:     %bubble_lines_per_response = ();
 4814:     while ($env{"form.scantron.bubblelines.$line"}) {
 4815: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4816: 	$bubble_lines_per_response{$line} = $value;
 4817: 	$first_bubble_line{$line}  =
 4818: 	    $env{"form.scantron.first_bubble_line.$line"};
 4819:         $subdivided_bubble_lines{$line} =
 4820:             $env{"form.scantron.sub_bubblelines.$line"};
 4821:         $responsetype_per_response{$line} =
 4822:             $env{"form.scantron.responsetype.$line"};
 4823: 	$line++;
 4824:     }
 4825: }
 4826: 
 4827: #  Given the parsed scanline, get the response for 
 4828: #  'answer' number n:
 4829: 
 4830: sub get_response_bubbles {
 4831:     my ($parsed_line, $response)  = @_;
 4832: 
 4833:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4834:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4835:     
 4836:     my $selected = "";
 4837: 
 4838:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4839: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4840: 	$bubble_line++;
 4841:     }
 4842:     return $selected;
 4843: }
 4844: 
 4845: =pod 
 4846: 
 4847: =item scantron_filenames
 4848: 
 4849:    Returns a list of the scantron files in the current course 
 4850: 
 4851: =cut
 4852: 
 4853: sub scantron_filenames {
 4854:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4855:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4856:     my $getpropath = 1;
 4857:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4858:                                        $getpropath);
 4859:     my @possiblenames;
 4860:     foreach my $filename (sort(@files)) {
 4861: 	($filename)=split(/&/,$filename);
 4862: 	if ($filename!~/^scantron_orig_/) { next ; }
 4863: 	$filename=~s/^scantron_orig_//;
 4864: 	push(@possiblenames,$filename);
 4865:     }
 4866:     return @possiblenames;
 4867: }
 4868: 
 4869: =pod 
 4870: 
 4871: =item scantron_uploads
 4872: 
 4873:    Returns  html drop-down list of scantron files in current course.
 4874: 
 4875:  Arguments:
 4876:    $file2grade - filename to set as selected in the dropdown
 4877: 
 4878: =cut
 4879: 
 4880: sub scantron_uploads {
 4881:     my ($file2grade) = @_;
 4882:     my $result=	'<select name="scantron_selectfile">';
 4883:     $result.="<option></option>";
 4884:     foreach my $filename (sort(&scantron_filenames())) {
 4885: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4886:     }
 4887:     $result.="</select>";
 4888:     return $result;
 4889: }
 4890: 
 4891: =pod 
 4892: 
 4893: =item scantron_scantab
 4894: 
 4895:   Returns html drop down of the scantron formats in the scantronformat.tab
 4896:   file.
 4897: 
 4898: =cut
 4899: 
 4900: sub scantron_scantab {
 4901:     my $result='<select name="scantron_format">'."\n";
 4902:     $result.='<option></option>'."\n";
 4903:     my @lines = &get_scantronformat_file();
 4904:     if (@lines > 0) {
 4905:         foreach my $line (@lines) {
 4906:             next if (($line =~ /^\#/) || ($line eq ''));
 4907: 	    my ($name,$descrip)=split(/:/,$line);
 4908: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4909:         }
 4910:     }
 4911:     $result.='</select>'."\n";
 4912:     return $result;
 4913: }
 4914: 
 4915: =pod
 4916: 
 4917: =item get_scantronformat_file
 4918: 
 4919:   Returns an array containing lines from the scantron format file for
 4920:   the domain of the course.
 4921: 
 4922:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4923:   lines are from this file.
 4924: 
 4925:   Otherwise, if a default.tab has been published in RES space by the 
 4926:   domainconfig user, lines are from this file.
 4927: 
 4928:   Otherwise, fall back to getting lines from the legacy file on the
 4929:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4930: 
 4931: =cut
 4932: 
 4933: sub get_scantronformat_file {
 4934:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4935:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4936:     my $gottab = 0;
 4937:     my @lines;
 4938:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4939:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4940:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4941:             if ($formatfile ne '-1') {
 4942:                 @lines = split("\n",$formatfile,-1);
 4943:                 $gottab = 1;
 4944:             }
 4945:         }
 4946:     }
 4947:     if (!$gottab) {
 4948:         my $confname = $cdom.'-domainconfig';
 4949:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4950:         my $formatfile =  &Apache::lonnet::getfile($default);
 4951:         if ($formatfile ne '-1') {
 4952:             @lines = split("\n",$formatfile,-1);
 4953:             $gottab = 1;
 4954:         }
 4955:     }
 4956:     if (!$gottab) {
 4957:         my @domains = &Apache::lonnet::current_machine_domains();
 4958:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4959:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4960:             @lines = <$fh>;
 4961:             close($fh);
 4962:         } else {
 4963:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4964:             @lines = <$fh>;
 4965:             close($fh);
 4966:         }
 4967:     }
 4968:     return @lines;
 4969: }
 4970: 
 4971: =pod 
 4972: 
 4973: =item scantron_CODElist
 4974: 
 4975:   Returns html drop down of the saved CODE lists from current course,
 4976:   generated from earlier printings.
 4977: 
 4978: =cut
 4979: 
 4980: sub scantron_CODElist {
 4981:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4982:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4983:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4984:     my $namechoice='<option></option>';
 4985:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4986: 	if ($name =~ /^error: 2 /) { next; }
 4987: 	if ($name =~ /^type\0/) { next; }
 4988: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4989:     }
 4990:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4991:     return $namechoice;
 4992: }
 4993: 
 4994: =pod 
 4995: 
 4996: =item scantron_CODEunique
 4997: 
 4998:   Returns the html for "Each CODE to be used once" radio.
 4999: 
 5000: =cut
 5001: 
 5002: sub scantron_CODEunique {
 5003:     my $result='<span class="LC_nobreak">
 5004:                  <label><input type="radio" name="scantron_CODEunique"
 5005:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5006:                 </span>
 5007:                 <span class="LC_nobreak">
 5008:                  <label><input type="radio" name="scantron_CODEunique"
 5009:                         value="no" />'.&mt('No').' </label>
 5010:                 </span>';
 5011:     return $result;
 5012: }
 5013: 
 5014: =pod 
 5015: 
 5016: =item scantron_selectphase
 5017: 
 5018:   Generates the initial screen to start the bubble sheet process.
 5019:   Allows for - starting a grading run.
 5020:              - downloading existing scan data (original, corrected
 5021:                                                 or skipped info)
 5022: 
 5023:              - uploading new scan data
 5024: 
 5025:  Arguments:
 5026:   $r          - The Apache request object
 5027:   $file2grade - name of the file that contain the scanned data to score
 5028: 
 5029: =cut
 5030: 
 5031: sub scantron_selectphase {
 5032:     my ($r,$file2grade) = @_;
 5033:     my ($symb)=&get_symb($r);
 5034:     if (!$symb) {return '';}
 5035:     my $sequence_selector=&getSequenceDropDown($symb);
 5036:     my $default_form_data=&defaultFormData($symb);
 5037:     my $grading_menu_button=&show_grading_menu_form($symb);
 5038:     my $file_selector=&scantron_uploads($file2grade);
 5039:     my $format_selector=&scantron_scantab();
 5040:     my $CODE_selector=&scantron_CODElist();
 5041:     my $CODE_unique=&scantron_CODEunique();
 5042:     my $result;
 5043: 
 5044:     $ssi_error = 0;
 5045: 
 5046:     # Chunk of form to prompt for a file to grade and how:
 5047: 
 5048:     $result.= '
 5049:     <br />
 5050:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5051:     <input type="hidden" name="command" value="scantron_warning" />
 5052:     '.$default_form_data.'
 5053:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5054:        '.&Apache::loncommon::start_data_table_header_row().'
 5055:             <th colspan="2">
 5056:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5057:             </th>
 5058:        '.&Apache::loncommon::end_data_table_header_row().'
 5059:        '.&Apache::loncommon::start_data_table_row().'
 5060:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5061:        '.&Apache::loncommon::end_data_table_row().'
 5062:        '.&Apache::loncommon::start_data_table_row().'
 5063:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5064:        '.&Apache::loncommon::end_data_table_row().'
 5065:        '.&Apache::loncommon::start_data_table_row().'
 5066:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5067:        '.&Apache::loncommon::end_data_table_row().'
 5068:        '.&Apache::loncommon::start_data_table_row().'
 5069:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5070:        '.&Apache::loncommon::end_data_table_row().'
 5071:        '.&Apache::loncommon::start_data_table_row().'
 5072:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5073:        '.&Apache::loncommon::end_data_table_row().'
 5074:        '.&Apache::loncommon::start_data_table_row().'
 5075: 	    <td> '.&mt('Options:').' </td>
 5076:             <td>
 5077: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5078:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5079:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5080: 	    </td>
 5081:        '.&Apache::loncommon::end_data_table_row().'
 5082:        '.&Apache::loncommon::start_data_table_row().'
 5083:             <td colspan="2">
 5084:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5085:             </td>
 5086:        '.&Apache::loncommon::end_data_table_row().'
 5087:     '.&Apache::loncommon::end_data_table().'
 5088:     </form>
 5089: ';
 5090:    
 5091:     $r->print($result);
 5092: 
 5093:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5094:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5095: 
 5096: 	# Chunk of form to prompt for a scantron file upload.
 5097: 
 5098:         $r->print('
 5099:     <br />
 5100:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5101:        '.&Apache::loncommon::start_data_table_header_row().'
 5102:             <th>
 5103:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5104:             </th>
 5105:        '.&Apache::loncommon::end_data_table_header_row().'
 5106:        '.&Apache::loncommon::start_data_table_row().'
 5107:             <td>
 5108: ');
 5109:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5110:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5111:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5112:     $r->print('
 5113:               <script type="text/javascript" language="javascript">
 5114:     function checkUpload(formname) {
 5115: 	if (formname.upfile.value == "") {
 5116: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5117: 	    return false;
 5118: 	}
 5119: 	formname.submit();
 5120:     }
 5121:               </script>
 5122: 
 5123:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5124:                 '.$default_form_data.'
 5125:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5126:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5127:                 <input name="command" value="scantronupload_save" type="hidden" />
 5128:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5129:                 <br />
 5130:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5131:               </form>
 5132: ');
 5133: 
 5134:         $r->print('
 5135:             </td>
 5136:        '.&Apache::loncommon::end_data_table_row().'
 5137:        '.&Apache::loncommon::end_data_table().'
 5138: ');
 5139:     }
 5140: 
 5141:     # Chunk of the form that prompts to view a scoring office file,
 5142:     # corrected file, skipped records in a file.
 5143: 
 5144:     $r->print('
 5145:    <br />
 5146:    <form action="/adm/grades" name="scantron_download">
 5147:      '.$default_form_data.'
 5148:      <input type="hidden" name="command" value="scantron_download" />
 5149:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5150:        '.&Apache::loncommon::start_data_table_header_row().'
 5151:               <th>
 5152:                 &nbsp;'.&mt('Download a scoring office file').'
 5153:               </th>
 5154:        '.&Apache::loncommon::end_data_table_header_row().'
 5155:        '.&Apache::loncommon::start_data_table_row().'
 5156:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5157:                 <br />
 5158:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5159:        '.&Apache::loncommon::end_data_table_row().'
 5160:      '.&Apache::loncommon::end_data_table().'
 5161:    </form>
 5162:    <br />
 5163: ');
 5164: 
 5165:     &Apache::lonpickcode::code_list($r,2);
 5166: 
 5167:     $r->print('<br /><form method="post" name="checkscantron">'.
 5168:              $default_form_data."\n".
 5169:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5170:              &Apache::loncommon::start_data_table_header_row()."\n".
 5171:              '<th colspan="2">
 5172:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5173:              '</th>'."\n".
 5174:               &Apache::loncommon::end_data_table_header_row()."\n".
 5175:               &Apache::loncommon::start_data_table_row()."\n".
 5176:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5177:               '<td> '.$sequence_selector.' </td>'.
 5178:               &Apache::loncommon::end_data_table_row()."\n".
 5179:               &Apache::loncommon::start_data_table_row()."\n".
 5180:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5181:               '<td> '.$file_selector.' </td>'."\n".
 5182:               &Apache::loncommon::end_data_table_row()."\n".
 5183:               &Apache::loncommon::start_data_table_row()."\n".
 5184:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5185:               '<td> '.$format_selector.' </td>'."\n".
 5186:               &Apache::loncommon::end_data_table_row()."\n".
 5187:               &Apache::loncommon::start_data_table_row()."\n".
 5188:               '<td> '.&mt('Options').' </td>'."\n".
 5189:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5190:               &Apache::loncommon::end_data_table_row()."\n".
 5191:               &Apache::loncommon::start_data_table_row()."\n".
 5192:               '<td colspan="2">'."\n".
 5193:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5194:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5195:               '</td>'."\n".
 5196:               &Apache::loncommon::end_data_table_row()."\n".
 5197:               &Apache::loncommon::end_data_table()."\n".
 5198:               '</form><br />');
 5199:     $r->print($grading_menu_button);
 5200:     return;
 5201: }
 5202: 
 5203: =pod
 5204: 
 5205: =item get_scantron_config
 5206: 
 5207:    Parse and return the scantron configuration line selected as a
 5208:    hash of configuration file fields.
 5209: 
 5210:  Arguments:
 5211:     which - the name of the configuration to parse from the file.
 5212: 
 5213: 
 5214:  Returns:
 5215:             If the named configuration is not in the file, an empty
 5216:             hash is returned.
 5217:     a hash with the fields
 5218:       name         - internal name for the this configuration setup
 5219:       description  - text to display to operator that describes this config
 5220:       CODElocation - if 0 or the string 'none'
 5221:                           - no CODE exists for this config
 5222:                      if -1 || the string 'letter'
 5223:                           - a CODE exists for this config and is
 5224:                             a string of letters
 5225:                      Unsupported value (but planned for future support)
 5226:                           if a positive integer
 5227:                                - The CODE exists as the first n items from
 5228:                                  the question section of the form
 5229:                           if the string 'number'
 5230:                                - The CODE exists for this config and is
 5231:                                  a string of numbers
 5232:       CODEstart   - (only matter if a CODE exists) column in the line where
 5233:                      the CODE starts
 5234:       CODElength  - length of the CODE
 5235:       IDstart     - column where the student/employee ID number starts
 5236:       IDlength    - length of the student/employee ID info
 5237:       Qstart      - column where the information from the bubbled
 5238:                     'questions' start
 5239:       Qlength     - number of columns comprising a single bubble line from
 5240:                     the sheet. (usually either 1 or 10)
 5241:       Qon         - either a single character representing the character used
 5242:                     to signal a bubble was chosen in the positional setup, or
 5243:                     the string 'letter' if the letter of the chosen bubble is
 5244:                     in the final, or 'number' if a number representing the
 5245:                     chosen bubble is in the file (1->A 0->J)
 5246:       Qoff        - the character used to represent that a bubble was
 5247:                     left blank
 5248:       PaperID     - if the scanning process generates a unique number for each
 5249:                     sheet scanned the column that this ID number starts in
 5250:       PaperIDlength - number of columns that comprise the unique ID number
 5251:                       for the sheet of paper
 5252:       FirstName   - column that the first name starts in
 5253:       FirstNameLength - number of columns that the first name spans
 5254:  
 5255:       LastName    - column that the last name starts in
 5256:       LastNameLength - number of columns that the last name spans
 5257: 
 5258: =cut
 5259: 
 5260: sub get_scantron_config {
 5261:     my ($which) = @_;
 5262:     my @lines = &get_scantronformat_file();
 5263:     my %config;
 5264:     #FIXME probably should move to XML it has already gotten a bit much now
 5265:     foreach my $line (@lines) {
 5266: 	my ($name,$descrip)=split(/:/,$line);
 5267: 	if ($name ne $which ) { next; }
 5268: 	chomp($line);
 5269: 	my @config=split(/:/,$line);
 5270: 	$config{'name'}=$config[0];
 5271: 	$config{'description'}=$config[1];
 5272: 	$config{'CODElocation'}=$config[2];
 5273: 	$config{'CODEstart'}=$config[3];
 5274: 	$config{'CODElength'}=$config[4];
 5275: 	$config{'IDstart'}=$config[5];
 5276: 	$config{'IDlength'}=$config[6];
 5277: 	$config{'Qstart'}=$config[7];
 5278:  	$config{'Qlength'}=$config[8];
 5279: 	$config{'Qoff'}=$config[9];
 5280: 	$config{'Qon'}=$config[10];
 5281: 	$config{'PaperID'}=$config[11];
 5282: 	$config{'PaperIDlength'}=$config[12];
 5283: 	$config{'FirstName'}=$config[13];
 5284: 	$config{'FirstNamelength'}=$config[14];
 5285: 	$config{'LastName'}=$config[15];
 5286: 	$config{'LastNamelength'}=$config[16];
 5287: 	last;
 5288:     }
 5289:     return %config;
 5290: }
 5291: 
 5292: =pod 
 5293: 
 5294: =item username_to_idmap
 5295: 
 5296:     creates a hash keyed by student/employee ID with values of the corresponding
 5297:     student username:domain.
 5298: 
 5299:   Arguments:
 5300: 
 5301:     $classlist - reference to the class list hash. This is a hash
 5302:                  keyed by student name:domain  whose elements are references
 5303:                  to arrays containing various chunks of information
 5304:                  about the student. (See loncoursedata for more info).
 5305: 
 5306:   Returns
 5307:     %idmap - the constructed hash
 5308: 
 5309: =cut
 5310: 
 5311: sub username_to_idmap {
 5312:     my ($classlist)= @_;
 5313:     my %idmap;
 5314:     foreach my $student (keys(%$classlist)) {
 5315: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5316: 	    $student;
 5317:     }
 5318:     return %idmap;
 5319: }
 5320: 
 5321: =pod
 5322: 
 5323: =item scantron_fixup_scanline
 5324: 
 5325:    Process a requested correction to a scanline.
 5326: 
 5327:   Arguments:
 5328:     $scantron_config   - hash from &get_scantron_config()
 5329:     $scan_data         - hash of correction information 
 5330:                           (see &scantron_getfile())
 5331:     $line              - existing scanline
 5332:     $whichline         - line number of the passed in scanline
 5333:     $field             - type of change to process 
 5334:                          (either 
 5335:                           'ID'     -> correct the student/employee ID number
 5336:                           'CODE'   -> correct the CODE
 5337:                           'answer' -> fixup the submitted answers)
 5338:     
 5339:    $args               - hash of additional info,
 5340:                           - 'ID' 
 5341:                                'newid' -> studentID to use in replacement
 5342:                                           of existing one
 5343:                           - 'CODE' 
 5344:                                'CODE_ignore_dup' - set to true if duplicates
 5345:                                                    should be ignored.
 5346: 	                       'CODE' - is new code or 'use_unfound'
 5347:                                         if the existing unfound code should
 5348:                                         be used as is
 5349:                           - 'answer'
 5350:                                'response' - new answer or 'none' if blank
 5351:                                'question' - the bubble line to change
 5352:                                'questionnum' - the question identifier,
 5353:                                                may include subquestion. 
 5354: 
 5355:   Returns:
 5356:     $line - the modified scanline
 5357: 
 5358:   Side effects: 
 5359:     $scan_data - may be updated
 5360: 
 5361: =cut
 5362: 
 5363: 
 5364: sub scantron_fixup_scanline {
 5365:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5366:     if ($field eq 'ID') {
 5367: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5368: 	    return ($line,1,'New value too large');
 5369: 	}
 5370: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5371: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5372: 				     $args->{'newid'});
 5373: 	}
 5374: 	substr($line,$$scantron_config{'IDstart'}-1,
 5375: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5376: 	if ($args->{'newid'}=~/^\s*$/) {
 5377: 	    &scan_data($scan_data,"$whichline.user",
 5378: 		       $args->{'username'}.':'.$args->{'domain'});
 5379: 	}
 5380:     } elsif ($field eq 'CODE') {
 5381: 	if ($args->{'CODE_ignore_dup'}) {
 5382: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5383: 	}
 5384: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5385: 	if ($args->{'CODE'} ne 'use_unfound') {
 5386: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5387: 		return ($line,1,'New CODE value too large');
 5388: 	    }
 5389: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5390: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5391: 	    }
 5392: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5393: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5394: 	}
 5395:     } elsif ($field eq 'answer') {
 5396: 	my $length=$scantron_config->{'Qlength'};
 5397: 	my $off=$scantron_config->{'Qoff'};
 5398: 	my $on=$scantron_config->{'Qon'};
 5399: 	my $answer=${off}x$length;
 5400: 	if ($args->{'response'} eq 'none') {
 5401: 	    &scan_data($scan_data,
 5402: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5403: 	} else {
 5404: 	    if ($on eq 'letter') {
 5405: 		my @alphabet=('A'..'Z');
 5406: 		$answer=$alphabet[$args->{'response'}];
 5407: 	    } elsif ($on eq 'number') {
 5408: 		$answer=$args->{'response'}+1;
 5409: 		if ($answer == 10) { $answer = '0'; }
 5410: 	    } else {
 5411: 		substr($answer,$args->{'response'},1)=$on;
 5412: 	    }
 5413: 	    &scan_data($scan_data,
 5414: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5415: 	}
 5416: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5417: 	substr($line,$where-1,$length)=$answer;
 5418:     }
 5419:     return $line;
 5420: }
 5421: 
 5422: =pod
 5423: 
 5424: =item scan_data
 5425: 
 5426:     Edit or look up  an item in the scan_data hash.
 5427: 
 5428:   Arguments:
 5429:     $scan_data  - The hash (see scantron_getfile)
 5430:     $key        - shorthand of the key to edit (actual key is
 5431:                   scantronfilename_key).
 5432:     $data        - New value of the hash entry.
 5433:     $delete      - If true, the entry is removed from the hash.
 5434: 
 5435:   Returns:
 5436:     The new value of the hash table field (undefined if deleted).
 5437: 
 5438: =cut
 5439: 
 5440: 
 5441: sub scan_data {
 5442:     my ($scan_data,$key,$value,$delete)=@_;
 5443:     my $filename=$env{'form.scantron_selectfile'};
 5444:     if (defined($value)) {
 5445: 	$scan_data->{$filename.'_'.$key} = $value;
 5446:     }
 5447:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5448:     return $scan_data->{$filename.'_'.$key};
 5449: }
 5450: 
 5451: # ----- These first few routines are general use routines.----
 5452: 
 5453: # Return the number of occurences of a pattern in a string.
 5454: 
 5455: sub occurence_count {
 5456:     my ($string, $pattern) = @_;
 5457: 
 5458:     my @matches = ($string =~ /$pattern/g);
 5459: 
 5460:     return scalar(@matches);
 5461: }
 5462: 
 5463: 
 5464: # Take a string known to have digits and convert all the
 5465: # digits into letters in the range J,A..I.
 5466: 
 5467: sub digits_to_letters {
 5468:     my ($input) = @_;
 5469: 
 5470:     my @alphabet = ('J', 'A'..'I');
 5471: 
 5472:     my @input    = split(//, $input);
 5473:     my $output ='';
 5474:     for (my $i = 0; $i < scalar(@input); $i++) {
 5475: 	if ($input[$i] =~ /\d/) {
 5476: 	    $output .= $alphabet[$input[$i]];
 5477: 	} else {
 5478: 	    $output .= $input[$i];
 5479: 	}
 5480:     }
 5481:     return $output;
 5482: }
 5483: 
 5484: =pod 
 5485: 
 5486: =item scantron_parse_scanline
 5487: 
 5488:   Decodes a scanline from the selected scantron file
 5489: 
 5490:  Arguments:
 5491:     line             - The text of the scantron file line to process
 5492:     whichline        - Line number
 5493:     scantron_config  - Hash describing the format of the scantron lines.
 5494:     scan_data        - Hash of extra information about the scanline
 5495:                        (see scantron_getfile for more information)
 5496:     just_header      - True if should not process question answers but only
 5497:                        the stuff to the left of the answers.
 5498:  Returns:
 5499:    Hash containing the result of parsing the scanline
 5500: 
 5501:    Keys are all proceeded by the string 'scantron.'
 5502: 
 5503:        CODE    - the CODE in use for this scanline
 5504:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5505:                  by the operator
 5506:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5507:                             CODEs were selected, but the usage has been
 5508:                             forced by the operator
 5509:        ID  - student/employee ID
 5510:        PaperID - if used, the ID number printed on the sheet when the 
 5511:                  paper was scanned
 5512:        FirstName - first name from the sheet
 5513:        LastName  - last name from the sheet
 5514: 
 5515:      if just_header was not true these key may also exist
 5516: 
 5517:        missingerror - a list of bubble ranges that are considered to be answers
 5518:                       to a single question that don't have any bubbles filled in.
 5519:                       Of the form questionnumber:firstbubblenumber:count.
 5520:        doubleerror  - a list of bubble ranges that are considered to be answers
 5521:                       to a single question that have more than one bubble filled in.
 5522:                       Of the form questionnumber::firstbubblenumber:count
 5523:    
 5524:                 In the above, count is the number of bubble responses in the
 5525:                 input line needed to represent the possible answers to the question.
 5526:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5527:                 per line would have count = 2.
 5528: 
 5529:        maxquest     - the number of the last bubble line that was parsed
 5530: 
 5531:        (<number> starts at 1)
 5532:        <number>.answer - zero or more letters representing the selected
 5533:                          letters from the scanline for the bubble line 
 5534:                          <number>.
 5535:                          if blank there was either no bubble or there where
 5536:                          multiple bubbles, (consult the keys missingerror and
 5537:                          doubleerror if this is an error condition)
 5538: 
 5539: =cut
 5540: 
 5541: sub scantron_parse_scanline {
 5542:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5543: 
 5544:     my %record;
 5545:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5546:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5547:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5548:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5549: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5550: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5551: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5552: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5553: 	    $record{'scantron.CODE'}=substr($data,
 5554: 					    $$scantron_config{'CODEstart'}-1,
 5555: 					    $$scantron_config{'CODElength'});
 5556: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5557: 		$record{'scantron.useCODE'}=1;
 5558: 	    }
 5559: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5560: 		$record{'scantron.CODE_ignore_dup'}=1;
 5561: 	    }
 5562: 	} else {
 5563: 	    #FIXME interpret first N questions
 5564: 	}
 5565:     }
 5566:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5567: 				  $$scantron_config{'IDlength'});
 5568:     $record{'scantron.PaperID'}=
 5569: 	substr($data,$$scantron_config{'PaperID'}-1,
 5570: 	       $$scantron_config{'PaperIDlength'});
 5571:     $record{'scantron.FirstName'}=
 5572: 	substr($data,$$scantron_config{'FirstName'}-1,
 5573: 	       $$scantron_config{'FirstNamelength'});
 5574:     $record{'scantron.LastName'}=
 5575: 	substr($data,$$scantron_config{'LastName'}-1,
 5576: 	       $$scantron_config{'LastNamelength'});
 5577:     if ($just_header) { return \%record; }
 5578: 
 5579:     my @alphabet=('A'..'Z');
 5580:     my $questnum=0;
 5581:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5582: 
 5583:     chomp($questions);		# Get rid of any trailing \n.
 5584:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5585:     while (length($questions)) {
 5586: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5587:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5588:                              || 1;
 5589:         $questnum++;
 5590:         my $quest_id = $questnum;
 5591:         my $currentquest = substr($questions,0,$answer_length);
 5592:         $questions       = substr($questions,$answer_length);
 5593:         if (length($currentquest) < $answer_length) { next; }
 5594: 
 5595:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5596:             my $subquestnum = 1;
 5597:             my $subquestions = $currentquest;
 5598:             my @subanswers_needed = 
 5599:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5600:             foreach my $subans (@subanswers_needed) {
 5601:                 my $subans_length =
 5602:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5603:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5604:                 $subquestions   = substr($subquestions,$subans_length);
 5605:                 $quest_id = "$questnum.$subquestnum";
 5606:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5607:                     ($$scantron_config{'Qon'} eq 'number')) {
 5608:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5609:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5610:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5611:                 } else {
 5612:                     $ansnum = &scantron_validator_positional($ansnum,
 5613:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5614:                 }
 5615:                 $subquestnum ++;
 5616:             }
 5617:         } else {
 5618:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5619:                 ($$scantron_config{'Qon'} eq 'number')) {
 5620:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5621:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5622:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5623:             } else {
 5624:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5625:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5626:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5627:             }
 5628:         }
 5629:     }
 5630:     $record{'scantron.maxquest'}=$questnum;
 5631:     return \%record;
 5632: }
 5633: 
 5634: sub scantron_validator_lettnum {
 5635:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5636:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5637: 
 5638:     # Qon 'letter' implies for each slot in currquest we have:
 5639:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5640:     #    about anything else (esp. a value of Qoff) for missing
 5641:     #    bubbles.
 5642:     #
 5643:     # Qon 'number' implies each slot gives a digit that indexes the
 5644:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5645:     #    and * or ? for double bubbles on a single line.
 5646:     #
 5647: 
 5648:     my $matchon;
 5649:     if ($$scantron_config{'Qon'} eq 'letter') {
 5650:         $matchon = '[A-Z]';
 5651:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5652:         $matchon = '\d';
 5653:     }
 5654:     my $occurrences = 0;
 5655:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5656:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5657:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5658:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5659:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5660:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5661:         my @singlelines = split('',$currquest);
 5662:         foreach my $entry (@singlelines) {
 5663:             $occurrences = &occurence_count($entry,$matchon);
 5664:             if ($occurrences > 1) {
 5665:                 last;
 5666:             }
 5667:         } 
 5668:     } else {
 5669:         $occurrences = &occurence_count($currquest,$matchon); 
 5670:     }
 5671:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5672:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5673:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5674:             my $bubble = substr($currquest,$ans,1);
 5675:             if ($bubble =~ /$matchon/ ) {
 5676:                 if ($$scantron_config{'Qon'} eq 'number') {
 5677:                     if ($bubble == 0) {
 5678:                         $bubble = 10; 
 5679:                     }
 5680:                     $record->{"scantron.$ansnum.answer"} = 
 5681:                         $alphabet->[$bubble-1];
 5682:                 } else {
 5683:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5684:                 }
 5685:             } else {
 5686:                 $record->{"scantron.$ansnum.answer"}='';
 5687:             }
 5688:             $ansnum++;
 5689:         }
 5690:     } elsif (!defined($currquest)
 5691:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5692:             || (&occurence_count($currquest,$matchon) == 0)) {
 5693:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5694:             $record->{"scantron.$ansnum.answer"}='';
 5695:             $ansnum++;
 5696:         }
 5697:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5698:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5699:         }
 5700:     } else {
 5701:         if ($$scantron_config{'Qon'} eq 'number') {
 5702:             $currquest = &digits_to_letters($currquest);            
 5703:         }
 5704:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5705:             my $bubble = substr($currquest,$ans,1);
 5706:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5707:             $ansnum++;
 5708:         }
 5709:     }
 5710:     return $ansnum;
 5711: }
 5712: 
 5713: sub scantron_validator_positional {
 5714:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5715:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5716: 
 5717:     # Otherwise there's a positional notation;
 5718:     # each bubble line requires Qlength items, and there are filled in
 5719:     # bubbles for each case where there 'Qon' characters.
 5720:     #
 5721: 
 5722:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5723: 
 5724:     # If the split only gives us one element.. the full length of the
 5725:     # answer string, no bubbles are filled in:
 5726: 
 5727:     if ($answers_needed eq '') {
 5728:         return;
 5729:     }
 5730: 
 5731:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5732:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5733:             $record->{"scantron.$ansnum.answer"}='';
 5734:             $ansnum++;
 5735:         }
 5736:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5737:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5738:         }
 5739:     } elsif (scalar(@array) == 2) {
 5740:         my $location = length($array[0]);
 5741:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5742:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5743:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5744:             if ($ans eq $line_num) {
 5745:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5746:             } else {
 5747:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5748:             }
 5749:             $ansnum++;
 5750:          }
 5751:     } else {
 5752:         #  If there's more than one instance of a bubble character
 5753:         #  That's a double bubble; with positional notation we can
 5754:         #  record all the bubbles filled in as well as the
 5755:         #  fact this response consists of multiple bubbles.
 5756:         #
 5757:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5758:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5759:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5760:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5761:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5762:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5763:             my $doubleerror = 0;
 5764:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5765:                    (!$doubleerror)) {
 5766:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5767:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5768:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5769:                if (length(@currarray) > 2) {
 5770:                    $doubleerror = 1;
 5771:                } 
 5772:             }
 5773:             if ($doubleerror) {
 5774:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5775:             }
 5776:         } else {
 5777:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5778:         }
 5779:         my $item = $ansnum;
 5780:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5781:             $record->{"scantron.$item.answer"} = '';
 5782:             $item ++;
 5783:         }
 5784: 
 5785:         my @ans=@array;
 5786:         my $i=0;
 5787:         my $increment = 0;
 5788:         while ($#ans) {
 5789:             $i+=length($ans[0]) + $increment;
 5790:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5791:             my $bubble = $i%$$scantron_config{'Qlength'};
 5792:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5793:             shift(@ans);
 5794:             $increment = 1;
 5795:         }
 5796:         $ansnum += $answers_needed;
 5797:     }
 5798:     return $ansnum;
 5799: }
 5800: 
 5801: =pod
 5802: 
 5803: =item scantron_add_delay
 5804: 
 5805:    Adds an error message that occurred during the grading phase to a
 5806:    queue of messages to be shown after grading pass is complete
 5807: 
 5808:  Arguments:
 5809:    $delayqueue  - arrary ref of hash ref of error messages
 5810:    $scanline    - the scanline that caused the error
 5811:    $errormesage - the error message
 5812:    $errorcode   - a numeric code for the error
 5813: 
 5814:  Side Effects:
 5815:    updates the $delayqueue to have a new hash ref of the error
 5816: 
 5817: =cut
 5818: 
 5819: sub scantron_add_delay {
 5820:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5821:     push(@$delayqueue,
 5822: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5823: 	  'ecode' => $errorcode }
 5824: 	 );
 5825: }
 5826: 
 5827: =pod
 5828: 
 5829: =item scantron_find_student
 5830: 
 5831:    Finds the username for the current scanline
 5832: 
 5833:   Arguments:
 5834:    $scantron_record - hash result from scantron_parse_scanline
 5835:    $scan_data       - hash of correction information 
 5836:                       (see &scantron_getfile() form more information)
 5837:    $idmap           - hash from &username_to_idmap()
 5838:    $line            - number of current scanline
 5839:  
 5840:   Returns:
 5841:    Either 'username:domain' or undef if unknown
 5842: 
 5843: =cut
 5844: 
 5845: sub scantron_find_student {
 5846:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5847:     my $scanID=$$scantron_record{'scantron.ID'};
 5848:     if ($scanID =~ /^\s*$/) {
 5849:  	return &scan_data($scan_data,"$line.user");
 5850:     }
 5851:     foreach my $id (keys(%$idmap)) {
 5852:  	if (lc($id) eq lc($scanID)) {
 5853:  	    return $$idmap{$id};
 5854:  	}
 5855:     }
 5856:     return undef;
 5857: }
 5858: 
 5859: =pod
 5860: 
 5861: =item scantron_filter
 5862: 
 5863:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5864:    hidden resources was selected
 5865: 
 5866: =cut
 5867: 
 5868: sub scantron_filter {
 5869:     my ($curres)=@_;
 5870: 
 5871:     if (ref($curres) && $curres->is_problem()) {
 5872: 	# if the user has asked to not have either hidden
 5873: 	# or 'randomout' controlled resources to be graded
 5874: 	# don't include them
 5875: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5876: 	    && $curres->randomout) {
 5877: 	    return 0;
 5878: 	}
 5879: 	return 1;
 5880:     }
 5881:     return 0;
 5882: }
 5883: 
 5884: =pod
 5885: 
 5886: =item scantron_process_corrections
 5887: 
 5888:    Gets correction information out of submitted form data and corrects
 5889:    the scanline
 5890: 
 5891: =cut
 5892: 
 5893: sub scantron_process_corrections {
 5894:     my ($r) = @_;
 5895:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5896:     my ($scanlines,$scan_data)=&scantron_getfile();
 5897:     my $classlist=&Apache::loncoursedata::get_classlist();
 5898:     my $which=$env{'form.scantron_line'};
 5899:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5900:     my ($skip,$err,$errmsg);
 5901:     if ($env{'form.scantron_skip_record'}) {
 5902: 	$skip=1;
 5903:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5904: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5905: 	    $env{'form.scantron_domain'};
 5906: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5907: 	($line,$err,$errmsg)=
 5908: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5909: 				     'ID',{'newid'=>$newid,
 5910: 				    'username'=>$env{'form.scantron_username'},
 5911: 				    'domain'=>$env{'form.scantron_domain'}});
 5912:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5913: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5914: 	my $newCODE;
 5915: 	my %args;
 5916: 	if      ($resolution eq 'use_unfound') {
 5917: 	    $newCODE='use_unfound';
 5918: 	} elsif ($resolution eq 'use_found') {
 5919: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5920: 	} elsif ($resolution eq 'use_typed') {
 5921: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5922: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5923: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5924: 	}
 5925: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5926: 	    $args{'CODE_ignore_dup'}=1;
 5927: 	}
 5928: 	$args{'CODE'}=$newCODE;
 5929: 	($line,$err,$errmsg)=
 5930: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5931: 				     'CODE',\%args);
 5932:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5933: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5934: 	    ($line,$err,$errmsg)=
 5935: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5936: 					 $which,'answer',
 5937: 					 { 'question'=>$question,
 5938: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5939:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5940: 	    if ($err) { last; }
 5941: 	}
 5942:     }
 5943:     if ($err) {
 5944: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5945:     } else {
 5946: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5947: 	&scantron_putfile($scanlines,$scan_data);
 5948:     }
 5949: }
 5950: 
 5951: =pod
 5952: 
 5953: =item reset_skipping_status
 5954: 
 5955:    Forgets the current set of remember skipped scanlines (and thus
 5956:    reverts back to considering all lines in the
 5957:    scantron_skipped_<filename> file)
 5958: 
 5959: =cut
 5960: 
 5961: sub reset_skipping_status {
 5962:     my ($scanlines,$scan_data)=&scantron_getfile();
 5963:     &scan_data($scan_data,'remember_skipping',undef,1);
 5964:     &scantron_putfile(undef,$scan_data);
 5965: }
 5966: 
 5967: =pod
 5968: 
 5969: =item start_skipping
 5970: 
 5971:    Marks a scanline to be skipped. 
 5972: 
 5973: =cut
 5974: 
 5975: sub start_skipping {
 5976:     my ($scan_data,$i)=@_;
 5977:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5978:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5979: 	$remembered{$i}=2;
 5980:     } else {
 5981: 	$remembered{$i}=1;
 5982:     }
 5983:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5984: }
 5985: 
 5986: =pod
 5987: 
 5988: =item should_be_skipped
 5989: 
 5990:    Checks whether a scanline should be skipped.
 5991: 
 5992: =cut
 5993: 
 5994: sub should_be_skipped {
 5995:     my ($scanlines,$scan_data,$i)=@_;
 5996:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5997: 	# not redoing old skips
 5998: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5999: 	return 0;
 6000:     }
 6001:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6002: 
 6003:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6004: 	return 0;
 6005:     }
 6006:     return 1;
 6007: }
 6008: 
 6009: =pod
 6010: 
 6011: =item remember_current_skipped
 6012: 
 6013:    Discovers what scanlines are in the scantron_skipped_<filename>
 6014:    file and remembers them into scan_data for later use.
 6015: 
 6016: =cut
 6017: 
 6018: sub remember_current_skipped {
 6019:     my ($scanlines,$scan_data)=&scantron_getfile();
 6020:     my %to_remember;
 6021:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6022: 	if ($scanlines->{'skipped'}[$i]) {
 6023: 	    $to_remember{$i}=1;
 6024: 	}
 6025:     }
 6026: 
 6027:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6028:     &scantron_putfile(undef,$scan_data);
 6029: }
 6030: 
 6031: =pod
 6032: 
 6033: =item check_for_error
 6034: 
 6035:     Checks if there was an error when attempting to remove a specific
 6036:     scantron_.. bubble sheet data file. Prints out an error if
 6037:     something went wrong.
 6038: 
 6039: =cut
 6040: 
 6041: sub check_for_error {
 6042:     my ($r,$result)=@_;
 6043:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6044: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6045:     }
 6046: }
 6047: 
 6048: =pod
 6049: 
 6050: =item scantron_warning_screen
 6051: 
 6052:    Interstitial screen to make sure the operator has selected the
 6053:    correct options before we start the validation phase.
 6054: 
 6055: =cut
 6056: 
 6057: sub scantron_warning_screen {
 6058:     my ($button_text)=@_;
 6059:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6060:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6061:     my $CODElist;
 6062:     if ($scantron_config{'CODElocation'} &&
 6063: 	$scantron_config{'CODEstart'} &&
 6064: 	$scantron_config{'CODElength'}) {
 6065: 	$CODElist=$env{'form.scantron_CODElist'};
 6066: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6067: 	$CODElist=
 6068: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6069: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6070:     }
 6071:     return ('
 6072: <p>
 6073: <span class="LC_warning">
 6074: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6075: </p>
 6076: <table>
 6077: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6078: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6079: '.$CODElist.'
 6080: </table>
 6081: <br />
 6082: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6083: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6084: 
 6085: <br />
 6086: ');
 6087: }
 6088: 
 6089: =pod
 6090: 
 6091: =item scantron_do_warning
 6092: 
 6093:    Check if the operator has picked something for all required
 6094:    fields. Error out if something is missing.
 6095: 
 6096: =cut
 6097: 
 6098: sub scantron_do_warning {
 6099:     my ($r)=@_;
 6100:     my ($symb)=&get_symb($r);
 6101:     if (!$symb) {return '';}
 6102:     my $default_form_data=&defaultFormData($symb);
 6103:     $r->print(&scantron_form_start().$default_form_data);
 6104:     if ( $env{'form.selectpage'} eq '' ||
 6105: 	 $env{'form.scantron_selectfile'} eq '' ||
 6106: 	 $env{'form.scantron_format'} eq '' ) {
 6107: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6108: 	if ( $env{'form.selectpage'} eq '') {
 6109: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6110: 	} 
 6111: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6112: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6113: 	} 
 6114: 	if ( $env{'form.scantron_format'} eq '') {
 6115: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6116: 	} 
 6117:     } else {
 6118: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6119: 	$r->print('
 6120: '.$warning.'
 6121: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6122: <input type="hidden" name="command" value="scantron_validate" />
 6123: ');
 6124:     }
 6125:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6126:     return '';
 6127: }
 6128: 
 6129: =pod
 6130: 
 6131: =item scantron_form_start
 6132: 
 6133:     html hidden input for remembering all selected grading options
 6134: 
 6135: =cut
 6136: 
 6137: sub scantron_form_start {
 6138:     my ($max_bubble)=@_;
 6139:     my $result= <<SCANTRONFORM;
 6140: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6141:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6142:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6143:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6144:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6145:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6146:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6147:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6148:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6149:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6150: SCANTRONFORM
 6151: 
 6152:   my $line = 0;
 6153:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6154:        my $chunk =
 6155: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6156:        $chunk .=
 6157: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6158:        $chunk .= 
 6159:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6160:        $chunk .=
 6161:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6162:        $result .= $chunk;
 6163:        $line++;
 6164:    }
 6165:     return $result;
 6166: }
 6167: 
 6168: =pod
 6169: 
 6170: =item scantron_validate_file
 6171: 
 6172:     Dispatch routine for doing validation of a bubble sheet data file.
 6173: 
 6174:     Also processes any necessary information resets that need to
 6175:     occur before validation begins (ignore previous corrections,
 6176:     restarting the skipped records processing)
 6177: 
 6178: =cut
 6179: 
 6180: sub scantron_validate_file {
 6181:     my ($r) = @_;
 6182:     my ($symb)=&get_symb($r);
 6183:     if (!$symb) {return '';}
 6184:     my $default_form_data=&defaultFormData($symb);
 6185:     
 6186:     # do the detection of only doing skipped records first befroe we delete
 6187:     # them when doing the corrections reset
 6188:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6189: 	&reset_skipping_status();
 6190:     }
 6191:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6192: 	&remember_current_skipped();
 6193: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6194:     }
 6195: 
 6196:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6197: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6198: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6199: 	&check_for_error($r,&scantron_remove_scan_data());
 6200: 	$env{'form.scantron_options_ignore'}='done';
 6201:     }
 6202: 
 6203:     if ($env{'form.scantron_corrections'}) {
 6204: 	&scantron_process_corrections($r);
 6205:     }
 6206:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6207:     #get the student pick code ready
 6208:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6209:     my $max_bubble=&scantron_get_maxbubble();
 6210:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6211:     $r->print($result);
 6212:     
 6213:     my @validate_phases=( 'sequence',
 6214: 			  'ID',
 6215: 			  'CODE',
 6216: 			  'doublebubble',
 6217: 			  'missingbubbles');
 6218:     if (!$env{'form.validatepass'}) {
 6219: 	$env{'form.validatepass'} = 0;
 6220:     }
 6221:     my $currentphase=$env{'form.validatepass'};
 6222: 
 6223: 
 6224:     my $stop=0;
 6225:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6226: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6227: 	$r->rflush();
 6228: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6229: 	{
 6230: 	    no strict 'refs';
 6231: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6232: 	}
 6233:     }
 6234:     if (!$stop) {
 6235: 	my $warning=&scantron_warning_screen('Start Grading');
 6236: 	$r->print(&mt('Validation process complete.').'<br />'.
 6237:                   $warning.
 6238:                   &mt('Perform verification for each student after storage of submissions?').
 6239:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6240:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6241:                   ('&nbsp;'x3).'<label>'.
 6242:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6243:                   '</label></span><br />'.
 6244:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6245:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6246:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6247:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6248:     } else {
 6249: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6250: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6251:     }
 6252:     if ($stop) {
 6253: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6254: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6255: 	    $r->print(' '.&mt('this error').' <br />');
 6256: 
 6257: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6258: 	} else {
 6259:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6260: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6261:             } else {
 6262:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6263:             }
 6264: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6265: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6266: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6267: 	}
 6268:     }
 6269:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6270:     return '';
 6271: }
 6272: 
 6273: 
 6274: =pod
 6275: 
 6276: =item scantron_remove_file
 6277: 
 6278:    Removes the requested bubble sheet data file, makes sure that
 6279:    scantron_original_<filename> is never removed
 6280: 
 6281: 
 6282: =cut
 6283: 
 6284: sub scantron_remove_file {
 6285:     my ($which)=@_;
 6286:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6287:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6288:     my $file='scantron_';
 6289:     if ($which eq 'corrected' || $which eq 'skipped') {
 6290: 	$file.=$which.'_';
 6291:     } else {
 6292: 	return 'refused';
 6293:     }
 6294:     $file.=$env{'form.scantron_selectfile'};
 6295:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6296: }
 6297: 
 6298: 
 6299: =pod
 6300: 
 6301: =item scantron_remove_scan_data
 6302: 
 6303:    Removes all scan_data correction for the requested bubble sheet
 6304:    data file.  (In the case that both the are doing skipped records we need
 6305:    to remember the old skipped lines for the time being so that element
 6306:    persists for a while.)
 6307: 
 6308: =cut
 6309: 
 6310: sub scantron_remove_scan_data {
 6311:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6312:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6313:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6314:     my @todelete;
 6315:     my $filename=$env{'form.scantron_selectfile'};
 6316:     foreach my $key (@keys) {
 6317: 	if ($key=~/^\Q$filename\E_/) {
 6318: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6319: 		$key=~/remember_skipping/) {
 6320: 		next;
 6321: 	    }
 6322: 	    push(@todelete,$key);
 6323: 	}
 6324:     }
 6325:     my $result;
 6326:     if (@todelete) {
 6327: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6328: 				       \@todelete,$cdom,$cname);
 6329:     } else {
 6330: 	$result = 'ok';
 6331:     }
 6332:     return $result;
 6333: }
 6334: 
 6335: 
 6336: =pod
 6337: 
 6338: =item scantron_getfile
 6339: 
 6340:     Fetches the requested bubble sheet data file (all 3 versions), and
 6341:     the scan_data hash
 6342:   
 6343:   Arguments:
 6344:     None
 6345: 
 6346:   Returns:
 6347:     2 hash references
 6348: 
 6349:      - first one has 
 6350:          orig      -
 6351:          corrected -
 6352:          skipped   -  each of which points to an array ref of the specified
 6353:                       file broken up into individual lines
 6354:          count     - number of scanlines
 6355:  
 6356:      - second is the scan_data hash possible keys are
 6357:        ($number refers to scanline numbered $number and thus the key affects
 6358:         only that scanline
 6359:         $bubline refers to the specific bubble line element and the aspects
 6360:         refers to that specific bubble line element)
 6361: 
 6362:        $number.user - username:domain to use
 6363:        $number.CODE_ignore_dup 
 6364:                     - ignore the duplicate CODE error 
 6365:        $number.useCODE
 6366:                     - use the CODE in the scanline as is
 6367:        $number.no_bubble.$bubline
 6368:                     - it is valid that there is no bubbled in bubble
 6369:                       at $number $bubline
 6370:        remember_skipping
 6371:                     - a frozen hash containing keys of $number and values
 6372:                       of either 
 6373:                         1 - we are on a 'do skipped records pass' and plan
 6374:                             on processing this line
 6375:                         2 - we are on a 'do skipped records pass' and this
 6376:                             scanline has been marked to skip yet again
 6377: 
 6378: =cut
 6379: 
 6380: sub scantron_getfile {
 6381:     #FIXME really would prefer a scantron directory
 6382:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6383:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6384:     my $lines;
 6385:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6386: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6387:     my %scanlines;
 6388:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6389:     my $temp=$scanlines{'orig'};
 6390:     $scanlines{'count'}=$#$temp;
 6391: 
 6392:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6393: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6394:     if ($lines eq '-1') {
 6395: 	$scanlines{'corrected'}=[];
 6396:     } else {
 6397: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6398:     }
 6399:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6400: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6401:     if ($lines eq '-1') {
 6402: 	$scanlines{'skipped'}=[];
 6403:     } else {
 6404: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6405:     }
 6406:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6407:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6408:     my %scan_data = @tmp;
 6409:     return (\%scanlines,\%scan_data);
 6410: }
 6411: 
 6412: =pod
 6413: 
 6414: =item lonnet_putfile
 6415: 
 6416:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6417: 
 6418:  Arguments:
 6419:    $contents - data to store
 6420:    $filename - filename to store $contents into
 6421: 
 6422:  Returns:
 6423:    result value from &Apache::lonnet::finishuserfileupload
 6424: 
 6425: =cut
 6426: 
 6427: sub lonnet_putfile {
 6428:     my ($contents,$filename)=@_;
 6429:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6430:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6431:     $env{'form.sillywaytopassafilearound'}=$contents;
 6432:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6433: 
 6434: }
 6435: 
 6436: =pod
 6437: 
 6438: =item scantron_putfile
 6439: 
 6440:     Stores the current version of the bubble sheet data files, and the
 6441:     scan_data hash. (Does not modify the original version only the
 6442:     corrected and skipped versions.
 6443: 
 6444:  Arguments:
 6445:     $scanlines - hash ref that looks like the first return value from
 6446:                  &scantron_getfile()
 6447:     $scan_data - hash ref that looks like the second return value from
 6448:                  &scantron_getfile()
 6449: 
 6450: =cut
 6451: 
 6452: sub scantron_putfile {
 6453:     my ($scanlines,$scan_data) = @_;
 6454:     #FIXME really would prefer a scantron directory
 6455:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6456:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6457:     if ($scanlines) {
 6458: 	my $prefix='scantron_';
 6459: # no need to update orig, shouldn't change
 6460: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6461: #		    $env{'form.scantron_selectfile'});
 6462: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6463: 			$prefix.'corrected_'.
 6464: 			$env{'form.scantron_selectfile'});
 6465: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6466: 			$prefix.'skipped_'.
 6467: 			$env{'form.scantron_selectfile'});
 6468:     }
 6469:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6470: }
 6471: 
 6472: =pod
 6473: 
 6474: =item scantron_get_line
 6475: 
 6476:    Returns the correct version of the scanline
 6477: 
 6478:  Arguments:
 6479:     $scanlines - hash ref that looks like the first return value from
 6480:                  &scantron_getfile()
 6481:     $scan_data - hash ref that looks like the second return value from
 6482:                  &scantron_getfile()
 6483:     $i         - number of the requested line (starts at 0)
 6484: 
 6485:  Returns:
 6486:    A scanline, (either the original or the corrected one if it
 6487:    exists), or undef if the requested scanline should be
 6488:    skipped. (Either because it's an skipped scanline, or it's an
 6489:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6490:    pass.
 6491: 
 6492: =cut
 6493: 
 6494: sub scantron_get_line {
 6495:     my ($scanlines,$scan_data,$i)=@_;
 6496:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6497:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6498:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6499:     return $scanlines->{'orig'}[$i]; 
 6500: }
 6501: 
 6502: =pod
 6503: 
 6504: =item scantron_todo_count
 6505: 
 6506:     Counts the number of scanlines that need processing.
 6507: 
 6508:  Arguments:
 6509:     $scanlines - hash ref that looks like the first return value from
 6510:                  &scantron_getfile()
 6511:     $scan_data - hash ref that looks like the second return value from
 6512:                  &scantron_getfile()
 6513: 
 6514:  Returns:
 6515:     $count - number of scanlines to process
 6516: 
 6517: =cut
 6518: 
 6519: sub get_todo_count {
 6520:     my ($scanlines,$scan_data)=@_;
 6521:     my $count=0;
 6522:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6523: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6524: 	if ($line=~/^[\s\cz]*$/) { next; }
 6525: 	$count++;
 6526:     }
 6527:     return $count;
 6528: }
 6529: 
 6530: =pod
 6531: 
 6532: =item scantron_put_line
 6533: 
 6534:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6535:     data file.
 6536: 
 6537:  Arguments:
 6538:     $scanlines - hash ref that looks like the first return value from
 6539:                  &scantron_getfile()
 6540:     $scan_data - hash ref that looks like the second return value from
 6541:                  &scantron_getfile()
 6542:     $i         - line number to update
 6543:     $newline   - contents of the updated scanline
 6544:     $skip      - if true make the line for skipping and update the
 6545:                  'skipped' file
 6546: 
 6547: =cut
 6548: 
 6549: sub scantron_put_line {
 6550:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6551:     if ($skip) {
 6552: 	$scanlines->{'skipped'}[$i]=$newline;
 6553: 	&start_skipping($scan_data,$i);
 6554: 	return;
 6555:     }
 6556:     $scanlines->{'corrected'}[$i]=$newline;
 6557: }
 6558: 
 6559: =pod
 6560: 
 6561: =item scantron_clear_skip
 6562: 
 6563:    Remove a line from the 'skipped' file
 6564: 
 6565:  Arguments:
 6566:     $scanlines - hash ref that looks like the first return value from
 6567:                  &scantron_getfile()
 6568:     $scan_data - hash ref that looks like the second return value from
 6569:                  &scantron_getfile()
 6570:     $i         - line number to update
 6571: 
 6572: =cut
 6573: 
 6574: sub scantron_clear_skip {
 6575:     my ($scanlines,$scan_data,$i)=@_;
 6576:     if (exists($scanlines->{'skipped'}[$i])) {
 6577: 	undef($scanlines->{'skipped'}[$i]);
 6578: 	return 1;
 6579:     }
 6580:     return 0;
 6581: }
 6582: 
 6583: =pod
 6584: 
 6585: =item scantron_filter_not_exam
 6586: 
 6587:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6588:    filter out resources that are not marked as 'exam' mode
 6589: 
 6590: =cut
 6591: 
 6592: sub scantron_filter_not_exam {
 6593:     my ($curres)=@_;
 6594:     
 6595:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6596: 	# if the user has asked to not have either hidden
 6597: 	# or 'randomout' controlled resources to be graded
 6598: 	# don't include them
 6599: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6600: 	    && $curres->randomout) {
 6601: 	    return 0;
 6602: 	}
 6603: 	return 1;
 6604:     }
 6605:     return 0;
 6606: }
 6607: 
 6608: =pod
 6609: 
 6610: =item scantron_validate_sequence
 6611: 
 6612:     Validates the selected sequence, checking for resource that are
 6613:     not set to exam mode.
 6614: 
 6615: =cut
 6616: 
 6617: sub scantron_validate_sequence {
 6618:     my ($r,$currentphase) = @_;
 6619: 
 6620:     my $navmap=Apache::lonnavmaps::navmap->new();
 6621:     my (undef,undef,$sequence)=
 6622: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6623: 
 6624:     my $map=$navmap->getResourceByUrl($sequence);
 6625: 
 6626:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6627:                                     value="ignore" />');
 6628:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6629: 	my @resources=
 6630: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6631: 	if (@resources) {
 6632: 	    $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>");
 6633: 	    return (1,$currentphase);
 6634: 	}
 6635:     }
 6636: 
 6637:     return (0,$currentphase+1);
 6638: }
 6639: 
 6640: 
 6641: 
 6642: sub scantron_validate_ID {
 6643:     my ($r,$currentphase) = @_;
 6644:     
 6645:     #get student info
 6646:     my $classlist=&Apache::loncoursedata::get_classlist();
 6647:     my %idmap=&username_to_idmap($classlist);
 6648: 
 6649:     #get scantron line setup
 6650:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6651:     my ($scanlines,$scan_data)=&scantron_getfile();
 6652:     
 6653:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6654: 
 6655:     my %found=('ids'=>{},'usernames'=>{});
 6656:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6657: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6658: 	if ($line=~/^[\s\cz]*$/) { next; }
 6659: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6660: 						 $scan_data);
 6661: 	my $id=$$scan_record{'scantron.ID'};
 6662: 	my $found;
 6663: 	foreach my $checkid (keys(%idmap)) {
 6664: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6665: 	}
 6666: 	if ($found) {
 6667: 	    my $username=$idmap{$found};
 6668: 	    if ($found{'ids'}{$found}) {
 6669: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6670: 					 $line,'duplicateID',$found);
 6671: 		return(1,$currentphase);
 6672: 	    } elsif ($found{'usernames'}{$username}) {
 6673: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6674: 					 $line,'duplicateID',$username);
 6675: 		return(1,$currentphase);
 6676: 	    }
 6677: 	    #FIXME store away line we previously saw the ID on to use above
 6678: 	    $found{'ids'}{$found}++;
 6679: 	    $found{'usernames'}{$username}++;
 6680: 	} else {
 6681: 	    if ($id =~ /^\s*$/) {
 6682: 		my $username=&scan_data($scan_data,"$i.user");
 6683: 		if (defined($username) && $found{'usernames'}{$username}) {
 6684: 		    &scantron_get_correction($r,$i,$scan_record,
 6685: 					     \%scantron_config,
 6686: 					     $line,'duplicateID',$username);
 6687: 		    return(1,$currentphase);
 6688: 		} elsif (!defined($username)) {
 6689: 		    &scantron_get_correction($r,$i,$scan_record,
 6690: 					     \%scantron_config,
 6691: 					     $line,'incorrectID');
 6692: 		    return(1,$currentphase);
 6693: 		}
 6694: 		$found{'usernames'}{$username}++;
 6695: 	    } else {
 6696: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6697: 					 $line,'incorrectID');
 6698: 		return(1,$currentphase);
 6699: 	    }
 6700: 	}
 6701:     }
 6702: 
 6703:     return (0,$currentphase+1);
 6704: }
 6705: 
 6706: 
 6707: sub scantron_get_correction {
 6708:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6709: #FIXME in the case of a duplicated ID the previous line, probably need
 6710: #to show both the current line and the previous one and allow skipping
 6711: #the previous one or the current one
 6712: 
 6713:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6714: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6715: 			    " for PaperID <tt>[_1]</tt>",
 6716: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6717:     } else {
 6718: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6719: 			    " in scanline [_1] <pre>[_2]</pre>",
 6720: 			    $i,$line)."</p> \n");
 6721:     }
 6722:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6723: 			  "The name on the paper is [_2],[_3]",
 6724: 			  $$scan_record{'scantron.ID'},
 6725: 			  $$scan_record{'scantron.LastName'},
 6726: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6727: 
 6728:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6729:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6730:                            # Array populated for doublebubble or
 6731:     my @lines_to_correct;  # missingbubble errors to build javascript
 6732:                            # to validate radio button checking   
 6733: 
 6734:     if ($error =~ /ID$/) {
 6735: 	if ($error eq 'incorrectID') {
 6736: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6737: 		      "</p>\n");
 6738: 	} elsif ($error eq 'duplicateID') {
 6739: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6740: 	}
 6741: 	$r->print($message);
 6742: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6743: 	$r->print("\n<ul><li> ");
 6744: 	#FIXME it would be nice if this sent back the user ID and
 6745: 	#could do partial userID matches
 6746: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6747: 				       'scantron_username','scantron_domain'));
 6748: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6749: 	$r->print("\n@".
 6750: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6751: 
 6752: 	$r->print('</li>');
 6753:     } elsif ($error =~ /CODE$/) {
 6754: 	if ($error eq 'incorrectCODE') {
 6755: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6756: 	} elsif ($error eq 'duplicateCODE') {
 6757: 	    $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");
 6758: 	}
 6759: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6760: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6761: 	$r->print($message);
 6762: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6763: 	$r->print("\n<br /> ");
 6764: 	my $i=0;
 6765: 	if ($error eq 'incorrectCODE' 
 6766: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6767: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6768: 	    if ($closest > 0) {
 6769: 		foreach my $testcode (@{$closest}) {
 6770: 		    my $checked='';
 6771: 		    if (!$i) { $checked=' checked="checked" '; }
 6772: 		    $r->print("
 6773:    <label>
 6774:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6775:        ".&mt("Use the similar CODE [_1] instead.",
 6776: 	    "<b><tt>".$testcode."</tt></b>")."
 6777:     </label>
 6778:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6779: 		    $r->print("\n<br />");
 6780: 		    $i++;
 6781: 		}
 6782: 	    }
 6783: 	}
 6784: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6785: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6786: 	    $r->print("
 6787:     <label>
 6788:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6789:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6790: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6791:     </label>");
 6792: 	    $r->print("\n<br />");
 6793: 	}
 6794: 
 6795: 	$r->print(<<ENDSCRIPT);
 6796: <script type="text/javascript">
 6797: function change_radio(field) {
 6798:     var slct=document.scantronupload.scantron_CODE_resolution;
 6799:     var i;
 6800:     for (i=0;i<slct.length;i++) {
 6801:         if (slct[i].value==field) { slct[i].checked=true; }
 6802:     }
 6803: }
 6804: </script>
 6805: ENDSCRIPT
 6806: 	my $href="/adm/pickcode?".
 6807: 	   "form=".&escape("scantronupload").
 6808: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6809: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6810: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6811: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6812: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6813: 	    $r->print("
 6814:     <label>
 6815:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6816:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6817: 	     "<a target='_blank' href='$href'>","</a>")."
 6818:     </label> 
 6819:     ".&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\')" />'));
 6820: 	    $r->print("\n<br />");
 6821: 	}
 6822: 	$r->print("
 6823:     <label>
 6824:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6825:        ".&mt("Use [_1] as the CODE.",
 6826: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6827: 	$r->print("\n<br /><br />");
 6828:     } elsif ($error eq 'doublebubble') {
 6829: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6830: 
 6831: 	# The form field scantron_questions is acutally a list of line numbers.
 6832: 	# represented by this form so:
 6833: 
 6834: 	my $line_list = &questions_to_line_list($arg);
 6835: 
 6836: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6837: 		  $line_list.'" />');
 6838: 	$r->print($message);
 6839: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6840: 	foreach my $question (@{$arg}) {
 6841: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6842:                                                    $scan_record, $error);
 6843:             push(@lines_to_correct,@linenums);
 6844: 	}
 6845:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6846:     } elsif ($error eq 'missingbubble') {
 6847: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6848: 	$r->print($message);
 6849: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6850: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6851: 
 6852: 	# The form field scantron_questions is actually a list of line numbers not
 6853: 	# a list of question numbers. Therefore:
 6854: 	#
 6855: 	
 6856: 	my $line_list = &questions_to_line_list($arg);
 6857: 
 6858: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6859: 		  $line_list.'" />');
 6860: 	foreach my $question (@{$arg}) {
 6861: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6862:                                                    $scan_record, $error);
 6863:             push(@lines_to_correct,@linenums);
 6864: 	}
 6865:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6866:     } else {
 6867: 	$r->print("\n<ul>");
 6868:     }
 6869:     $r->print("\n</li></ul>");
 6870: }
 6871: 
 6872: sub verify_bubbles_checked {
 6873:     my (@ansnums) = @_;
 6874:     my $ansnumstr = join('","',@ansnums);
 6875:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6876:     my $output = (<<ENDSCRIPT);
 6877: <script type="text/javascript">
 6878: function verify_bubble_radio(form) {
 6879:     var ansnumArray = new Array ("$ansnumstr");
 6880:     var need_bubble_count = 0;
 6881:     for (var i=0; i<ansnumArray.length; i++) {
 6882:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6883:             var bubble_picked = 0; 
 6884:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6885:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6886:                     bubble_picked = 1;
 6887:                 }
 6888:             }
 6889:             if (bubble_picked == 0) {
 6890:                 need_bubble_count ++;
 6891:             }
 6892:         }
 6893:     }
 6894:     if (need_bubble_count) {
 6895:         alert("$warning");
 6896:         return;
 6897:     }
 6898:     form.submit(); 
 6899: }
 6900: </script>
 6901: ENDSCRIPT
 6902:     return $output;
 6903: }
 6904: 
 6905: =pod
 6906: 
 6907: =item  questions_to_line_list
 6908: 
 6909: Converts a list of questions into a string of comma separated
 6910: line numbers in the answer sheet used by the questions.  This is
 6911: used to fill in the scantron_questions form field.
 6912: 
 6913:   Arguments:
 6914:      questions    - Reference to an array of questions.
 6915: 
 6916: =cut
 6917: 
 6918: 
 6919: sub questions_to_line_list {
 6920:     my ($questions) = @_;
 6921:     my @lines;
 6922: 
 6923:     foreach my $item (@{$questions}) {
 6924:         my $question = $item;
 6925:         my ($first,$count,$last);
 6926:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6927:             $question = $1;
 6928:             my $subquestion = $2;
 6929:             $first = $first_bubble_line{$question-1} + 1;
 6930:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6931:             my $subcount = 1;
 6932:             while ($subcount<$subquestion) {
 6933:                 $first += $subans[$subcount-1];
 6934:                 $subcount ++;
 6935:             }
 6936:             $count = $subans[$subquestion-1];
 6937:         } else {
 6938: 	    $first   = $first_bubble_line{$question-1} + 1;
 6939: 	    $count   = $bubble_lines_per_response{$question-1};
 6940:         }
 6941:         $last = $first+$count-1;
 6942:         push(@lines, ($first..$last));
 6943:     }
 6944:     return join(',', @lines);
 6945: }
 6946: 
 6947: =pod 
 6948: 
 6949: =item prompt_for_corrections
 6950: 
 6951: Prompts for a potentially multiline correction to the
 6952: user's bubbling (factors out common code from scantron_get_correction
 6953: for multi and missing bubble cases).
 6954: 
 6955:  Arguments:
 6956:    $r           - Apache request object.
 6957:    $question    - The question number to prompt for.
 6958:    $scan_config - The scantron file configuration hash.
 6959:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6960:    $error       - Type of error
 6961: 
 6962:  Implicit inputs:
 6963:    %bubble_lines_per_response   - Starting line numbers for each question.
 6964:                                   Numbered from 0 (but question numbers are from
 6965:                                   1.
 6966:    %first_bubble_line           - Starting bubble line for each question.
 6967:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6968:                                   type problems render as separate sub-questions, 
 6969:                                   in exam mode. This hash contains a 
 6970:                                   comma-separated list of the lines per 
 6971:                                   sub-question.
 6972:    %responsetype_per_response   - essayresponse, formularesponse,
 6973:                                   stringresponse, imageresponse, reactionresponse,
 6974:                                   and organicresponse type problem parts can have
 6975:                                   multiple lines per response if the weight
 6976:                                   assigned exceeds 10.  In this case, only
 6977:                                   one bubble per line is permitted, but more 
 6978:                                   than one line might contain bubbles, e.g.
 6979:                                   bubbling of: line 1 - J, line 2 - J, 
 6980:                                   line 3 - B would assign 22 points.  
 6981: 
 6982: =cut
 6983: 
 6984: sub prompt_for_corrections {
 6985:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6986:     my ($current_line,$lines);
 6987:     my @linenums;
 6988:     my $questionnum = $question;
 6989:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6990:         $question = $1;
 6991:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6992:         my $subquestion = $2;
 6993:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6994:         my $subcount = 1;
 6995:         while ($subcount<$subquestion) {
 6996:             $current_line += $subans[$subcount-1];
 6997:             $subcount ++;
 6998:         }
 6999:         $lines = $subans[$subquestion-1];
 7000:     } else {
 7001:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7002:         $lines        = $bubble_lines_per_response{$question-1};
 7003:     }
 7004:     if ($lines > 1) {
 7005:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7006:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7007:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7008:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7009:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7010:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7011:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7012:             $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 />');
 7013:         } else {
 7014:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7015:         }
 7016:     }
 7017:     for (my $i =0; $i < $lines; $i++) {
 7018:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7019: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7020: 	        		  $questionnum,$error,split('', $selected));
 7021:         push(@linenums,$current_line);
 7022: 	$current_line++;
 7023:     }
 7024:     if ($lines > 1) {
 7025: 	$r->print("<hr /><br />");
 7026:     }
 7027:     return @linenums;
 7028: }
 7029: 
 7030: =pod
 7031: 
 7032: =item scantron_bubble_selector
 7033:   
 7034:    Generates the html radiobuttons to correct a single bubble line
 7035:    possibly showing the existing the selected bubbles if known
 7036: 
 7037:  Arguments:
 7038:     $r           - Apache request object
 7039:     $scan_config - hash from &get_scantron_config()
 7040:     $line        - Number of the line being displayed.
 7041:     $questionnum - Question number (may include subquestion)
 7042:     $error       - Type of error.
 7043:     @selected    - Array of bubbles picked on this line.
 7044: 
 7045: =cut
 7046: 
 7047: sub scantron_bubble_selector {
 7048:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7049:     my $max=$$scan_config{'Qlength'};
 7050: 
 7051:     my $scmode=$$scan_config{'Qon'};
 7052:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7053: 
 7054:     my @alphabet=('A'..'Z');
 7055:     $r->print(&Apache::loncommon::start_data_table().
 7056:               &Apache::loncommon::start_data_table_row());
 7057:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7058:     for (my $i=0;$i<$max+1;$i++) {
 7059: 	$r->print("\n".'<td align="center">');
 7060: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7061: 	else { $r->print('&nbsp;'); }
 7062: 	$r->print('</td>');
 7063:     }
 7064:     $r->print(&Apache::loncommon::end_data_table_row().
 7065:               &Apache::loncommon::start_data_table_row());
 7066:     for (my $i=0;$i<$max;$i++) {
 7067: 	$r->print("\n".
 7068: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7069: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7070:     }
 7071:     my $nobub_checked = ' ';
 7072:     if ($error eq 'missingbubble') {
 7073:         $nobub_checked = ' checked = "checked" ';
 7074:     }
 7075:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7076: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7077:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7078:               $line.'" value="'.$questionnum.'" /></td>');
 7079:     $r->print(&Apache::loncommon::end_data_table_row().
 7080:               &Apache::loncommon::end_data_table());
 7081: }
 7082: 
 7083: =pod
 7084: 
 7085: =item num_matches
 7086: 
 7087:    Counts the number of characters that are the same between the two arguments.
 7088: 
 7089:  Arguments:
 7090:    $orig - CODE from the scanline
 7091:    $code - CODE to match against
 7092: 
 7093:  Returns:
 7094:    $count - integer count of the number of same characters between the
 7095:             two arguments
 7096: 
 7097: =cut
 7098: 
 7099: sub num_matches {
 7100:     my ($orig,$code) = @_;
 7101:     my @code=split(//,$code);
 7102:     my @orig=split(//,$orig);
 7103:     my $same=0;
 7104:     for (my $i=0;$i<scalar(@code);$i++) {
 7105: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7106:     }
 7107:     return $same;
 7108: }
 7109: 
 7110: =pod
 7111: 
 7112: =item scantron_get_closely_matching_CODEs
 7113: 
 7114:    Cycles through all CODEs and finds the set that has the greatest
 7115:    number of same characters as the provided CODE
 7116: 
 7117:  Arguments:
 7118:    $allcodes - hash ref returned by &get_codes()
 7119:    $CODE     - CODE from the current scanline
 7120: 
 7121:  Returns:
 7122:    2 element list
 7123:     - first elements is number of how closely matching the best fit is 
 7124:       (5 means best set has 5 matching characters)
 7125:     - second element is an arrary ref containing the set of valid CODEs
 7126:       that best fit the passed in CODE
 7127: 
 7128: =cut
 7129: 
 7130: sub scantron_get_closely_matching_CODEs {
 7131:     my ($allcodes,$CODE)=@_;
 7132:     my @CODEs;
 7133:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7134: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7135:     }
 7136: 
 7137:     return ($#CODEs,$CODEs[-1]);
 7138: }
 7139: 
 7140: =pod
 7141: 
 7142: =item get_codes
 7143: 
 7144:    Builds a hash which has keys of all of the valid CODEs from the selected
 7145:    set of remembered CODEs.
 7146: 
 7147:  Arguments:
 7148:   $old_name - name of the set of remembered CODEs
 7149:   $cdom     - domain of the course
 7150:   $cnum     - internal course name
 7151: 
 7152:  Returns:
 7153:   %allcodes - keys are the valid CODEs, values are all 1
 7154: 
 7155: =cut
 7156: 
 7157: sub get_codes {
 7158:     my ($old_name, $cdom, $cnum) = @_;
 7159:     if (!$old_name) {
 7160: 	$old_name=$env{'form.scantron_CODElist'};
 7161:     }
 7162:     if (!$cdom) {
 7163: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7164:     }
 7165:     if (!$cnum) {
 7166: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7167:     }
 7168:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7169: 				    $cdom,$cnum);
 7170:     my %allcodes;
 7171:     if ($result{"type\0$old_name"} eq 'number') {
 7172: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7173:     } else {
 7174: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7175:     }
 7176:     return %allcodes;
 7177: }
 7178: 
 7179: =pod
 7180: 
 7181: =item scantron_validate_CODE
 7182: 
 7183:    Validates all scanlines in the selected file to not have any
 7184:    invalid or underspecified CODEs and that none of the codes are
 7185:    duplicated if this was requested.
 7186: 
 7187: =cut
 7188: 
 7189: sub scantron_validate_CODE {
 7190:     my ($r,$currentphase) = @_;
 7191:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7192:     if ($scantron_config{'CODElocation'} &&
 7193: 	$scantron_config{'CODEstart'} &&
 7194: 	$scantron_config{'CODElength'}) {
 7195: 	if (!defined($env{'form.scantron_CODElist'})) {
 7196: 	    &FIXME_blow_up()
 7197: 	}
 7198:     } else {
 7199: 	return (0,$currentphase+1);
 7200:     }
 7201:     
 7202:     my %usedCODEs;
 7203: 
 7204:     my %allcodes=&get_codes();
 7205: 
 7206:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7207: 
 7208:     my ($scanlines,$scan_data)=&scantron_getfile();
 7209:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7210: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7211: 	if ($line=~/^[\s\cz]*$/) { next; }
 7212: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7213: 						 $scan_data);
 7214: 	my $CODE=$$scan_record{'scantron.CODE'};
 7215: 	my $error=0;
 7216: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7217: 	    &scantron_get_correction($r,$i,$scan_record,
 7218: 				     \%scantron_config,
 7219: 				     $line,'incorrectCODE',\%allcodes);
 7220: 	    return(1,$currentphase);
 7221: 	}
 7222: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7223: 	    && !$$scan_record{'scantron.useCODE'}) {
 7224: 	    &scantron_get_correction($r,$i,$scan_record,
 7225: 				     \%scantron_config,
 7226: 				     $line,'incorrectCODE',\%allcodes);
 7227: 	    return(1,$currentphase);
 7228: 	}
 7229: 	if (exists($usedCODEs{$CODE}) 
 7230: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7231: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7232: 	    &scantron_get_correction($r,$i,$scan_record,
 7233: 				     \%scantron_config,
 7234: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7235: 	    return(1,$currentphase);
 7236: 	}
 7237: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7238:     }
 7239:     return (0,$currentphase+1);
 7240: }
 7241: 
 7242: =pod
 7243: 
 7244: =item scantron_validate_doublebubble
 7245: 
 7246:    Validates all scanlines in the selected file to not have any
 7247:    bubble lines with multiple bubbles marked.
 7248: 
 7249: =cut
 7250: 
 7251: sub scantron_validate_doublebubble {
 7252:     my ($r,$currentphase) = @_;
 7253:     #get student info
 7254:     my $classlist=&Apache::loncoursedata::get_classlist();
 7255:     my %idmap=&username_to_idmap($classlist);
 7256: 
 7257:     #get scantron line setup
 7258:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7259:     my ($scanlines,$scan_data)=&scantron_getfile();
 7260:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7261: 
 7262:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7263: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7264: 	if ($line=~/^[\s\cz]*$/) { next; }
 7265: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7266: 						 $scan_data);
 7267: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7268: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7269: 				 'doublebubble',
 7270: 				 $$scan_record{'scantron.doubleerror'});
 7271:     	return (1,$currentphase);
 7272:     }
 7273:     return (0,$currentphase+1);
 7274: }
 7275: 
 7276: 
 7277: sub scantron_get_maxbubble {
 7278:     if (defined($env{'form.scantron_maxbubble'}) &&
 7279: 	$env{'form.scantron_maxbubble'}) {
 7280: 	&restore_bubble_lines();
 7281: 	return $env{'form.scantron_maxbubble'};
 7282:     }
 7283: 
 7284:     my (undef, undef, $sequence) =
 7285: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7286: 
 7287:     my $navmap=Apache::lonnavmaps::navmap->new();
 7288:     my $map=$navmap->getResourceByUrl($sequence);
 7289:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7290: 
 7291:     &Apache::lonxml::clear_problem_counter();
 7292: 
 7293:     my $uname       = $env{'user.name'};
 7294:     my $udom        = $env{'user.domain'};
 7295:     my $cid         = $env{'request.course.id'};
 7296:     my $total_lines = 0;
 7297:     %bubble_lines_per_response = ();
 7298:     %first_bubble_line         = ();
 7299:     %subdivided_bubble_lines   = ();
 7300:     %responsetype_per_response = ();
 7301: 
 7302:     my $response_number = 0;
 7303:     my $bubble_line     = 0;
 7304:     foreach my $resource (@resources) {
 7305:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7306:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7307: 	    foreach my $part_id (@{$parts}) {
 7308:                 my $lines;
 7309: 
 7310: 	        # TODO - make this a persistent hash not an array.
 7311: 
 7312:                 # optionresponse, matchresponse and rankresponse type items 
 7313:                 # render as separate sub-questions in exam mode.
 7314:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7315:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7316:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7317:                     my ($numbub,$numshown);
 7318:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7319:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7320:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7321:                         }
 7322:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7323:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7324:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7325:                         }
 7326:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7327:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7328:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7329:                         }
 7330:                     }
 7331:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7332:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7333:                     }
 7334:                     my $bubbles_per_line = 10;
 7335:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7336:                     if (($numbub % $bubbles_per_line) != 0) {
 7337:                         $inner_bubble_lines++;
 7338:                     }
 7339:                     for (my $i=0; $i<$numshown; $i++) {
 7340:                         $subdivided_bubble_lines{$response_number} .= 
 7341:                             $inner_bubble_lines.',';
 7342:                     }
 7343:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7344:                     $lines = $numshown * $inner_bubble_lines;
 7345:                 } else {
 7346:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7347:                 } 
 7348: 
 7349:                 $first_bubble_line{$response_number} = $bubble_line;
 7350: 	        $bubble_lines_per_response{$response_number} = $lines;
 7351:                 $responsetype_per_response{$response_number} = 
 7352:                     $analysis->{$part_id.'.type'};
 7353: 	        $response_number++;
 7354: 
 7355: 	        $bubble_line +=  $lines;
 7356: 	        $total_lines +=  $lines;
 7357: 	    }
 7358:         }
 7359:     }
 7360:     &Apache::lonnet::delenv('scantron.');
 7361: 
 7362:     &save_bubble_lines();
 7363:     $env{'form.scantron_maxbubble'} =
 7364: 	$total_lines;
 7365:     return $env{'form.scantron_maxbubble'};
 7366: }
 7367: 
 7368: sub scantron_validate_missingbubbles {
 7369:     my ($r,$currentphase) = @_;
 7370:     #get student info
 7371:     my $classlist=&Apache::loncoursedata::get_classlist();
 7372:     my %idmap=&username_to_idmap($classlist);
 7373: 
 7374:     #get scantron line setup
 7375:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7376:     my ($scanlines,$scan_data)=&scantron_getfile();
 7377:     my $max_bubble=&scantron_get_maxbubble();
 7378:     if (!$max_bubble) { $max_bubble=2**31; }
 7379:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7380: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7381: 	if ($line=~/^[\s\cz]*$/) { next; }
 7382: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7383: 						 $scan_data);
 7384: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7385: 	my @to_correct;
 7386: 	
 7387: 	# Probably here's where the error is...
 7388: 
 7389: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7390:             my $lastbubble;
 7391:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7392:                my $question = $1;
 7393:                my $subquestion = $2;
 7394:                if (!defined($first_bubble_line{$question -1})) { next; }
 7395:                my $first = $first_bubble_line{$question-1};
 7396:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7397:                my $subcount = 1;
 7398:                while ($subcount<$subquestion) {
 7399:                    $first += $subans[$subcount-1];
 7400:                    $subcount ++;
 7401:                }
 7402:                my $count = $subans[$subquestion-1];
 7403:                $lastbubble = $first + $count;
 7404:             } else {
 7405:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7406:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7407:             }
 7408:             if ($lastbubble > $max_bubble) { next; }
 7409: 	    push(@to_correct,$missing);
 7410: 	}
 7411: 	if (@to_correct) {
 7412: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7413: 				     $line,'missingbubble',\@to_correct);
 7414: 	    return (1,$currentphase);
 7415: 	}
 7416: 
 7417:     }
 7418:     return (0,$currentphase+1);
 7419: }
 7420: 
 7421: 
 7422: sub scantron_process_students {
 7423:     my ($r) = @_;
 7424: 
 7425:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7426:     my ($symb)=&get_symb($r);
 7427:     if (!$symb) {
 7428: 	return '';
 7429:     }
 7430:     my $default_form_data=&defaultFormData($symb);
 7431: 
 7432:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7433:     my ($scanlines,$scan_data)=&scantron_getfile();
 7434:     my $classlist=&Apache::loncoursedata::get_classlist();
 7435:     my %idmap=&username_to_idmap($classlist);
 7436:     my $navmap=Apache::lonnavmaps::navmap->new();
 7437:     my $map=$navmap->getResourceByUrl($sequence);
 7438:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7439:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7440:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7441:                             \%grader_randomlists_by_symb);
 7442:     foreach my $resource (@resources) {
 7443:         my $ressymb = $resource->symb();
 7444:         my ($analysis,$parts) =
 7445:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7446:                                       $env{'user.name'},$env{'user.domain'},1);
 7447:         $grader_partids_by_symb{$ressymb} = $parts;
 7448:         if (ref($analysis) eq 'HASH') {
 7449:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7450:                 $grader_randomlists_by_symb{$ressymb} = 
 7451:                     $analysis->{'parts_withrandomlist'};
 7452:             }
 7453:         }
 7454:     }
 7455: 
 7456:     my ($uname,$udom);
 7457:     my $result= <<SCANTRONFORM;
 7458: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7459:   <input type="hidden" name="command" value="scantron_configphase" />
 7460:   $default_form_data
 7461: SCANTRONFORM
 7462:     $r->print($result);
 7463: 
 7464:     my @delayqueue;
 7465:     my (%completedstudents,%scandata);
 7466:     
 7467:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7468:     my $count=&get_todo_count($scanlines,$scan_data);
 7469:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7470:  				    'Scantron Progress',$count,
 7471: 				    'inline',undef,'scantronupload');
 7472:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7473: 					  'Processing first student');
 7474:     $r->print('<br />');
 7475:     my $start=&Time::HiRes::time();
 7476:     my $i=-1;
 7477:     my $started;
 7478: 
 7479:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7480: 
 7481:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7482:     # the user and return.
 7483: 
 7484:     if ($ssi_error) {
 7485: 	$r->print("</form>");
 7486: 	&ssi_print_error($r);
 7487: 	$r->print(&show_grading_menu_form($symb));
 7488:         &Apache::lonnet::remove_lock($lock);
 7489: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7490:     }
 7491: 
 7492:     my %lettdig = &letter_to_digits();
 7493:     my $numletts = scalar(keys(%lettdig));
 7494: 
 7495:     while ($i<$scanlines->{'count'}) {
 7496:  	($uname,$udom)=('','');
 7497:  	$i++;
 7498:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7499:  	if ($line=~/^[\s\cz]*$/) { next; }
 7500: 	if ($started) {
 7501: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7502: 						     'last student');
 7503: 	}
 7504: 	$started=1;
 7505:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7506:  						 $scan_data);
 7507:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7508:  					      \%idmap,$i)) {
 7509:   	    &scantron_add_delay(\@delayqueue,$line,
 7510:  				'Unable to find a student that matches',1);
 7511:  	    next;
 7512:   	}
 7513:  	if (exists $completedstudents{$uname}) {
 7514:  	    &scantron_add_delay(\@delayqueue,$line,
 7515:  				'Student '.$uname.' has multiple sheets',2);
 7516:  	    next;
 7517:  	}
 7518:   	($uname,$udom)=split(/:/,$uname);
 7519: 
 7520:         my %partids_by_symb;
 7521:         foreach my $resource (@resources) {
 7522:             my $ressymb = $resource->symb();
 7523:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7524:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7525:                 my ($analysis,$parts) =
 7526:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7527:                 $partids_by_symb{$ressymb} = $parts;
 7528:             } else {
 7529:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7530:             }
 7531:         }
 7532: 
 7533: 	&Apache::lonxml::clear_problem_counter();
 7534:   	&Apache::lonnet::appenv($scan_record);
 7535: 
 7536: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7537: 	    &scantron_putfile($scanlines,$scan_data);
 7538: 	}
 7539: 	
 7540:         my $scancode;
 7541:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7542:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7543:             $scancode = $scan_record->{'scantron.CODE'};
 7544:         } else {
 7545:             $scancode = '';
 7546:         }
 7547: 
 7548:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7549:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7550:             $ssi_error = 0; # So end of handler error message does not trigger.
 7551:             $r->print("</form>");
 7552:             &ssi_print_error($r);
 7553:             $r->print(&show_grading_menu_form($symb));
 7554:             &Apache::lonnet::remove_lock($lock);
 7555:             return '';      # Why return ''?  Beats me.
 7556:         }
 7557: 
 7558: 	$completedstudents{$uname}={'line'=>$line};
 7559:         if ($env{'form.verifyrecord'}) {
 7560:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7561:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7562:             chomp($studentdata);
 7563:             $studentdata =~ s/\r$//;
 7564:             my $studentrecord = '';
 7565:             my $counter = -1;
 7566:             foreach my $resource (@resources) {
 7567:                 my $ressymb = $resource->symb();
 7568:                 ($counter,my $recording) =
 7569:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7570:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7571:                                              \%scantron_config,\%lettdig,$numletts);
 7572:                 $studentrecord .= $recording;
 7573:             }
 7574:             if ($studentrecord ne $studentdata) {
 7575:                 &Apache::lonxml::clear_problem_counter();
 7576:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7577:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7578:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7579:                     $r->print("</form>");
 7580:                     &ssi_print_error($r);
 7581:                     $r->print(&show_grading_menu_form($symb));
 7582:                     &Apache::lonnet::remove_lock($lock);
 7583:                     delete($completedstudents{$uname});
 7584:                     return '';
 7585:                 }
 7586:                 $counter = -1;
 7587:                 $studentrecord = '';
 7588:                 foreach my $resource (@resources) {
 7589:                     my $ressymb = $resource->symb();
 7590:                     ($counter,my $recording) =
 7591:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7592:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7593:                                                  \%scantron_config,\%lettdig,$numletts);
 7594:                     $studentrecord .= $recording;
 7595:                 }
 7596:                 if ($studentrecord ne $studentdata) {
 7597:                     $r->print('<p><span class="LC_error">');
 7598:                     if ($scancode eq '') {
 7599:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7600:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7601:                     } else {
 7602:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7603:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7604:                     }
 7605:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7606:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7607:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7608:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7609:                               &Apache::loncommon::start_data_table_row().
 7610:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7611:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7612:                               &Apache::loncommon::end_data_table_row().
 7613:                               &Apache::loncommon::start_data_table_row().
 7614:                               '<td>Stored submissions</td>'.
 7615:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7616:                               &Apache::loncommon::end_data_table_row().
 7617:                               &Apache::loncommon::end_data_table().'</p>');
 7618:                 } else {
 7619:                     $r->print('<br /><span class="LC_warning">'.
 7620:                              &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 />'.
 7621:                              &mt("As a consequence, this user's submission history records two tries.").
 7622:                                  '</span><br />');
 7623:                 }
 7624:             }
 7625:         }
 7626:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7627:     } continue {
 7628: 	&Apache::lonxml::clear_problem_counter();
 7629: 	&Apache::lonnet::delenv('scantron.');
 7630:     }
 7631:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7632:     &Apache::lonnet::remove_lock($lock);
 7633: #    my $lasttime = &Time::HiRes::time()-$start;
 7634: #    $r->print("<p>took $lasttime</p>");
 7635: 
 7636:     $r->print("</form>");
 7637:     $r->print(&show_grading_menu_form($symb));
 7638:     return '';
 7639: }
 7640: 
 7641: sub graders_resources_pass {
 7642:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7643:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7644:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7645:         foreach my $resource (@{$resources}) {
 7646:             my $ressymb = $resource->symb();
 7647:             my ($analysis,$parts) =
 7648:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7649:                                           $env{'user.name'},$env{'user.domain'},1);
 7650:             $grader_partids_by_symb->{$ressymb} = $parts;
 7651:             if (ref($analysis) eq 'HASH') {
 7652:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7653:                     $grader_randomlists_by_symb->{$ressymb} =
 7654:                         $analysis->{'parts_withrandomlist'};
 7655:                 }
 7656:             }
 7657:         }
 7658:     }
 7659:     return;
 7660: }
 7661: 
 7662: sub grade_student_bubbles {
 7663:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7664:     if (ref($resources) eq 'ARRAY') {
 7665:         my $count = 0;
 7666:         foreach my $resource (@{$resources}) {
 7667:             my $ressymb = $resource->symb();
 7668:             my %form = ('submitted'      => 'scantron',
 7669:                         'grade_target'   => 'grade',
 7670:                         'grade_username' => $uname,
 7671:                         'grade_domain'   => $udom,
 7672:                         'grade_courseid' => $env{'request.course.id'},
 7673:                         'grade_symb'     => $ressymb,
 7674:                         'CODE'           => $scancode
 7675:                        );
 7676:             if (ref($parts) eq 'HASH') {
 7677:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7678:                     foreach my $part (@{$parts->{$ressymb}}) {
 7679:                         $form{'scantron_questnum_start.'.$part} =
 7680:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7681:                         $count++;
 7682:                     }
 7683:                 }
 7684:             }
 7685:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7686:             return 'ssi_error' if ($ssi_error);
 7687:             last if (&Apache::loncommon::connection_aborted($r));
 7688:         }
 7689:     }
 7690:     return;
 7691: }
 7692: 
 7693: sub scantron_upload_scantron_data {
 7694:     my ($r)=@_;
 7695:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7696:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7697: 							  'domainid',
 7698: 							  'coursename');
 7699:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7700: 						   'domainid');
 7701:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7702:     $r->print('
 7703: <script type="text/javascript" language="javascript">
 7704:     function checkUpload(formname) {
 7705: 	if (formname.upfile.value == "") {
 7706: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 7707: 	    return false;
 7708: 	}
 7709: 	formname.submit();
 7710:     }
 7711: </script>
 7712: 
 7713: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7714: '.$default_form_data.'
 7715: <table>
 7716: <tr><td>'.$select_link.'                             </td></tr>
 7717: <tr><td>'.&mt('Course ID:').'     </td>
 7718:     <td><input name="courseid"   type="text" />      </td></tr>
 7719: <tr><td>'.&mt('Course Name:').'   </td>
 7720:     <td><input name="coursename" type="text" />      </td></tr>
 7721: <tr><td>'.&mt('Domain:').'        </td>
 7722:     <td>'.$domsel.'                                  </td></tr>
 7723: <tr><td>'.&mt('File to upload:').'</td>
 7724:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7725: </table>
 7726: <input name="command" value="scantronupload_save" type="hidden" />
 7727: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7728: </form>
 7729: ');
 7730:     return '';
 7731: }
 7732: 
 7733: 
 7734: sub scantron_upload_scantron_data_save {
 7735:     my($r)=@_;
 7736:     my ($symb)=&get_symb($r,1);
 7737:     my $doanotherupload=
 7738: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7739: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7740: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7741: 	'</form>'."\n";
 7742:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7743: 	!&Apache::lonnet::allowed('usc',
 7744: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7745: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7746: 	if ($symb) {
 7747: 	    $r->print(&show_grading_menu_form($symb));
 7748: 	} else {
 7749: 	    $r->print($doanotherupload);
 7750: 	}
 7751: 	return '';
 7752:     }
 7753:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7754:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7755:     my $fname=$env{'form.upfile.filename'};
 7756:     #FIXME
 7757:     #copied from lonnet::userfileupload()
 7758:     #make that function able to target a specified course
 7759:     # Replace Windows backslashes by forward slashes
 7760:     $fname=~s/\\/\//g;
 7761:     # Get rid of everything but the actual filename
 7762:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7763:     # Replace spaces by underscores
 7764:     $fname=~s/\s+/\_/g;
 7765:     # Replace all other weird characters by nothing
 7766:     $fname=~s/[^\w\.\-]//g;
 7767:     # See if there is anything left
 7768:     unless ($fname) { return 'error: no uploaded file'; }
 7769:     my $uploadedfile=$fname;
 7770:     $fname='scantron_orig_'.$fname;
 7771:     if (length($env{'form.upfile'}) < 2) {
 7772: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7773:     } else {
 7774: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7775: 	if ($result =~ m|^/uploaded/|) {
 7776: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7777: 			  (length($env{'form.upfile'})-1),
 7778: 			  '<span class="LC_filename">'.$result."</span>"));
 7779: 	} else {
 7780: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7781: 			  $result,
 7782: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7783: 
 7784: 	}
 7785:     }
 7786:     if ($symb) {
 7787: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7788:     } else {
 7789: 	$r->print($doanotherupload);
 7790:     }
 7791:     return '';
 7792: }
 7793: 
 7794: sub valid_file {
 7795:     my ($requested_file)=@_;
 7796:     foreach my $filename (sort(&scantron_filenames())) {
 7797: 	if ($requested_file eq $filename) { return 1; }
 7798:     }
 7799:     return 0;
 7800: }
 7801: 
 7802: sub scantron_download_scantron_data {
 7803:     my ($r)=@_;
 7804:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7805:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7806:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7807:     my $file=$env{'form.scantron_selectfile'};
 7808:     if (! &valid_file($file)) {
 7809: 	$r->print('
 7810: 	<p>
 7811: 	    '.&mt('The requested file name was invalid.').'
 7812:         </p>
 7813: ');
 7814: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7815: 	return;
 7816:     }
 7817:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7818:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7819:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7820:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7821:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7822:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7823:     $r->print('
 7824:     <p>
 7825: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7826: 	      '<a href="'.$orig.'">','</a>').'
 7827:     </p>
 7828:     <p>
 7829: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7830: 	      '<a href="'.$corrected.'">','</a>').'
 7831:     </p>
 7832:     <p>
 7833: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7834: 	      '<a href="'.$skipped.'">','</a>').'
 7835:     </p>
 7836: ');
 7837:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7838:     return '';
 7839: }
 7840: 
 7841: sub checkscantron_results {
 7842:     my ($r) = @_;
 7843:     my ($symb)=&get_symb($r);
 7844:     if (!$symb) {return '';}
 7845:     my $grading_menu_button=&show_grading_menu_form($symb);
 7846:     my $cid = $env{'request.course.id'};
 7847:     my %lettdig = &letter_to_digits();
 7848:     my $numletts = scalar(keys(%lettdig));
 7849:     my $cnum = $env{'course.'.$cid.'.num'};
 7850:     my $cdom = $env{'course.'.$cid.'.domain'};
 7851:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7852:     my %record;
 7853:     my %scantron_config =
 7854:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7855:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7856:     my $classlist=&Apache::loncoursedata::get_classlist();
 7857:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7858:     my $navmap=Apache::lonnavmaps::navmap->new();
 7859:     my $map=$navmap->getResourceByUrl($sequence);
 7860:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7861:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7862:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 7863: 
 7864:     my ($uname,$udom);
 7865:     my (%scandata,%lastname,%bylast);
 7866:     $r->print('
 7867: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7868: 
 7869:     my @delayqueue;
 7870:     my %completedstudents;
 7871: 
 7872:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7873:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7874:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7875:                                     'inline',undef,'checkscantron');
 7876:     my ($username,$domain,$started);
 7877: 
 7878:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7879: 
 7880:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7881:                                           'Processing first student');
 7882:     my $start=&Time::HiRes::time();
 7883:     my $i=-1;
 7884: 
 7885:     while ($i<$scanlines->{'count'}) {
 7886:         ($username,$domain,$uname)=('','','');
 7887:         $i++;
 7888:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7889:         if ($line=~/^[\s\cz]*$/) { next; }
 7890:         if ($started) {
 7891:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7892:                                                      'last student');
 7893:         }
 7894:         $started=1;
 7895:         my $scan_record=
 7896:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7897:                                                      $scan_data);
 7898:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7899:                                                               \%idmap,$i)) {
 7900:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7901:                                 'Unable to find a student that matches',1);
 7902:             next;
 7903:         }
 7904:         if (exists $completedstudents{$uname}) {
 7905:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7906:                                 'Student '.$uname.' has multiple sheets',2);
 7907:             next;
 7908:         }
 7909:         my $pid = $scan_record->{'scantron.ID'};
 7910:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7911:         push(@{$bylast{$lastname{$pid}}},$pid);
 7912:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7913:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7914:         chomp($scandata{$pid});
 7915:         $scandata{$pid} =~ s/\r$//;
 7916:         ($username,$domain)=split(/:/,$uname);
 7917:         my $counter = -1;
 7918:         foreach my $resource (@resources) {
 7919:             my $parts;
 7920:             my $ressymb = $resource->symb();
 7921:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7922:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7923:                 (my $analysis,$parts) =
 7924:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 7925:             } else {
 7926:                 $parts = $grader_partids_by_symb{$ressymb};
 7927:             }
 7928:             ($counter,my $recording) =
 7929:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7930:                                          $scandata{$pid},$parts,
 7931:                                          \%scantron_config,\%lettdig,$numletts);
 7932:             $record{$pid} .= $recording;
 7933:         }
 7934:     }
 7935:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7936:     $r->print('<br />');
 7937:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 7938:     $passed = 0;
 7939:     $failed = 0;
 7940:     $numstudents = 0;
 7941:     foreach my $last (sort(keys(%bylast))) {
 7942:         if (ref($bylast{$last}) eq 'ARRAY') {
 7943:             foreach my $pid (sort(@{$bylast{$last}})) {
 7944:                 my $showscandata = $scandata{$pid};
 7945:                 my $showrecord = $record{$pid};
 7946:                 $showscandata =~ s/\s/&nbsp;/g;
 7947:                 $showrecord =~ s/\s/&nbsp;/g;
 7948:                 if ($scandata{$pid} eq $record{$pid}) {
 7949:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 7950:                     $okstudents .= '<tr class="'.$css_class.'">'.
 7951: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7952: '</tr>'."\n".
 7953: '<tr class="'.$css_class.'">'."\n".
 7954: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 7955:                     $passed ++;
 7956:                 } else {
 7957:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 7958:                     $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".
 7959: '</tr>'."\n".
 7960: '<tr class="'.$css_class.'">'."\n".
 7961: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 7962: '</tr>'."\n";
 7963:                     $failed ++;
 7964:                 }
 7965:                 $numstudents ++;
 7966:             }
 7967:         }
 7968:     }
 7969:     $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>');
 7970:     $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>');
 7971:     if ($passed) {
 7972:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 7973:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7974:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7975:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7976:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7977:                  $okstudents."\n".
 7978:                  &Apache::loncommon::end_data_table().'<br />');
 7979:     }
 7980:     if ($failed) {
 7981:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 7982:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7983:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7984:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7985:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7986:                  $badstudents."\n".
 7987:                  &Apache::loncommon::end_data_table()).'<br />'.
 7988:                  &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.');  
 7989:     }
 7990:     $r->print('</form><br />'.$grading_menu_button);
 7991:     return;
 7992: }
 7993: 
 7994: sub verify_scantron_grading {
 7995:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 7996:         $scantron_config,$lettdig,$numletts) = @_;
 7997:     my ($record,%expected,%startpos);
 7998:     return ($counter,$record) if (!ref($resource));
 7999:     return ($counter,$record) if (!$resource->is_problem());
 8000:     my $symb = $resource->symb();
 8001:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8002:     foreach my $part_id (@{$partids}) {
 8003:         $counter ++;
 8004:         $expected{$part_id} = 0;
 8005:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8006:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8007:             foreach my $item (@sub_lines) {
 8008:                 $expected{$part_id} += $item;
 8009:             }
 8010:         } else {
 8011:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8012:         }
 8013:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8014:     }
 8015:     if ($symb) {
 8016:         my %recorded;
 8017:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8018:         if ($returnhash{'version'}) {
 8019:             my %lasthash=();
 8020:             my $version;
 8021:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8022:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8023:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8024:                 }
 8025:             }
 8026:             foreach my $key (keys(%lasthash)) {
 8027:                 if ($key =~ /\.scantron$/) {
 8028:                     my $value = &unescape($lasthash{$key});
 8029:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8030:                     if ($value eq '') {
 8031:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8032:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8033:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8034:                             }
 8035:                         }
 8036:                     } else {
 8037:                         my @tocheck;
 8038:                         my @items = split(//,$value);
 8039:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8040:                             ($scantron_config->{'Qon'} eq 'number')) {
 8041:                             if (@items < $expected{$part_id}) {
 8042:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8043:                                 my @singles = split(//,$fragment);
 8044:                                 foreach my $pos (@singles) {
 8045:                                     if ($pos eq ' ') {
 8046:                                         push(@tocheck,$pos);
 8047:                                     } else {
 8048:                                         my $next = shift(@items);
 8049:                                         push(@tocheck,$next);
 8050:                                     }
 8051:                                 }
 8052:                             } else {
 8053:                                 @tocheck = @items;
 8054:                             }
 8055:                             foreach my $letter (@tocheck) {
 8056:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8057:                                     if ($letter !~ /^[A-J]$/) {
 8058:                                         $letter = $scantron_config->{'Qoff'};
 8059:                                     }
 8060:                                     $recorded{$part_id} .= $letter;
 8061:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8062:                                     my $digit;
 8063:                                     if ($letter !~ /^[A-J]$/) {
 8064:                                         $digit = $scantron_config->{'Qoff'};
 8065:                                     } else {
 8066:                                         $digit = $lettdig->{$letter};
 8067:                                     }
 8068:                                     $recorded{$part_id} .= $digit;
 8069:                                 }
 8070:                             }
 8071:                         } else {
 8072:                             @tocheck = @items;
 8073:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8074:                                 my $curr_sub = shift(@tocheck);
 8075:                                 my $digit;
 8076:                                 if ($curr_sub =~ /^[A-J]$/) {
 8077:                                     $digit = $lettdig->{$curr_sub}-1;
 8078:                                 }
 8079:                                 if ($curr_sub eq 'J') {
 8080:                                     $digit += scalar($numletts);
 8081:                                 }
 8082:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8083:                                     if ($j == $digit) {
 8084:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8085:                                     } else {
 8086:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8087:                                     }
 8088:                                 }
 8089:                             }
 8090:                         }
 8091:                     }
 8092:                 }
 8093:             }
 8094:         }
 8095:         foreach my $part_id (@{$partids}) {
 8096:             if ($recorded{$part_id} eq '') {
 8097:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8098:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8099:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8100:                     }
 8101:                 }
 8102:             }
 8103:             $record .= $recorded{$part_id};
 8104:         }
 8105:     }
 8106:     return ($counter,$record);
 8107: }
 8108: 
 8109: sub letter_to_digits { 
 8110:     my %lettdig = (
 8111:                     A => 1,
 8112:                     B => 2,
 8113:                     C => 3,
 8114:                     D => 4,
 8115:                     E => 5,
 8116:                     F => 6,
 8117:                     G => 7,
 8118:                     H => 8,
 8119:                     I => 9,
 8120:                     J => 0,
 8121:                   );
 8122:     return %lettdig;
 8123: }
 8124: 
 8125: 
 8126: #-------- end of section for handling grading scantron forms -------
 8127: #
 8128: #-------------------------------------------------------------------
 8129: 
 8130: #-------------------------- Menu interface -------------------------
 8131: #
 8132: #--- Show a Grading Menu button - Calls the next routine ---
 8133: sub show_grading_menu_form {
 8134:     my ($symb)=@_;
 8135:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8136: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8137: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8138: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8139: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8140: 	'</form>'."\n";
 8141:     return $result;
 8142: }
 8143: 
 8144: # -- Retrieve choices for grading form
 8145: sub savedState {
 8146:     my %savedState = ();
 8147:     if ($env{'form.saveState'}) {
 8148: 	foreach (split(/:/,$env{'form.saveState'})) {
 8149: 	    my ($key,$value) = split(/=/,$_,2);
 8150: 	    $savedState{$key} = $value;
 8151: 	}
 8152:     }
 8153:     return \%savedState;
 8154: }
 8155: 
 8156: sub grading_menu {
 8157:     my ($request) = @_;
 8158:     my ($symb)=&get_symb($request);
 8159:     if (!$symb) {return '';}
 8160:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8161:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8162: 
 8163:     $request->print($table);
 8164:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8165:                   'handgrade'=>$hdgrade,
 8166:                   'probTitle'=>$probTitle,
 8167:                   'command'=>'submit_options',
 8168:                   'saveState'=>"",
 8169:                   'gradingMenu'=>1,
 8170:                   'showgrading'=>"yes");
 8171:     
 8172:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8173:     
 8174:     $fields{'command'} = 'csvform';
 8175:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8176:     
 8177:     $fields{'command'} = 'processclicker';
 8178:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8179:     
 8180:     $fields{'command'} = 'scantron_selectphase';
 8181:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8182:     
 8183:     my @menu = ({	categorytitle=>'Course Grading',
 8184:             items =>[
 8185:                         {	linktext => 'Manual Grading/View Submissions',
 8186:                     		url => $url1,
 8187:                     		permission => 'F',
 8188:                     		icon => 'edit-find-replace.png',
 8189:                     		linktitle => 'Start the process of hand grading submissions.'
 8190:                         },
 8191:                 	    {	linktext => 'Upload Scores',
 8192:                     		url => $url2,
 8193:                     		permission => 'F',
 8194:                     		icon => 'uploadscores.png',
 8195:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8196:                 	    },
 8197:                 	    {	linktext => 'Process Clicker',
 8198:                     		url => $url3,
 8199:                     		permission => 'F',
 8200:                     		icon => 'addClickerInfoFile.png',
 8201:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8202:                 	    },
 8203:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
 8204:                     		url => $url4,
 8205:                     		permission => 'F',
 8206:                     		icon => 'stat.png',
 8207:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8208:                 	    }
 8209:                     ]
 8210:             });
 8211: 
 8212:     #$fields{'command'} = 'verify';
 8213:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8214:     #
 8215:     # Create the menu
 8216:     my $Str;
 8217:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8218:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8219:     $Str .= '<input type="hidden" name="command" value="" />'.
 8220:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8221: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8222: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8223: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8224: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8225: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8226: 
 8227:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8228:     #$menudata->{'jscript'}
 8229:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8230:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8231:         ' /> '.
 8232:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8233:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8234: 
 8235:     $Str .="</form>\n";
 8236:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8237:     $request->print(<<GRADINGMENUJS);
 8238: <script type="text/javascript" language="javascript">
 8239:     function checkChoice(formname,val,cmdx) {
 8240: 	if (val <= 2) {
 8241: 	    var cmd = radioSelection(formname.radioChoice);
 8242: 	    var cmdsave = cmd;
 8243: 	} else {
 8244: 	    cmd = cmdx;
 8245: 	    cmdsave = 'submission';
 8246: 	}
 8247: 	formname.command.value = cmd;
 8248: 	if (val < 5) formname.submit();
 8249: 	if (val == 5) {
 8250: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8251: 	        return false;
 8252: 	    } else {
 8253: 	        formname.submit();
 8254: 	    }
 8255: 	}
 8256:     }
 8257: 
 8258:     function checkReceiptNo(formname,nospace) {
 8259: 	var receiptNo = formname.receipt.value;
 8260: 	var checkOpt = false;
 8261: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8262: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8263: 	if (checkOpt) {
 8264: 	    alert("$receiptalert");
 8265: 	    formname.receipt.value = "";
 8266: 	    formname.receipt.focus();
 8267: 	    return false;
 8268: 	}
 8269: 	return true;
 8270:     }
 8271: </script>
 8272: GRADINGMENUJS
 8273:     &commonJSfunctions($request);
 8274:     return $Str;    
 8275: }
 8276: 
 8277: 
 8278: #--- Displays the submissions first page -------
 8279: sub submit_options {
 8280:     my ($request) = @_;
 8281:     my ($symb)=&get_symb($request);
 8282:     if (!$symb) {return '';}
 8283:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8284: 
 8285:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8286:     $request->print(<<GRADINGMENUJS);
 8287: <script type="text/javascript" language="javascript">
 8288:     function checkChoice(formname,val,cmdx) {
 8289: 	if (val <= 2) {
 8290: 	    var cmd = radioSelection(formname.radioChoice);
 8291: 	    var cmdsave = cmd;
 8292: 	} else {
 8293: 	    cmd = cmdx;
 8294: 	    cmdsave = 'submission';
 8295: 	}
 8296: 	formname.command.value = cmd;
 8297: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8298: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8299: 	if (val < 5) formname.submit();
 8300: 	if (val == 5) {
 8301: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8302: 	    formname.submit();
 8303: 	}
 8304: 	if (val < 7) formname.submit();
 8305:     }
 8306: 
 8307:     function checkReceiptNo(formname,nospace) {
 8308: 	var receiptNo = formname.receipt.value;
 8309: 	var checkOpt = false;
 8310: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8311: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8312: 	if (checkOpt) {
 8313: 	    alert("$receiptalert");
 8314: 	    formname.receipt.value = "";
 8315: 	    formname.receipt.focus();
 8316: 	    return false;
 8317: 	}
 8318: 	return true;
 8319:     }
 8320: </script>
 8321: GRADINGMENUJS
 8322:     &commonJSfunctions($request);
 8323:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8324:     my $result;
 8325:     my (undef,$sections) = &getclasslist('all','0');
 8326:     my $savedState = &savedState();
 8327:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8328:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8329:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8330:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8331: 
 8332:     # Preselect sections
 8333:     my $selsec="";
 8334:     if (ref($sections)) {
 8335:         foreach my $section (sort(@$sections)) {
 8336:             $selsec.='<option value="'.$section.'" '.
 8337:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8338:         }
 8339:     }
 8340: 
 8341:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8342: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8343: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8344: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8345: 	'<input type="hidden" name="command"     value="" />'."\n".
 8346: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8347: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8348: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8349: 
 8350:     $result.='
 8351: <h2>
 8352:   '.&mt('Grade Current Resource').'
 8353: </h2>
 8354: <div>
 8355:   '.$table.'
 8356: </div>
 8357: 
 8358: <div class="LC_columnSection">
 8359:   
 8360:     <fieldset>
 8361:       <legend>
 8362:        '.&mt('Sections').'
 8363:       </legend>
 8364:       <select name="section" multiple="multiple" size="5">'."\n";
 8365:     $result.= $selsec;
 8366:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8367:     $result.='
 8368:     </fieldset>
 8369:   
 8370:     <fieldset>
 8371:       <legend>
 8372:         '.&mt('Groups').'
 8373:       </legend>
 8374:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8375:     </fieldset>
 8376:   
 8377:     <fieldset>
 8378:       <legend>
 8379:         '.&mt('Access Status').'
 8380:       </legend>
 8381:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8382:     </fieldset>
 8383:   
 8384:     <fieldset>
 8385:       <legend>
 8386:         '.&mt('Submission Status').'
 8387:       </legend>
 8388:       <select name="submitonly" size="5">
 8389: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8390: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8391: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8392: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8393:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8394:       </select>
 8395:     </fieldset>
 8396:   
 8397: </div>
 8398: 
 8399: <br />
 8400:           <div>
 8401:             <div>
 8402:               <label>
 8403:                 <input type="radio" name="radioChoice" value="submission" '.
 8404:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8405:              &mt('Select individual students to grade and view submissions.').'
 8406: 	      </label> 
 8407:             </div>
 8408:             <div>
 8409: 	      <label>
 8410:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8411:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8412:                     &mt('Grade all selected students in a grading table.').'
 8413:               </label>
 8414:             </div>
 8415:             <div>
 8416: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8417:             </div>
 8418:           </div>
 8419: 
 8420: 
 8421:         <h2>
 8422:          '.&mt('Grade Complete Folder for One Student').'
 8423:         </h2>
 8424:         <div>
 8425:             <div>
 8426:               <label>
 8427:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8428: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8429:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8430:               </label>
 8431:             </div>
 8432:             <div>
 8433: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8434:             </div>
 8435:         </div>
 8436:   </form>';
 8437:     $result .= &show_grading_menu_form($symb);
 8438:     return $result;
 8439: }
 8440: 
 8441: sub reset_perm {
 8442:     undef(%perm);
 8443: }
 8444: 
 8445: sub init_perm {
 8446:     &reset_perm();
 8447:     foreach my $test_perm ('vgr','mgr','opa') {
 8448: 
 8449: 	my $scope = $env{'request.course.id'};
 8450: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8451: 
 8452: 	    $scope .= '/'.$env{'request.course.sec'};
 8453: 	    if ( $perm{$test_perm}=
 8454: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8455: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8456: 	    } else {
 8457: 		delete($perm{$test_perm});
 8458: 	    }
 8459: 	}
 8460:     }
 8461: }
 8462: 
 8463: sub gather_clicker_ids {
 8464:     my %clicker_ids;
 8465: 
 8466:     my $classlist = &Apache::loncoursedata::get_classlist();
 8467: 
 8468:     # Set up a couple variables.
 8469:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8470:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8471:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8472: 
 8473:     foreach my $student (keys(%$classlist)) {
 8474:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8475:         my $username = $classlist->{$student}->[$username_idx];
 8476:         my $domain   = $classlist->{$student}->[$domain_idx];
 8477:         my $clickers =
 8478: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8479:         foreach my $id (split(/\,/,$clickers)) {
 8480:             $id=~s/^[\#0]+//;
 8481:             $id=~s/[\-\:]//g;
 8482:             if (exists($clicker_ids{$id})) {
 8483: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8484:             } else {
 8485: 		$clicker_ids{$id}=$username.':'.$domain;
 8486:             }
 8487:         }
 8488:     }
 8489:     return %clicker_ids;
 8490: }
 8491: 
 8492: sub gather_adv_clicker_ids {
 8493:     my %clicker_ids;
 8494:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8495:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8496:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8497:     foreach my $element (sort(keys(%coursepersonnel))) {
 8498:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8499:             my ($puname,$pudom)=split(/\:/,$person);
 8500:             my $clickers =
 8501: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8502:             foreach my $id (split(/\,/,$clickers)) {
 8503: 		$id=~s/^[\#0]+//;
 8504:                 $id=~s/[\-\:]//g;
 8505: 		if (exists($clicker_ids{$id})) {
 8506: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8507: 		} else {
 8508: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8509: 		}
 8510:             }
 8511:         }
 8512:     }
 8513:     return %clicker_ids;
 8514: }
 8515: 
 8516: sub clicker_grading_parameters {
 8517:     return ('gradingmechanism' => 'scalar',
 8518:             'upfiletype' => 'scalar',
 8519:             'specificid' => 'scalar',
 8520:             'pcorrect' => 'scalar',
 8521:             'pincorrect' => 'scalar');
 8522: }
 8523: 
 8524: sub process_clicker {
 8525:     my ($r)=@_;
 8526:     my ($symb)=&get_symb($r);
 8527:     if (!$symb) {return '';}
 8528:     my $result=&checkforfile_js();
 8529:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8530:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8531:     $result.=$table;
 8532:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8533:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8534:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8535:         '</b></td></tr>'."\n";
 8536:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8537: # Attempt to restore parameters from last session, set defaults if not present
 8538:     my %Saveable_Parameters=&clicker_grading_parameters();
 8539:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8540:                                                  \%Saveable_Parameters);
 8541:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8542:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8543:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8544:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8545: 
 8546:     my %checked;
 8547:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8548:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8549:           $checked{$gradingmechanism}="checked='checked'";
 8550:        }
 8551:     }
 8552: 
 8553:     my $upload=&mt("Upload File");
 8554:     my $type=&mt("Type");
 8555:     my $attendance=&mt("Award points just for participation");
 8556:     my $personnel=&mt("Correctness determined from response by course personnel");
 8557:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8558:     my $given=&mt("Correctness determined from given list of answers").' '.
 8559:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8560:     my $pcorrect=&mt("Percentage points for correct solution");
 8561:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8562:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8563: 						   ('iclicker' => 'i>clicker',
 8564:                                                     'interwrite' => 'interwrite PRS'));
 8565:     $symb = &Apache::lonenc::check_encrypt($symb);
 8566:     $result.=<<ENDUPFORM;
 8567: <script type="text/javascript">
 8568: function sanitycheck() {
 8569: // Accept only integer percentages
 8570:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8571:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8572: // Find out grading choice
 8573:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8574:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8575:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8576:       }
 8577:    }
 8578: // By default, new choice equals user selection
 8579:    newgradingchoice=gradingchoice;
 8580: // Not good to give more points for false answers than correct ones
 8581:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8582:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8583:    }
 8584: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8585:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8586:       document.forms.gradesupload.pcorrect.value=100;
 8587:       document.forms.gradesupload.pincorrect.value=100;
 8588:    }
 8589: // If the values are different, cannot be attendance only
 8590:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8591:        (gradingchoice=='attendance')) {
 8592:        newgradingchoice='personnel';
 8593:    }
 8594: // Change grading choice to new one
 8595:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8596:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8597:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8598:       } else {
 8599:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8600:       }
 8601:    }
 8602: // Remember the old state
 8603:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8604: }
 8605: </script>
 8606: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8607: <input type="hidden" name="symb" value="$symb" />
 8608: <input type="hidden" name="command" value="processclickerfile" />
 8609: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8610: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8611: <input type="file" name="upfile" size="50" />
 8612: <br /><label>$type: $selectform</label>
 8613: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8614: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8615: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8616: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8617: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8618: <br />&nbsp;&nbsp;&nbsp;
 8619: <input type="text" name="givenanswer" size="50" />
 8620: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8621: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8622: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8623: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8624: </form>
 8625: ENDUPFORM
 8626:     $result.='</td></tr></table>'."\n".
 8627:              '</td></tr></table><br /><br />'."\n";
 8628:     $result.=&show_grading_menu_form($symb);
 8629:     return $result;
 8630: }
 8631: 
 8632: sub process_clicker_file {
 8633:     my ($r)=@_;
 8634:     my ($symb)=&get_symb($r);
 8635:     if (!$symb) {return '';}
 8636: 
 8637:     my %Saveable_Parameters=&clicker_grading_parameters();
 8638:     &Apache::loncommon::store_course_settings('grades_clicker',
 8639:                                               \%Saveable_Parameters);
 8640: 
 8641:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8642:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8643: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8644: 	return $result.&show_grading_menu_form($symb);
 8645:     }
 8646:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8647:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8648:         return $result.&show_grading_menu_form($symb);
 8649:     }
 8650:     my $foundgiven=0;
 8651:     if ($env{'form.gradingmechanism'} eq 'given') {
 8652:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8653:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8654:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8655:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8656:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8657:         $foundgiven=$#answers+1;
 8658:     }
 8659:     my %clicker_ids=&gather_clicker_ids();
 8660:     my %correct_ids;
 8661:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8662: 	%correct_ids=&gather_adv_clicker_ids();
 8663:     }
 8664:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8665: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8666: 	   $correct_id=~tr/a-z/A-Z/;
 8667: 	   $correct_id=~s/\s//gs;
 8668: 	   $correct_id=~s/^[\#0]+//;
 8669:            $correct_id=~s/[\-\:]//g;
 8670:            if ($correct_id) {
 8671: 	      $correct_ids{$correct_id}='specified';
 8672:            }
 8673:         }
 8674:     }
 8675:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8676: 	$result.=&mt('Score based on attendance only');
 8677:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8678:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8679:     } else {
 8680: 	my $number=0;
 8681: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8682: 	foreach my $id (sort(keys(%correct_ids))) {
 8683: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8684: 	    if ($correct_ids{$id} eq 'specified') {
 8685: 		$result.=&mt('specified');
 8686: 	    } else {
 8687: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8688: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8689: 	    }
 8690: 	    $number++;
 8691: 	}
 8692:         $result.="</p>\n";
 8693: 	if ($number==0) {
 8694: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8695: 	    return $result.&show_grading_menu_form($symb);
 8696: 	}
 8697:     }
 8698:     if (length($env{'form.upfile'}) < 2) {
 8699:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8700: 		     '<span class="LC_error">',
 8701: 		     '</span>',
 8702: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8703:         return $result.&show_grading_menu_form($symb);
 8704:     }
 8705: 
 8706: # Were able to get all the info needed, now analyze the file
 8707: 
 8708:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8709:     $symb = &Apache::lonenc::check_encrypt($symb);
 8710:     my $heading=&mt('Scanning clicker file');
 8711:     $result.=(<<ENDHEADER);
 8712: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8713: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8714: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8715: <form method="post" action="/adm/grades" name="clickeranalysis">
 8716: <input type="hidden" name="symb" value="$symb" />
 8717: <input type="hidden" name="command" value="assignclickergrades" />
 8718: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8719: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8720: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8721: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8722: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8723: ENDHEADER
 8724:     if ($env{'form.gradingmechanism'} eq 'given') {
 8725:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8726:     } 
 8727:     my %responses;
 8728:     my @questiontitles;
 8729:     my $errormsg='';
 8730:     my $number=0;
 8731:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8732: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8733:     }
 8734:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8735:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8736:     }
 8737:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8738:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8739:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8740:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8741:              '<br />';
 8742:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8743:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8744:        return $result.&show_grading_menu_form($symb);
 8745:     } 
 8746: # Remember Question Titles
 8747: # FIXME: Possibly need delimiter other than ":"
 8748:     for (my $i=0;$i<$number;$i++) {
 8749:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8750:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8751:     }
 8752:     my $correct_count=0;
 8753:     my $student_count=0;
 8754:     my $unknown_count=0;
 8755: # Match answers with usernames
 8756: # FIXME: Possibly need delimiter other than ":"
 8757:     foreach my $id (keys(%responses)) {
 8758:        if ($correct_ids{$id}) {
 8759:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8760:           $correct_count++;
 8761:        } elsif ($clicker_ids{$id}) {
 8762:           if ($clicker_ids{$id}=~/\,/) {
 8763: # More than one user with the same clicker!
 8764:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8765:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8766:                            "<select name='multi".$id."'>";
 8767:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8768:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8769:              }
 8770:              $result.='</select>';
 8771:              $unknown_count++;
 8772:           } else {
 8773: # Good: found one and only one user with the right clicker
 8774:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8775:              $student_count++;
 8776:           }
 8777:        } else {
 8778:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8779:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8780:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8781:                    "\n".&mt("Domain").": ".
 8782:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8783:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8784:           $unknown_count++;
 8785:        }
 8786:     }
 8787:     $result.='<hr />'.
 8788:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8789:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8790:        if ($correct_count==0) {
 8791:           $errormsg.="Found no correct answers answers for grading!";
 8792:        } elsif ($correct_count>1) {
 8793:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8794:        }
 8795:     }
 8796:     if ($number<1) {
 8797:        $errormsg.="Found no questions.";
 8798:     }
 8799:     if ($errormsg) {
 8800:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8801:     } else {
 8802:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8803:     }
 8804:     $result.='</form></td></tr></table>'."\n".
 8805:              '</td></tr></table><br /><br />'."\n";
 8806:     return $result.&show_grading_menu_form($symb);
 8807: }
 8808: 
 8809: sub iclicker_eval {
 8810:     my ($questiontitles,$responses)=@_;
 8811:     my $number=0;
 8812:     my $errormsg='';
 8813:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8814:         my %components=&Apache::loncommon::record_sep($line);
 8815:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8816: 	if ($entries[0] eq 'Question') {
 8817: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8818: 		$$questiontitles[$number]=$entries[$i];
 8819: 		$number++;
 8820: 	    }
 8821: 	}
 8822: 	if ($entries[0]=~/^\#/) {
 8823: 	    my $id=$entries[0];
 8824: 	    my @idresponses;
 8825: 	    $id=~s/^[\#0]+//;
 8826: 	    for (my $i=0;$i<$number;$i++) {
 8827: 		my $idx=3+$i*6;
 8828: 		push(@idresponses,$entries[$idx]);
 8829: 	    }
 8830: 	    $$responses{$id}=join(',',@idresponses);
 8831: 	}
 8832:     }
 8833:     return ($errormsg,$number);
 8834: }
 8835: 
 8836: sub interwrite_eval {
 8837:     my ($questiontitles,$responses)=@_;
 8838:     my $number=0;
 8839:     my $errormsg='';
 8840:     my $skipline=1;
 8841:     my $questionnumber=0;
 8842:     my %idresponses=();
 8843:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8844:         my %components=&Apache::loncommon::record_sep($line);
 8845:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8846:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8847:         if ($entries[1] eq 'Response') { $skipline=1; }
 8848:         next if $skipline;
 8849:         if ($entries[0]!=$questionnumber) {
 8850:            $questionnumber=$entries[0];
 8851:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8852:            $number++;
 8853:         }
 8854:         my $id=$entries[4];
 8855:         $id=~s/^[\#0]+//;
 8856:         $id=~s/^v\d*\://i;
 8857:         $id=~s/[\-\:]//g;
 8858:         $idresponses{$id}[$number]=$entries[6];
 8859:     }
 8860:     foreach my $id (keys(%idresponses)) {
 8861:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8862:        $$responses{$id}=~s/^\s*\,//;
 8863:     }
 8864:     return ($errormsg,$number);
 8865: }
 8866: 
 8867: sub assign_clicker_grades {
 8868:     my ($r)=@_;
 8869:     my ($symb)=&get_symb($r);
 8870:     if (!$symb) {return '';}
 8871: # See which part we are saving to
 8872:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8873: # FIXME: This should probably look for the first handgradeable part
 8874:     my $part=$$partlist[0];
 8875: # Start screen output
 8876:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8877: 
 8878:     my $heading=&mt('Assigning grades based on clicker file');
 8879:     $result.=(<<ENDHEADER);
 8880: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8881: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8882: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8883: ENDHEADER
 8884: # Get correct result
 8885: # FIXME: Possibly need delimiter other than ":"
 8886:     my @correct=();
 8887:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8888:     my $number=$env{'form.number'};
 8889:     if ($gradingmechanism ne 'attendance') {
 8890:        foreach my $key (keys(%env)) {
 8891:           if ($key=~/^form\.correct\:/) {
 8892:              my @input=split(/\,/,$env{$key});
 8893:              for (my $i=0;$i<=$#input;$i++) {
 8894:                  if (($correct[$i]) && ($input[$i]) &&
 8895:                      ($correct[$i] ne $input[$i])) {
 8896:                     $result.='<br /><span class="LC_warning">'.
 8897:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8898:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8899:                  } elsif ($input[$i]) {
 8900:                     $correct[$i]=$input[$i];
 8901:                  }
 8902:              }
 8903:           }
 8904:        }
 8905:        for (my $i=0;$i<$number;$i++) {
 8906:           if (!$correct[$i]) {
 8907:              $result.='<br /><span class="LC_error">'.
 8908:                       &mt('No correct result given for question "[_1]"!',
 8909:                           $env{'form.question:'.$i}).'</span>';
 8910:           }
 8911:        }
 8912:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8913:     }
 8914: # Start grading
 8915:     my $pcorrect=$env{'form.pcorrect'};
 8916:     my $pincorrect=$env{'form.pincorrect'};
 8917:     my $storecount=0;
 8918:     foreach my $key (keys(%env)) {
 8919:        my $user='';
 8920:        if ($key=~/^form\.student\:(.*)$/) {
 8921:           $user=$1;
 8922:        }
 8923:        if ($key=~/^form\.unknown\:(.*)$/) {
 8924:           my $id=$1;
 8925:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8926:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8927:           } elsif ($env{'form.multi'.$id}) {
 8928:              $user=$env{'form.multi'.$id};
 8929:           }
 8930:        }
 8931:        if ($user) { 
 8932:           my @answer=split(/\,/,$env{$key});
 8933:           my $sum=0;
 8934:           my $realnumber=$number;
 8935:           for (my $i=0;$i<$number;$i++) {
 8936:              if ($answer[$i]) {
 8937:                 if ($gradingmechanism eq 'attendance') {
 8938:                    $sum+=$pcorrect;
 8939:                 } elsif ($answer[$i] eq '*') {
 8940:                    $sum+=$pcorrect;
 8941:                 } elsif ($answer[$i] eq '-') {
 8942:                    $realnumber--;
 8943:                 } else {
 8944:                    if ($answer[$i] eq $correct[$i]) {
 8945:                       $sum+=$pcorrect;
 8946:                    } else {
 8947:                       $sum+=$pincorrect;
 8948:                    }
 8949:                 }
 8950:              }
 8951:           }
 8952:           my $ave=$sum/(100*$realnumber);
 8953: # Store
 8954:           my ($username,$domain)=split(/\:/,$user);
 8955:           my %grades=();
 8956:           $grades{"resource.$part.solved"}='correct_by_override';
 8957:           $grades{"resource.$part.awarded"}=$ave;
 8958:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8959:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8960:                                                  $env{'request.course.id'},
 8961:                                                  $domain,$username);
 8962:           if ($returncode ne 'ok') {
 8963:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8964:           } else {
 8965:              $storecount++;
 8966:           }
 8967:        }
 8968:     }
 8969: # We are done
 8970:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 8971:              '</td></tr></table>'."\n".
 8972:              '</td></tr></table><br /><br />'."\n";
 8973:     return $result.&show_grading_menu_form($symb);
 8974: }
 8975: 
 8976: sub handler {
 8977:     my $request=$_[0];
 8978:     &reset_caches();
 8979:     if ($env{'browser.mathml'}) {
 8980: 	&Apache::loncommon::content_type($request,'text/xml');
 8981:     } else {
 8982: 	&Apache::loncommon::content_type($request,'text/html');
 8983:     }
 8984:     $request->send_http_header;
 8985:     return '' if $request->header_only;
 8986:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8987:     my $symb=&get_symb($request,1);
 8988:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8989:     my $command=$commands[0];
 8990: 
 8991:     if ($#commands > 0) {
 8992: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8993:     }
 8994: 
 8995:     $ssi_error = 0;
 8996:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 8997:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 8998:                                           {'bread_crumbs' => $brcrum}));
 8999:     if ($symb eq '' && $command eq '') {
 9000: 	if ($env{'user.adv'}) {
 9001: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9002: 		($env{'form.codethree'})) {
 9003: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9004: 		    $env{'form.codethree'};
 9005: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9006: 		    &Apache::lonnet::checkin($token);
 9007: 		if ($tsymb) {
 9008: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9009: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9010: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9011: 					  ('grade_username' => $tuname,
 9012: 					   'grade_domain' => $tudom,
 9013: 					   'grade_courseid' => $tcrsid,
 9014: 					   'grade_symb' => $tsymb)));
 9015: 		    } else {
 9016: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9017: 		    }
 9018: 		} else {
 9019: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9020: 		}
 9021: 	    } else {
 9022: 		$request->print(&Apache::lonxml::tokeninputfield());
 9023: 	    }
 9024: 	}
 9025:     } else {
 9026: 	&init_perm();
 9027: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9028: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9029: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9030: 	    &pickStudentPage($request);
 9031: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9032: 	    &displayPage($request);
 9033: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9034: 	    &updateGradeByPage($request);
 9035: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9036: 	    &processGroup($request);
 9037: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9038: 	    $request->print(&grading_menu($request));
 9039: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9040: 	    $request->print(&submit_options($request));
 9041: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9042: 	    $request->print(&viewgrades($request));
 9043: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9044: 	    $request->print(&processHandGrade($request));
 9045: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9046: 	    $request->print(&editgrades($request));
 9047: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9048: 	    $request->print(&verifyreceipt($request));
 9049:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9050:             $request->print(&process_clicker($request));
 9051:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9052:             $request->print(&process_clicker_file($request));
 9053:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9054:             $request->print(&assign_clicker_grades($request));
 9055: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9056: 	    $request->print(&upcsvScores_form($request));
 9057: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9058: 	    $request->print(&csvupload($request));
 9059: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9060: 	    $request->print(&csvuploadmap($request));
 9061: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9062: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9063: 		$request->print(&csvuploadoptions($request));
 9064: 	    } else {
 9065: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9066: 		    $env{'form.upfile_associate'} = 'reverse';
 9067: 		} else {
 9068: 		    $env{'form.upfile_associate'} = 'forward';
 9069: 		}
 9070: 		$request->print(&csvuploadmap($request));
 9071: 	    }
 9072: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9073: 	    $request->print(&csvuploadassign($request));
 9074: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9075: 	    $request->print(&scantron_selectphase($request));
 9076:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9077:  	    $request->print(&scantron_do_warning($request));
 9078: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9079: 	    $request->print(&scantron_validate_file($request));
 9080: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9081: 	    $request->print(&scantron_process_students($request));
 9082:  	} elsif ($command eq 'scantronupload' && 
 9083:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9084: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9085:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9086:  	} elsif ($command eq 'scantronupload_save' &&
 9087:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9088: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9089:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9090:  	} elsif ($command eq 'scantron_download' &&
 9091: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9092:  	    $request->print(&scantron_download_scantron_data($request));
 9093:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9094:             $request->print(&checkscantron_results($request));     
 9095: 	} elsif ($command) {
 9096: 	    $request->print("Access Denied ($command)");
 9097: 	}
 9098:     }
 9099:     if ($ssi_error) {
 9100: 	&ssi_print_error($request);
 9101:     }
 9102:     $request->print(&Apache::loncommon::end_page());
 9103:     &reset_caches();
 9104:     return '';
 9105: }
 9106: 
 9107: 1;
 9108: 
 9109: __END__;
 9110: 
 9111: 
 9112: =head1 NAME
 9113: 
 9114: Apache::grades
 9115: 
 9116: =head1 SYNOPSIS
 9117: 
 9118: Handles the viewing of grades.
 9119: 
 9120: This is part of the LearningOnline Network with CAPA project
 9121: described at http://www.lon-capa.org.
 9122: 
 9123: =head1 OVERVIEW
 9124: 
 9125: Do an ssi with retries:
 9126: While I'd love to factor out this with the vesrion in lonprintout,
 9127: 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
 9128: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9129: 
 9130: At least the logic that drives this has been pulled out into loncommon.
 9131: 
 9132: 
 9133: 
 9134: ssi_with_retries - Does the server side include of a resource.
 9135:                      if the ssi call returns an error we'll retry it up to
 9136:                      the number of times requested by the caller.
 9137:                      If we still have a proble, no text is appended to the
 9138:                      output and we set some global variables.
 9139:                      to indicate to the caller an SSI error occurred.  
 9140:                      All of this is supposed to deal with the issues described
 9141:                      in LonCAPA BZ 5631 see:
 9142:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9143:                      by informing the user that this happened.
 9144: 
 9145: Parameters:
 9146:   resource   - The resource to include.  This is passed directly, without
 9147:                interpretation to lonnet::ssi.
 9148:   form       - The form hash parameters that guide the interpretation of the resource
 9149:                
 9150:   retries    - Number of retries allowed before giving up completely.
 9151: Returns:
 9152:   On success, returns the rendered resource identified by the resource parameter.
 9153: Side Effects:
 9154:   The following global variables can be set:
 9155:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9156:                               It is up to the caller to initialize this to false
 9157:                               if desired.
 9158:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9159:                               of the resource that could not be rendered by the ssi
 9160:                               call.
 9161:    ssi_error_message   - The error string fetched from the ssi response
 9162:                               in the event of an error.
 9163: 
 9164: 
 9165: =head1 HANDLER SUBROUTINE
 9166: 
 9167: ssi_with_retries()
 9168: 
 9169: =head1 SUBROUTINES
 9170: 
 9171: =over
 9172: 
 9173: =item scantron_get_correction() : 
 9174: 
 9175:    Builds the interface screen to interact with the operator to fix a
 9176:    specific error condition in a specific scanline
 9177: 
 9178:  Arguments:
 9179:     $r           - Apache request object
 9180:     $i           - number of the current scanline
 9181:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9182:     $scan_config - hash ref as returned from &get_scantron_config()
 9183:     $line        - full contents of the current scanline
 9184:     $error       - error condition, valid values are
 9185:                    'incorrectCODE', 'duplicateCODE',
 9186:                    'doublebubble', 'missingbubble',
 9187:                    'duplicateID', 'incorrectID'
 9188:     $arg         - extra information needed
 9189:        For errors:
 9190:          - duplicateID   - paper number that this studentID was seen before on
 9191:          - duplicateCODE - array ref of the paper numbers this CODE was
 9192:                            seen on before
 9193:          - incorrectCODE - current incorrect CODE 
 9194:          - doublebubble  - array ref of the bubble lines that have double
 9195:                            bubble errors
 9196:          - missingbubble - array ref of the bubble lines that have missing
 9197:                            bubble errors
 9198: 
 9199: =item  scantron_get_maxbubble() : 
 9200: 
 9201:    Returns the maximum number of bubble lines that are expected to
 9202:    occur. Does this by walking the selected sequence rendering the
 9203:    resource and then checking &Apache::lonxml::get_problem_counter()
 9204:    for what the current value of the problem counter is.
 9205: 
 9206:    Caches the results to $env{'form.scantron_maxbubble'},
 9207:    $env{'form.scantron.bubble_lines.n'}, 
 9208:    $env{'form.scantron.first_bubble_line.n'} and
 9209:    $env{"form.scantron.sub_bubblelines.n"}
 9210:    which are the total number of bubble, lines, the number of bubble
 9211:    lines for response n and number of the first bubble line for response n,
 9212:    and a comma separated list of numbers of bubble lines for sub-questions
 9213:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9214: 
 9215: 
 9216: =item  scantron_validate_missingbubbles() : 
 9217: 
 9218:    Validates all scanlines in the selected file to not have any
 9219:     answers that don't have bubbles that have not been verified
 9220:     to be bubble free.
 9221: 
 9222: =item  scantron_process_students() : 
 9223: 
 9224:    Routine that does the actual grading of the bubble sheet information.
 9225: 
 9226:    The parsed scanline hash is added to %env 
 9227: 
 9228:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9229:    foreach resource , with the form data of
 9230: 
 9231: 	'submitted'     =>'scantron' 
 9232: 	'grade_target'  =>'grade',
 9233: 	'grade_username'=> username of student
 9234: 	'grade_domain'  => domain of student
 9235: 	'grade_courseid'=> of course
 9236: 	'grade_symb'    => symb of resource to grade
 9237: 
 9238:     This triggers a grading pass. The problem grading code takes care
 9239:     of converting the bubbled letter information (now in %env) into a
 9240:     valid submission.
 9241: 
 9242: =item  scantron_upload_scantron_data() :
 9243: 
 9244:     Creates the screen for adding a new bubble sheet data file to a course.
 9245: 
 9246: =item  scantron_upload_scantron_data_save() : 
 9247: 
 9248:    Adds a provided bubble information data file to the course if user
 9249:    has the correct privileges to do so. 
 9250: 
 9251: =item  valid_file() :
 9252: 
 9253:    Validates that the requested bubble data file exists in the course.
 9254: 
 9255: =item  scantron_download_scantron_data() : 
 9256: 
 9257:    Shows a list of the three internal files (original, corrected,
 9258:    skipped) for a specific bubble sheet data file that exists in the
 9259:    course.
 9260: 
 9261: =item  scantron_validate_ID() : 
 9262: 
 9263:    Validates all scanlines in the selected file to not have any
 9264:    invalid or underspecified student/employee IDs
 9265: 
 9266: =back
 9267: 
 9268: =cut

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