File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.560: download - view: text, annotated - select for diffs
Thu Mar 19 21:00:42 2009 UTC (15 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Apply &mt() to complete phrases.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.560 2009/03/19 21:00:42 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 ($common_header,$specific_header);
 3230:     if ($env{'form.section'} eq 'all') {
 3231: 	$common_header = &mt('Assign Common Grade to Class');
 3232:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3233:     } elsif ($env{'form.section'} eq 'none') {
 3234:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3235: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3236:     } else {
 3237:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3238:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3239: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3240:     }
 3241:     $result.= '<h3>'.$common_header.'</h3>'.&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>'.$specific_header.'</h3>'.
 3300:               &Apache::loncommon::start_data_table().
 3301: 	      &Apache::loncommon::start_data_table_header_row().
 3302: 	      '<th>'.&mt('No.').'</th>'.
 3303: 	      '<th>'.&nameUserString('header')."</th>\n";
 3304:     my (@parts) = sort(&getpartlist($symb));
 3305:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3306:     my @partids = ();
 3307:     foreach my $part (@parts) {
 3308: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3309:         my $narrowtext = &mt('Tries');
 3310: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3311: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3312: 	my ($partid) = &split_part_type($part);
 3313:         push(@partids,$partid);
 3314: 	my $display_part=&get_display_part($partid,$symb);
 3315: 	if ($display =~ /^Partial Credit Factor/) {
 3316: 	    $result.='<th>'.
 3317: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3318: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3319: 	    next;
 3320: 	    
 3321: 	} else {
 3322: 	    if ($display =~ /Problem Status/) {
 3323: 		my $grade_status_mt = &mt('Grade Status');
 3324: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3325: 	    }
 3326: 	    my $part_mt = &mt('Part:');
 3327: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3328: 	}
 3329: 
 3330: 	$result.='<th>'.$display.'</th>'."\n";
 3331:     }
 3332:     $result.=&Apache::loncommon::end_data_table_header_row();
 3333: 
 3334:     my %last_resets = 
 3335: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3336: 
 3337:     #get info for each student
 3338:     #list all the students - with points and grade status
 3339:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3340:     my $ctr = 0;
 3341:     foreach (sort 
 3342: 	     {
 3343: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3344: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3345: 		 }
 3346: 		 return $a cmp $b;
 3347: 	     } (keys(%$fullname))) {
 3348: 	$ctr++;
 3349: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3350: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3351:     }
 3352:     $result.=&Apache::loncommon::end_data_table();
 3353:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3354:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3355: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3356:     if (scalar(%$fullname) eq 0) {
 3357: 	my $colspan=3+scalar(@parts);
 3358: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3359:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3360: 	$result='<span class="LC_warning">'.
 3361: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3362: 	        $section_display, $stu_status).
 3363: 	    '</span>';
 3364:     }
 3365:     $result.=&show_grading_menu_form($symb);
 3366:     return $result;
 3367: }
 3368: 
 3369: #--- call by previous routine to display each student
 3370: sub viewstudentgrade {
 3371:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3372:     my ($uname,$udom) = split(/:/,$student);
 3373:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3374:     my %aggregates = (); 
 3375:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3376: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3377: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3378: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3379: 	'\');" target="_self">'.$fullname.'</a> '.
 3380: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3381:     $student=~s/:/_/; # colon doen't work in javascript for names
 3382:     foreach my $apart (@$parts) {
 3383: 	my ($part,$type) = &split_part_type($apart);
 3384: 	my $score=$record{"resource.$part.$type"};
 3385:         $result.='<td align="center">';
 3386:         my ($aggtries,$totaltries);
 3387:         unless (exists($aggregates{$part})) {
 3388: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3389: 
 3390: 	    $aggtries = $totaltries;
 3391:             if ($$last_resets{$part}) {  
 3392:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3393: 					   $part);
 3394:             }
 3395:             $result.='<input type="hidden" name="'.
 3396:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3397:             $result.='<input type="hidden" name="'.
 3398:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3399:             $aggregates{$part} = 1;
 3400:         }
 3401: 	if ($type eq 'awarded') {
 3402: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3403: 	    $result.='<input type="hidden" name="'.
 3404: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3405: 	    $result.='<input type="text" name="'.
 3406: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3407: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3408: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3409: 	} elsif ($type eq 'solved') {
 3410: 	    my ($status,$foo)=split(/_/,$score,2);
 3411: 	    $status = 'nothing' if ($status eq '');
 3412: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3413: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3414: 	    $result.='&nbsp;<select name="'.
 3415: 		'GD_'.$student.'_'.$part.'_solved" '.
 3416: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3417: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3418: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3419: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3420: 	    $result.="</select>&nbsp;</td>\n";
 3421: 	} else {
 3422: 	    $result.='<input type="hidden" name="'.
 3423: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3424: 		    "\n";
 3425: 	    $result.='<input type="text" name="'.
 3426: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3427: 		'value="'.$score.'" size="4" /></td>'."\n";
 3428: 	}
 3429:     }
 3430:     $result.=&Apache::loncommon::end_data_table_row();
 3431:     return $result;
 3432: }
 3433: 
 3434: #--- change scores for all the students in a section/class
 3435: #    record does not get update if unchanged
 3436: sub editgrades {
 3437:     my ($request) = @_;
 3438: 
 3439:     my $symb=&get_symb($request);
 3440:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3441:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3442:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3443:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3444: 
 3445:     my $result= &Apache::loncommon::start_data_table().
 3446: 	&Apache::loncommon::start_data_table_header_row().
 3447: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3448: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3449:     my %scoreptr = (
 3450: 		    'correct'  =>'correct_by_override',
 3451: 		    'incorrect'=>'incorrect_by_override',
 3452: 		    'excused'  =>'excused',
 3453: 		    'ungraded' =>'ungraded_attempted',
 3454: 		    'nothing'  => '',
 3455: 		    );
 3456:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3457: 
 3458:     my (@partid);
 3459:     my %weight = ();
 3460:     my %columns = ();
 3461:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3462: 
 3463:     my (@parts) = sort(&getpartlist($symb));
 3464:     my $header;
 3465:     while ($ctr < $env{'form.totalparts'}) {
 3466: 	my $partid = $env{'form.partid_'.$ctr};
 3467: 	push(@partid,$partid);
 3468: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3469: 	$ctr++;
 3470:     }
 3471:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3472:     foreach my $partid (@partid) {
 3473: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3474: 	    '<th align="center">'.&mt('New Score').'</th>';
 3475: 	$columns{$partid}=2;
 3476: 	foreach my $stores (@parts) {
 3477: 	    my ($part,$type) = &split_part_type($stores);
 3478: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3479: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3480: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3481: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3482:             my $narrowtext = &mt('Tries');
 3483: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3484: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3485: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3486: 	    $columns{$partid}+=2;
 3487: 	}
 3488:     }
 3489:     foreach my $partid (@partid) {
 3490: 	my $display_part=&get_display_part($partid,$symb);
 3491: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3492: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3493: 	    '</th>';
 3494: 
 3495:     }
 3496:     $result .= &Apache::loncommon::end_data_table_header_row().
 3497: 	&Apache::loncommon::start_data_table_header_row().
 3498: 	$header.
 3499: 	&Apache::loncommon::end_data_table_header_row();
 3500:     my @noupdate;
 3501:     my ($updateCtr,$noupdateCtr) = (1,1);
 3502:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3503: 	my $line;
 3504: 	my $user = $env{'form.ctr'.$i};
 3505: 	my ($uname,$udom)=split(/:/,$user);
 3506: 	my %newrecord;
 3507: 	my $updateflag = 0;
 3508: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3509: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3510: 	if (!&canmodify($usec)) {
 3511: 	    my $numcols=scalar(@partid)*4+2;
 3512: 	    push(@noupdate,
 3513: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3514: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3515: 	    next;
 3516: 	}
 3517:         my %aggregate = ();
 3518:         my $aggregateflag = 0;
 3519: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3520: 	foreach (@partid) {
 3521: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3522: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3523: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3524: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3525: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3526: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3527: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3528: 	    my $score;
 3529: 	    if ($partial eq '') {
 3530: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3531: 	    } elsif ($partial > 0) {
 3532: 		$score = 'correct_by_override';
 3533: 	    } elsif ($partial == 0) {
 3534: 		$score = 'incorrect_by_override';
 3535: 	    }
 3536: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3537: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3538: 
 3539: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3540: 		"$env{'user.name'}:$env{'user.domain'}";
 3541: 	    if ($dropMenu eq 'reset status' &&
 3542: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3543: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3544: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3545: 		$newrecord{'resource.'.$_.'.award'} = '';
 3546: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3547: 		$updateflag = 1;
 3548:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3549:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3550:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3551:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3552:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3553:                     $aggregateflag = 1;
 3554:                 }
 3555: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3556: 		$updateflag = 1;
 3557: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3558: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3559: 		$rec_update++;
 3560: 	    }
 3561: 
 3562: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3563: 		'<td align="center">'.$awarded.
 3564: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3565: 
 3566: 
 3567: 	    my $partid=$_;
 3568: 	    foreach my $stores (@parts) {
 3569: 		my ($part,$type) = &split_part_type($stores);
 3570: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3571: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3572: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3573: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3574: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3575: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3576: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3577: 		    $updateflag=1;
 3578: 		}
 3579: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3580: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3581: 	    }
 3582: 	}
 3583: 	$line.="\n";
 3584: 
 3585: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3586: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3587: 
 3588: 	if ($updateflag) {
 3589: 	    $count++;
 3590: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3591: 				    $udom,$uname);
 3592: 
 3593: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3594: 					      $cnum,$udom,$uname)) {
 3595: 		# need to figure out if should be in queue.
 3596: 		my %record =  
 3597: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3598: 					     $udom,$uname);
 3599: 		my $all_graded = 1;
 3600: 		my $none_graded = 1;
 3601: 		foreach my $part (@parts) {
 3602: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3603: 			$all_graded = 0;
 3604: 		    } else {
 3605: 			$none_graded = 0;
 3606: 		    }
 3607: 		}
 3608: 
 3609: 		if ($all_graded || $none_graded) {
 3610: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3611: 							   $symb,$cdom,$cnum,
 3612: 							   $udom,$uname);
 3613: 		}
 3614: 	    }
 3615: 
 3616: 	    $result.=&Apache::loncommon::start_data_table_row().
 3617: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3618: 		&Apache::loncommon::end_data_table_row();
 3619: 	    $updateCtr++;
 3620: 	} else {
 3621: 	    push(@noupdate,
 3622: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3623: 	    $noupdateCtr++;
 3624: 	}
 3625:         if ($aggregateflag) {
 3626:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3627: 				  $cdom,$cnum);
 3628:         }
 3629:     }
 3630:     if (@noupdate) {
 3631: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3632: 	my $numcols=scalar(@partid)*4+2;
 3633: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3634: 	    '<td align="center" colspan="'.$numcols.'">'.
 3635: 	    &mt('No Changes Occurred For the Students Below').
 3636: 	    '</td>'.
 3637: 	    &Apache::loncommon::end_data_table_row();
 3638: 	foreach my $line (@noupdate) {
 3639: 	    $result.=
 3640: 		&Apache::loncommon::start_data_table_row().
 3641: 		$line.
 3642: 		&Apache::loncommon::end_data_table_row();
 3643: 	}
 3644:     }
 3645:     $result .= &Apache::loncommon::end_data_table().
 3646: 	&show_grading_menu_form($symb);
 3647:     my $msg = '<p><b>'.
 3648: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3649: 	    $rec_update,$count).'</b><br />'.
 3650: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3651: 	'</b></p>';
 3652:     return $title.$msg.$result;
 3653: }
 3654: 
 3655: sub split_part_type {
 3656:     my ($partstr) = @_;
 3657:     my ($temp,@allparts)=split(/_/,$partstr);
 3658:     my $type=pop(@allparts);
 3659:     my $part=join('_',@allparts);
 3660:     return ($part,$type);
 3661: }
 3662: 
 3663: #------------- end of section for handling grading by section/class ---------
 3664: #
 3665: #----------------------------------------------------------------------------
 3666: 
 3667: 
 3668: #----------------------------------------------------------------------------
 3669: #
 3670: #-------------------------- Next few routines handles grading by csv upload
 3671: #
 3672: #--- Javascript to handle csv upload
 3673: sub csvupload_javascript_reverse_associate {
 3674:     my $error1=&mt('You need to specify the username or ID');
 3675:     my $error2=&mt('You need to specify at least one grading field');
 3676:   return(<<ENDPICK);
 3677:   function verify(vf) {
 3678:     var foundsomething=0;
 3679:     var founduname=0;
 3680:     var foundID=0;
 3681:     for (i=0;i<=vf.nfields.value;i++) {
 3682:       tw=eval('vf.f'+i+'.selectedIndex');
 3683:       if (i==0 && tw!=0) { foundID=1; }
 3684:       if (i==1 && tw!=0) { founduname=1; }
 3685:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3686:     }
 3687:     if (founduname==0 && foundID==0) {
 3688: 	alert('$error1');
 3689: 	return;
 3690:     }
 3691:     if (foundsomething==0) {
 3692: 	alert('$error2');
 3693: 	return;
 3694:     }
 3695:     vf.submit();
 3696:   }
 3697:   function flip(vf,tf) {
 3698:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3699:     var i;
 3700:     for (i=0;i<=vf.nfields.value;i++) {
 3701:       //can not pick the same destination field for both name and domain
 3702:       if (((i ==0)||(i ==1)) && 
 3703:           ((tf==0)||(tf==1)) && 
 3704:           (i!=tf) &&
 3705:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3706:         eval('vf.f'+i+'.selectedIndex=0;')
 3707:       }
 3708:     }
 3709:   }
 3710: ENDPICK
 3711: }
 3712: 
 3713: sub csvupload_javascript_forward_associate {
 3714:     my $error1=&mt('You need to specify the username or ID');
 3715:     my $error2=&mt('You need to specify at least one grading field');
 3716:   return(<<ENDPICK);
 3717:   function verify(vf) {
 3718:     var foundsomething=0;
 3719:     var founduname=0;
 3720:     var foundID=0;
 3721:     for (i=0;i<=vf.nfields.value;i++) {
 3722:       tw=eval('vf.f'+i+'.selectedIndex');
 3723:       if (tw==1) { foundID=1; }
 3724:       if (tw==2) { founduname=1; }
 3725:       if (tw>3) { foundsomething=1; }
 3726:     }
 3727:     if (founduname==0 && foundID==0) {
 3728: 	alert('$error1');
 3729: 	return;
 3730:     }
 3731:     if (foundsomething==0) {
 3732: 	alert('$error2');
 3733: 	return;
 3734:     }
 3735:     vf.submit();
 3736:   }
 3737:   function flip(vf,tf) {
 3738:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3739:     var i;
 3740:     //can not pick the same destination field twice
 3741:     for (i=0;i<=vf.nfields.value;i++) {
 3742:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3743:         eval('vf.f'+i+'.selectedIndex=0;')
 3744:       }
 3745:     }
 3746:   }
 3747: ENDPICK
 3748: }
 3749: 
 3750: sub csvuploadmap_header {
 3751:     my ($request,$symb,$datatoken,$distotal)= @_;
 3752:     my $javascript;
 3753:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3754: 	$javascript=&csvupload_javascript_reverse_associate();
 3755:     } else {
 3756: 	$javascript=&csvupload_javascript_forward_associate();
 3757:     }
 3758: 
 3759:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3760:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3761:     my $ignore=&mt('Ignore First Line');
 3762:     $symb = &Apache::lonenc::check_encrypt($symb);
 3763:     $request->print(<<ENDPICK);
 3764: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3765: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3766: $result
 3767: <hr />
 3768: <h3>Identify fields</h3>
 3769: Total number of records found in file: $distotal <hr />
 3770: Enter as many fields as you can. The system will inform you and bring you back
 3771: to this page if the data selected is insufficient to run your class.<hr />
 3772: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3773: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3774: <input type="hidden" name="associate"  value="" />
 3775: <input type="hidden" name="phase"      value="three" />
 3776: <input type="hidden" name="datatoken"  value="$datatoken" />
 3777: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3778: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3779: <input type="hidden" name="upfile_associate" 
 3780:                                        value="$env{'form.upfile_associate'}" />
 3781: <input type="hidden" name="symb"       value="$symb" />
 3782: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3783: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3784: <input type="hidden" name="command"    value="csvuploadoptions" />
 3785: <hr />
 3786: <script type="text/javascript" language="Javascript">
 3787: $javascript
 3788: </script>
 3789: ENDPICK
 3790:     return '';
 3791: 
 3792: }
 3793: 
 3794: sub csvupload_fields {
 3795:     my ($symb) = @_;
 3796:     my (@parts) = &getpartlist($symb);
 3797:     my @fields=(['ID','Student/Employee ID'],
 3798: 		['username','Student Username'],
 3799: 		['domain','Student Domain']);
 3800:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3801:     foreach my $part (sort(@parts)) {
 3802: 	my @datum;
 3803: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3804: 	my $name=$part;
 3805: 	if  (!$display) { $display = $name; }
 3806: 	@datum=($name,$display);
 3807: 	if ($name=~/^stores_(.*)_awarded/) {
 3808: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3809: 	}
 3810: 	push(@fields,\@datum);
 3811:     }
 3812:     return (@fields);
 3813: }
 3814: 
 3815: sub csvuploadmap_footer {
 3816:     my ($request,$i,$keyfields) =@_;
 3817:     $request->print(<<ENDPICK);
 3818: </table>
 3819: <input type="hidden" name="nfields" value="$i" />
 3820: <input type="hidden" name="keyfields" value="$keyfields" />
 3821: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3822: </form>
 3823: ENDPICK
 3824: }
 3825: 
 3826: sub checkforfile_js {
 3827:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3828:     my $result =<<CSVFORMJS;
 3829: <script type="text/javascript" language="javascript">
 3830:     function checkUpload(formname) {
 3831: 	if (formname.upfile.value == "") {
 3832: 	    alert("$alertmsg");
 3833: 	    return false;
 3834: 	}
 3835: 	formname.submit();
 3836:     }
 3837:     </script>
 3838: CSVFORMJS
 3839:     return $result;
 3840: }
 3841: 
 3842: sub upcsvScores_form {
 3843:     my ($request) = shift;
 3844:     my ($symb)=&get_symb($request);
 3845:     if (!$symb) {return '';}
 3846:     my $result=&checkforfile_js();
 3847:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3848:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3849:     $result.=$table;
 3850:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3851:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3852:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3853: 	'</b></td></tr>'."\n";
 3854:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3855:     my $upload=&mt("Upload Scores");
 3856:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3857:     my $ignore=&mt('Ignore First Line');
 3858:     $symb = &Apache::lonenc::check_encrypt($symb);
 3859:     $result.=<<ENDUPFORM;
 3860: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3861: <input type="hidden" name="symb" value="$symb" />
 3862: <input type="hidden" name="command" value="csvuploadmap" />
 3863: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3864: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3865: $upfile_select
 3866: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3867: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3868: </form>
 3869: ENDUPFORM
 3870:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3871:                            &mt("How do I create a CSV file from a spreadsheet"))
 3872:     .'</td></tr></table>'."\n";
 3873:     $result.='</td></tr></table><br /><br />'."\n";
 3874:     $result.=&show_grading_menu_form($symb);
 3875:     return $result;
 3876: }
 3877: 
 3878: 
 3879: sub csvuploadmap {
 3880:     my ($request)= @_;
 3881:     my ($symb)=&get_symb($request);
 3882:     if (!$symb) {return '';}
 3883: 
 3884:     my $datatoken;
 3885:     if (!$env{'form.datatoken'}) {
 3886: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3887:     } else {
 3888: 	$datatoken=$env{'form.datatoken'};
 3889: 	&Apache::loncommon::load_tmp_file($request);
 3890:     }
 3891:     my @records=&Apache::loncommon::upfile_record_sep();
 3892:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3893:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3894:     my ($i,$keyfields);
 3895:     if (@records) {
 3896: 	my @fields=&csvupload_fields($symb);
 3897: 
 3898: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3899: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3900: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3901: 							  \@fields);
 3902: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3903: 	    chop($keyfields);
 3904: 	} else {
 3905: 	    unshift(@fields,['none','']);
 3906: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3907: 							    \@fields);
 3908:             foreach my $rec (@records) {
 3909:                 my %temp = &Apache::loncommon::record_sep($rec);
 3910:                 if (%temp) {
 3911:                     $keyfields=join(',',sort(keys(%temp)));
 3912:                     last;
 3913:                 }
 3914:             }
 3915: 	}
 3916:     }
 3917:     &csvuploadmap_footer($request,$i,$keyfields);
 3918:     $request->print(&show_grading_menu_form($symb));
 3919: 
 3920:     return '';
 3921: }
 3922: 
 3923: sub csvuploadoptions {
 3924:     my ($request)= @_;
 3925:     my ($symb)=&get_symb($request);
 3926:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3927:     my $ignore=&mt('Ignore First Line');
 3928:     $request->print(<<ENDPICK);
 3929: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3930: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3931: <input type="hidden" name="command"    value="csvuploadassign" />
 3932: <!--
 3933: <p>
 3934: <label>
 3935:    <input type="checkbox" name="show_full_results" />
 3936:    Show a table of all changes
 3937: </label>
 3938: </p>
 3939: -->
 3940: <p>
 3941: <label>
 3942:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3943:    Overwrite any existing score
 3944: </label>
 3945: </p>
 3946: ENDPICK
 3947:     my %fields=&get_fields();
 3948:     if (!defined($fields{'domain'})) {
 3949: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3950: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3951:     }
 3952:     foreach my $key (sort(keys(%env))) {
 3953: 	if ($key !~ /^form\.(.*)$/) { next; }
 3954: 	my $cleankey=$1;
 3955: 	if ($cleankey eq 'command') { next; }
 3956: 	$request->print('<input type="hidden" name="'.$cleankey.
 3957: 			'"  value="'.$env{$key}.'" />'."\n");
 3958:     }
 3959:     # FIXME do a check for any duplicated user ids...
 3960:     # FIXME do a check for any invalid user ids?...
 3961:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3962: <hr /></form>'."\n");
 3963:     $request->print(&show_grading_menu_form($symb));
 3964:     return '';
 3965: }
 3966: 
 3967: sub get_fields {
 3968:     my %fields;
 3969:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3970:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3971: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3972: 	    if ($env{'form.f'.$i} ne 'none') {
 3973: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3974: 	    }
 3975: 	} else {
 3976: 	    if ($env{'form.f'.$i} ne 'none') {
 3977: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3978: 	    }
 3979: 	}
 3980:     }
 3981:     return %fields;
 3982: }
 3983: 
 3984: sub csvuploadassign {
 3985:     my ($request)= @_;
 3986:     my ($symb)=&get_symb($request);
 3987:     if (!$symb) {return '';}
 3988:     my $error_msg = '';
 3989:     &Apache::loncommon::load_tmp_file($request);
 3990:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3991:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3992:     my %fields=&get_fields();
 3993:     $request->print('<h3>Assigning Grades</h3>');
 3994:     my $courseid=$env{'request.course.id'};
 3995:     my ($classlist) = &getclasslist('all',0);
 3996:     my @notallowed;
 3997:     my @skipped;
 3998:     my $countdone=0;
 3999:     foreach my $grade (@gradedata) {
 4000: 	my %entries=&Apache::loncommon::record_sep($grade);
 4001: 	my $domain;
 4002: 	if ($entries{$fields{'domain'}}) {
 4003: 	    $domain=$entries{$fields{'domain'}};
 4004: 	} else {
 4005: 	    $domain=$env{'form.default_domain'};
 4006: 	}
 4007: 	$domain=~s/\s//g;
 4008: 	my $username=$entries{$fields{'username'}};
 4009: 	$username=~s/\s//g;
 4010: 	if (!$username) {
 4011: 	    my $id=$entries{$fields{'ID'}};
 4012: 	    $id=~s/\s//g;
 4013: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4014: 	    $username=$ids{$id};
 4015: 	}
 4016: 	if (!exists($$classlist{"$username:$domain"})) {
 4017: 	    my $id=$entries{$fields{'ID'}};
 4018: 	    $id=~s/\s//g;
 4019: 	    if ($id) {
 4020: 		push(@skipped,"$id:$domain");
 4021: 	    } else {
 4022: 		push(@skipped,"$username:$domain");
 4023: 	    }
 4024: 	    next;
 4025: 	}
 4026: 	my $usec=$classlist->{"$username:$domain"}[5];
 4027: 	if (!&canmodify($usec)) {
 4028: 	    push(@notallowed,"$username:$domain");
 4029: 	    next;
 4030: 	}
 4031: 	my %points;
 4032: 	my %grades;
 4033: 	foreach my $dest (keys(%fields)) {
 4034: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4035: 		$dest eq 'domain') { next; }
 4036: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4037: 	    if ($dest=~/stores_(.*)_points/) {
 4038: 		my $part=$1;
 4039: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4040: 					      $symb,$domain,$username);
 4041:                 if ($wgt) {
 4042:                     $entries{$fields{$dest}}=~s/\s//g;
 4043:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4044:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4045:                                           : 'correct_by_override';
 4046:                     $grades{"resource.$part.awarded"}=$pcr;
 4047:                     $grades{"resource.$part.solved"}=$award;
 4048:                     $points{$part}=1;
 4049:                 } else {
 4050:                     $error_msg = "<br />" .
 4051:                         &mt("Some point values were assigned"
 4052:                             ." for problems with a weight "
 4053:                             ."of zero. These values were "
 4054:                             ."ignored.");
 4055:                 }
 4056: 	    } else {
 4057: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4058: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4059: 		my $store_key=$dest;
 4060: 		$store_key=~s/^stores/resource/;
 4061: 		$store_key=~s/_/\./g;
 4062: 		$grades{$store_key}=$entries{$fields{$dest}};
 4063: 	    }
 4064: 	}
 4065: 	if (! %grades) { 
 4066:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4067:         } else {
 4068: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4069: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4070: 					   $env{'request.course.id'},
 4071: 					   $domain,$username);
 4072: 	   if ($result eq 'ok') {
 4073: 	      $request->print('.');
 4074: 	   } else {
 4075: 	      $request->print("<p><span class=\"LC_error\">".
 4076:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4077:                                   "$username:$domain",$result)."</span></p>");
 4078: 	   }
 4079: 	   $request->rflush();
 4080: 	   $countdone++;
 4081:         }
 4082:     }
 4083:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4084:     if (@skipped) {
 4085: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4086: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4087:     }
 4088:     if (@notallowed) {
 4089: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4090: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4091:     }
 4092:     $request->print("<br />\n");
 4093:     $request->print(&show_grading_menu_form($symb));
 4094:     return $error_msg;
 4095: }
 4096: #------------- end of section for handling csv file upload ---------
 4097: #
 4098: #-------------------------------------------------------------------
 4099: #
 4100: #-------------- Next few routines handle grading by page/sequence
 4101: #
 4102: #--- Select a page/sequence and a student to grade
 4103: sub pickStudentPage {
 4104:     my ($request) = shift;
 4105: 
 4106:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4107:     $request->print(<<LISTJAVASCRIPT);
 4108: <script type="text/javascript" language="javascript">
 4109: 
 4110: function checkPickOne(formname) {
 4111:     if (radioSelection(formname.student) == null) {
 4112: 	alert("$alertmsg");
 4113: 	return;
 4114:     }
 4115:     ptr = pullDownSelection(formname.selectpage);
 4116:     formname.page.value = formname["page"+ptr].value;
 4117:     formname.title.value = formname["title"+ptr].value;
 4118:     formname.submit();
 4119: }
 4120: 
 4121: </script>
 4122: LISTJAVASCRIPT
 4123:     &commonJSfunctions($request);
 4124:     my ($symb) = &get_symb($request);
 4125:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4126:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4127:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4128: 
 4129:     my $result='<h3><span class="LC_info">&nbsp;'.
 4130: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4131: 
 4132:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4133:     my ($titles,$symbx) = &getSymbMap();
 4134:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4135: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4136: #    my $type=($curpage =~ /\.(page|sequence)/);
 4137:     my $select = '<select name="selectpage">'."\n";
 4138:     my $ctr=0;
 4139:     foreach (@$titles) {
 4140: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4141: 	$select.='<option value="'.$ctr.'" '.
 4142: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4143: 	    '>'.$showtitle.'</option>'."\n";
 4144: 	$ctr++;
 4145:     }
 4146:     $select.= '</select>';
 4147:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4148: 
 4149:     $ctr=0;
 4150:     foreach (@$titles) {
 4151: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4152: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4153: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4154: 	$ctr++;
 4155:     }
 4156:     $result.='<input type="hidden" name="page" />'."\n".
 4157: 	'<input type="hidden" name="title" />'."\n";
 4158: 
 4159:     my $options =
 4160: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4161: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4162:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4163: 
 4164:     $options =
 4165: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4166: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4167: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4168:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4169:     
 4170:     $result.=&build_section_inputs();
 4171:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4172:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4173: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4174: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4175: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4176: 
 4177:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4178: 
 4179:     $result.='&nbsp;<input type="button" '.
 4180: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4181: 
 4182:     $request->print($result);
 4183: 
 4184:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4185: 	&Apache::loncommon::start_data_table().
 4186: 	&Apache::loncommon::start_data_table_header_row().
 4187: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4188: 	'<th>'.&nameUserString('header').'</th>'.
 4189: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4190: 	'<th>'.&nameUserString('header').'</th>'.
 4191: 	&Apache::loncommon::end_data_table_header_row();
 4192:  
 4193:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4194:     my $ptr = 1;
 4195:     foreach my $student (sort 
 4196: 			 {
 4197: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4198: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4199: 			     }
 4200: 			     return $a cmp $b;
 4201: 			 } (keys(%$fullname))) {
 4202: 	my ($uname,$udom) = split(/:/,$student);
 4203: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4204:                                   : '</td>');
 4205: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4206: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4207: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4208: 	$studentTable.=
 4209: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4210:                          : '');
 4211: 	$ptr++;
 4212:     }
 4213:     if ($ptr%2 == 0) {
 4214: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4215: 	    &Apache::loncommon::end_data_table_row();
 4216:     }
 4217:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4218:     $studentTable.='<input type="button" '.
 4219: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4220: 
 4221:     $studentTable.=&show_grading_menu_form($symb);
 4222:     $request->print($studentTable);
 4223: 
 4224:     return '';
 4225: }
 4226: 
 4227: sub getSymbMap {
 4228:     my $navmap = Apache::lonnavmaps::navmap->new();
 4229: 
 4230:     my %symbx = ();
 4231:     my @titles = ();
 4232:     my $minder = 0;
 4233: 
 4234:     # Gather every sequence that has problems.
 4235:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4236: 					       1,0,1);
 4237:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4238: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4239: 	    my $title = $minder.'.'.
 4240: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4241: 	    push(@titles, $title); # minder in case two titles are identical
 4242: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4243: 	    $minder++;
 4244: 	}
 4245:     }
 4246:     return \@titles,\%symbx;
 4247: }
 4248: 
 4249: #
 4250: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4251: sub displayPage {
 4252:     my ($request) = shift;
 4253: 
 4254:     my ($symb) = &get_symb($request);
 4255:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4256:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4257:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4258:     my $pageTitle = $env{'form.page'};
 4259:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4260:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4261:     my $usec=$classlist->{$env{'form.student'}}[5];
 4262: 
 4263:     #need to make sure we have the correct data for later EXT calls, 
 4264:     #thus invalidate the cache
 4265:     &Apache::lonnet::devalidatecourseresdata(
 4266:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4267:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4268:     &Apache::lonnet::clear_EXT_cache_status();
 4269: 
 4270:     if (!&canview($usec)) {
 4271: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4272: 	$request->print(&show_grading_menu_form($symb));
 4273: 	return;
 4274:     }
 4275:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4276:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4277: 	'</h3>'."\n";
 4278:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4279:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4280: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4281:     } else {
 4282: 	delete($env{'form.CODE'});
 4283:     }
 4284:     &sub_page_js($request);
 4285:     $request->print($result);
 4286: 
 4287:     my $navmap = Apache::lonnavmaps::navmap->new();
 4288:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4289:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4290:     if (!$map) {
 4291: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4292: 	$request->print(&show_grading_menu_form($symb));
 4293: 	return; 
 4294:     }
 4295:     my $iterator = $navmap->getIterator($map->map_start(),
 4296: 					$map->map_finish());
 4297: 
 4298:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4299: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4300: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4301: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4302: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4303: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4304: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4305: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4306: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4307: 
 4308:     if (defined($env{'form.CODE'})) {
 4309: 	$studentTable.=
 4310: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4311:     }
 4312:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4313: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4314: 
 4315:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4316: 	&Apache::loncommon::start_data_table().
 4317: 	&Apache::loncommon::start_data_table_header_row().
 4318: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4319: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4320: 	&Apache::loncommon::end_data_table_header_row();
 4321: 
 4322:     &Apache::lonxml::clear_problem_counter();
 4323:     my ($depth,$question,$prob) = (1,1,1);
 4324:     $iterator->next(); # skip the first BEGIN_MAP
 4325:     my $curRes = $iterator->next(); # for "current resource"
 4326:     while ($depth > 0) {
 4327:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4328:         if($curRes == $iterator->END_MAP) { $depth--; }
 4329: 
 4330:         if (ref($curRes) && $curRes->is_problem()) {
 4331: 	    my $parts = $curRes->parts();
 4332:             my $title = $curRes->compTitle();
 4333: 	    my $symbx = $curRes->symb();
 4334: 	    $studentTable.=
 4335: 		&Apache::loncommon::start_data_table_row().
 4336: 		'<td align="center" valign="top" >'.$prob.
 4337: 		(scalar(@{$parts}) == 1 ? '' 
 4338: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4339: 							scalar(@{$parts}))
 4340: 		 ).
 4341: 		 '</td>';
 4342: 	    $studentTable.='<td valign="top">';
 4343: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4344: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4345: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4346: 					     undef,'both',\%form);
 4347: 	    } else {
 4348: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4349: 		$companswer =~ s|<form(.*?)>||g;
 4350: 		$companswer =~ s|</form>||g;
 4351: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4352: #		    $companswer =~ s/$1/ /ms;
 4353: #		    $request->print('match='.$1."<br />\n");
 4354: #		}
 4355: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4356: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4357: 	    }
 4358: 
 4359: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4360: 
 4361: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4362: 		if ($record{'version'} eq '') {
 4363: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4364: 		} else {
 4365: 		    my %responseType = ();
 4366: 		    foreach my $partid (@{$parts}) {
 4367: 			my @responseIds =$curRes->responseIds($partid);
 4368: 			my @responseType =$curRes->responseType($partid);
 4369: 			my %responseIds;
 4370: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4371: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4372: 			}
 4373: 			$responseType{$partid} = \%responseIds;
 4374: 		    }
 4375: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4376: 
 4377: 		}
 4378: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4379: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4380: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4381: 									$env{'request.course.id'},
 4382: 									'','.submission');
 4383:  
 4384: 	    }
 4385: 	    if (&canmodify($usec)) {
 4386: 		foreach my $partid (@{$parts}) {
 4387: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4388: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4389: 		    $question++;
 4390: 		}
 4391: 		$prob++;
 4392: 	    }
 4393: 	    $studentTable.='</td></tr>';
 4394: 
 4395: 	}
 4396:         $curRes = $iterator->next();
 4397:     }
 4398: 
 4399:     $studentTable.='</table>'."\n".
 4400: 	'<input type="button" value="'.&mt('Save').'" '.
 4401: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4402: 	'</form>'."\n";
 4403:     $studentTable.=&show_grading_menu_form($symb);
 4404:     $request->print($studentTable);
 4405: 
 4406:     return '';
 4407: }
 4408: 
 4409: sub displaySubByDates {
 4410:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4411:     my $isCODE=0;
 4412:     my $isTask = ($symb =~/\.task$/);
 4413:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4414:     my $studentTable=&Apache::loncommon::start_data_table().
 4415: 	&Apache::loncommon::start_data_table_header_row().
 4416: 	'<th>'.&mt('Date/Time').'</th>'.
 4417: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4418: 	'<th>'.&mt('Submission').'</th>'.
 4419: 	'<th>'.&mt('Status').'</th>'.
 4420: 	&Apache::loncommon::end_data_table_header_row();
 4421:     my ($version);
 4422:     my %mark;
 4423:     my %orders;
 4424:     $mark{'correct_by_student'} = $checkIcon;
 4425:     if (!exists($$record{'1:timestamp'})) {
 4426: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4427:     }
 4428: 
 4429:     my $interaction;
 4430:     my $no_increment = 1;
 4431:     for ($version=1;$version<=$$record{'version'};$version++) {
 4432: 	my $timestamp = 
 4433: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4434: 	if (exists($$record{$version.':resource.0.version'})) {
 4435: 	    $interaction = $$record{$version.':resource.0.version'};
 4436: 	}
 4437: 
 4438: 	my $where = ($isTask ? "$version:resource.$interaction"
 4439: 		             : "$version:resource");
 4440: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4441: 	    '<td>'.$timestamp.'</td>';
 4442: 	if ($isCODE) {
 4443: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4444: 	}
 4445: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4446: 	my @displaySub = ();
 4447: 	foreach my $partid (@{$parts}) {
 4448: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4449: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4450: 	    
 4451: 
 4452: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4453: 	    my $display_part=&get_display_part($partid,$symb);
 4454: 	    foreach my $matchKey (@matchKey) {
 4455: 		if (exists($$record{$version.':'.$matchKey}) &&
 4456: 		    $$record{$version.':'.$matchKey} ne '') {
 4457: 
 4458: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4459: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4460: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4461: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4462: 			$responseId.')</span>&nbsp;<b>';
 4463: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4464: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4465: 		    } else {
 4466: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4467: 					    $$record{"$where.$partid.tries"});
 4468: 		    }
 4469: 		    my $responseType=($isTask ? 'Task'
 4470:                                               : $responseType->{$partid}->{$responseId});
 4471: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4472: 		    if (!exists($orders{$partid}->{$responseId})) {
 4473: 			$orders{$partid}->{$responseId}=
 4474: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4475:                                        $no_increment);
 4476: 		    }
 4477: 		    $displaySub[0].='</b>&nbsp; '.
 4478: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4479: 		}
 4480: 	    }
 4481: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4482: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4483: 				    $$record{"$where.$partid.checkedin"},
 4484: 				    $$record{"$where.$partid.checkedin.slot"}).
 4485: 					'<br />';
 4486: 	    }
 4487: 	    if (exists $$record{"$where.$partid.award"}) {
 4488: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4489: 		    lc($$record{"$where.$partid.award"}).' '.
 4490: 		    $mark{$$record{"$where.$partid.solved"}}.
 4491: 		    '<br />';
 4492: 	    }
 4493: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4494: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4495: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4496: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4497: 		$displaySub[2].=
 4498: 		    $$record{"$version:resource.$partid.regrader"}.
 4499: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4500: 	    }
 4501: 	}
 4502: 	# needed because old essay regrader has not parts info
 4503: 	if (exists $$record{"$version:resource.regrader"}) {
 4504: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4505: 	}
 4506: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4507: 	if ($displaySub[2]) {
 4508: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4509: 	}
 4510: 	$studentTable.='&nbsp;</td>'.
 4511: 	    &Apache::loncommon::end_data_table_row();
 4512:     }
 4513:     $studentTable.=&Apache::loncommon::end_data_table();
 4514:     return $studentTable;
 4515: }
 4516: 
 4517: sub updateGradeByPage {
 4518:     my ($request) = shift;
 4519: 
 4520:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4521:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4522:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4523:     my $pageTitle = $env{'form.page'};
 4524:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4525:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4526:     my $usec=$classlist->{$env{'form.student'}}[5];
 4527:     if (!&canmodify($usec)) {
 4528: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4529: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4530: 	return;
 4531:     }
 4532:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4533:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4534: 	'</h3>'."\n";
 4535: 
 4536:     $request->print($result);
 4537: 
 4538:     my $navmap = Apache::lonnavmaps::navmap->new();
 4539:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4540:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4541:     if (!$map) {
 4542: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4543: 	my ($symb)=&get_symb($request);
 4544: 	$request->print(&show_grading_menu_form($symb));
 4545: 	return; 
 4546:     }
 4547:     my $iterator = $navmap->getIterator($map->map_start(),
 4548: 					$map->map_finish());
 4549: 
 4550:     my $studentTable=
 4551: 	&Apache::loncommon::start_data_table().
 4552: 	&Apache::loncommon::start_data_table_header_row().
 4553: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4554: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4555: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4556: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4557: 	&Apache::loncommon::end_data_table_header_row();
 4558: 
 4559:     $iterator->next(); # skip the first BEGIN_MAP
 4560:     my $curRes = $iterator->next(); # for "current resource"
 4561:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4562:     while ($depth > 0) {
 4563:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4564:         if($curRes == $iterator->END_MAP) { $depth--; }
 4565: 
 4566:         if (ref($curRes) && $curRes->is_problem()) {
 4567: 	    my $parts = $curRes->parts();
 4568:             my $title = $curRes->compTitle();
 4569: 	    my $symbx = $curRes->symb();
 4570: 	    $studentTable.=
 4571: 		&Apache::loncommon::start_data_table_row().
 4572: 		'<td align="center" valign="top" >'.$prob.
 4573: 		(scalar(@{$parts}) == 1 ? '' 
 4574:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4575: 		.')').'</td>';
 4576: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4577: 
 4578: 	    my %newrecord=();
 4579: 	    my @displayPts=();
 4580:             my %aggregate = ();
 4581:             my $aggregateflag = 0;
 4582: 	    foreach my $partid (@{$parts}) {
 4583: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4584: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4585: 
 4586: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4587: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4588: 		my $partial = $newpts/$wgt;
 4589: 		my $score;
 4590: 		if ($partial > 0) {
 4591: 		    $score = 'correct_by_override';
 4592: 		} elsif ($newpts ne '') { #empty is taken as 0
 4593: 		    $score = 'incorrect_by_override';
 4594: 		}
 4595: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4596: 		if ($dropMenu eq 'excused') {
 4597: 		    $partial = '';
 4598: 		    $score = 'excused';
 4599: 		} elsif ($dropMenu eq 'reset status'
 4600: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4601: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4602: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4603: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4604: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4605: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4606: 		    $changeflag++;
 4607: 		    $newpts = '';
 4608:                     
 4609:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4610:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4611:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4612:                     if ($aggtries > 0) {
 4613:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4614:                         $aggregateflag = 1;
 4615:                     }
 4616: 		}
 4617: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4618: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4619: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4620: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4621: 		    '&nbsp;<br />';
 4622: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4623: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4624: 		    '&nbsp;<br />';
 4625: 		$question++;
 4626: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4627: 
 4628: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4629: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4630: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4631: 		    if (scalar(keys(%newrecord)) > 0);
 4632: 
 4633: 		$changeflag++;
 4634: 	    }
 4635: 	    if (scalar(keys(%newrecord)) > 0) {
 4636: 		my %record = 
 4637: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4638: 					     $udom,$uname);
 4639: 
 4640: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4641: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4642: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4643: 		    $newrecord{'resource.CODE'} = '';
 4644: 		}
 4645: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4646: 					$udom,$uname);
 4647: 		%record = &Apache::lonnet::restore($symbx,
 4648: 						   $env{'request.course.id'},
 4649: 						   $udom,$uname);
 4650: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4651: 					     $cdom,$cnum,$udom,$uname);
 4652: 	    }
 4653: 	    
 4654:             if ($aggregateflag) {
 4655:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4656:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4657:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4658:             }
 4659: 
 4660: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4661: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4662: 		&Apache::loncommon::end_data_table_row();
 4663: 
 4664: 	    $prob++;
 4665: 	}
 4666:         $curRes = $iterator->next();
 4667:     }
 4668: 
 4669:     $studentTable.=&Apache::loncommon::end_data_table();
 4670:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4671:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4672: 		  &mt('The scores were changed for [quant,_1,problem].',
 4673: 		  $changeflag));
 4674:     $request->print($grademsg.$studentTable);
 4675: 
 4676:     return '';
 4677: }
 4678: 
 4679: #-------- end of section for handling grading by page/sequence ---------
 4680: #
 4681: #-------------------------------------------------------------------
 4682: 
 4683: #--------------------Scantron Grading-----------------------------------
 4684: #
 4685: #------ start of section for handling grading by page/sequence ---------
 4686: 
 4687: =pod
 4688: 
 4689: =head1 Bubble sheet grading routines
 4690: 
 4691:   For this documentation:
 4692: 
 4693:    'scanline' refers to the full line of characters
 4694:    from the file that we are parsing that represents one entire sheet
 4695: 
 4696:    'bubble line' refers to the data
 4697:    representing the line of bubbles that are on the physical bubble sheet
 4698: 
 4699: 
 4700: The overall process is that a scanned in bubble sheet data is uploaded
 4701: into a course. When a user wants to grade, they select a
 4702: sequence/folder of resources, a file of bubble sheet info, and pick
 4703: one of the predefined configurations for what each scanline looks
 4704: like.
 4705: 
 4706: Next each scanline is checked for any errors of either 'missing
 4707: bubbles' (it's an error because it may have been mis-scanned
 4708: because too light bubbling), 'double bubble' (each bubble line should
 4709: have no more that one letter picked), invalid or duplicated CODE,
 4710: invalid student/employee ID
 4711: 
 4712: If the CODE option is used that determines the randomization of the
 4713: homework problems, either way the student/employee ID is looked up into a
 4714: username:domain.
 4715: 
 4716: During the validation phase the instructor can choose to skip scanlines. 
 4717: 
 4718: After the validation phase, there are now 3 bubble sheet files
 4719: 
 4720:   scantron_original_filename (unmodified original file)
 4721:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4722:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4723: 
 4724: Also there is a separate hash nohist_scantrondata that contains extra
 4725: correction information that isn't representable in the bubble sheet
 4726: file (see &scantron_getfile() for more information)
 4727: 
 4728: After all scanlines are either valid, marked as valid or skipped, then
 4729: foreach line foreach problem in the picked sequence, an ssi request is
 4730: made that simulates a user submitting their selected letter(s) against
 4731: the homework problem.
 4732: 
 4733: =over 4
 4734: 
 4735: 
 4736: 
 4737: =item defaultFormData
 4738: 
 4739:   Returns html hidden inputs used to hold context/default values.
 4740: 
 4741:  Arguments:
 4742:   $symb - $symb of the current resource 
 4743: 
 4744: =cut
 4745: 
 4746: sub defaultFormData {
 4747:     my ($symb)=@_;
 4748:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4749:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4750:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4751: }
 4752: 
 4753: 
 4754: =pod 
 4755: 
 4756: =item getSequenceDropDown
 4757: 
 4758:    Return html dropdown of possible sequences to grade
 4759:  
 4760:  Arguments:
 4761:    $symb - $symb of the current resource 
 4762: 
 4763: =cut
 4764: 
 4765: sub getSequenceDropDown {
 4766:     my ($symb)=@_;
 4767:     my $result='<select name="selectpage">'."\n";
 4768:     my ($titles,$symbx) = &getSymbMap();
 4769:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4770:     my $ctr=0;
 4771:     foreach (@$titles) {
 4772: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4773: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4774: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4775: 	    '>'.$showtitle.'</option>'."\n";
 4776: 	$ctr++;
 4777:     }
 4778:     $result.= '</select>';
 4779:     return $result;
 4780: }
 4781: 
 4782: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4783:                                    # key is zero-based index - 0, 1, 2 ...
 4784: 
 4785: my %first_bubble_line;             # First bubble line no. for each bubble.
 4786: 
 4787: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4788:                                    # matchresponse or rankresponse, where 
 4789:                                    # an individual response can have multiple 
 4790:                                    # lines
 4791: 
 4792: my %responsetype_per_response;     # responsetype for each response
 4793: 
 4794: # Save and restore the bubble lines array to the form env.
 4795: 
 4796: 
 4797: sub save_bubble_lines {
 4798:     foreach my $line (keys(%bubble_lines_per_response)) {
 4799: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4800: 	$env{"form.scantron.first_bubble_line.$line"} =
 4801: 	    $first_bubble_line{$line};
 4802:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4803:             $subdivided_bubble_lines{$line};
 4804:         $env{"form.scantron.responsetype.$line"} =
 4805:             $responsetype_per_response{$line};
 4806:     }
 4807: }
 4808: 
 4809: 
 4810: sub restore_bubble_lines {
 4811:     my $line = 0;
 4812:     %bubble_lines_per_response = ();
 4813:     while ($env{"form.scantron.bubblelines.$line"}) {
 4814: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4815: 	$bubble_lines_per_response{$line} = $value;
 4816: 	$first_bubble_line{$line}  =
 4817: 	    $env{"form.scantron.first_bubble_line.$line"};
 4818:         $subdivided_bubble_lines{$line} =
 4819:             $env{"form.scantron.sub_bubblelines.$line"};
 4820:         $responsetype_per_response{$line} =
 4821:             $env{"form.scantron.responsetype.$line"};
 4822: 	$line++;
 4823:     }
 4824: }
 4825: 
 4826: #  Given the parsed scanline, get the response for 
 4827: #  'answer' number n:
 4828: 
 4829: sub get_response_bubbles {
 4830:     my ($parsed_line, $response)  = @_;
 4831: 
 4832:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4833:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4834:     
 4835:     my $selected = "";
 4836: 
 4837:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4838: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4839: 	$bubble_line++;
 4840:     }
 4841:     return $selected;
 4842: }
 4843: 
 4844: =pod 
 4845: 
 4846: =item scantron_filenames
 4847: 
 4848:    Returns a list of the scantron files in the current course 
 4849: 
 4850: =cut
 4851: 
 4852: sub scantron_filenames {
 4853:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4854:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4855:     my $getpropath = 1;
 4856:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4857:                                        $getpropath);
 4858:     my @possiblenames;
 4859:     foreach my $filename (sort(@files)) {
 4860: 	($filename)=split(/&/,$filename);
 4861: 	if ($filename!~/^scantron_orig_/) { next ; }
 4862: 	$filename=~s/^scantron_orig_//;
 4863: 	push(@possiblenames,$filename);
 4864:     }
 4865:     return @possiblenames;
 4866: }
 4867: 
 4868: =pod 
 4869: 
 4870: =item scantron_uploads
 4871: 
 4872:    Returns  html drop-down list of scantron files in current course.
 4873: 
 4874:  Arguments:
 4875:    $file2grade - filename to set as selected in the dropdown
 4876: 
 4877: =cut
 4878: 
 4879: sub scantron_uploads {
 4880:     my ($file2grade) = @_;
 4881:     my $result=	'<select name="scantron_selectfile">';
 4882:     $result.="<option></option>";
 4883:     foreach my $filename (sort(&scantron_filenames())) {
 4884: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4885:     }
 4886:     $result.="</select>";
 4887:     return $result;
 4888: }
 4889: 
 4890: =pod 
 4891: 
 4892: =item scantron_scantab
 4893: 
 4894:   Returns html drop down of the scantron formats in the scantronformat.tab
 4895:   file.
 4896: 
 4897: =cut
 4898: 
 4899: sub scantron_scantab {
 4900:     my $result='<select name="scantron_format">'."\n";
 4901:     $result.='<option></option>'."\n";
 4902:     my @lines = &get_scantronformat_file();
 4903:     if (@lines > 0) {
 4904:         foreach my $line (@lines) {
 4905:             next if (($line =~ /^\#/) || ($line eq ''));
 4906: 	    my ($name,$descrip)=split(/:/,$line);
 4907: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4908:         }
 4909:     }
 4910:     $result.='</select>'."\n";
 4911:     return $result;
 4912: }
 4913: 
 4914: =pod
 4915: 
 4916: =item get_scantronformat_file
 4917: 
 4918:   Returns an array containing lines from the scantron format file for
 4919:   the domain of the course.
 4920: 
 4921:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4922:   lines are from this file.
 4923: 
 4924:   Otherwise, if a default.tab has been published in RES space by the 
 4925:   domainconfig user, lines are from this file.
 4926: 
 4927:   Otherwise, fall back to getting lines from the legacy file on the
 4928:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4929: 
 4930: =cut
 4931: 
 4932: sub get_scantronformat_file {
 4933:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4934:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4935:     my $gottab = 0;
 4936:     my @lines;
 4937:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4938:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4939:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4940:             if ($formatfile ne '-1') {
 4941:                 @lines = split("\n",$formatfile,-1);
 4942:                 $gottab = 1;
 4943:             }
 4944:         }
 4945:     }
 4946:     if (!$gottab) {
 4947:         my $confname = $cdom.'-domainconfig';
 4948:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4949:         my $formatfile =  &Apache::lonnet::getfile($default);
 4950:         if ($formatfile ne '-1') {
 4951:             @lines = split("\n",$formatfile,-1);
 4952:             $gottab = 1;
 4953:         }
 4954:     }
 4955:     if (!$gottab) {
 4956:         my @domains = &Apache::lonnet::current_machine_domains();
 4957:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4958:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4959:             @lines = <$fh>;
 4960:             close($fh);
 4961:         } else {
 4962:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4963:             @lines = <$fh>;
 4964:             close($fh);
 4965:         }
 4966:     }
 4967:     return @lines;
 4968: }
 4969: 
 4970: =pod 
 4971: 
 4972: =item scantron_CODElist
 4973: 
 4974:   Returns html drop down of the saved CODE lists from current course,
 4975:   generated from earlier printings.
 4976: 
 4977: =cut
 4978: 
 4979: sub scantron_CODElist {
 4980:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4981:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4982:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4983:     my $namechoice='<option></option>';
 4984:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4985: 	if ($name =~ /^error: 2 /) { next; }
 4986: 	if ($name =~ /^type\0/) { next; }
 4987: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4988:     }
 4989:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4990:     return $namechoice;
 4991: }
 4992: 
 4993: =pod 
 4994: 
 4995: =item scantron_CODEunique
 4996: 
 4997:   Returns the html for "Each CODE to be used once" radio.
 4998: 
 4999: =cut
 5000: 
 5001: sub scantron_CODEunique {
 5002:     my $result='<span class="LC_nobreak">
 5003:                  <label><input type="radio" name="scantron_CODEunique"
 5004:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5005:                 </span>
 5006:                 <span class="LC_nobreak">
 5007:                  <label><input type="radio" name="scantron_CODEunique"
 5008:                         value="no" />'.&mt('No').' </label>
 5009:                 </span>';
 5010:     return $result;
 5011: }
 5012: 
 5013: =pod 
 5014: 
 5015: =item scantron_selectphase
 5016: 
 5017:   Generates the initial screen to start the bubble sheet process.
 5018:   Allows for - starting a grading run.
 5019:              - downloading existing scan data (original, corrected
 5020:                                                 or skipped info)
 5021: 
 5022:              - uploading new scan data
 5023: 
 5024:  Arguments:
 5025:   $r          - The Apache request object
 5026:   $file2grade - name of the file that contain the scanned data to score
 5027: 
 5028: =cut
 5029: 
 5030: sub scantron_selectphase {
 5031:     my ($r,$file2grade) = @_;
 5032:     my ($symb)=&get_symb($r);
 5033:     if (!$symb) {return '';}
 5034:     my $sequence_selector=&getSequenceDropDown($symb);
 5035:     my $default_form_data=&defaultFormData($symb);
 5036:     my $grading_menu_button=&show_grading_menu_form($symb);
 5037:     my $file_selector=&scantron_uploads($file2grade);
 5038:     my $format_selector=&scantron_scantab();
 5039:     my $CODE_selector=&scantron_CODElist();
 5040:     my $CODE_unique=&scantron_CODEunique();
 5041:     my $result;
 5042: 
 5043:     $ssi_error = 0;
 5044: 
 5045:     # Chunk of form to prompt for a file to grade and how:
 5046: 
 5047:     $result.= '
 5048:     <br />
 5049:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5050:     <input type="hidden" name="command" value="scantron_warning" />
 5051:     '.$default_form_data.'
 5052:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5053:        '.&Apache::loncommon::start_data_table_header_row().'
 5054:             <th colspan="2">
 5055:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5056:             </th>
 5057:        '.&Apache::loncommon::end_data_table_header_row().'
 5058:        '.&Apache::loncommon::start_data_table_row().'
 5059:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5060:        '.&Apache::loncommon::end_data_table_row().'
 5061:        '.&Apache::loncommon::start_data_table_row().'
 5062:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5063:        '.&Apache::loncommon::end_data_table_row().'
 5064:        '.&Apache::loncommon::start_data_table_row().'
 5065:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5066:        '.&Apache::loncommon::end_data_table_row().'
 5067:        '.&Apache::loncommon::start_data_table_row().'
 5068:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5069:        '.&Apache::loncommon::end_data_table_row().'
 5070:        '.&Apache::loncommon::start_data_table_row().'
 5071:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5072:        '.&Apache::loncommon::end_data_table_row().'
 5073:        '.&Apache::loncommon::start_data_table_row().'
 5074: 	    <td> '.&mt('Options:').' </td>
 5075:             <td>
 5076: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5077:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5078:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5079: 	    </td>
 5080:        '.&Apache::loncommon::end_data_table_row().'
 5081:        '.&Apache::loncommon::start_data_table_row().'
 5082:             <td colspan="2">
 5083:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5084:             </td>
 5085:        '.&Apache::loncommon::end_data_table_row().'
 5086:     '.&Apache::loncommon::end_data_table().'
 5087:     </form>
 5088: ';
 5089:    
 5090:     $r->print($result);
 5091: 
 5092:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5093:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5094: 
 5095: 	# Chunk of form to prompt for a scantron file upload.
 5096: 
 5097:         $r->print('
 5098:     <br />
 5099:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5100:        '.&Apache::loncommon::start_data_table_header_row().'
 5101:             <th>
 5102:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5103:             </th>
 5104:        '.&Apache::loncommon::end_data_table_header_row().'
 5105:        '.&Apache::loncommon::start_data_table_row().'
 5106:             <td>
 5107: ');
 5108:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5109:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5110:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5111:     $r->print('
 5112:               <script type="text/javascript" language="javascript">
 5113:     function checkUpload(formname) {
 5114: 	if (formname.upfile.value == "") {
 5115: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5116: 	    return false;
 5117: 	}
 5118: 	formname.submit();
 5119:     }
 5120:               </script>
 5121: 
 5122:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5123:                 '.$default_form_data.'
 5124:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5125:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5126:                 <input name="command" value="scantronupload_save" type="hidden" />
 5127:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5128:                 <br />
 5129:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5130:               </form>
 5131: ');
 5132: 
 5133:         $r->print('
 5134:             </td>
 5135:        '.&Apache::loncommon::end_data_table_row().'
 5136:        '.&Apache::loncommon::end_data_table().'
 5137: ');
 5138:     }
 5139: 
 5140:     # Chunk of the form that prompts to view a scoring office file,
 5141:     # corrected file, skipped records in a file.
 5142: 
 5143:     $r->print('
 5144:    <br />
 5145:    <form action="/adm/grades" name="scantron_download">
 5146:      '.$default_form_data.'
 5147:      <input type="hidden" name="command" value="scantron_download" />
 5148:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5149:        '.&Apache::loncommon::start_data_table_header_row().'
 5150:               <th>
 5151:                 &nbsp;'.&mt('Download a scoring office file').'
 5152:               </th>
 5153:        '.&Apache::loncommon::end_data_table_header_row().'
 5154:        '.&Apache::loncommon::start_data_table_row().'
 5155:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5156:                 <br />
 5157:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5158:        '.&Apache::loncommon::end_data_table_row().'
 5159:      '.&Apache::loncommon::end_data_table().'
 5160:    </form>
 5161:    <br />
 5162: ');
 5163: 
 5164:     &Apache::lonpickcode::code_list($r,2);
 5165: 
 5166:     $r->print('<br /><form method="post" name="checkscantron">'.
 5167:              $default_form_data."\n".
 5168:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5169:              &Apache::loncommon::start_data_table_header_row()."\n".
 5170:              '<th colspan="2">
 5171:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5172:              '</th>'."\n".
 5173:               &Apache::loncommon::end_data_table_header_row()."\n".
 5174:               &Apache::loncommon::start_data_table_row()."\n".
 5175:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5176:               '<td> '.$sequence_selector.' </td>'.
 5177:               &Apache::loncommon::end_data_table_row()."\n".
 5178:               &Apache::loncommon::start_data_table_row()."\n".
 5179:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5180:               '<td> '.$file_selector.' </td>'."\n".
 5181:               &Apache::loncommon::end_data_table_row()."\n".
 5182:               &Apache::loncommon::start_data_table_row()."\n".
 5183:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5184:               '<td> '.$format_selector.' </td>'."\n".
 5185:               &Apache::loncommon::end_data_table_row()."\n".
 5186:               &Apache::loncommon::start_data_table_row()."\n".
 5187:               '<td> '.&mt('Options').' </td>'."\n".
 5188:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5189:               &Apache::loncommon::end_data_table_row()."\n".
 5190:               &Apache::loncommon::start_data_table_row()."\n".
 5191:               '<td colspan="2">'."\n".
 5192:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5193:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5194:               '</td>'."\n".
 5195:               &Apache::loncommon::end_data_table_row()."\n".
 5196:               &Apache::loncommon::end_data_table()."\n".
 5197:               '</form><br />');
 5198:     $r->print($grading_menu_button);
 5199:     return;
 5200: }
 5201: 
 5202: =pod
 5203: 
 5204: =item get_scantron_config
 5205: 
 5206:    Parse and return the scantron configuration line selected as a
 5207:    hash of configuration file fields.
 5208: 
 5209:  Arguments:
 5210:     which - the name of the configuration to parse from the file.
 5211: 
 5212: 
 5213:  Returns:
 5214:             If the named configuration is not in the file, an empty
 5215:             hash is returned.
 5216:     a hash with the fields
 5217:       name         - internal name for the this configuration setup
 5218:       description  - text to display to operator that describes this config
 5219:       CODElocation - if 0 or the string 'none'
 5220:                           - no CODE exists for this config
 5221:                      if -1 || the string 'letter'
 5222:                           - a CODE exists for this config and is
 5223:                             a string of letters
 5224:                      Unsupported value (but planned for future support)
 5225:                           if a positive integer
 5226:                                - The CODE exists as the first n items from
 5227:                                  the question section of the form
 5228:                           if the string 'number'
 5229:                                - The CODE exists for this config and is
 5230:                                  a string of numbers
 5231:       CODEstart   - (only matter if a CODE exists) column in the line where
 5232:                      the CODE starts
 5233:       CODElength  - length of the CODE
 5234:       IDstart     - column where the student/employee ID number starts
 5235:       IDlength    - length of the student/employee ID info
 5236:       Qstart      - column where the information from the bubbled
 5237:                     'questions' start
 5238:       Qlength     - number of columns comprising a single bubble line from
 5239:                     the sheet. (usually either 1 or 10)
 5240:       Qon         - either a single character representing the character used
 5241:                     to signal a bubble was chosen in the positional setup, or
 5242:                     the string 'letter' if the letter of the chosen bubble is
 5243:                     in the final, or 'number' if a number representing the
 5244:                     chosen bubble is in the file (1->A 0->J)
 5245:       Qoff        - the character used to represent that a bubble was
 5246:                     left blank
 5247:       PaperID     - if the scanning process generates a unique number for each
 5248:                     sheet scanned the column that this ID number starts in
 5249:       PaperIDlength - number of columns that comprise the unique ID number
 5250:                       for the sheet of paper
 5251:       FirstName   - column that the first name starts in
 5252:       FirstNameLength - number of columns that the first name spans
 5253:  
 5254:       LastName    - column that the last name starts in
 5255:       LastNameLength - number of columns that the last name spans
 5256: 
 5257: =cut
 5258: 
 5259: sub get_scantron_config {
 5260:     my ($which) = @_;
 5261:     my @lines = &get_scantronformat_file();
 5262:     my %config;
 5263:     #FIXME probably should move to XML it has already gotten a bit much now
 5264:     foreach my $line (@lines) {
 5265: 	my ($name,$descrip)=split(/:/,$line);
 5266: 	if ($name ne $which ) { next; }
 5267: 	chomp($line);
 5268: 	my @config=split(/:/,$line);
 5269: 	$config{'name'}=$config[0];
 5270: 	$config{'description'}=$config[1];
 5271: 	$config{'CODElocation'}=$config[2];
 5272: 	$config{'CODEstart'}=$config[3];
 5273: 	$config{'CODElength'}=$config[4];
 5274: 	$config{'IDstart'}=$config[5];
 5275: 	$config{'IDlength'}=$config[6];
 5276: 	$config{'Qstart'}=$config[7];
 5277:  	$config{'Qlength'}=$config[8];
 5278: 	$config{'Qoff'}=$config[9];
 5279: 	$config{'Qon'}=$config[10];
 5280: 	$config{'PaperID'}=$config[11];
 5281: 	$config{'PaperIDlength'}=$config[12];
 5282: 	$config{'FirstName'}=$config[13];
 5283: 	$config{'FirstNamelength'}=$config[14];
 5284: 	$config{'LastName'}=$config[15];
 5285: 	$config{'LastNamelength'}=$config[16];
 5286: 	last;
 5287:     }
 5288:     return %config;
 5289: }
 5290: 
 5291: =pod 
 5292: 
 5293: =item username_to_idmap
 5294: 
 5295:     creates a hash keyed by student/employee ID with values of the corresponding
 5296:     student username:domain.
 5297: 
 5298:   Arguments:
 5299: 
 5300:     $classlist - reference to the class list hash. This is a hash
 5301:                  keyed by student name:domain  whose elements are references
 5302:                  to arrays containing various chunks of information
 5303:                  about the student. (See loncoursedata for more info).
 5304: 
 5305:   Returns
 5306:     %idmap - the constructed hash
 5307: 
 5308: =cut
 5309: 
 5310: sub username_to_idmap {
 5311:     my ($classlist)= @_;
 5312:     my %idmap;
 5313:     foreach my $student (keys(%$classlist)) {
 5314: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5315: 	    $student;
 5316:     }
 5317:     return %idmap;
 5318: }
 5319: 
 5320: =pod
 5321: 
 5322: =item scantron_fixup_scanline
 5323: 
 5324:    Process a requested correction to a scanline.
 5325: 
 5326:   Arguments:
 5327:     $scantron_config   - hash from &get_scantron_config()
 5328:     $scan_data         - hash of correction information 
 5329:                           (see &scantron_getfile())
 5330:     $line              - existing scanline
 5331:     $whichline         - line number of the passed in scanline
 5332:     $field             - type of change to process 
 5333:                          (either 
 5334:                           'ID'     -> correct the student/employee ID number
 5335:                           'CODE'   -> correct the CODE
 5336:                           'answer' -> fixup the submitted answers)
 5337:     
 5338:    $args               - hash of additional info,
 5339:                           - 'ID' 
 5340:                                'newid' -> studentID to use in replacement
 5341:                                           of existing one
 5342:                           - 'CODE' 
 5343:                                'CODE_ignore_dup' - set to true if duplicates
 5344:                                                    should be ignored.
 5345: 	                       'CODE' - is new code or 'use_unfound'
 5346:                                         if the existing unfound code should
 5347:                                         be used as is
 5348:                           - 'answer'
 5349:                                'response' - new answer or 'none' if blank
 5350:                                'question' - the bubble line to change
 5351:                                'questionnum' - the question identifier,
 5352:                                                may include subquestion. 
 5353: 
 5354:   Returns:
 5355:     $line - the modified scanline
 5356: 
 5357:   Side effects: 
 5358:     $scan_data - may be updated
 5359: 
 5360: =cut
 5361: 
 5362: 
 5363: sub scantron_fixup_scanline {
 5364:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5365:     if ($field eq 'ID') {
 5366: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5367: 	    return ($line,1,'New value too large');
 5368: 	}
 5369: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5370: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5371: 				     $args->{'newid'});
 5372: 	}
 5373: 	substr($line,$$scantron_config{'IDstart'}-1,
 5374: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5375: 	if ($args->{'newid'}=~/^\s*$/) {
 5376: 	    &scan_data($scan_data,"$whichline.user",
 5377: 		       $args->{'username'}.':'.$args->{'domain'});
 5378: 	}
 5379:     } elsif ($field eq 'CODE') {
 5380: 	if ($args->{'CODE_ignore_dup'}) {
 5381: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5382: 	}
 5383: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5384: 	if ($args->{'CODE'} ne 'use_unfound') {
 5385: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5386: 		return ($line,1,'New CODE value too large');
 5387: 	    }
 5388: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5389: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5390: 	    }
 5391: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5392: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5393: 	}
 5394:     } elsif ($field eq 'answer') {
 5395: 	my $length=$scantron_config->{'Qlength'};
 5396: 	my $off=$scantron_config->{'Qoff'};
 5397: 	my $on=$scantron_config->{'Qon'};
 5398: 	my $answer=${off}x$length;
 5399: 	if ($args->{'response'} eq 'none') {
 5400: 	    &scan_data($scan_data,
 5401: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5402: 	} else {
 5403: 	    if ($on eq 'letter') {
 5404: 		my @alphabet=('A'..'Z');
 5405: 		$answer=$alphabet[$args->{'response'}];
 5406: 	    } elsif ($on eq 'number') {
 5407: 		$answer=$args->{'response'}+1;
 5408: 		if ($answer == 10) { $answer = '0'; }
 5409: 	    } else {
 5410: 		substr($answer,$args->{'response'},1)=$on;
 5411: 	    }
 5412: 	    &scan_data($scan_data,
 5413: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5414: 	}
 5415: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5416: 	substr($line,$where-1,$length)=$answer;
 5417:     }
 5418:     return $line;
 5419: }
 5420: 
 5421: =pod
 5422: 
 5423: =item scan_data
 5424: 
 5425:     Edit or look up  an item in the scan_data hash.
 5426: 
 5427:   Arguments:
 5428:     $scan_data  - The hash (see scantron_getfile)
 5429:     $key        - shorthand of the key to edit (actual key is
 5430:                   scantronfilename_key).
 5431:     $data        - New value of the hash entry.
 5432:     $delete      - If true, the entry is removed from the hash.
 5433: 
 5434:   Returns:
 5435:     The new value of the hash table field (undefined if deleted).
 5436: 
 5437: =cut
 5438: 
 5439: 
 5440: sub scan_data {
 5441:     my ($scan_data,$key,$value,$delete)=@_;
 5442:     my $filename=$env{'form.scantron_selectfile'};
 5443:     if (defined($value)) {
 5444: 	$scan_data->{$filename.'_'.$key} = $value;
 5445:     }
 5446:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5447:     return $scan_data->{$filename.'_'.$key};
 5448: }
 5449: 
 5450: # ----- These first few routines are general use routines.----
 5451: 
 5452: # Return the number of occurences of a pattern in a string.
 5453: 
 5454: sub occurence_count {
 5455:     my ($string, $pattern) = @_;
 5456: 
 5457:     my @matches = ($string =~ /$pattern/g);
 5458: 
 5459:     return scalar(@matches);
 5460: }
 5461: 
 5462: 
 5463: # Take a string known to have digits and convert all the
 5464: # digits into letters in the range J,A..I.
 5465: 
 5466: sub digits_to_letters {
 5467:     my ($input) = @_;
 5468: 
 5469:     my @alphabet = ('J', 'A'..'I');
 5470: 
 5471:     my @input    = split(//, $input);
 5472:     my $output ='';
 5473:     for (my $i = 0; $i < scalar(@input); $i++) {
 5474: 	if ($input[$i] =~ /\d/) {
 5475: 	    $output .= $alphabet[$input[$i]];
 5476: 	} else {
 5477: 	    $output .= $input[$i];
 5478: 	}
 5479:     }
 5480:     return $output;
 5481: }
 5482: 
 5483: =pod 
 5484: 
 5485: =item scantron_parse_scanline
 5486: 
 5487:   Decodes a scanline from the selected scantron file
 5488: 
 5489:  Arguments:
 5490:     line             - The text of the scantron file line to process
 5491:     whichline        - Line number
 5492:     scantron_config  - Hash describing the format of the scantron lines.
 5493:     scan_data        - Hash of extra information about the scanline
 5494:                        (see scantron_getfile for more information)
 5495:     just_header      - True if should not process question answers but only
 5496:                        the stuff to the left of the answers.
 5497:  Returns:
 5498:    Hash containing the result of parsing the scanline
 5499: 
 5500:    Keys are all proceeded by the string 'scantron.'
 5501: 
 5502:        CODE    - the CODE in use for this scanline
 5503:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5504:                  by the operator
 5505:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5506:                             CODEs were selected, but the usage has been
 5507:                             forced by the operator
 5508:        ID  - student/employee ID
 5509:        PaperID - if used, the ID number printed on the sheet when the 
 5510:                  paper was scanned
 5511:        FirstName - first name from the sheet
 5512:        LastName  - last name from the sheet
 5513: 
 5514:      if just_header was not true these key may also exist
 5515: 
 5516:        missingerror - a list of bubble ranges that are considered to be answers
 5517:                       to a single question that don't have any bubbles filled in.
 5518:                       Of the form questionnumber:firstbubblenumber:count.
 5519:        doubleerror  - a list of bubble ranges that are considered to be answers
 5520:                       to a single question that have more than one bubble filled in.
 5521:                       Of the form questionnumber::firstbubblenumber:count
 5522:    
 5523:                 In the above, count is the number of bubble responses in the
 5524:                 input line needed to represent the possible answers to the question.
 5525:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5526:                 per line would have count = 2.
 5527: 
 5528:        maxquest     - the number of the last bubble line that was parsed
 5529: 
 5530:        (<number> starts at 1)
 5531:        <number>.answer - zero or more letters representing the selected
 5532:                          letters from the scanline for the bubble line 
 5533:                          <number>.
 5534:                          if blank there was either no bubble or there where
 5535:                          multiple bubbles, (consult the keys missingerror and
 5536:                          doubleerror if this is an error condition)
 5537: 
 5538: =cut
 5539: 
 5540: sub scantron_parse_scanline {
 5541:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5542: 
 5543:     my %record;
 5544:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5545:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5546:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5547:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5548: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5549: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5550: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5551: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5552: 	    $record{'scantron.CODE'}=substr($data,
 5553: 					    $$scantron_config{'CODEstart'}-1,
 5554: 					    $$scantron_config{'CODElength'});
 5555: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5556: 		$record{'scantron.useCODE'}=1;
 5557: 	    }
 5558: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5559: 		$record{'scantron.CODE_ignore_dup'}=1;
 5560: 	    }
 5561: 	} else {
 5562: 	    #FIXME interpret first N questions
 5563: 	}
 5564:     }
 5565:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5566: 				  $$scantron_config{'IDlength'});
 5567:     $record{'scantron.PaperID'}=
 5568: 	substr($data,$$scantron_config{'PaperID'}-1,
 5569: 	       $$scantron_config{'PaperIDlength'});
 5570:     $record{'scantron.FirstName'}=
 5571: 	substr($data,$$scantron_config{'FirstName'}-1,
 5572: 	       $$scantron_config{'FirstNamelength'});
 5573:     $record{'scantron.LastName'}=
 5574: 	substr($data,$$scantron_config{'LastName'}-1,
 5575: 	       $$scantron_config{'LastNamelength'});
 5576:     if ($just_header) { return \%record; }
 5577: 
 5578:     my @alphabet=('A'..'Z');
 5579:     my $questnum=0;
 5580:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5581: 
 5582:     chomp($questions);		# Get rid of any trailing \n.
 5583:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5584:     while (length($questions)) {
 5585: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5586:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5587:                              || 1;
 5588:         $questnum++;
 5589:         my $quest_id = $questnum;
 5590:         my $currentquest = substr($questions,0,$answer_length);
 5591:         $questions       = substr($questions,$answer_length);
 5592:         if (length($currentquest) < $answer_length) { next; }
 5593: 
 5594:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5595:             my $subquestnum = 1;
 5596:             my $subquestions = $currentquest;
 5597:             my @subanswers_needed = 
 5598:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5599:             foreach my $subans (@subanswers_needed) {
 5600:                 my $subans_length =
 5601:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5602:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5603:                 $subquestions   = substr($subquestions,$subans_length);
 5604:                 $quest_id = "$questnum.$subquestnum";
 5605:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5606:                     ($$scantron_config{'Qon'} eq 'number')) {
 5607:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5608:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5609:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5610:                 } else {
 5611:                     $ansnum = &scantron_validator_positional($ansnum,
 5612:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5613:                 }
 5614:                 $subquestnum ++;
 5615:             }
 5616:         } else {
 5617:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5618:                 ($$scantron_config{'Qon'} eq 'number')) {
 5619:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5620:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5621:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5622:             } else {
 5623:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5624:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5625:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5626:             }
 5627:         }
 5628:     }
 5629:     $record{'scantron.maxquest'}=$questnum;
 5630:     return \%record;
 5631: }
 5632: 
 5633: sub scantron_validator_lettnum {
 5634:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5635:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5636: 
 5637:     # Qon 'letter' implies for each slot in currquest we have:
 5638:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5639:     #    about anything else (esp. a value of Qoff) for missing
 5640:     #    bubbles.
 5641:     #
 5642:     # Qon 'number' implies each slot gives a digit that indexes the
 5643:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5644:     #    and * or ? for double bubbles on a single line.
 5645:     #
 5646: 
 5647:     my $matchon;
 5648:     if ($$scantron_config{'Qon'} eq 'letter') {
 5649:         $matchon = '[A-Z]';
 5650:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5651:         $matchon = '\d';
 5652:     }
 5653:     my $occurrences = 0;
 5654:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5655:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5656:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5657:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5658:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5659:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5660:         my @singlelines = split('',$currquest);
 5661:         foreach my $entry (@singlelines) {
 5662:             $occurrences = &occurence_count($entry,$matchon);
 5663:             if ($occurrences > 1) {
 5664:                 last;
 5665:             }
 5666:         } 
 5667:     } else {
 5668:         $occurrences = &occurence_count($currquest,$matchon); 
 5669:     }
 5670:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5671:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5672:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5673:             my $bubble = substr($currquest,$ans,1);
 5674:             if ($bubble =~ /$matchon/ ) {
 5675:                 if ($$scantron_config{'Qon'} eq 'number') {
 5676:                     if ($bubble == 0) {
 5677:                         $bubble = 10; 
 5678:                     }
 5679:                     $record->{"scantron.$ansnum.answer"} = 
 5680:                         $alphabet->[$bubble-1];
 5681:                 } else {
 5682:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5683:                 }
 5684:             } else {
 5685:                 $record->{"scantron.$ansnum.answer"}='';
 5686:             }
 5687:             $ansnum++;
 5688:         }
 5689:     } elsif (!defined($currquest)
 5690:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5691:             || (&occurence_count($currquest,$matchon) == 0)) {
 5692:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5693:             $record->{"scantron.$ansnum.answer"}='';
 5694:             $ansnum++;
 5695:         }
 5696:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5697:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5698:         }
 5699:     } else {
 5700:         if ($$scantron_config{'Qon'} eq 'number') {
 5701:             $currquest = &digits_to_letters($currquest);            
 5702:         }
 5703:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5704:             my $bubble = substr($currquest,$ans,1);
 5705:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5706:             $ansnum++;
 5707:         }
 5708:     }
 5709:     return $ansnum;
 5710: }
 5711: 
 5712: sub scantron_validator_positional {
 5713:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5714:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5715: 
 5716:     # Otherwise there's a positional notation;
 5717:     # each bubble line requires Qlength items, and there are filled in
 5718:     # bubbles for each case where there 'Qon' characters.
 5719:     #
 5720: 
 5721:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5722: 
 5723:     # If the split only gives us one element.. the full length of the
 5724:     # answer string, no bubbles are filled in:
 5725: 
 5726:     if ($answers_needed eq '') {
 5727:         return;
 5728:     }
 5729: 
 5730:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5731:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5732:             $record->{"scantron.$ansnum.answer"}='';
 5733:             $ansnum++;
 5734:         }
 5735:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5736:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5737:         }
 5738:     } elsif (scalar(@array) == 2) {
 5739:         my $location = length($array[0]);
 5740:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5741:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5742:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5743:             if ($ans eq $line_num) {
 5744:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5745:             } else {
 5746:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5747:             }
 5748:             $ansnum++;
 5749:          }
 5750:     } else {
 5751:         #  If there's more than one instance of a bubble character
 5752:         #  That's a double bubble; with positional notation we can
 5753:         #  record all the bubbles filled in as well as the
 5754:         #  fact this response consists of multiple bubbles.
 5755:         #
 5756:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5757:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5758:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5759:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5760:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5761:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5762:             my $doubleerror = 0;
 5763:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5764:                    (!$doubleerror)) {
 5765:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5766:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5767:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5768:                if (length(@currarray) > 2) {
 5769:                    $doubleerror = 1;
 5770:                } 
 5771:             }
 5772:             if ($doubleerror) {
 5773:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5774:             }
 5775:         } else {
 5776:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5777:         }
 5778:         my $item = $ansnum;
 5779:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5780:             $record->{"scantron.$item.answer"} = '';
 5781:             $item ++;
 5782:         }
 5783: 
 5784:         my @ans=@array;
 5785:         my $i=0;
 5786:         my $increment = 0;
 5787:         while ($#ans) {
 5788:             $i+=length($ans[0]) + $increment;
 5789:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5790:             my $bubble = $i%$$scantron_config{'Qlength'};
 5791:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5792:             shift(@ans);
 5793:             $increment = 1;
 5794:         }
 5795:         $ansnum += $answers_needed;
 5796:     }
 5797:     return $ansnum;
 5798: }
 5799: 
 5800: =pod
 5801: 
 5802: =item scantron_add_delay
 5803: 
 5804:    Adds an error message that occurred during the grading phase to a
 5805:    queue of messages to be shown after grading pass is complete
 5806: 
 5807:  Arguments:
 5808:    $delayqueue  - arrary ref of hash ref of error messages
 5809:    $scanline    - the scanline that caused the error
 5810:    $errormesage - the error message
 5811:    $errorcode   - a numeric code for the error
 5812: 
 5813:  Side Effects:
 5814:    updates the $delayqueue to have a new hash ref of the error
 5815: 
 5816: =cut
 5817: 
 5818: sub scantron_add_delay {
 5819:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5820:     push(@$delayqueue,
 5821: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5822: 	  'ecode' => $errorcode }
 5823: 	 );
 5824: }
 5825: 
 5826: =pod
 5827: 
 5828: =item scantron_find_student
 5829: 
 5830:    Finds the username for the current scanline
 5831: 
 5832:   Arguments:
 5833:    $scantron_record - hash result from scantron_parse_scanline
 5834:    $scan_data       - hash of correction information 
 5835:                       (see &scantron_getfile() form more information)
 5836:    $idmap           - hash from &username_to_idmap()
 5837:    $line            - number of current scanline
 5838:  
 5839:   Returns:
 5840:    Either 'username:domain' or undef if unknown
 5841: 
 5842: =cut
 5843: 
 5844: sub scantron_find_student {
 5845:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5846:     my $scanID=$$scantron_record{'scantron.ID'};
 5847:     if ($scanID =~ /^\s*$/) {
 5848:  	return &scan_data($scan_data,"$line.user");
 5849:     }
 5850:     foreach my $id (keys(%$idmap)) {
 5851:  	if (lc($id) eq lc($scanID)) {
 5852:  	    return $$idmap{$id};
 5853:  	}
 5854:     }
 5855:     return undef;
 5856: }
 5857: 
 5858: =pod
 5859: 
 5860: =item scantron_filter
 5861: 
 5862:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5863:    hidden resources was selected
 5864: 
 5865: =cut
 5866: 
 5867: sub scantron_filter {
 5868:     my ($curres)=@_;
 5869: 
 5870:     if (ref($curres) && $curres->is_problem()) {
 5871: 	# if the user has asked to not have either hidden
 5872: 	# or 'randomout' controlled resources to be graded
 5873: 	# don't include them
 5874: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5875: 	    && $curres->randomout) {
 5876: 	    return 0;
 5877: 	}
 5878: 	return 1;
 5879:     }
 5880:     return 0;
 5881: }
 5882: 
 5883: =pod
 5884: 
 5885: =item scantron_process_corrections
 5886: 
 5887:    Gets correction information out of submitted form data and corrects
 5888:    the scanline
 5889: 
 5890: =cut
 5891: 
 5892: sub scantron_process_corrections {
 5893:     my ($r) = @_;
 5894:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5895:     my ($scanlines,$scan_data)=&scantron_getfile();
 5896:     my $classlist=&Apache::loncoursedata::get_classlist();
 5897:     my $which=$env{'form.scantron_line'};
 5898:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5899:     my ($skip,$err,$errmsg);
 5900:     if ($env{'form.scantron_skip_record'}) {
 5901: 	$skip=1;
 5902:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5903: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5904: 	    $env{'form.scantron_domain'};
 5905: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5906: 	($line,$err,$errmsg)=
 5907: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5908: 				     'ID',{'newid'=>$newid,
 5909: 				    'username'=>$env{'form.scantron_username'},
 5910: 				    'domain'=>$env{'form.scantron_domain'}});
 5911:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5912: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5913: 	my $newCODE;
 5914: 	my %args;
 5915: 	if      ($resolution eq 'use_unfound') {
 5916: 	    $newCODE='use_unfound';
 5917: 	} elsif ($resolution eq 'use_found') {
 5918: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5919: 	} elsif ($resolution eq 'use_typed') {
 5920: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5921: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5922: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5923: 	}
 5924: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5925: 	    $args{'CODE_ignore_dup'}=1;
 5926: 	}
 5927: 	$args{'CODE'}=$newCODE;
 5928: 	($line,$err,$errmsg)=
 5929: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5930: 				     'CODE',\%args);
 5931:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5932: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5933: 	    ($line,$err,$errmsg)=
 5934: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5935: 					 $which,'answer',
 5936: 					 { 'question'=>$question,
 5937: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5938:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5939: 	    if ($err) { last; }
 5940: 	}
 5941:     }
 5942:     if ($err) {
 5943: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5944:     } else {
 5945: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5946: 	&scantron_putfile($scanlines,$scan_data);
 5947:     }
 5948: }
 5949: 
 5950: =pod
 5951: 
 5952: =item reset_skipping_status
 5953: 
 5954:    Forgets the current set of remember skipped scanlines (and thus
 5955:    reverts back to considering all lines in the
 5956:    scantron_skipped_<filename> file)
 5957: 
 5958: =cut
 5959: 
 5960: sub reset_skipping_status {
 5961:     my ($scanlines,$scan_data)=&scantron_getfile();
 5962:     &scan_data($scan_data,'remember_skipping',undef,1);
 5963:     &scantron_putfile(undef,$scan_data);
 5964: }
 5965: 
 5966: =pod
 5967: 
 5968: =item start_skipping
 5969: 
 5970:    Marks a scanline to be skipped. 
 5971: 
 5972: =cut
 5973: 
 5974: sub start_skipping {
 5975:     my ($scan_data,$i)=@_;
 5976:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5977:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5978: 	$remembered{$i}=2;
 5979:     } else {
 5980: 	$remembered{$i}=1;
 5981:     }
 5982:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5983: }
 5984: 
 5985: =pod
 5986: 
 5987: =item should_be_skipped
 5988: 
 5989:    Checks whether a scanline should be skipped.
 5990: 
 5991: =cut
 5992: 
 5993: sub should_be_skipped {
 5994:     my ($scanlines,$scan_data,$i)=@_;
 5995:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5996: 	# not redoing old skips
 5997: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5998: 	return 0;
 5999:     }
 6000:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6001: 
 6002:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6003: 	return 0;
 6004:     }
 6005:     return 1;
 6006: }
 6007: 
 6008: =pod
 6009: 
 6010: =item remember_current_skipped
 6011: 
 6012:    Discovers what scanlines are in the scantron_skipped_<filename>
 6013:    file and remembers them into scan_data for later use.
 6014: 
 6015: =cut
 6016: 
 6017: sub remember_current_skipped {
 6018:     my ($scanlines,$scan_data)=&scantron_getfile();
 6019:     my %to_remember;
 6020:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6021: 	if ($scanlines->{'skipped'}[$i]) {
 6022: 	    $to_remember{$i}=1;
 6023: 	}
 6024:     }
 6025: 
 6026:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6027:     &scantron_putfile(undef,$scan_data);
 6028: }
 6029: 
 6030: =pod
 6031: 
 6032: =item check_for_error
 6033: 
 6034:     Checks if there was an error when attempting to remove a specific
 6035:     scantron_.. bubble sheet data file. Prints out an error if
 6036:     something went wrong.
 6037: 
 6038: =cut
 6039: 
 6040: sub check_for_error {
 6041:     my ($r,$result)=@_;
 6042:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6043: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6044:     }
 6045: }
 6046: 
 6047: =pod
 6048: 
 6049: =item scantron_warning_screen
 6050: 
 6051:    Interstitial screen to make sure the operator has selected the
 6052:    correct options before we start the validation phase.
 6053: 
 6054: =cut
 6055: 
 6056: sub scantron_warning_screen {
 6057:     my ($button_text)=@_;
 6058:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6059:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6060:     my $CODElist;
 6061:     if ($scantron_config{'CODElocation'} &&
 6062: 	$scantron_config{'CODEstart'} &&
 6063: 	$scantron_config{'CODElength'}) {
 6064: 	$CODElist=$env{'form.scantron_CODElist'};
 6065: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6066: 	$CODElist=
 6067: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6068: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6069:     }
 6070:     return ('
 6071: <p>
 6072: <span class="LC_warning">
 6073: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6074: </p>
 6075: <table>
 6076: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6077: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6078: '.$CODElist.'
 6079: </table>
 6080: <br />
 6081: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6082: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6083: 
 6084: <br />
 6085: ');
 6086: }
 6087: 
 6088: =pod
 6089: 
 6090: =item scantron_do_warning
 6091: 
 6092:    Check if the operator has picked something for all required
 6093:    fields. Error out if something is missing.
 6094: 
 6095: =cut
 6096: 
 6097: sub scantron_do_warning {
 6098:     my ($r)=@_;
 6099:     my ($symb)=&get_symb($r);
 6100:     if (!$symb) {return '';}
 6101:     my $default_form_data=&defaultFormData($symb);
 6102:     $r->print(&scantron_form_start().$default_form_data);
 6103:     if ( $env{'form.selectpage'} eq '' ||
 6104: 	 $env{'form.scantron_selectfile'} eq '' ||
 6105: 	 $env{'form.scantron_format'} eq '' ) {
 6106: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6107: 	if ( $env{'form.selectpage'} eq '') {
 6108: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6109: 	} 
 6110: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6111: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6112: 	} 
 6113: 	if ( $env{'form.scantron_format'} eq '') {
 6114: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6115: 	} 
 6116:     } else {
 6117: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6118: 	$r->print('
 6119: '.$warning.'
 6120: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6121: <input type="hidden" name="command" value="scantron_validate" />
 6122: ');
 6123:     }
 6124:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6125:     return '';
 6126: }
 6127: 
 6128: =pod
 6129: 
 6130: =item scantron_form_start
 6131: 
 6132:     html hidden input for remembering all selected grading options
 6133: 
 6134: =cut
 6135: 
 6136: sub scantron_form_start {
 6137:     my ($max_bubble)=@_;
 6138:     my $result= <<SCANTRONFORM;
 6139: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6140:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6141:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6142:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6143:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6144:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6145:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6146:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6147:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6148:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6149: SCANTRONFORM
 6150: 
 6151:   my $line = 0;
 6152:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6153:        my $chunk =
 6154: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6155:        $chunk .=
 6156: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6157:        $chunk .= 
 6158:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6159:        $chunk .=
 6160:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6161:        $result .= $chunk;
 6162:        $line++;
 6163:    }
 6164:     return $result;
 6165: }
 6166: 
 6167: =pod
 6168: 
 6169: =item scantron_validate_file
 6170: 
 6171:     Dispatch routine for doing validation of a bubble sheet data file.
 6172: 
 6173:     Also processes any necessary information resets that need to
 6174:     occur before validation begins (ignore previous corrections,
 6175:     restarting the skipped records processing)
 6176: 
 6177: =cut
 6178: 
 6179: sub scantron_validate_file {
 6180:     my ($r) = @_;
 6181:     my ($symb)=&get_symb($r);
 6182:     if (!$symb) {return '';}
 6183:     my $default_form_data=&defaultFormData($symb);
 6184:     
 6185:     # do the detection of only doing skipped records first befroe we delete
 6186:     # them when doing the corrections reset
 6187:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6188: 	&reset_skipping_status();
 6189:     }
 6190:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6191: 	&remember_current_skipped();
 6192: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6193:     }
 6194: 
 6195:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6196: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6197: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6198: 	&check_for_error($r,&scantron_remove_scan_data());
 6199: 	$env{'form.scantron_options_ignore'}='done';
 6200:     }
 6201: 
 6202:     if ($env{'form.scantron_corrections'}) {
 6203: 	&scantron_process_corrections($r);
 6204:     }
 6205:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6206:     #get the student pick code ready
 6207:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6208:     my $max_bubble=&scantron_get_maxbubble();
 6209:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6210:     $r->print($result);
 6211:     
 6212:     my @validate_phases=( 'sequence',
 6213: 			  'ID',
 6214: 			  'CODE',
 6215: 			  'doublebubble',
 6216: 			  'missingbubbles');
 6217:     if (!$env{'form.validatepass'}) {
 6218: 	$env{'form.validatepass'} = 0;
 6219:     }
 6220:     my $currentphase=$env{'form.validatepass'};
 6221: 
 6222: 
 6223:     my $stop=0;
 6224:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6225: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6226: 	$r->rflush();
 6227: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6228: 	{
 6229: 	    no strict 'refs';
 6230: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6231: 	}
 6232:     }
 6233:     if (!$stop) {
 6234: 	my $warning=&scantron_warning_screen('Start Grading');
 6235: 	$r->print(&mt('Validation process complete.').'<br />'.
 6236:                   $warning.
 6237:                   &mt('Perform verification for each student after storage of submissions?').
 6238:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6239:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6240:                   ('&nbsp;'x3).'<label>'.
 6241:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6242:                   '</label></span><br />'.
 6243:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6244:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6245:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6246:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6247:     } else {
 6248: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6249: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6250:     }
 6251:     if ($stop) {
 6252: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6253: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6254: 	    $r->print(' '.&mt('this error').' <br />');
 6255: 
 6256: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6257: 	} else {
 6258:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6259: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6260:             } else {
 6261:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6262:             }
 6263: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6264: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6265: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6266: 	}
 6267:     }
 6268:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6269:     return '';
 6270: }
 6271: 
 6272: 
 6273: =pod
 6274: 
 6275: =item scantron_remove_file
 6276: 
 6277:    Removes the requested bubble sheet data file, makes sure that
 6278:    scantron_original_<filename> is never removed
 6279: 
 6280: 
 6281: =cut
 6282: 
 6283: sub scantron_remove_file {
 6284:     my ($which)=@_;
 6285:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6286:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6287:     my $file='scantron_';
 6288:     if ($which eq 'corrected' || $which eq 'skipped') {
 6289: 	$file.=$which.'_';
 6290:     } else {
 6291: 	return 'refused';
 6292:     }
 6293:     $file.=$env{'form.scantron_selectfile'};
 6294:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6295: }
 6296: 
 6297: 
 6298: =pod
 6299: 
 6300: =item scantron_remove_scan_data
 6301: 
 6302:    Removes all scan_data correction for the requested bubble sheet
 6303:    data file.  (In the case that both the are doing skipped records we need
 6304:    to remember the old skipped lines for the time being so that element
 6305:    persists for a while.)
 6306: 
 6307: =cut
 6308: 
 6309: sub scantron_remove_scan_data {
 6310:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6311:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6312:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6313:     my @todelete;
 6314:     my $filename=$env{'form.scantron_selectfile'};
 6315:     foreach my $key (@keys) {
 6316: 	if ($key=~/^\Q$filename\E_/) {
 6317: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6318: 		$key=~/remember_skipping/) {
 6319: 		next;
 6320: 	    }
 6321: 	    push(@todelete,$key);
 6322: 	}
 6323:     }
 6324:     my $result;
 6325:     if (@todelete) {
 6326: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6327: 				       \@todelete,$cdom,$cname);
 6328:     } else {
 6329: 	$result = 'ok';
 6330:     }
 6331:     return $result;
 6332: }
 6333: 
 6334: 
 6335: =pod
 6336: 
 6337: =item scantron_getfile
 6338: 
 6339:     Fetches the requested bubble sheet data file (all 3 versions), and
 6340:     the scan_data hash
 6341:   
 6342:   Arguments:
 6343:     None
 6344: 
 6345:   Returns:
 6346:     2 hash references
 6347: 
 6348:      - first one has 
 6349:          orig      -
 6350:          corrected -
 6351:          skipped   -  each of which points to an array ref of the specified
 6352:                       file broken up into individual lines
 6353:          count     - number of scanlines
 6354:  
 6355:      - second is the scan_data hash possible keys are
 6356:        ($number refers to scanline numbered $number and thus the key affects
 6357:         only that scanline
 6358:         $bubline refers to the specific bubble line element and the aspects
 6359:         refers to that specific bubble line element)
 6360: 
 6361:        $number.user - username:domain to use
 6362:        $number.CODE_ignore_dup 
 6363:                     - ignore the duplicate CODE error 
 6364:        $number.useCODE
 6365:                     - use the CODE in the scanline as is
 6366:        $number.no_bubble.$bubline
 6367:                     - it is valid that there is no bubbled in bubble
 6368:                       at $number $bubline
 6369:        remember_skipping
 6370:                     - a frozen hash containing keys of $number and values
 6371:                       of either 
 6372:                         1 - we are on a 'do skipped records pass' and plan
 6373:                             on processing this line
 6374:                         2 - we are on a 'do skipped records pass' and this
 6375:                             scanline has been marked to skip yet again
 6376: 
 6377: =cut
 6378: 
 6379: sub scantron_getfile {
 6380:     #FIXME really would prefer a scantron directory
 6381:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6382:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6383:     my $lines;
 6384:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6385: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6386:     my %scanlines;
 6387:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6388:     my $temp=$scanlines{'orig'};
 6389:     $scanlines{'count'}=$#$temp;
 6390: 
 6391:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6392: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6393:     if ($lines eq '-1') {
 6394: 	$scanlines{'corrected'}=[];
 6395:     } else {
 6396: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6397:     }
 6398:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6399: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6400:     if ($lines eq '-1') {
 6401: 	$scanlines{'skipped'}=[];
 6402:     } else {
 6403: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6404:     }
 6405:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6406:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6407:     my %scan_data = @tmp;
 6408:     return (\%scanlines,\%scan_data);
 6409: }
 6410: 
 6411: =pod
 6412: 
 6413: =item lonnet_putfile
 6414: 
 6415:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6416: 
 6417:  Arguments:
 6418:    $contents - data to store
 6419:    $filename - filename to store $contents into
 6420: 
 6421:  Returns:
 6422:    result value from &Apache::lonnet::finishuserfileupload
 6423: 
 6424: =cut
 6425: 
 6426: sub lonnet_putfile {
 6427:     my ($contents,$filename)=@_;
 6428:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6429:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6430:     $env{'form.sillywaytopassafilearound'}=$contents;
 6431:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6432: 
 6433: }
 6434: 
 6435: =pod
 6436: 
 6437: =item scantron_putfile
 6438: 
 6439:     Stores the current version of the bubble sheet data files, and the
 6440:     scan_data hash. (Does not modify the original version only the
 6441:     corrected and skipped versions.
 6442: 
 6443:  Arguments:
 6444:     $scanlines - hash ref that looks like the first return value from
 6445:                  &scantron_getfile()
 6446:     $scan_data - hash ref that looks like the second return value from
 6447:                  &scantron_getfile()
 6448: 
 6449: =cut
 6450: 
 6451: sub scantron_putfile {
 6452:     my ($scanlines,$scan_data) = @_;
 6453:     #FIXME really would prefer a scantron directory
 6454:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6455:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6456:     if ($scanlines) {
 6457: 	my $prefix='scantron_';
 6458: # no need to update orig, shouldn't change
 6459: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6460: #		    $env{'form.scantron_selectfile'});
 6461: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6462: 			$prefix.'corrected_'.
 6463: 			$env{'form.scantron_selectfile'});
 6464: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6465: 			$prefix.'skipped_'.
 6466: 			$env{'form.scantron_selectfile'});
 6467:     }
 6468:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6469: }
 6470: 
 6471: =pod
 6472: 
 6473: =item scantron_get_line
 6474: 
 6475:    Returns the correct version of the scanline
 6476: 
 6477:  Arguments:
 6478:     $scanlines - hash ref that looks like the first return value from
 6479:                  &scantron_getfile()
 6480:     $scan_data - hash ref that looks like the second return value from
 6481:                  &scantron_getfile()
 6482:     $i         - number of the requested line (starts at 0)
 6483: 
 6484:  Returns:
 6485:    A scanline, (either the original or the corrected one if it
 6486:    exists), or undef if the requested scanline should be
 6487:    skipped. (Either because it's an skipped scanline, or it's an
 6488:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6489:    pass.
 6490: 
 6491: =cut
 6492: 
 6493: sub scantron_get_line {
 6494:     my ($scanlines,$scan_data,$i)=@_;
 6495:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6496:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6497:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6498:     return $scanlines->{'orig'}[$i]; 
 6499: }
 6500: 
 6501: =pod
 6502: 
 6503: =item scantron_todo_count
 6504: 
 6505:     Counts the number of scanlines that need processing.
 6506: 
 6507:  Arguments:
 6508:     $scanlines - hash ref that looks like the first return value from
 6509:                  &scantron_getfile()
 6510:     $scan_data - hash ref that looks like the second return value from
 6511:                  &scantron_getfile()
 6512: 
 6513:  Returns:
 6514:     $count - number of scanlines to process
 6515: 
 6516: =cut
 6517: 
 6518: sub get_todo_count {
 6519:     my ($scanlines,$scan_data)=@_;
 6520:     my $count=0;
 6521:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6522: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6523: 	if ($line=~/^[\s\cz]*$/) { next; }
 6524: 	$count++;
 6525:     }
 6526:     return $count;
 6527: }
 6528: 
 6529: =pod
 6530: 
 6531: =item scantron_put_line
 6532: 
 6533:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6534:     data file.
 6535: 
 6536:  Arguments:
 6537:     $scanlines - hash ref that looks like the first return value from
 6538:                  &scantron_getfile()
 6539:     $scan_data - hash ref that looks like the second return value from
 6540:                  &scantron_getfile()
 6541:     $i         - line number to update
 6542:     $newline   - contents of the updated scanline
 6543:     $skip      - if true make the line for skipping and update the
 6544:                  'skipped' file
 6545: 
 6546: =cut
 6547: 
 6548: sub scantron_put_line {
 6549:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6550:     if ($skip) {
 6551: 	$scanlines->{'skipped'}[$i]=$newline;
 6552: 	&start_skipping($scan_data,$i);
 6553: 	return;
 6554:     }
 6555:     $scanlines->{'corrected'}[$i]=$newline;
 6556: }
 6557: 
 6558: =pod
 6559: 
 6560: =item scantron_clear_skip
 6561: 
 6562:    Remove a line from the 'skipped' file
 6563: 
 6564:  Arguments:
 6565:     $scanlines - hash ref that looks like the first return value from
 6566:                  &scantron_getfile()
 6567:     $scan_data - hash ref that looks like the second return value from
 6568:                  &scantron_getfile()
 6569:     $i         - line number to update
 6570: 
 6571: =cut
 6572: 
 6573: sub scantron_clear_skip {
 6574:     my ($scanlines,$scan_data,$i)=@_;
 6575:     if (exists($scanlines->{'skipped'}[$i])) {
 6576: 	undef($scanlines->{'skipped'}[$i]);
 6577: 	return 1;
 6578:     }
 6579:     return 0;
 6580: }
 6581: 
 6582: =pod
 6583: 
 6584: =item scantron_filter_not_exam
 6585: 
 6586:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6587:    filter out resources that are not marked as 'exam' mode
 6588: 
 6589: =cut
 6590: 
 6591: sub scantron_filter_not_exam {
 6592:     my ($curres)=@_;
 6593:     
 6594:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6595: 	# if the user has asked to not have either hidden
 6596: 	# or 'randomout' controlled resources to be graded
 6597: 	# don't include them
 6598: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6599: 	    && $curres->randomout) {
 6600: 	    return 0;
 6601: 	}
 6602: 	return 1;
 6603:     }
 6604:     return 0;
 6605: }
 6606: 
 6607: =pod
 6608: 
 6609: =item scantron_validate_sequence
 6610: 
 6611:     Validates the selected sequence, checking for resource that are
 6612:     not set to exam mode.
 6613: 
 6614: =cut
 6615: 
 6616: sub scantron_validate_sequence {
 6617:     my ($r,$currentphase) = @_;
 6618: 
 6619:     my $navmap=Apache::lonnavmaps::navmap->new();
 6620:     my (undef,undef,$sequence)=
 6621: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6622: 
 6623:     my $map=$navmap->getResourceByUrl($sequence);
 6624: 
 6625:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6626:                                     value="ignore" />');
 6627:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6628: 	my @resources=
 6629: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6630: 	if (@resources) {
 6631: 	    $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>");
 6632: 	    return (1,$currentphase);
 6633: 	}
 6634:     }
 6635: 
 6636:     return (0,$currentphase+1);
 6637: }
 6638: 
 6639: 
 6640: 
 6641: sub scantron_validate_ID {
 6642:     my ($r,$currentphase) = @_;
 6643:     
 6644:     #get student info
 6645:     my $classlist=&Apache::loncoursedata::get_classlist();
 6646:     my %idmap=&username_to_idmap($classlist);
 6647: 
 6648:     #get scantron line setup
 6649:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6650:     my ($scanlines,$scan_data)=&scantron_getfile();
 6651:     
 6652:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6653: 
 6654:     my %found=('ids'=>{},'usernames'=>{});
 6655:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6656: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6657: 	if ($line=~/^[\s\cz]*$/) { next; }
 6658: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6659: 						 $scan_data);
 6660: 	my $id=$$scan_record{'scantron.ID'};
 6661: 	my $found;
 6662: 	foreach my $checkid (keys(%idmap)) {
 6663: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6664: 	}
 6665: 	if ($found) {
 6666: 	    my $username=$idmap{$found};
 6667: 	    if ($found{'ids'}{$found}) {
 6668: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6669: 					 $line,'duplicateID',$found);
 6670: 		return(1,$currentphase);
 6671: 	    } elsif ($found{'usernames'}{$username}) {
 6672: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6673: 					 $line,'duplicateID',$username);
 6674: 		return(1,$currentphase);
 6675: 	    }
 6676: 	    #FIXME store away line we previously saw the ID on to use above
 6677: 	    $found{'ids'}{$found}++;
 6678: 	    $found{'usernames'}{$username}++;
 6679: 	} else {
 6680: 	    if ($id =~ /^\s*$/) {
 6681: 		my $username=&scan_data($scan_data,"$i.user");
 6682: 		if (defined($username) && $found{'usernames'}{$username}) {
 6683: 		    &scantron_get_correction($r,$i,$scan_record,
 6684: 					     \%scantron_config,
 6685: 					     $line,'duplicateID',$username);
 6686: 		    return(1,$currentphase);
 6687: 		} elsif (!defined($username)) {
 6688: 		    &scantron_get_correction($r,$i,$scan_record,
 6689: 					     \%scantron_config,
 6690: 					     $line,'incorrectID');
 6691: 		    return(1,$currentphase);
 6692: 		}
 6693: 		$found{'usernames'}{$username}++;
 6694: 	    } else {
 6695: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6696: 					 $line,'incorrectID');
 6697: 		return(1,$currentphase);
 6698: 	    }
 6699: 	}
 6700:     }
 6701: 
 6702:     return (0,$currentphase+1);
 6703: }
 6704: 
 6705: 
 6706: sub scantron_get_correction {
 6707:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6708: #FIXME in the case of a duplicated ID the previous line, probably need
 6709: #to show both the current line and the previous one and allow skipping
 6710: #the previous one or the current one
 6711: 
 6712:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6713: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6714: 			    " for PaperID <tt>[_1]</tt>",
 6715: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6716:     } else {
 6717: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6718: 			    " in scanline [_1] <pre>[_2]</pre>",
 6719: 			    $i,$line)."</p> \n");
 6720:     }
 6721:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6722: 			  "The name on the paper is [_2],[_3]",
 6723: 			  $$scan_record{'scantron.ID'},
 6724: 			  $$scan_record{'scantron.LastName'},
 6725: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6726: 
 6727:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6728:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6729:                            # Array populated for doublebubble or
 6730:     my @lines_to_correct;  # missingbubble errors to build javascript
 6731:                            # to validate radio button checking   
 6732: 
 6733:     if ($error =~ /ID$/) {
 6734: 	if ($error eq 'incorrectID') {
 6735: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6736: 		      "</p>\n");
 6737: 	} elsif ($error eq 'duplicateID') {
 6738: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6739: 	}
 6740: 	$r->print($message);
 6741: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6742: 	$r->print("\n<ul><li> ");
 6743: 	#FIXME it would be nice if this sent back the user ID and
 6744: 	#could do partial userID matches
 6745: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6746: 				       'scantron_username','scantron_domain'));
 6747: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6748: 	$r->print("\n@".
 6749: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6750: 
 6751: 	$r->print('</li>');
 6752:     } elsif ($error =~ /CODE$/) {
 6753: 	if ($error eq 'incorrectCODE') {
 6754: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6755: 	} elsif ($error eq 'duplicateCODE') {
 6756: 	    $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");
 6757: 	}
 6758: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6759: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6760: 	$r->print($message);
 6761: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6762: 	$r->print("\n<br /> ");
 6763: 	my $i=0;
 6764: 	if ($error eq 'incorrectCODE' 
 6765: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6766: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6767: 	    if ($closest > 0) {
 6768: 		foreach my $testcode (@{$closest}) {
 6769: 		    my $checked='';
 6770: 		    if (!$i) { $checked=' checked="checked" '; }
 6771: 		    $r->print("
 6772:    <label>
 6773:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6774:        ".&mt("Use the similar CODE [_1] instead.",
 6775: 	    "<b><tt>".$testcode."</tt></b>")."
 6776:     </label>
 6777:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6778: 		    $r->print("\n<br />");
 6779: 		    $i++;
 6780: 		}
 6781: 	    }
 6782: 	}
 6783: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6784: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6785: 	    $r->print("
 6786:     <label>
 6787:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6788:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6789: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6790:     </label>");
 6791: 	    $r->print("\n<br />");
 6792: 	}
 6793: 
 6794: 	$r->print(<<ENDSCRIPT);
 6795: <script type="text/javascript">
 6796: function change_radio(field) {
 6797:     var slct=document.scantronupload.scantron_CODE_resolution;
 6798:     var i;
 6799:     for (i=0;i<slct.length;i++) {
 6800:         if (slct[i].value==field) { slct[i].checked=true; }
 6801:     }
 6802: }
 6803: </script>
 6804: ENDSCRIPT
 6805: 	my $href="/adm/pickcode?".
 6806: 	   "form=".&escape("scantronupload").
 6807: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6808: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6809: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6810: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6811: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6812: 	    $r->print("
 6813:     <label>
 6814:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6815:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6816: 	     "<a target='_blank' href='$href'>","</a>")."
 6817:     </label> 
 6818:     ".&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\')" />'));
 6819: 	    $r->print("\n<br />");
 6820: 	}
 6821: 	$r->print("
 6822:     <label>
 6823:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6824:        ".&mt("Use [_1] as the CODE.",
 6825: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6826: 	$r->print("\n<br /><br />");
 6827:     } elsif ($error eq 'doublebubble') {
 6828: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6829: 
 6830: 	# The form field scantron_questions is acutally a list of line numbers.
 6831: 	# represented by this form so:
 6832: 
 6833: 	my $line_list = &questions_to_line_list($arg);
 6834: 
 6835: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6836: 		  $line_list.'" />');
 6837: 	$r->print($message);
 6838: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6839: 	foreach my $question (@{$arg}) {
 6840: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6841:                                                    $scan_record, $error);
 6842:             push(@lines_to_correct,@linenums);
 6843: 	}
 6844:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6845:     } elsif ($error eq 'missingbubble') {
 6846: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6847: 	$r->print($message);
 6848: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6849: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6850: 
 6851: 	# The form field scantron_questions is actually a list of line numbers not
 6852: 	# a list of question numbers. Therefore:
 6853: 	#
 6854: 	
 6855: 	my $line_list = &questions_to_line_list($arg);
 6856: 
 6857: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6858: 		  $line_list.'" />');
 6859: 	foreach my $question (@{$arg}) {
 6860: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6861:                                                    $scan_record, $error);
 6862:             push(@lines_to_correct,@linenums);
 6863: 	}
 6864:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6865:     } else {
 6866: 	$r->print("\n<ul>");
 6867:     }
 6868:     $r->print("\n</li></ul>");
 6869: }
 6870: 
 6871: sub verify_bubbles_checked {
 6872:     my (@ansnums) = @_;
 6873:     my $ansnumstr = join('","',@ansnums);
 6874:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6875:     my $output = (<<ENDSCRIPT);
 6876: <script type="text/javascript">
 6877: function verify_bubble_radio(form) {
 6878:     var ansnumArray = new Array ("$ansnumstr");
 6879:     var need_bubble_count = 0;
 6880:     for (var i=0; i<ansnumArray.length; i++) {
 6881:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6882:             var bubble_picked = 0; 
 6883:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6884:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6885:                     bubble_picked = 1;
 6886:                 }
 6887:             }
 6888:             if (bubble_picked == 0) {
 6889:                 need_bubble_count ++;
 6890:             }
 6891:         }
 6892:     }
 6893:     if (need_bubble_count) {
 6894:         alert("$warning");
 6895:         return;
 6896:     }
 6897:     form.submit(); 
 6898: }
 6899: </script>
 6900: ENDSCRIPT
 6901:     return $output;
 6902: }
 6903: 
 6904: =pod
 6905: 
 6906: =item  questions_to_line_list
 6907: 
 6908: Converts a list of questions into a string of comma separated
 6909: line numbers in the answer sheet used by the questions.  This is
 6910: used to fill in the scantron_questions form field.
 6911: 
 6912:   Arguments:
 6913:      questions    - Reference to an array of questions.
 6914: 
 6915: =cut
 6916: 
 6917: 
 6918: sub questions_to_line_list {
 6919:     my ($questions) = @_;
 6920:     my @lines;
 6921: 
 6922:     foreach my $item (@{$questions}) {
 6923:         my $question = $item;
 6924:         my ($first,$count,$last);
 6925:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6926:             $question = $1;
 6927:             my $subquestion = $2;
 6928:             $first = $first_bubble_line{$question-1} + 1;
 6929:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6930:             my $subcount = 1;
 6931:             while ($subcount<$subquestion) {
 6932:                 $first += $subans[$subcount-1];
 6933:                 $subcount ++;
 6934:             }
 6935:             $count = $subans[$subquestion-1];
 6936:         } else {
 6937: 	    $first   = $first_bubble_line{$question-1} + 1;
 6938: 	    $count   = $bubble_lines_per_response{$question-1};
 6939:         }
 6940:         $last = $first+$count-1;
 6941:         push(@lines, ($first..$last));
 6942:     }
 6943:     return join(',', @lines);
 6944: }
 6945: 
 6946: =pod 
 6947: 
 6948: =item prompt_for_corrections
 6949: 
 6950: Prompts for a potentially multiline correction to the
 6951: user's bubbling (factors out common code from scantron_get_correction
 6952: for multi and missing bubble cases).
 6953: 
 6954:  Arguments:
 6955:    $r           - Apache request object.
 6956:    $question    - The question number to prompt for.
 6957:    $scan_config - The scantron file configuration hash.
 6958:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6959:    $error       - Type of error
 6960: 
 6961:  Implicit inputs:
 6962:    %bubble_lines_per_response   - Starting line numbers for each question.
 6963:                                   Numbered from 0 (but question numbers are from
 6964:                                   1.
 6965:    %first_bubble_line           - Starting bubble line for each question.
 6966:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6967:                                   type problems render as separate sub-questions, 
 6968:                                   in exam mode. This hash contains a 
 6969:                                   comma-separated list of the lines per 
 6970:                                   sub-question.
 6971:    %responsetype_per_response   - essayresponse, formularesponse,
 6972:                                   stringresponse, imageresponse, reactionresponse,
 6973:                                   and organicresponse type problem parts can have
 6974:                                   multiple lines per response if the weight
 6975:                                   assigned exceeds 10.  In this case, only
 6976:                                   one bubble per line is permitted, but more 
 6977:                                   than one line might contain bubbles, e.g.
 6978:                                   bubbling of: line 1 - J, line 2 - J, 
 6979:                                   line 3 - B would assign 22 points.  
 6980: 
 6981: =cut
 6982: 
 6983: sub prompt_for_corrections {
 6984:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6985:     my ($current_line,$lines);
 6986:     my @linenums;
 6987:     my $questionnum = $question;
 6988:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6989:         $question = $1;
 6990:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6991:         my $subquestion = $2;
 6992:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6993:         my $subcount = 1;
 6994:         while ($subcount<$subquestion) {
 6995:             $current_line += $subans[$subcount-1];
 6996:             $subcount ++;
 6997:         }
 6998:         $lines = $subans[$subquestion-1];
 6999:     } else {
 7000:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7001:         $lines        = $bubble_lines_per_response{$question-1};
 7002:     }
 7003:     if ($lines > 1) {
 7004:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7005:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7006:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7007:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7008:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7009:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7010:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7011:             $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 />');
 7012:         } else {
 7013:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7014:         }
 7015:     }
 7016:     for (my $i =0; $i < $lines; $i++) {
 7017:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7018: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7019: 	        		  $questionnum,$error,split('', $selected));
 7020:         push(@linenums,$current_line);
 7021: 	$current_line++;
 7022:     }
 7023:     if ($lines > 1) {
 7024: 	$r->print("<hr /><br />");
 7025:     }
 7026:     return @linenums;
 7027: }
 7028: 
 7029: =pod
 7030: 
 7031: =item scantron_bubble_selector
 7032:   
 7033:    Generates the html radiobuttons to correct a single bubble line
 7034:    possibly showing the existing the selected bubbles if known
 7035: 
 7036:  Arguments:
 7037:     $r           - Apache request object
 7038:     $scan_config - hash from &get_scantron_config()
 7039:     $line        - Number of the line being displayed.
 7040:     $questionnum - Question number (may include subquestion)
 7041:     $error       - Type of error.
 7042:     @selected    - Array of bubbles picked on this line.
 7043: 
 7044: =cut
 7045: 
 7046: sub scantron_bubble_selector {
 7047:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7048:     my $max=$$scan_config{'Qlength'};
 7049: 
 7050:     my $scmode=$$scan_config{'Qon'};
 7051:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7052: 
 7053:     my @alphabet=('A'..'Z');
 7054:     $r->print(&Apache::loncommon::start_data_table().
 7055:               &Apache::loncommon::start_data_table_row());
 7056:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7057:     for (my $i=0;$i<$max+1;$i++) {
 7058: 	$r->print("\n".'<td align="center">');
 7059: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7060: 	else { $r->print('&nbsp;'); }
 7061: 	$r->print('</td>');
 7062:     }
 7063:     $r->print(&Apache::loncommon::end_data_table_row().
 7064:               &Apache::loncommon::start_data_table_row());
 7065:     for (my $i=0;$i<$max;$i++) {
 7066: 	$r->print("\n".
 7067: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7068: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7069:     }
 7070:     my $nobub_checked = ' ';
 7071:     if ($error eq 'missingbubble') {
 7072:         $nobub_checked = ' checked = "checked" ';
 7073:     }
 7074:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7075: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7076:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7077:               $line.'" value="'.$questionnum.'" /></td>');
 7078:     $r->print(&Apache::loncommon::end_data_table_row().
 7079:               &Apache::loncommon::end_data_table());
 7080: }
 7081: 
 7082: =pod
 7083: 
 7084: =item num_matches
 7085: 
 7086:    Counts the number of characters that are the same between the two arguments.
 7087: 
 7088:  Arguments:
 7089:    $orig - CODE from the scanline
 7090:    $code - CODE to match against
 7091: 
 7092:  Returns:
 7093:    $count - integer count of the number of same characters between the
 7094:             two arguments
 7095: 
 7096: =cut
 7097: 
 7098: sub num_matches {
 7099:     my ($orig,$code) = @_;
 7100:     my @code=split(//,$code);
 7101:     my @orig=split(//,$orig);
 7102:     my $same=0;
 7103:     for (my $i=0;$i<scalar(@code);$i++) {
 7104: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7105:     }
 7106:     return $same;
 7107: }
 7108: 
 7109: =pod
 7110: 
 7111: =item scantron_get_closely_matching_CODEs
 7112: 
 7113:    Cycles through all CODEs and finds the set that has the greatest
 7114:    number of same characters as the provided CODE
 7115: 
 7116:  Arguments:
 7117:    $allcodes - hash ref returned by &get_codes()
 7118:    $CODE     - CODE from the current scanline
 7119: 
 7120:  Returns:
 7121:    2 element list
 7122:     - first elements is number of how closely matching the best fit is 
 7123:       (5 means best set has 5 matching characters)
 7124:     - second element is an arrary ref containing the set of valid CODEs
 7125:       that best fit the passed in CODE
 7126: 
 7127: =cut
 7128: 
 7129: sub scantron_get_closely_matching_CODEs {
 7130:     my ($allcodes,$CODE)=@_;
 7131:     my @CODEs;
 7132:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7133: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7134:     }
 7135: 
 7136:     return ($#CODEs,$CODEs[-1]);
 7137: }
 7138: 
 7139: =pod
 7140: 
 7141: =item get_codes
 7142: 
 7143:    Builds a hash which has keys of all of the valid CODEs from the selected
 7144:    set of remembered CODEs.
 7145: 
 7146:  Arguments:
 7147:   $old_name - name of the set of remembered CODEs
 7148:   $cdom     - domain of the course
 7149:   $cnum     - internal course name
 7150: 
 7151:  Returns:
 7152:   %allcodes - keys are the valid CODEs, values are all 1
 7153: 
 7154: =cut
 7155: 
 7156: sub get_codes {
 7157:     my ($old_name, $cdom, $cnum) = @_;
 7158:     if (!$old_name) {
 7159: 	$old_name=$env{'form.scantron_CODElist'};
 7160:     }
 7161:     if (!$cdom) {
 7162: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7163:     }
 7164:     if (!$cnum) {
 7165: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7166:     }
 7167:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7168: 				    $cdom,$cnum);
 7169:     my %allcodes;
 7170:     if ($result{"type\0$old_name"} eq 'number') {
 7171: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7172:     } else {
 7173: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7174:     }
 7175:     return %allcodes;
 7176: }
 7177: 
 7178: =pod
 7179: 
 7180: =item scantron_validate_CODE
 7181: 
 7182:    Validates all scanlines in the selected file to not have any
 7183:    invalid or underspecified CODEs and that none of the codes are
 7184:    duplicated if this was requested.
 7185: 
 7186: =cut
 7187: 
 7188: sub scantron_validate_CODE {
 7189:     my ($r,$currentphase) = @_;
 7190:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7191:     if ($scantron_config{'CODElocation'} &&
 7192: 	$scantron_config{'CODEstart'} &&
 7193: 	$scantron_config{'CODElength'}) {
 7194: 	if (!defined($env{'form.scantron_CODElist'})) {
 7195: 	    &FIXME_blow_up()
 7196: 	}
 7197:     } else {
 7198: 	return (0,$currentphase+1);
 7199:     }
 7200:     
 7201:     my %usedCODEs;
 7202: 
 7203:     my %allcodes=&get_codes();
 7204: 
 7205:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7206: 
 7207:     my ($scanlines,$scan_data)=&scantron_getfile();
 7208:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7209: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7210: 	if ($line=~/^[\s\cz]*$/) { next; }
 7211: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7212: 						 $scan_data);
 7213: 	my $CODE=$$scan_record{'scantron.CODE'};
 7214: 	my $error=0;
 7215: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7216: 	    &scantron_get_correction($r,$i,$scan_record,
 7217: 				     \%scantron_config,
 7218: 				     $line,'incorrectCODE',\%allcodes);
 7219: 	    return(1,$currentphase);
 7220: 	}
 7221: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7222: 	    && !$$scan_record{'scantron.useCODE'}) {
 7223: 	    &scantron_get_correction($r,$i,$scan_record,
 7224: 				     \%scantron_config,
 7225: 				     $line,'incorrectCODE',\%allcodes);
 7226: 	    return(1,$currentphase);
 7227: 	}
 7228: 	if (exists($usedCODEs{$CODE}) 
 7229: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7230: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7231: 	    &scantron_get_correction($r,$i,$scan_record,
 7232: 				     \%scantron_config,
 7233: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7234: 	    return(1,$currentphase);
 7235: 	}
 7236: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7237:     }
 7238:     return (0,$currentphase+1);
 7239: }
 7240: 
 7241: =pod
 7242: 
 7243: =item scantron_validate_doublebubble
 7244: 
 7245:    Validates all scanlines in the selected file to not have any
 7246:    bubble lines with multiple bubbles marked.
 7247: 
 7248: =cut
 7249: 
 7250: sub scantron_validate_doublebubble {
 7251:     my ($r,$currentphase) = @_;
 7252:     #get student info
 7253:     my $classlist=&Apache::loncoursedata::get_classlist();
 7254:     my %idmap=&username_to_idmap($classlist);
 7255: 
 7256:     #get scantron line setup
 7257:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7258:     my ($scanlines,$scan_data)=&scantron_getfile();
 7259:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7260: 
 7261:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7262: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7263: 	if ($line=~/^[\s\cz]*$/) { next; }
 7264: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7265: 						 $scan_data);
 7266: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7267: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7268: 				 'doublebubble',
 7269: 				 $$scan_record{'scantron.doubleerror'});
 7270:     	return (1,$currentphase);
 7271:     }
 7272:     return (0,$currentphase+1);
 7273: }
 7274: 
 7275: 
 7276: sub scantron_get_maxbubble {
 7277:     if (defined($env{'form.scantron_maxbubble'}) &&
 7278: 	$env{'form.scantron_maxbubble'}) {
 7279: 	&restore_bubble_lines();
 7280: 	return $env{'form.scantron_maxbubble'};
 7281:     }
 7282: 
 7283:     my (undef, undef, $sequence) =
 7284: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7285: 
 7286:     my $navmap=Apache::lonnavmaps::navmap->new();
 7287:     my $map=$navmap->getResourceByUrl($sequence);
 7288:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7289: 
 7290:     &Apache::lonxml::clear_problem_counter();
 7291: 
 7292:     my $uname       = $env{'user.name'};
 7293:     my $udom        = $env{'user.domain'};
 7294:     my $cid         = $env{'request.course.id'};
 7295:     my $total_lines = 0;
 7296:     %bubble_lines_per_response = ();
 7297:     %first_bubble_line         = ();
 7298:     %subdivided_bubble_lines   = ();
 7299:     %responsetype_per_response = ();
 7300: 
 7301:     my $response_number = 0;
 7302:     my $bubble_line     = 0;
 7303:     foreach my $resource (@resources) {
 7304:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7305:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7306: 	    foreach my $part_id (@{$parts}) {
 7307:                 my $lines;
 7308: 
 7309: 	        # TODO - make this a persistent hash not an array.
 7310: 
 7311:                 # optionresponse, matchresponse and rankresponse type items 
 7312:                 # render as separate sub-questions in exam mode.
 7313:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7314:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7315:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7316:                     my ($numbub,$numshown);
 7317:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7318:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7319:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7320:                         }
 7321:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7322:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7323:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7324:                         }
 7325:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7326:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7327:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7328:                         }
 7329:                     }
 7330:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7331:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7332:                     }
 7333:                     my $bubbles_per_line = 10;
 7334:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7335:                     if (($numbub % $bubbles_per_line) != 0) {
 7336:                         $inner_bubble_lines++;
 7337:                     }
 7338:                     for (my $i=0; $i<$numshown; $i++) {
 7339:                         $subdivided_bubble_lines{$response_number} .= 
 7340:                             $inner_bubble_lines.',';
 7341:                     }
 7342:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7343:                     $lines = $numshown * $inner_bubble_lines;
 7344:                 } else {
 7345:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7346:                 } 
 7347: 
 7348:                 $first_bubble_line{$response_number} = $bubble_line;
 7349: 	        $bubble_lines_per_response{$response_number} = $lines;
 7350:                 $responsetype_per_response{$response_number} = 
 7351:                     $analysis->{$part_id.'.type'};
 7352: 	        $response_number++;
 7353: 
 7354: 	        $bubble_line +=  $lines;
 7355: 	        $total_lines +=  $lines;
 7356: 	    }
 7357:         }
 7358:     }
 7359:     &Apache::lonnet::delenv('scantron.');
 7360: 
 7361:     &save_bubble_lines();
 7362:     $env{'form.scantron_maxbubble'} =
 7363: 	$total_lines;
 7364:     return $env{'form.scantron_maxbubble'};
 7365: }
 7366: 
 7367: sub scantron_validate_missingbubbles {
 7368:     my ($r,$currentphase) = @_;
 7369:     #get student info
 7370:     my $classlist=&Apache::loncoursedata::get_classlist();
 7371:     my %idmap=&username_to_idmap($classlist);
 7372: 
 7373:     #get scantron line setup
 7374:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7375:     my ($scanlines,$scan_data)=&scantron_getfile();
 7376:     my $max_bubble=&scantron_get_maxbubble();
 7377:     if (!$max_bubble) { $max_bubble=2**31; }
 7378:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7379: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7380: 	if ($line=~/^[\s\cz]*$/) { next; }
 7381: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7382: 						 $scan_data);
 7383: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7384: 	my @to_correct;
 7385: 	
 7386: 	# Probably here's where the error is...
 7387: 
 7388: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7389:             my $lastbubble;
 7390:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7391:                my $question = $1;
 7392:                my $subquestion = $2;
 7393:                if (!defined($first_bubble_line{$question -1})) { next; }
 7394:                my $first = $first_bubble_line{$question-1};
 7395:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7396:                my $subcount = 1;
 7397:                while ($subcount<$subquestion) {
 7398:                    $first += $subans[$subcount-1];
 7399:                    $subcount ++;
 7400:                }
 7401:                my $count = $subans[$subquestion-1];
 7402:                $lastbubble = $first + $count;
 7403:             } else {
 7404:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7405:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7406:             }
 7407:             if ($lastbubble > $max_bubble) { next; }
 7408: 	    push(@to_correct,$missing);
 7409: 	}
 7410: 	if (@to_correct) {
 7411: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7412: 				     $line,'missingbubble',\@to_correct);
 7413: 	    return (1,$currentphase);
 7414: 	}
 7415: 
 7416:     }
 7417:     return (0,$currentphase+1);
 7418: }
 7419: 
 7420: 
 7421: sub scantron_process_students {
 7422:     my ($r) = @_;
 7423: 
 7424:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7425:     my ($symb)=&get_symb($r);
 7426:     if (!$symb) {
 7427: 	return '';
 7428:     }
 7429:     my $default_form_data=&defaultFormData($symb);
 7430: 
 7431:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7432:     my ($scanlines,$scan_data)=&scantron_getfile();
 7433:     my $classlist=&Apache::loncoursedata::get_classlist();
 7434:     my %idmap=&username_to_idmap($classlist);
 7435:     my $navmap=Apache::lonnavmaps::navmap->new();
 7436:     my $map=$navmap->getResourceByUrl($sequence);
 7437:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7438:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7439:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7440:                             \%grader_randomlists_by_symb);
 7441:     foreach my $resource (@resources) {
 7442:         my $ressymb = $resource->symb();
 7443:         my ($analysis,$parts) =
 7444:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7445:                                       $env{'user.name'},$env{'user.domain'},1);
 7446:         $grader_partids_by_symb{$ressymb} = $parts;
 7447:         if (ref($analysis) eq 'HASH') {
 7448:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7449:                 $grader_randomlists_by_symb{$ressymb} = 
 7450:                     $analysis->{'parts_withrandomlist'};
 7451:             }
 7452:         }
 7453:     }
 7454: 
 7455:     my ($uname,$udom);
 7456:     my $result= <<SCANTRONFORM;
 7457: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7458:   <input type="hidden" name="command" value="scantron_configphase" />
 7459:   $default_form_data
 7460: SCANTRONFORM
 7461:     $r->print($result);
 7462: 
 7463:     my @delayqueue;
 7464:     my (%completedstudents,%scandata);
 7465:     
 7466:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7467:     my $count=&get_todo_count($scanlines,$scan_data);
 7468:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7469:  				    'Scantron Progress',$count,
 7470: 				    'inline',undef,'scantronupload');
 7471:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7472: 					  'Processing first student');
 7473:     $r->print('<br />');
 7474:     my $start=&Time::HiRes::time();
 7475:     my $i=-1;
 7476:     my $started;
 7477: 
 7478:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7479: 
 7480:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7481:     # the user and return.
 7482: 
 7483:     if ($ssi_error) {
 7484: 	$r->print("</form>");
 7485: 	&ssi_print_error($r);
 7486: 	$r->print(&show_grading_menu_form($symb));
 7487:         &Apache::lonnet::remove_lock($lock);
 7488: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7489:     }
 7490: 
 7491:     my %lettdig = &letter_to_digits();
 7492:     my $numletts = scalar(keys(%lettdig));
 7493: 
 7494:     while ($i<$scanlines->{'count'}) {
 7495:  	($uname,$udom)=('','');
 7496:  	$i++;
 7497:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7498:  	if ($line=~/^[\s\cz]*$/) { next; }
 7499: 	if ($started) {
 7500: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7501: 						     'last student');
 7502: 	}
 7503: 	$started=1;
 7504:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7505:  						 $scan_data);
 7506:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7507:  					      \%idmap,$i)) {
 7508:   	    &scantron_add_delay(\@delayqueue,$line,
 7509:  				'Unable to find a student that matches',1);
 7510:  	    next;
 7511:   	}
 7512:  	if (exists $completedstudents{$uname}) {
 7513:  	    &scantron_add_delay(\@delayqueue,$line,
 7514:  				'Student '.$uname.' has multiple sheets',2);
 7515:  	    next;
 7516:  	}
 7517:   	($uname,$udom)=split(/:/,$uname);
 7518: 
 7519:         my %partids_by_symb;
 7520:         foreach my $resource (@resources) {
 7521:             my $ressymb = $resource->symb();
 7522:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7523:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7524:                 my ($analysis,$parts) =
 7525:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7526:                 $partids_by_symb{$ressymb} = $parts;
 7527:             } else {
 7528:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7529:             }
 7530:         }
 7531: 
 7532: 	&Apache::lonxml::clear_problem_counter();
 7533:   	&Apache::lonnet::appenv($scan_record);
 7534: 
 7535: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7536: 	    &scantron_putfile($scanlines,$scan_data);
 7537: 	}
 7538: 	
 7539:         my $scancode;
 7540:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7541:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7542:             $scancode = $scan_record->{'scantron.CODE'};
 7543:         } else {
 7544:             $scancode = '';
 7545:         }
 7546: 
 7547:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7548:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7549:             $ssi_error = 0; # So end of handler error message does not trigger.
 7550:             $r->print("</form>");
 7551:             &ssi_print_error($r);
 7552:             $r->print(&show_grading_menu_form($symb));
 7553:             &Apache::lonnet::remove_lock($lock);
 7554:             return '';      # Why return ''?  Beats me.
 7555:         }
 7556: 
 7557: 	$completedstudents{$uname}={'line'=>$line};
 7558:         if ($env{'form.verifyrecord'}) {
 7559:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7560:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7561:             chomp($studentdata);
 7562:             $studentdata =~ s/\r$//;
 7563:             my $studentrecord = '';
 7564:             my $counter = -1;
 7565:             foreach my $resource (@resources) {
 7566:                 my $ressymb = $resource->symb();
 7567:                 ($counter,my $recording) =
 7568:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7569:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7570:                                              \%scantron_config,\%lettdig,$numletts);
 7571:                 $studentrecord .= $recording;
 7572:             }
 7573:             if ($studentrecord ne $studentdata) {
 7574:                 &Apache::lonxml::clear_problem_counter();
 7575:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7576:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7577:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7578:                     $r->print("</form>");
 7579:                     &ssi_print_error($r);
 7580:                     $r->print(&show_grading_menu_form($symb));
 7581:                     &Apache::lonnet::remove_lock($lock);
 7582:                     delete($completedstudents{$uname});
 7583:                     return '';
 7584:                 }
 7585:                 $counter = -1;
 7586:                 $studentrecord = '';
 7587:                 foreach my $resource (@resources) {
 7588:                     my $ressymb = $resource->symb();
 7589:                     ($counter,my $recording) =
 7590:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7591:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7592:                                                  \%scantron_config,\%lettdig,$numletts);
 7593:                     $studentrecord .= $recording;
 7594:                 }
 7595:                 if ($studentrecord ne $studentdata) {
 7596:                     $r->print('<p><span class="LC_error">');
 7597:                     if ($scancode eq '') {
 7598:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7599:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7600:                     } else {
 7601:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7602:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7603:                     }
 7604:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7605:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7606:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7607:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7608:                               &Apache::loncommon::start_data_table_row().
 7609:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7610:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7611:                               &Apache::loncommon::end_data_table_row().
 7612:                               &Apache::loncommon::start_data_table_row().
 7613:                               '<td>Stored submissions</td>'.
 7614:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7615:                               &Apache::loncommon::end_data_table_row().
 7616:                               &Apache::loncommon::end_data_table().'</p>');
 7617:                 } else {
 7618:                     $r->print('<br /><span class="LC_warning">'.
 7619:                              &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 />'.
 7620:                              &mt("As a consequence, this user's submission history records two tries.").
 7621:                                  '</span><br />');
 7622:                 }
 7623:             }
 7624:         }
 7625:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7626:     } continue {
 7627: 	&Apache::lonxml::clear_problem_counter();
 7628: 	&Apache::lonnet::delenv('scantron.');
 7629:     }
 7630:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7631:     &Apache::lonnet::remove_lock($lock);
 7632: #    my $lasttime = &Time::HiRes::time()-$start;
 7633: #    $r->print("<p>took $lasttime</p>");
 7634: 
 7635:     $r->print("</form>");
 7636:     $r->print(&show_grading_menu_form($symb));
 7637:     return '';
 7638: }
 7639: 
 7640: sub graders_resources_pass {
 7641:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7642:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7643:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7644:         foreach my $resource (@{$resources}) {
 7645:             my $ressymb = $resource->symb();
 7646:             my ($analysis,$parts) =
 7647:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7648:                                           $env{'user.name'},$env{'user.domain'},1);
 7649:             $grader_partids_by_symb->{$ressymb} = $parts;
 7650:             if (ref($analysis) eq 'HASH') {
 7651:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7652:                     $grader_randomlists_by_symb->{$ressymb} =
 7653:                         $analysis->{'parts_withrandomlist'};
 7654:                 }
 7655:             }
 7656:         }
 7657:     }
 7658:     return;
 7659: }
 7660: 
 7661: sub grade_student_bubbles {
 7662:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7663:     if (ref($resources) eq 'ARRAY') {
 7664:         my $count = 0;
 7665:         foreach my $resource (@{$resources}) {
 7666:             my $ressymb = $resource->symb();
 7667:             my %form = ('submitted'      => 'scantron',
 7668:                         'grade_target'   => 'grade',
 7669:                         'grade_username' => $uname,
 7670:                         'grade_domain'   => $udom,
 7671:                         'grade_courseid' => $env{'request.course.id'},
 7672:                         'grade_symb'     => $ressymb,
 7673:                         'CODE'           => $scancode
 7674:                        );
 7675:             if (ref($parts) eq 'HASH') {
 7676:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7677:                     foreach my $part (@{$parts->{$ressymb}}) {
 7678:                         $form{'scantron_questnum_start.'.$part} =
 7679:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7680:                         $count++;
 7681:                     }
 7682:                 }
 7683:             }
 7684:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7685:             return 'ssi_error' if ($ssi_error);
 7686:             last if (&Apache::loncommon::connection_aborted($r));
 7687:         }
 7688:     }
 7689:     return;
 7690: }
 7691: 
 7692: sub scantron_upload_scantron_data {
 7693:     my ($r)=@_;
 7694:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7695:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7696: 							  'domainid',
 7697: 							  'coursename');
 7698:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7699: 						   'domainid');
 7700:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7701:     $r->print('
 7702: <script type="text/javascript" language="javascript">
 7703:     function checkUpload(formname) {
 7704: 	if (formname.upfile.value == "") {
 7705: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 7706: 	    return false;
 7707: 	}
 7708: 	formname.submit();
 7709:     }
 7710: </script>
 7711: 
 7712: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7713: '.$default_form_data.'
 7714: <table>
 7715: <tr><td>'.$select_link.'                             </td></tr>
 7716: <tr><td>'.&mt('Course ID:').'     </td>
 7717:     <td><input name="courseid"   type="text" />      </td></tr>
 7718: <tr><td>'.&mt('Course Name:').'   </td>
 7719:     <td><input name="coursename" type="text" />      </td></tr>
 7720: <tr><td>'.&mt('Domain:').'        </td>
 7721:     <td>'.$domsel.'                                  </td></tr>
 7722: <tr><td>'.&mt('File to upload:').'</td>
 7723:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7724: </table>
 7725: <input name="command" value="scantronupload_save" type="hidden" />
 7726: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7727: </form>
 7728: ');
 7729:     return '';
 7730: }
 7731: 
 7732: 
 7733: sub scantron_upload_scantron_data_save {
 7734:     my($r)=@_;
 7735:     my ($symb)=&get_symb($r,1);
 7736:     my $doanotherupload=
 7737: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7738: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7739: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7740: 	'</form>'."\n";
 7741:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7742: 	!&Apache::lonnet::allowed('usc',
 7743: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7744: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7745: 	if ($symb) {
 7746: 	    $r->print(&show_grading_menu_form($symb));
 7747: 	} else {
 7748: 	    $r->print($doanotherupload);
 7749: 	}
 7750: 	return '';
 7751:     }
 7752:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7753:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7754:     my $fname=$env{'form.upfile.filename'};
 7755:     #FIXME
 7756:     #copied from lonnet::userfileupload()
 7757:     #make that function able to target a specified course
 7758:     # Replace Windows backslashes by forward slashes
 7759:     $fname=~s/\\/\//g;
 7760:     # Get rid of everything but the actual filename
 7761:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7762:     # Replace spaces by underscores
 7763:     $fname=~s/\s+/\_/g;
 7764:     # Replace all other weird characters by nothing
 7765:     $fname=~s/[^\w\.\-]//g;
 7766:     # See if there is anything left
 7767:     unless ($fname) { return 'error: no uploaded file'; }
 7768:     my $uploadedfile=$fname;
 7769:     $fname='scantron_orig_'.$fname;
 7770:     if (length($env{'form.upfile'}) < 2) {
 7771: 	$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>"));
 7772:     } else {
 7773: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7774: 	if ($result =~ m|^/uploaded/|) {
 7775: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7776: 			  (length($env{'form.upfile'})-1),
 7777: 			  '<span class="LC_filename">'.$result."</span>"));
 7778: 	} else {
 7779: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7780: 			  $result,
 7781: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7782: 
 7783: 	}
 7784:     }
 7785:     if ($symb) {
 7786: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7787:     } else {
 7788: 	$r->print($doanotherupload);
 7789:     }
 7790:     return '';
 7791: }
 7792: 
 7793: sub valid_file {
 7794:     my ($requested_file)=@_;
 7795:     foreach my $filename (sort(&scantron_filenames())) {
 7796: 	if ($requested_file eq $filename) { return 1; }
 7797:     }
 7798:     return 0;
 7799: }
 7800: 
 7801: sub scantron_download_scantron_data {
 7802:     my ($r)=@_;
 7803:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7804:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7805:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7806:     my $file=$env{'form.scantron_selectfile'};
 7807:     if (! &valid_file($file)) {
 7808: 	$r->print('
 7809: 	<p>
 7810: 	    '.&mt('The requested file name was invalid.').'
 7811:         </p>
 7812: ');
 7813: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7814: 	return;
 7815:     }
 7816:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7817:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7818:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7819:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7820:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7821:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7822:     $r->print('
 7823:     <p>
 7824: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7825: 	      '<a href="'.$orig.'">','</a>').'
 7826:     </p>
 7827:     <p>
 7828: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7829: 	      '<a href="'.$corrected.'">','</a>').'
 7830:     </p>
 7831:     <p>
 7832: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7833: 	      '<a href="'.$skipped.'">','</a>').'
 7834:     </p>
 7835: ');
 7836:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7837:     return '';
 7838: }
 7839: 
 7840: sub checkscantron_results {
 7841:     my ($r) = @_;
 7842:     my ($symb)=&get_symb($r);
 7843:     if (!$symb) {return '';}
 7844:     my $grading_menu_button=&show_grading_menu_form($symb);
 7845:     my $cid = $env{'request.course.id'};
 7846:     my %lettdig = &letter_to_digits();
 7847:     my $numletts = scalar(keys(%lettdig));
 7848:     my $cnum = $env{'course.'.$cid.'.num'};
 7849:     my $cdom = $env{'course.'.$cid.'.domain'};
 7850:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7851:     my %record;
 7852:     my %scantron_config =
 7853:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7854:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7855:     my $classlist=&Apache::loncoursedata::get_classlist();
 7856:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7857:     my $navmap=Apache::lonnavmaps::navmap->new();
 7858:     my $map=$navmap->getResourceByUrl($sequence);
 7859:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7860:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7861:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 7862: 
 7863:     my ($uname,$udom);
 7864:     my (%scandata,%lastname,%bylast);
 7865:     $r->print('
 7866: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7867: 
 7868:     my @delayqueue;
 7869:     my %completedstudents;
 7870: 
 7871:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7872:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7873:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7874:                                     'inline',undef,'checkscantron');
 7875:     my ($username,$domain,$started);
 7876: 
 7877:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7878: 
 7879:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7880:                                           'Processing first student');
 7881:     my $start=&Time::HiRes::time();
 7882:     my $i=-1;
 7883: 
 7884:     while ($i<$scanlines->{'count'}) {
 7885:         ($username,$domain,$uname)=('','','');
 7886:         $i++;
 7887:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7888:         if ($line=~/^[\s\cz]*$/) { next; }
 7889:         if ($started) {
 7890:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7891:                                                      'last student');
 7892:         }
 7893:         $started=1;
 7894:         my $scan_record=
 7895:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7896:                                                      $scan_data);
 7897:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7898:                                                               \%idmap,$i)) {
 7899:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7900:                                 'Unable to find a student that matches',1);
 7901:             next;
 7902:         }
 7903:         if (exists $completedstudents{$uname}) {
 7904:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7905:                                 'Student '.$uname.' has multiple sheets',2);
 7906:             next;
 7907:         }
 7908:         my $pid = $scan_record->{'scantron.ID'};
 7909:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7910:         push(@{$bylast{$lastname{$pid}}},$pid);
 7911:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7912:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7913:         chomp($scandata{$pid});
 7914:         $scandata{$pid} =~ s/\r$//;
 7915:         ($username,$domain)=split(/:/,$uname);
 7916:         my $counter = -1;
 7917:         foreach my $resource (@resources) {
 7918:             my $parts;
 7919:             my $ressymb = $resource->symb();
 7920:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7921:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7922:                 (my $analysis,$parts) =
 7923:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 7924:             } else {
 7925:                 $parts = $grader_partids_by_symb{$ressymb};
 7926:             }
 7927:             ($counter,my $recording) =
 7928:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7929:                                          $scandata{$pid},$parts,
 7930:                                          \%scantron_config,\%lettdig,$numletts);
 7931:             $record{$pid} .= $recording;
 7932:         }
 7933:     }
 7934:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7935:     $r->print('<br />');
 7936:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 7937:     $passed = 0;
 7938:     $failed = 0;
 7939:     $numstudents = 0;
 7940:     foreach my $last (sort(keys(%bylast))) {
 7941:         if (ref($bylast{$last}) eq 'ARRAY') {
 7942:             foreach my $pid (sort(@{$bylast{$last}})) {
 7943:                 my $showscandata = $scandata{$pid};
 7944:                 my $showrecord = $record{$pid};
 7945:                 $showscandata =~ s/\s/&nbsp;/g;
 7946:                 $showrecord =~ s/\s/&nbsp;/g;
 7947:                 if ($scandata{$pid} eq $record{$pid}) {
 7948:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 7949:                     $okstudents .= '<tr class="'.$css_class.'">'.
 7950: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7951: '</tr>'."\n".
 7952: '<tr class="'.$css_class.'">'."\n".
 7953: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 7954:                     $passed ++;
 7955:                 } else {
 7956:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 7957:                     $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".
 7958: '</tr>'."\n".
 7959: '<tr class="'.$css_class.'">'."\n".
 7960: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 7961: '</tr>'."\n";
 7962:                     $failed ++;
 7963:                 }
 7964:                 $numstudents ++;
 7965:             }
 7966:         }
 7967:     }
 7968:     $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>');
 7969:     $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>');
 7970:     if ($passed) {
 7971:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 7972:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7973:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7974:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7975:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7976:                  $okstudents."\n".
 7977:                  &Apache::loncommon::end_data_table().'<br />');
 7978:     }
 7979:     if ($failed) {
 7980:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 7981:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7982:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7983:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7984:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7985:                  $badstudents."\n".
 7986:                  &Apache::loncommon::end_data_table()).'<br />'.
 7987:                  &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.');  
 7988:     }
 7989:     $r->print('</form><br />'.$grading_menu_button);
 7990:     return;
 7991: }
 7992: 
 7993: sub verify_scantron_grading {
 7994:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 7995:         $scantron_config,$lettdig,$numletts) = @_;
 7996:     my ($record,%expected,%startpos);
 7997:     return ($counter,$record) if (!ref($resource));
 7998:     return ($counter,$record) if (!$resource->is_problem());
 7999:     my $symb = $resource->symb();
 8000:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8001:     foreach my $part_id (@{$partids}) {
 8002:         $counter ++;
 8003:         $expected{$part_id} = 0;
 8004:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8005:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8006:             foreach my $item (@sub_lines) {
 8007:                 $expected{$part_id} += $item;
 8008:             }
 8009:         } else {
 8010:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8011:         }
 8012:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8013:     }
 8014:     if ($symb) {
 8015:         my %recorded;
 8016:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8017:         if ($returnhash{'version'}) {
 8018:             my %lasthash=();
 8019:             my $version;
 8020:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8021:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8022:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8023:                 }
 8024:             }
 8025:             foreach my $key (keys(%lasthash)) {
 8026:                 if ($key =~ /\.scantron$/) {
 8027:                     my $value = &unescape($lasthash{$key});
 8028:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8029:                     if ($value eq '') {
 8030:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8031:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8032:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8033:                             }
 8034:                         }
 8035:                     } else {
 8036:                         my @tocheck;
 8037:                         my @items = split(//,$value);
 8038:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8039:                             ($scantron_config->{'Qon'} eq 'number')) {
 8040:                             if (@items < $expected{$part_id}) {
 8041:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8042:                                 my @singles = split(//,$fragment);
 8043:                                 foreach my $pos (@singles) {
 8044:                                     if ($pos eq ' ') {
 8045:                                         push(@tocheck,$pos);
 8046:                                     } else {
 8047:                                         my $next = shift(@items);
 8048:                                         push(@tocheck,$next);
 8049:                                     }
 8050:                                 }
 8051:                             } else {
 8052:                                 @tocheck = @items;
 8053:                             }
 8054:                             foreach my $letter (@tocheck) {
 8055:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8056:                                     if ($letter !~ /^[A-J]$/) {
 8057:                                         $letter = $scantron_config->{'Qoff'};
 8058:                                     }
 8059:                                     $recorded{$part_id} .= $letter;
 8060:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8061:                                     my $digit;
 8062:                                     if ($letter !~ /^[A-J]$/) {
 8063:                                         $digit = $scantron_config->{'Qoff'};
 8064:                                     } else {
 8065:                                         $digit = $lettdig->{$letter};
 8066:                                     }
 8067:                                     $recorded{$part_id} .= $digit;
 8068:                                 }
 8069:                             }
 8070:                         } else {
 8071:                             @tocheck = @items;
 8072:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8073:                                 my $curr_sub = shift(@tocheck);
 8074:                                 my $digit;
 8075:                                 if ($curr_sub =~ /^[A-J]$/) {
 8076:                                     $digit = $lettdig->{$curr_sub}-1;
 8077:                                 }
 8078:                                 if ($curr_sub eq 'J') {
 8079:                                     $digit += scalar($numletts);
 8080:                                 }
 8081:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8082:                                     if ($j == $digit) {
 8083:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8084:                                     } else {
 8085:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8086:                                     }
 8087:                                 }
 8088:                             }
 8089:                         }
 8090:                     }
 8091:                 }
 8092:             }
 8093:         }
 8094:         foreach my $part_id (@{$partids}) {
 8095:             if ($recorded{$part_id} eq '') {
 8096:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8097:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8098:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8099:                     }
 8100:                 }
 8101:             }
 8102:             $record .= $recorded{$part_id};
 8103:         }
 8104:     }
 8105:     return ($counter,$record);
 8106: }
 8107: 
 8108: sub letter_to_digits { 
 8109:     my %lettdig = (
 8110:                     A => 1,
 8111:                     B => 2,
 8112:                     C => 3,
 8113:                     D => 4,
 8114:                     E => 5,
 8115:                     F => 6,
 8116:                     G => 7,
 8117:                     H => 8,
 8118:                     I => 9,
 8119:                     J => 0,
 8120:                   );
 8121:     return %lettdig;
 8122: }
 8123: 
 8124: 
 8125: #-------- end of section for handling grading scantron forms -------
 8126: #
 8127: #-------------------------------------------------------------------
 8128: 
 8129: #-------------------------- Menu interface -------------------------
 8130: #
 8131: #--- Show a Grading Menu button - Calls the next routine ---
 8132: sub show_grading_menu_form {
 8133:     my ($symb)=@_;
 8134:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8135: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8136: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8137: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8138: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8139: 	'</form>'."\n";
 8140:     return $result;
 8141: }
 8142: 
 8143: # -- Retrieve choices for grading form
 8144: sub savedState {
 8145:     my %savedState = ();
 8146:     if ($env{'form.saveState'}) {
 8147: 	foreach (split(/:/,$env{'form.saveState'})) {
 8148: 	    my ($key,$value) = split(/=/,$_,2);
 8149: 	    $savedState{$key} = $value;
 8150: 	}
 8151:     }
 8152:     return \%savedState;
 8153: }
 8154: 
 8155: sub grading_menu {
 8156:     my ($request) = @_;
 8157:     my ($symb)=&get_symb($request);
 8158:     if (!$symb) {return '';}
 8159:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8160:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8161: 
 8162:     $request->print($table);
 8163:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8164:                   'handgrade'=>$hdgrade,
 8165:                   'probTitle'=>$probTitle,
 8166:                   'command'=>'submit_options',
 8167:                   'saveState'=>"",
 8168:                   'gradingMenu'=>1,
 8169:                   'showgrading'=>"yes");
 8170:     
 8171:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8172:     
 8173:     $fields{'command'} = 'csvform';
 8174:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8175:     
 8176:     $fields{'command'} = 'processclicker';
 8177:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8178:     
 8179:     $fields{'command'} = 'scantron_selectphase';
 8180:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8181:     
 8182:     my @menu = ({	categorytitle=>'Course Grading',
 8183:             items =>[
 8184:                         {	linktext => 'Manual Grading/View Submissions',
 8185:                     		url => $url1,
 8186:                     		permission => 'F',
 8187:                     		icon => 'edit-find-replace.png',
 8188:                     		linktitle => 'Start the process of hand grading submissions.'
 8189:                         },
 8190:                 	    {	linktext => 'Upload Scores',
 8191:                     		url => $url2,
 8192:                     		permission => 'F',
 8193:                     		icon => 'uploadscores.png',
 8194:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8195:                 	    },
 8196:                 	    {	linktext => 'Process Clicker',
 8197:                     		url => $url3,
 8198:                     		permission => 'F',
 8199:                     		icon => 'addClickerInfoFile.png',
 8200:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8201:                 	    },
 8202:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
 8203:                     		url => $url4,
 8204:                     		permission => 'F',
 8205:                     		icon => 'stat.png',
 8206:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8207:                 	    }
 8208:                     ]
 8209:             });
 8210: 
 8211:     #$fields{'command'} = 'verify';
 8212:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8213:     #
 8214:     # Create the menu
 8215:     my $Str;
 8216:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8217:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8218:     $Str .= '<input type="hidden" name="command" value="" />'.
 8219:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8220: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8221: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8222: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8223: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8224: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8225: 
 8226:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8227:     #$menudata->{'jscript'}
 8228:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8229:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8230:         ' /> '.
 8231:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8232:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8233: 
 8234:     $Str .="</form>\n";
 8235:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8236:     $request->print(<<GRADINGMENUJS);
 8237: <script type="text/javascript" language="javascript">
 8238:     function checkChoice(formname,val,cmdx) {
 8239: 	if (val <= 2) {
 8240: 	    var cmd = radioSelection(formname.radioChoice);
 8241: 	    var cmdsave = cmd;
 8242: 	} else {
 8243: 	    cmd = cmdx;
 8244: 	    cmdsave = 'submission';
 8245: 	}
 8246: 	formname.command.value = cmd;
 8247: 	if (val < 5) formname.submit();
 8248: 	if (val == 5) {
 8249: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8250: 	        return false;
 8251: 	    } else {
 8252: 	        formname.submit();
 8253: 	    }
 8254: 	}
 8255:     }
 8256: 
 8257:     function checkReceiptNo(formname,nospace) {
 8258: 	var receiptNo = formname.receipt.value;
 8259: 	var checkOpt = false;
 8260: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8261: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8262: 	if (checkOpt) {
 8263: 	    alert("$receiptalert");
 8264: 	    formname.receipt.value = "";
 8265: 	    formname.receipt.focus();
 8266: 	    return false;
 8267: 	}
 8268: 	return true;
 8269:     }
 8270: </script>
 8271: GRADINGMENUJS
 8272:     &commonJSfunctions($request);
 8273:     return $Str;    
 8274: }
 8275: 
 8276: 
 8277: #--- Displays the submissions first page -------
 8278: sub submit_options {
 8279:     my ($request) = @_;
 8280:     my ($symb)=&get_symb($request);
 8281:     if (!$symb) {return '';}
 8282:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8283: 
 8284:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8285:     $request->print(<<GRADINGMENUJS);
 8286: <script type="text/javascript" language="javascript">
 8287:     function checkChoice(formname,val,cmdx) {
 8288: 	if (val <= 2) {
 8289: 	    var cmd = radioSelection(formname.radioChoice);
 8290: 	    var cmdsave = cmd;
 8291: 	} else {
 8292: 	    cmd = cmdx;
 8293: 	    cmdsave = 'submission';
 8294: 	}
 8295: 	formname.command.value = cmd;
 8296: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8297: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8298: 	if (val < 5) formname.submit();
 8299: 	if (val == 5) {
 8300: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8301: 	    formname.submit();
 8302: 	}
 8303: 	if (val < 7) formname.submit();
 8304:     }
 8305: 
 8306:     function checkReceiptNo(formname,nospace) {
 8307: 	var receiptNo = formname.receipt.value;
 8308: 	var checkOpt = false;
 8309: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8310: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8311: 	if (checkOpt) {
 8312: 	    alert("$receiptalert");
 8313: 	    formname.receipt.value = "";
 8314: 	    formname.receipt.focus();
 8315: 	    return false;
 8316: 	}
 8317: 	return true;
 8318:     }
 8319: </script>
 8320: GRADINGMENUJS
 8321:     &commonJSfunctions($request);
 8322:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8323:     my $result;
 8324:     my (undef,$sections) = &getclasslist('all','0');
 8325:     my $savedState = &savedState();
 8326:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8327:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8328:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8329:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8330: 
 8331:     # Preselect sections
 8332:     my $selsec="";
 8333:     if (ref($sections)) {
 8334:         foreach my $section (sort(@$sections)) {
 8335:             $selsec.='<option value="'.$section.'" '.
 8336:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8337:         }
 8338:     }
 8339: 
 8340:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8341: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8342: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8343: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8344: 	'<input type="hidden" name="command"     value="" />'."\n".
 8345: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8346: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8347: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8348: 
 8349:     $result.='
 8350: <h2>
 8351:   '.&mt('Grade Current Resource').'
 8352: </h2>
 8353: <div>
 8354:   '.$table.'
 8355: </div>
 8356: 
 8357: <div class="LC_columnSection">
 8358:   
 8359:     <fieldset>
 8360:       <legend>
 8361:        '.&mt('Sections').'
 8362:       </legend>
 8363:       <select name="section" multiple="multiple" size="5">'."\n";
 8364:     $result.= $selsec;
 8365:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8366:     $result.='
 8367:     </fieldset>
 8368:   
 8369:     <fieldset>
 8370:       <legend>
 8371:         '.&mt('Groups').'
 8372:       </legend>
 8373:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8374:     </fieldset>
 8375:   
 8376:     <fieldset>
 8377:       <legend>
 8378:         '.&mt('Access Status').'
 8379:       </legend>
 8380:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8381:     </fieldset>
 8382:   
 8383:     <fieldset>
 8384:       <legend>
 8385:         '.&mt('Submission Status').'
 8386:       </legend>
 8387:       <select name="submitonly" size="5">
 8388: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8389: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8390: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8391: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8392:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8393:       </select>
 8394:     </fieldset>
 8395:   
 8396: </div>
 8397: 
 8398: <br />
 8399:           <div>
 8400:             <div>
 8401:               <label>
 8402:                 <input type="radio" name="radioChoice" value="submission" '.
 8403:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8404:              &mt('Select individual students to grade and view submissions.').'
 8405: 	      </label> 
 8406:             </div>
 8407:             <div>
 8408: 	      <label>
 8409:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8410:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8411:                     &mt('Grade all selected students in a grading table.').'
 8412:               </label>
 8413:             </div>
 8414:             <div>
 8415: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8416:             </div>
 8417:           </div>
 8418: 
 8419: 
 8420:         <h2>
 8421:          '.&mt('Grade Complete Folder for One Student').'
 8422:         </h2>
 8423:         <div>
 8424:             <div>
 8425:               <label>
 8426:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8427: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8428:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8429:               </label>
 8430:             </div>
 8431:             <div>
 8432: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8433:             </div>
 8434:         </div>
 8435:   </form>';
 8436:     $result .= &show_grading_menu_form($symb);
 8437:     return $result;
 8438: }
 8439: 
 8440: sub reset_perm {
 8441:     undef(%perm);
 8442: }
 8443: 
 8444: sub init_perm {
 8445:     &reset_perm();
 8446:     foreach my $test_perm ('vgr','mgr','opa') {
 8447: 
 8448: 	my $scope = $env{'request.course.id'};
 8449: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8450: 
 8451: 	    $scope .= '/'.$env{'request.course.sec'};
 8452: 	    if ( $perm{$test_perm}=
 8453: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8454: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8455: 	    } else {
 8456: 		delete($perm{$test_perm});
 8457: 	    }
 8458: 	}
 8459:     }
 8460: }
 8461: 
 8462: sub gather_clicker_ids {
 8463:     my %clicker_ids;
 8464: 
 8465:     my $classlist = &Apache::loncoursedata::get_classlist();
 8466: 
 8467:     # Set up a couple variables.
 8468:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8469:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8470:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8471: 
 8472:     foreach my $student (keys(%$classlist)) {
 8473:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8474:         my $username = $classlist->{$student}->[$username_idx];
 8475:         my $domain   = $classlist->{$student}->[$domain_idx];
 8476:         my $clickers =
 8477: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8478:         foreach my $id (split(/\,/,$clickers)) {
 8479:             $id=~s/^[\#0]+//;
 8480:             $id=~s/[\-\:]//g;
 8481:             if (exists($clicker_ids{$id})) {
 8482: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8483:             } else {
 8484: 		$clicker_ids{$id}=$username.':'.$domain;
 8485:             }
 8486:         }
 8487:     }
 8488:     return %clicker_ids;
 8489: }
 8490: 
 8491: sub gather_adv_clicker_ids {
 8492:     my %clicker_ids;
 8493:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8494:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8495:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8496:     foreach my $element (sort(keys(%coursepersonnel))) {
 8497:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8498:             my ($puname,$pudom)=split(/\:/,$person);
 8499:             my $clickers =
 8500: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8501:             foreach my $id (split(/\,/,$clickers)) {
 8502: 		$id=~s/^[\#0]+//;
 8503:                 $id=~s/[\-\:]//g;
 8504: 		if (exists($clicker_ids{$id})) {
 8505: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8506: 		} else {
 8507: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8508: 		}
 8509:             }
 8510:         }
 8511:     }
 8512:     return %clicker_ids;
 8513: }
 8514: 
 8515: sub clicker_grading_parameters {
 8516:     return ('gradingmechanism' => 'scalar',
 8517:             'upfiletype' => 'scalar',
 8518:             'specificid' => 'scalar',
 8519:             'pcorrect' => 'scalar',
 8520:             'pincorrect' => 'scalar');
 8521: }
 8522: 
 8523: sub process_clicker {
 8524:     my ($r)=@_;
 8525:     my ($symb)=&get_symb($r);
 8526:     if (!$symb) {return '';}
 8527:     my $result=&checkforfile_js();
 8528:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8529:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8530:     $result.=$table;
 8531:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8532:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8533:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8534:         '</b></td></tr>'."\n";
 8535:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8536: # Attempt to restore parameters from last session, set defaults if not present
 8537:     my %Saveable_Parameters=&clicker_grading_parameters();
 8538:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8539:                                                  \%Saveable_Parameters);
 8540:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8541:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8542:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8543:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8544: 
 8545:     my %checked;
 8546:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8547:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8548:           $checked{$gradingmechanism}="checked='checked'";
 8549:        }
 8550:     }
 8551: 
 8552:     my $upload=&mt("Upload File");
 8553:     my $type=&mt("Type");
 8554:     my $attendance=&mt("Award points just for participation");
 8555:     my $personnel=&mt("Correctness determined from response by course personnel");
 8556:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8557:     my $given=&mt("Correctness determined from given list of answers").' '.
 8558:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8559:     my $pcorrect=&mt("Percentage points for correct solution");
 8560:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8561:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8562: 						   ('iclicker' => 'i>clicker',
 8563:                                                     'interwrite' => 'interwrite PRS'));
 8564:     $symb = &Apache::lonenc::check_encrypt($symb);
 8565:     $result.=<<ENDUPFORM;
 8566: <script type="text/javascript">
 8567: function sanitycheck() {
 8568: // Accept only integer percentages
 8569:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8570:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8571: // Find out grading choice
 8572:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8573:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8574:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8575:       }
 8576:    }
 8577: // By default, new choice equals user selection
 8578:    newgradingchoice=gradingchoice;
 8579: // Not good to give more points for false answers than correct ones
 8580:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8581:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8582:    }
 8583: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8584:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8585:       document.forms.gradesupload.pcorrect.value=100;
 8586:       document.forms.gradesupload.pincorrect.value=100;
 8587:    }
 8588: // If the values are different, cannot be attendance only
 8589:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8590:        (gradingchoice=='attendance')) {
 8591:        newgradingchoice='personnel';
 8592:    }
 8593: // Change grading choice to new one
 8594:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8595:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8596:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8597:       } else {
 8598:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8599:       }
 8600:    }
 8601: // Remember the old state
 8602:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8603: }
 8604: </script>
 8605: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8606: <input type="hidden" name="symb" value="$symb" />
 8607: <input type="hidden" name="command" value="processclickerfile" />
 8608: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8609: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8610: <input type="file" name="upfile" size="50" />
 8611: <br /><label>$type: $selectform</label>
 8612: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8613: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8614: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8615: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8616: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8617: <br />&nbsp;&nbsp;&nbsp;
 8618: <input type="text" name="givenanswer" size="50" />
 8619: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8620: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8621: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8622: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8623: </form>
 8624: ENDUPFORM
 8625:     $result.='</td></tr></table>'."\n".
 8626:              '</td></tr></table><br /><br />'."\n";
 8627:     $result.=&show_grading_menu_form($symb);
 8628:     return $result;
 8629: }
 8630: 
 8631: sub process_clicker_file {
 8632:     my ($r)=@_;
 8633:     my ($symb)=&get_symb($r);
 8634:     if (!$symb) {return '';}
 8635: 
 8636:     my %Saveable_Parameters=&clicker_grading_parameters();
 8637:     &Apache::loncommon::store_course_settings('grades_clicker',
 8638:                                               \%Saveable_Parameters);
 8639: 
 8640:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8641:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8642: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8643: 	return $result.&show_grading_menu_form($symb);
 8644:     }
 8645:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8646:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8647:         return $result.&show_grading_menu_form($symb);
 8648:     }
 8649:     my $foundgiven=0;
 8650:     if ($env{'form.gradingmechanism'} eq 'given') {
 8651:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8652:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8653:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8654:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8655:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8656:         $foundgiven=$#answers+1;
 8657:     }
 8658:     my %clicker_ids=&gather_clicker_ids();
 8659:     my %correct_ids;
 8660:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8661: 	%correct_ids=&gather_adv_clicker_ids();
 8662:     }
 8663:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8664: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8665: 	   $correct_id=~tr/a-z/A-Z/;
 8666: 	   $correct_id=~s/\s//gs;
 8667: 	   $correct_id=~s/^[\#0]+//;
 8668:            $correct_id=~s/[\-\:]//g;
 8669:            if ($correct_id) {
 8670: 	      $correct_ids{$correct_id}='specified';
 8671:            }
 8672:         }
 8673:     }
 8674:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8675: 	$result.=&mt('Score based on attendance only');
 8676:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8677:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8678:     } else {
 8679: 	my $number=0;
 8680: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8681: 	foreach my $id (sort(keys(%correct_ids))) {
 8682: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8683: 	    if ($correct_ids{$id} eq 'specified') {
 8684: 		$result.=&mt('specified');
 8685: 	    } else {
 8686: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8687: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8688: 	    }
 8689: 	    $number++;
 8690: 	}
 8691:         $result.="</p>\n";
 8692: 	if ($number==0) {
 8693: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8694: 	    return $result.&show_grading_menu_form($symb);
 8695: 	}
 8696:     }
 8697:     if (length($env{'form.upfile'}) < 2) {
 8698:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8699: 		     '<span class="LC_error">',
 8700: 		     '</span>',
 8701: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8702:         return $result.&show_grading_menu_form($symb);
 8703:     }
 8704: 
 8705: # Were able to get all the info needed, now analyze the file
 8706: 
 8707:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8708:     $symb = &Apache::lonenc::check_encrypt($symb);
 8709:     my $heading=&mt('Scanning clicker file');
 8710:     $result.=(<<ENDHEADER);
 8711: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8712: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8713: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8714: <form method="post" action="/adm/grades" name="clickeranalysis">
 8715: <input type="hidden" name="symb" value="$symb" />
 8716: <input type="hidden" name="command" value="assignclickergrades" />
 8717: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8718: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8719: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8720: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8721: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8722: ENDHEADER
 8723:     if ($env{'form.gradingmechanism'} eq 'given') {
 8724:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8725:     } 
 8726:     my %responses;
 8727:     my @questiontitles;
 8728:     my $errormsg='';
 8729:     my $number=0;
 8730:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8731: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8732:     }
 8733:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8734:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8735:     }
 8736:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8737:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8738:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8739:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8740:              '<br />';
 8741:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8742:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8743:        return $result.&show_grading_menu_form($symb);
 8744:     } 
 8745: # Remember Question Titles
 8746: # FIXME: Possibly need delimiter other than ":"
 8747:     for (my $i=0;$i<$number;$i++) {
 8748:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8749:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8750:     }
 8751:     my $correct_count=0;
 8752:     my $student_count=0;
 8753:     my $unknown_count=0;
 8754: # Match answers with usernames
 8755: # FIXME: Possibly need delimiter other than ":"
 8756:     foreach my $id (keys(%responses)) {
 8757:        if ($correct_ids{$id}) {
 8758:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8759:           $correct_count++;
 8760:        } elsif ($clicker_ids{$id}) {
 8761:           if ($clicker_ids{$id}=~/\,/) {
 8762: # More than one user with the same clicker!
 8763:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8764:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8765:                            "<select name='multi".$id."'>";
 8766:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8767:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8768:              }
 8769:              $result.='</select>';
 8770:              $unknown_count++;
 8771:           } else {
 8772: # Good: found one and only one user with the right clicker
 8773:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8774:              $student_count++;
 8775:           }
 8776:        } else {
 8777:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8778:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8779:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8780:                    "\n".&mt("Domain").": ".
 8781:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8782:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8783:           $unknown_count++;
 8784:        }
 8785:     }
 8786:     $result.='<hr />'.
 8787:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8788:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8789:        if ($correct_count==0) {
 8790:           $errormsg.="Found no correct answers answers for grading!";
 8791:        } elsif ($correct_count>1) {
 8792:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8793:        }
 8794:     }
 8795:     if ($number<1) {
 8796:        $errormsg.="Found no questions.";
 8797:     }
 8798:     if ($errormsg) {
 8799:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8800:     } else {
 8801:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8802:     }
 8803:     $result.='</form></td></tr></table>'."\n".
 8804:              '</td></tr></table><br /><br />'."\n";
 8805:     return $result.&show_grading_menu_form($symb);
 8806: }
 8807: 
 8808: sub iclicker_eval {
 8809:     my ($questiontitles,$responses)=@_;
 8810:     my $number=0;
 8811:     my $errormsg='';
 8812:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8813:         my %components=&Apache::loncommon::record_sep($line);
 8814:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8815: 	if ($entries[0] eq 'Question') {
 8816: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8817: 		$$questiontitles[$number]=$entries[$i];
 8818: 		$number++;
 8819: 	    }
 8820: 	}
 8821: 	if ($entries[0]=~/^\#/) {
 8822: 	    my $id=$entries[0];
 8823: 	    my @idresponses;
 8824: 	    $id=~s/^[\#0]+//;
 8825: 	    for (my $i=0;$i<$number;$i++) {
 8826: 		my $idx=3+$i*6;
 8827: 		push(@idresponses,$entries[$idx]);
 8828: 	    }
 8829: 	    $$responses{$id}=join(',',@idresponses);
 8830: 	}
 8831:     }
 8832:     return ($errormsg,$number);
 8833: }
 8834: 
 8835: sub interwrite_eval {
 8836:     my ($questiontitles,$responses)=@_;
 8837:     my $number=0;
 8838:     my $errormsg='';
 8839:     my $skipline=1;
 8840:     my $questionnumber=0;
 8841:     my %idresponses=();
 8842:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8843:         my %components=&Apache::loncommon::record_sep($line);
 8844:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8845:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8846:         if ($entries[1] eq 'Response') { $skipline=1; }
 8847:         next if $skipline;
 8848:         if ($entries[0]!=$questionnumber) {
 8849:            $questionnumber=$entries[0];
 8850:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8851:            $number++;
 8852:         }
 8853:         my $id=$entries[4];
 8854:         $id=~s/^[\#0]+//;
 8855:         $id=~s/^v\d*\://i;
 8856:         $id=~s/[\-\:]//g;
 8857:         $idresponses{$id}[$number]=$entries[6];
 8858:     }
 8859:     foreach my $id (keys(%idresponses)) {
 8860:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8861:        $$responses{$id}=~s/^\s*\,//;
 8862:     }
 8863:     return ($errormsg,$number);
 8864: }
 8865: 
 8866: sub assign_clicker_grades {
 8867:     my ($r)=@_;
 8868:     my ($symb)=&get_symb($r);
 8869:     if (!$symb) {return '';}
 8870: # See which part we are saving to
 8871:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8872: # FIXME: This should probably look for the first handgradeable part
 8873:     my $part=$$partlist[0];
 8874: # Start screen output
 8875:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8876: 
 8877:     my $heading=&mt('Assigning grades based on clicker file');
 8878:     $result.=(<<ENDHEADER);
 8879: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8880: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8881: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8882: ENDHEADER
 8883: # Get correct result
 8884: # FIXME: Possibly need delimiter other than ":"
 8885:     my @correct=();
 8886:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8887:     my $number=$env{'form.number'};
 8888:     if ($gradingmechanism ne 'attendance') {
 8889:        foreach my $key (keys(%env)) {
 8890:           if ($key=~/^form\.correct\:/) {
 8891:              my @input=split(/\,/,$env{$key});
 8892:              for (my $i=0;$i<=$#input;$i++) {
 8893:                  if (($correct[$i]) && ($input[$i]) &&
 8894:                      ($correct[$i] ne $input[$i])) {
 8895:                     $result.='<br /><span class="LC_warning">'.
 8896:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8897:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8898:                  } elsif ($input[$i]) {
 8899:                     $correct[$i]=$input[$i];
 8900:                  }
 8901:              }
 8902:           }
 8903:        }
 8904:        for (my $i=0;$i<$number;$i++) {
 8905:           if (!$correct[$i]) {
 8906:              $result.='<br /><span class="LC_error">'.
 8907:                       &mt('No correct result given for question "[_1]"!',
 8908:                           $env{'form.question:'.$i}).'</span>';
 8909:           }
 8910:        }
 8911:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8912:     }
 8913: # Start grading
 8914:     my $pcorrect=$env{'form.pcorrect'};
 8915:     my $pincorrect=$env{'form.pincorrect'};
 8916:     my $storecount=0;
 8917:     foreach my $key (keys(%env)) {
 8918:        my $user='';
 8919:        if ($key=~/^form\.student\:(.*)$/) {
 8920:           $user=$1;
 8921:        }
 8922:        if ($key=~/^form\.unknown\:(.*)$/) {
 8923:           my $id=$1;
 8924:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8925:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8926:           } elsif ($env{'form.multi'.$id}) {
 8927:              $user=$env{'form.multi'.$id};
 8928:           }
 8929:        }
 8930:        if ($user) { 
 8931:           my @answer=split(/\,/,$env{$key});
 8932:           my $sum=0;
 8933:           my $realnumber=$number;
 8934:           for (my $i=0;$i<$number;$i++) {
 8935:              if ($answer[$i]) {
 8936:                 if ($gradingmechanism eq 'attendance') {
 8937:                    $sum+=$pcorrect;
 8938:                 } elsif ($answer[$i] eq '*') {
 8939:                    $sum+=$pcorrect;
 8940:                 } elsif ($answer[$i] eq '-') {
 8941:                    $realnumber--;
 8942:                 } else {
 8943:                    if ($answer[$i] eq $correct[$i]) {
 8944:                       $sum+=$pcorrect;
 8945:                    } else {
 8946:                       $sum+=$pincorrect;
 8947:                    }
 8948:                 }
 8949:              }
 8950:           }
 8951:           my $ave=$sum/(100*$realnumber);
 8952: # Store
 8953:           my ($username,$domain)=split(/\:/,$user);
 8954:           my %grades=();
 8955:           $grades{"resource.$part.solved"}='correct_by_override';
 8956:           $grades{"resource.$part.awarded"}=$ave;
 8957:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8958:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8959:                                                  $env{'request.course.id'},
 8960:                                                  $domain,$username);
 8961:           if ($returncode ne 'ok') {
 8962:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8963:           } else {
 8964:              $storecount++;
 8965:           }
 8966:        }
 8967:     }
 8968: # We are done
 8969:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 8970:              '</td></tr></table>'."\n".
 8971:              '</td></tr></table><br /><br />'."\n";
 8972:     return $result.&show_grading_menu_form($symb);
 8973: }
 8974: 
 8975: sub handler {
 8976:     my $request=$_[0];
 8977:     &reset_caches();
 8978:     if ($env{'browser.mathml'}) {
 8979: 	&Apache::loncommon::content_type($request,'text/xml');
 8980:     } else {
 8981: 	&Apache::loncommon::content_type($request,'text/html');
 8982:     }
 8983:     $request->send_http_header;
 8984:     return '' if $request->header_only;
 8985:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8986:     my $symb=&get_symb($request,1);
 8987:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8988:     my $command=$commands[0];
 8989: 
 8990:     if ($#commands > 0) {
 8991: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8992:     }
 8993: 
 8994:     $ssi_error = 0;
 8995:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 8996:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 8997:                                           {'bread_crumbs' => $brcrum}));
 8998:     if ($symb eq '' && $command eq '') {
 8999: 	if ($env{'user.adv'}) {
 9000: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9001: 		($env{'form.codethree'})) {
 9002: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9003: 		    $env{'form.codethree'};
 9004: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9005: 		    &Apache::lonnet::checkin($token);
 9006: 		if ($tsymb) {
 9007: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9008: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9009: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9010: 					  ('grade_username' => $tuname,
 9011: 					   'grade_domain' => $tudom,
 9012: 					   'grade_courseid' => $tcrsid,
 9013: 					   'grade_symb' => $tsymb)));
 9014: 		    } else {
 9015: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9016: 		    }
 9017: 		} else {
 9018: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9019: 		}
 9020: 	    } else {
 9021: 		$request->print(&Apache::lonxml::tokeninputfield());
 9022: 	    }
 9023: 	}
 9024:     } else {
 9025: 	&init_perm();
 9026: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9027: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9028: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9029: 	    &pickStudentPage($request);
 9030: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9031: 	    &displayPage($request);
 9032: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9033: 	    &updateGradeByPage($request);
 9034: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9035: 	    &processGroup($request);
 9036: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9037: 	    $request->print(&grading_menu($request));
 9038: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9039: 	    $request->print(&submit_options($request));
 9040: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9041: 	    $request->print(&viewgrades($request));
 9042: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9043: 	    $request->print(&processHandGrade($request));
 9044: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9045: 	    $request->print(&editgrades($request));
 9046: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9047: 	    $request->print(&verifyreceipt($request));
 9048:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9049:             $request->print(&process_clicker($request));
 9050:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9051:             $request->print(&process_clicker_file($request));
 9052:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9053:             $request->print(&assign_clicker_grades($request));
 9054: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9055: 	    $request->print(&upcsvScores_form($request));
 9056: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9057: 	    $request->print(&csvupload($request));
 9058: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9059: 	    $request->print(&csvuploadmap($request));
 9060: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9061: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9062: 		$request->print(&csvuploadoptions($request));
 9063: 	    } else {
 9064: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9065: 		    $env{'form.upfile_associate'} = 'reverse';
 9066: 		} else {
 9067: 		    $env{'form.upfile_associate'} = 'forward';
 9068: 		}
 9069: 		$request->print(&csvuploadmap($request));
 9070: 	    }
 9071: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9072: 	    $request->print(&csvuploadassign($request));
 9073: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9074: 	    $request->print(&scantron_selectphase($request));
 9075:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9076:  	    $request->print(&scantron_do_warning($request));
 9077: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9078: 	    $request->print(&scantron_validate_file($request));
 9079: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9080: 	    $request->print(&scantron_process_students($request));
 9081:  	} elsif ($command eq 'scantronupload' && 
 9082:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9083: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9084:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9085:  	} elsif ($command eq 'scantronupload_save' &&
 9086:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9087: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9088:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9089:  	} elsif ($command eq 'scantron_download' &&
 9090: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9091:  	    $request->print(&scantron_download_scantron_data($request));
 9092:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9093:             $request->print(&checkscantron_results($request));     
 9094: 	} elsif ($command) {
 9095: 	    $request->print("Access Denied ($command)");
 9096: 	}
 9097:     }
 9098:     if ($ssi_error) {
 9099: 	&ssi_print_error($request);
 9100:     }
 9101:     $request->print(&Apache::loncommon::end_page());
 9102:     &reset_caches();
 9103:     return '';
 9104: }
 9105: 
 9106: 1;
 9107: 
 9108: __END__;
 9109: 
 9110: 
 9111: =head1 NAME
 9112: 
 9113: Apache::grades
 9114: 
 9115: =head1 SYNOPSIS
 9116: 
 9117: Handles the viewing of grades.
 9118: 
 9119: This is part of the LearningOnline Network with CAPA project
 9120: described at http://www.lon-capa.org.
 9121: 
 9122: =head1 OVERVIEW
 9123: 
 9124: Do an ssi with retries:
 9125: While I'd love to factor out this with the vesrion in lonprintout,
 9126: 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
 9127: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9128: 
 9129: At least the logic that drives this has been pulled out into loncommon.
 9130: 
 9131: 
 9132: 
 9133: ssi_with_retries - Does the server side include of a resource.
 9134:                      if the ssi call returns an error we'll retry it up to
 9135:                      the number of times requested by the caller.
 9136:                      If we still have a proble, no text is appended to the
 9137:                      output and we set some global variables.
 9138:                      to indicate to the caller an SSI error occurred.  
 9139:                      All of this is supposed to deal with the issues described
 9140:                      in LonCAPA BZ 5631 see:
 9141:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9142:                      by informing the user that this happened.
 9143: 
 9144: Parameters:
 9145:   resource   - The resource to include.  This is passed directly, without
 9146:                interpretation to lonnet::ssi.
 9147:   form       - The form hash parameters that guide the interpretation of the resource
 9148:                
 9149:   retries    - Number of retries allowed before giving up completely.
 9150: Returns:
 9151:   On success, returns the rendered resource identified by the resource parameter.
 9152: Side Effects:
 9153:   The following global variables can be set:
 9154:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9155:                               It is up to the caller to initialize this to false
 9156:                               if desired.
 9157:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9158:                               of the resource that could not be rendered by the ssi
 9159:                               call.
 9160:    ssi_error_message   - The error string fetched from the ssi response
 9161:                               in the event of an error.
 9162: 
 9163: 
 9164: =head1 HANDLER SUBROUTINE
 9165: 
 9166: ssi_with_retries()
 9167: 
 9168: =head1 SUBROUTINES
 9169: 
 9170: =over
 9171: 
 9172: =item scantron_get_correction() : 
 9173: 
 9174:    Builds the interface screen to interact with the operator to fix a
 9175:    specific error condition in a specific scanline
 9176: 
 9177:  Arguments:
 9178:     $r           - Apache request object
 9179:     $i           - number of the current scanline
 9180:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9181:     $scan_config - hash ref as returned from &get_scantron_config()
 9182:     $line        - full contents of the current scanline
 9183:     $error       - error condition, valid values are
 9184:                    'incorrectCODE', 'duplicateCODE',
 9185:                    'doublebubble', 'missingbubble',
 9186:                    'duplicateID', 'incorrectID'
 9187:     $arg         - extra information needed
 9188:        For errors:
 9189:          - duplicateID   - paper number that this studentID was seen before on
 9190:          - duplicateCODE - array ref of the paper numbers this CODE was
 9191:                            seen on before
 9192:          - incorrectCODE - current incorrect CODE 
 9193:          - doublebubble  - array ref of the bubble lines that have double
 9194:                            bubble errors
 9195:          - missingbubble - array ref of the bubble lines that have missing
 9196:                            bubble errors
 9197: 
 9198: =item  scantron_get_maxbubble() : 
 9199: 
 9200:    Returns the maximum number of bubble lines that are expected to
 9201:    occur. Does this by walking the selected sequence rendering the
 9202:    resource and then checking &Apache::lonxml::get_problem_counter()
 9203:    for what the current value of the problem counter is.
 9204: 
 9205:    Caches the results to $env{'form.scantron_maxbubble'},
 9206:    $env{'form.scantron.bubble_lines.n'}, 
 9207:    $env{'form.scantron.first_bubble_line.n'} and
 9208:    $env{"form.scantron.sub_bubblelines.n"}
 9209:    which are the total number of bubble, lines, the number of bubble
 9210:    lines for response n and number of the first bubble line for response n,
 9211:    and a comma separated list of numbers of bubble lines for sub-questions
 9212:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9213: 
 9214: 
 9215: =item  scantron_validate_missingbubbles() : 
 9216: 
 9217:    Validates all scanlines in the selected file to not have any
 9218:     answers that don't have bubbles that have not been verified
 9219:     to be bubble free.
 9220: 
 9221: =item  scantron_process_students() : 
 9222: 
 9223:    Routine that does the actual grading of the bubble sheet information.
 9224: 
 9225:    The parsed scanline hash is added to %env 
 9226: 
 9227:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9228:    foreach resource , with the form data of
 9229: 
 9230: 	'submitted'     =>'scantron' 
 9231: 	'grade_target'  =>'grade',
 9232: 	'grade_username'=> username of student
 9233: 	'grade_domain'  => domain of student
 9234: 	'grade_courseid'=> of course
 9235: 	'grade_symb'    => symb of resource to grade
 9236: 
 9237:     This triggers a grading pass. The problem grading code takes care
 9238:     of converting the bubbled letter information (now in %env) into a
 9239:     valid submission.
 9240: 
 9241: =item  scantron_upload_scantron_data() :
 9242: 
 9243:     Creates the screen for adding a new bubble sheet data file to a course.
 9244: 
 9245: =item  scantron_upload_scantron_data_save() : 
 9246: 
 9247:    Adds a provided bubble information data file to the course if user
 9248:    has the correct privileges to do so. 
 9249: 
 9250: =item  valid_file() :
 9251: 
 9252:    Validates that the requested bubble data file exists in the course.
 9253: 
 9254: =item  scantron_download_scantron_data() : 
 9255: 
 9256:    Shows a list of the three internal files (original, corrected,
 9257:    skipped) for a specific bubble sheet data file that exists in the
 9258:    course.
 9259: 
 9260: =item  scantron_validate_ID() : 
 9261: 
 9262:    Validates all scanlines in the selected file to not have any
 9263:    invalid or underspecified student/employee IDs
 9264: 
 9265: =back
 9266: 
 9267: =cut

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