File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.581.2.1: download - view: text, annotated - select for diffs
Wed Jan 6 18:43:57 2010 UTC (14 years, 4 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Block CC access to individual student submission data via
    grading screens in gcitest courses.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.581.2.1 2010/01/06 18:43:57 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">'
  187:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  188:     } else {
  189: 	$display=$partID;
  190:     }
  191:     return $display;
  192: }
  193: 
  194: #--- Show resource title
  195: #--- and parts and response type
  196: sub showResourceInfo {
  197:     my ($symb,$probTitle,$checkboxes) = @_;
  198:     my $col=3;
  199:     if ($checkboxes) { $col=4; }
  200:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  201:     $result .='<table border="0">';
  202:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  203:     my %resptype = ();
  204:     my $hdgrade='no';
  205:     my %partsseen;
  206:     foreach my $partID (sort(keys(%$responseType))) {
  207: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  208: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  209: 	    my $responsetype = $responseType->{$partID}->{$resID};
  210: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  211: 	    $result.='<tr>';
  212: 	    if ($checkboxes) {
  213: 		if (exists($partsseen{$partID})) {
  214: 		    $result.="<td>&nbsp;</td>";
  215: 		} else {
  216: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  217: 		}
  218: 		$partsseen{$partID}=1;
  219: 	    }
  220: 	    my $display_part=&get_display_part($partID,$symb);
  221:             $result.='<td><b>'.&mt('Part: [_1]',$display_part).'</b>'.
  222:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  223:                 '<td><b>'.&mt('Type: [_1]',$responsetype).'</b></td></tr>';
  224: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  225: 	}
  226:     }
  227:     $result.='</table>'."\n";
  228:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  229: }
  230: 
  231: sub reset_caches {
  232:     &reset_analyze_cache();
  233:     &reset_perm();
  234: }
  235: 
  236: {
  237:     my %analyze_cache;
  238:     my %analyze_cache_formkeys;
  239: 
  240:     sub reset_analyze_cache {
  241: 	undef(%analyze_cache);
  242:         undef(%analyze_cache_formkeys);
  243:     }
  244: 
  245:     sub get_analyze {
  246: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  247: 	my $key = "$symb\0$uname\0$udom";
  248: 	if (exists($analyze_cache{$key})) {
  249:             my $getupdate = 0;
  250:             if (ref($add_to_hash) eq 'HASH') {
  251:                 foreach my $item (keys(%{$add_to_hash})) {
  252:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  253:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  254:                             $getupdate = 1;
  255:                             last;
  256:                         }
  257:                     } else {
  258:                         $getupdate = 1;
  259:                     }
  260:                 }
  261:             }
  262:             if (!$getupdate) {
  263:                 return $analyze_cache{$key};
  264:             }
  265:         }
  266: 
  267: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  268: 	$url=&Apache::lonnet::clutter($url);
  269:         my %form = ('grade_target'      => 'analyze',
  270:                     'grade_domain'      => $udom,
  271:                     'grade_symb'        => $symb,
  272:                     'grade_courseid'    =>  $env{'request.course.id'},
  273:                     'grade_username'    => $uname,
  274:                     'grade_noincrement' => $no_increment);
  275:         if (ref($add_to_hash)) {
  276:             %form = (%form,%{$add_to_hash});
  277:         } 
  278: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  279: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  280: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  281:         if (ref($add_to_hash) eq 'HASH') {
  282:             $analyze_cache_formkeys{$key} = $add_to_hash;
  283:         } else {
  284:             $analyze_cache_formkeys{$key} = {};
  285:         }
  286: 	return $analyze_cache{$key} = \%analyze;
  287:     }
  288: 
  289:     sub get_order {
  290: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  291: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  292: 	return $analyze->{"$partid.$respid.shown"};
  293:     }
  294: 
  295:     sub get_radiobutton_correct_foil {
  296: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  297: 	my $analyze = &get_analyze($symb,$uname,$udom);
  298:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  299:         if (ref($foils) eq 'ARRAY') {
  300: 	    foreach my $foil (@{$foils}) {
  301: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  302: 		    return $foil;
  303: 	        }
  304: 	    }
  305: 	}
  306:     }
  307: 
  308:     sub scantron_partids_tograde {
  309:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  310:         my (%analysis,@parts);
  311:         if (ref($resource)) {
  312:             my $symb = $resource->symb();
  313:             my $add_to_form;
  314:             if ($check_for_randomlist) {
  315:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  316:             }
  317:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  318:             if (ref($analyze) eq 'HASH') {
  319:                 %analysis = %{$analyze};
  320:             }
  321:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  322:                 foreach my $part (@{$analysis{'parts'}}) {
  323:                     my ($id,$respid) = split(/\./,$part);
  324:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  325:                         push(@parts,$part);
  326:                     }
  327:                 }
  328:             }
  329:         }
  330:         return (\%analysis,\@parts);
  331:     }
  332: 
  333: }
  334: 
  335: #--- Clean response type for display
  336: #--- Currently filters option/rank/radiobutton/match/essay/Task
  337: #        response types only.
  338: sub cleanRecord {
  339:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  340: 	$uname,$udom) = @_;
  341:     my $grayFont = '<span class="LC_internal_info">';
  342:     if ($response =~ /^(option|rank)$/) {
  343: 	my %answer=&Apache::lonnet::str2hash($answer);
  344: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  345: 	my ($toprow,$bottomrow);
  346: 	foreach my $foil (@$order) {
  347: 	    if ($grading{$foil} == 1) {
  348: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  349: 	    } else {
  350: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  351: 	    }
  352: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  353: 	}
  354: 	return '<blockquote><table border="1">'.
  355: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  356: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  357: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  358:     } elsif ($response eq 'match') {
  359: 	my %answer=&Apache::lonnet::str2hash($answer);
  360: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  361: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  362: 	my ($toprow,$middlerow,$bottomrow);
  363: 	foreach my $foil (@$order) {
  364: 	    my $item=shift(@items);
  365: 	    if ($grading{$foil} == 1) {
  366: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  367: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  368: 	    } else {
  369: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  370: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  371: 	    }
  372: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  373: 	}
  374: 	return '<blockquote><table border="1">'.
  375: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  376: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  377: 	    $middlerow.'</tr>'.
  378: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  379: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  380:     } elsif ($response eq 'radiobutton') {
  381: 	my %answer=&Apache::lonnet::str2hash($answer);
  382: 	my ($toprow,$bottomrow);
  383: 	my $correct = 
  384: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  385: 	foreach my $foil (@$order) {
  386: 	    if (exists($answer{$foil})) {
  387: 		if ($foil eq $correct) {
  388: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  389: 		} else {
  390: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  391: 		}
  392: 	    } else {
  393: 		$toprow.='<td>'.&mt('false').'</td>';
  394: 	    }
  395: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  396: 	}
  397: 	return '<blockquote><table border="1">'.
  398: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  399: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  400: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  401:     } elsif ($response eq 'essay') {
  402: 	if (! exists ($env{'form.'.$symb})) {
  403: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  404: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  405: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  406: 
  407: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  408: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  409: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  410: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  411: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  412: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  413: 	}
  414: 	$answer =~ s-\n-<br />-g;
  415: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  416:     } elsif ( $response eq 'organic') {
  417: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  418: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  419: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  420: 	return $result;
  421:     } elsif ( $response eq 'Task') {
  422: 	if ( $answer eq 'SUBMITTED') {
  423: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  424: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  425: 	    return $result;
  426: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  427: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  428: 			       keys(%{$record}));
  429: 	    return join('<br />',($version,@matches));
  430: 			       
  431: 			       
  432: 	} else {
  433: 	    my $result =
  434: 		'<p>'
  435: 		.&mt('Overall result: [_1]',
  436: 		     $record->{$version."resource.$respid.$partid.status"})
  437: 		.'</p>';
  438: 	    
  439: 	    $result .= '<ul>';
  440: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  441: 			     keys(%{$record}));
  442: 	    foreach my $grade (sort(@grade)) {
  443: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  444: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  445: 				     $dim, $record->{$grade}).
  446: 			  '</li>';
  447: 	    }
  448: 	    $result.='</ul>';
  449: 	    return $result;
  450: 	}
  451:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  452: 	$answer = 
  453: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  454: 							      $answer);
  455:     }
  456:     return $answer;
  457: }
  458: 
  459: #-- A couple of common js functions
  460: sub commonJSfunctions {
  461:     my $request = shift;
  462:     $request->print(<<COMMONJSFUNCTIONS);
  463: <script type="text/javascript" language="javascript">
  464:     function radioSelection(radioButton) {
  465: 	var selection=null;
  466: 	if (radioButton.length > 1) {
  467: 	    for (var i=0; i<radioButton.length; i++) {
  468: 		if (radioButton[i].checked) {
  469: 		    return radioButton[i].value;
  470: 		}
  471: 	    }
  472: 	} else {
  473: 	    if (radioButton.checked) return radioButton.value;
  474: 	}
  475: 	return selection;
  476:     }
  477: 
  478:     function pullDownSelection(selectOne) {
  479: 	var selection="";
  480: 	if (selectOne.length > 1) {
  481: 	    for (var i=0; i<selectOne.length; i++) {
  482: 		if (selectOne[i].selected) {
  483: 		    return selectOne[i].value;
  484: 		}
  485: 	    }
  486: 	} else {
  487:             // only one value it must be the selected one
  488: 	    return selectOne.value;
  489: 	}
  490:     }
  491: </script>
  492: COMMONJSFUNCTIONS
  493: }
  494: 
  495: #--- Dumps the class list with usernames,list of sections,
  496: #--- section, ids and fullnames for each user.
  497: sub getclasslist {
  498:     my ($getsec,$filterlist,$getgroup) = @_;
  499:     my @getsec;
  500:     my @getgroup;
  501:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  502:     if (!ref($getsec)) {
  503: 	if ($getsec ne '' && $getsec ne 'all') {
  504: 	    @getsec=($getsec);
  505: 	}
  506:     } else {
  507: 	@getsec=@{$getsec};
  508:     }
  509:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  510:     if (!ref($getgroup)) {
  511: 	if ($getgroup ne '' && $getgroup ne 'all') {
  512: 	    @getgroup=($getgroup);
  513: 	}
  514:     } else {
  515: 	@getgroup=@{$getgroup};
  516:     }
  517:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  518: 
  519:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  520:     # Bail out if we were unable to get the classlist
  521:     return if (! defined($classlist));
  522:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  523:     #
  524:     my %sections;
  525:     my %fullnames;
  526:     foreach my $student (keys(%$classlist)) {
  527:         my $end      = 
  528:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  529:         my $start    = 
  530:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  531:         my $id       = 
  532:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  533:         my $section  = 
  534:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  535:         my $fullname = 
  536:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  537:         my $status   = 
  538:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  539:         my $group   = 
  540:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  541: 	# filter students according to status selected
  542: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  543: 	    if (!($stu_status =~ $status)) {
  544: 		delete($classlist->{$student});
  545: 		next;
  546: 	    }
  547: 	}
  548: 	# filter students according to groups selected
  549: 	my @stu_groups = split(/,/,$group);
  550: 	if (@getgroup) {
  551: 	    my $exclude = 1;
  552: 	    foreach my $grp (@getgroup) {
  553: 	        foreach my $stu_group (@stu_groups) {
  554: 	            if ($stu_group eq $grp) {
  555: 	                $exclude = 0;
  556:     	            } 
  557: 	        }
  558:     	        if (($grp eq 'none') && !$group) {
  559:         	        $exclude = 0;
  560:         	}
  561: 	    }
  562: 	    if ($exclude) {
  563: 	        delete($classlist->{$student});
  564: 	    }
  565: 	}
  566: 	$section = ($section ne '' ? $section : 'none');
  567: 	if (&canview($section)) {
  568: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  569: 		$sections{$section}++;
  570: 		if ($classlist->{$student}) {
  571: 		    $fullnames{$student}=$fullname;
  572: 		}
  573: 	    } else {
  574: 		delete($classlist->{$student});
  575: 	    }
  576: 	} else {
  577: 	    delete($classlist->{$student});
  578: 	}
  579:     }
  580:     my %seen = ();
  581:     my @sections = sort(keys(%sections));
  582:     return ($classlist,\@sections,\%fullnames);
  583: }
  584: 
  585: sub canmodify {
  586:     my ($sec)=@_;
  587:     if ($perm{'mgr'}) {
  588: 	if (!defined($perm{'mgr_section'})) {
  589: 	    # can modify whole class
  590: 	    return 1;
  591: 	} else {
  592: 	    if ($sec eq $perm{'mgr_section'}) {
  593: 		#can modify the requested section
  594: 		return 1;
  595: 	    } else {
  596: 		# can't modify the request section
  597: 		return 0;
  598: 	    }
  599: 	}
  600:     }
  601:     #can't modify
  602:     return 0;
  603: }
  604: 
  605: sub canview {
  606:     my ($sec)=@_;
  607:     if ($perm{'vgr'}) {
  608: 	if (!defined($perm{'vgr_section'})) {
  609: 	    # can modify whole class
  610: 	    return 1;
  611: 	} else {
  612: 	    if ($sec eq $perm{'vgr_section'}) {
  613: 		#can modify the requested section
  614: 		return 1;
  615: 	    } else {
  616: 		# can't modify the request section
  617: 		return 0;
  618: 	    }
  619: 	}
  620:     }
  621:     #can't modify
  622:     return 0;
  623: }
  624: 
  625: #--- Retrieve the grade status of a student for all the parts
  626: sub student_gradeStatus {
  627:     my ($symb,$udom,$uname,$partlist) = @_;
  628:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  629:     my %partstatus = ();
  630:     foreach (@$partlist) {
  631: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  632: 	$status              = 'nothing' if ($status eq '');
  633: 	$partstatus{$_}      = $status;
  634: 	my $subkey           = "resource.$_.submitted_by";
  635: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  636:     }
  637:     return %partstatus;
  638: }
  639: 
  640: # hidden form and javascript that calls the form
  641: # Use by verifyscript and viewgrades
  642: # Shows a student's view of problem and submission
  643: sub jscriptNform {
  644:     my ($symb) = @_;
  645:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  646:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  647: 	'    function viewOneStudent(user,domain) {'."\n".
  648: 	'	document.onestudent.student.value = user;'."\n".
  649: 	'	document.onestudent.userdom.value = domain;'."\n".
  650: 	'	document.onestudent.submit();'."\n".
  651: 	'    }'."\n".
  652: 	'</script>'."\n";
  653:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  654: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  655: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  656: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  657: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  658: 	'<input type="hidden" name="command" value="submission" />'."\n".
  659: 	'<input type="hidden" name="student" value="" />'."\n".
  660: 	'<input type="hidden" name="userdom" value="" />'."\n".
  661: 	'</form>'."\n";
  662:     return $jscript;
  663: }
  664: 
  665: 
  666: 
  667: # Given the score (as a number [0-1] and the weight) what is the final
  668: # point value? This function will round to the nearest tenth, third,
  669: # or quarter if one of those is within the tolerance of .00001.
  670: sub compute_points {
  671:     my ($score, $weight) = @_;
  672:     
  673:     my $tolerance = .00001;
  674:     my $points = $score * $weight;
  675: 
  676:     # Check for nearness to 1/x.
  677:     my $check_for_nearness = sub {
  678:         my ($factor) = @_;
  679:         my $num = ($points * $factor) + $tolerance;
  680:         my $floored_num = floor($num);
  681:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  682:             return $floored_num / $factor;
  683:         }
  684:         return $points;
  685:     };
  686: 
  687:     $points = $check_for_nearness->(10);
  688:     $points = $check_for_nearness->(3);
  689:     $points = $check_for_nearness->(4);
  690:     
  691:     return $points;
  692: }
  693: 
  694: #------------------ End of general use routines --------------------
  695: 
  696: #
  697: # Find most similar essay
  698: #
  699: 
  700: sub most_similar {
  701:     my ($uname,$udom,$uessay,$old_essays)=@_;
  702: 
  703: # ignore spaces and punctuation
  704: 
  705:     $uessay=~s/\W+/ /gs;
  706: 
  707: # ignore empty submissions (occuring when only files are sent)
  708: 
  709:     unless ($uessay=~/\w+/) { return ''; }
  710: 
  711: # these will be returned. Do not care if not at least 50 percent similar
  712:     my $limit=0.6;
  713:     my $sname='';
  714:     my $sdom='';
  715:     my $scrsid='';
  716:     my $sessay='';
  717: # go through all essays ...
  718:     foreach my $tkey (keys(%$old_essays)) {
  719: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  720: # ... except the same student
  721:         next if (($tname eq $uname) && ($tdom eq $udom));
  722: 	my $tessay=$old_essays->{$tkey};
  723: 	$tessay=~s/\W+/ /gs;
  724: # String similarity gives up if not even limit
  725: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  726: # Found one
  727: 	if ($tsimilar>$limit) {
  728: 	    $limit=$tsimilar;
  729: 	    $sname=$tname;
  730: 	    $sdom=$tdom;
  731: 	    $scrsid=$tcrsid;
  732: 	    $sessay=$old_essays->{$tkey};
  733: 	}
  734:     }
  735:     if ($limit>0.6) {
  736:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  737:     } else {
  738:        return ('','','','',0);
  739:     }
  740: }
  741: 
  742: #-------------------------------------------------------------------
  743: 
  744: #------------------------------------ Receipt Verification Routines
  745: #
  746: #--- Check whether a receipt number is valid.---
  747: sub verifyreceipt {
  748:     my $request  = shift;
  749: 
  750:     my $courseid = $env{'request.course.id'};
  751:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  752: 	$env{'form.receipt'};
  753:     $receipt     =~ s/[^\-\d]//g;
  754:     my ($symb)   = &get_symb($request);
  755: 
  756:     my $title.=
  757: 	'<h3><span class="LC_info">'.
  758: 	&mt('Verifying  Receipt No. [_1]',$receipt).
  759: 	'</span></h3>'."\n".
  760: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  761: 	'</h4>'."\n";
  762: 
  763:     my ($string,$contents,$matches) = ('','',0);
  764:     my (undef,undef,$fullname) = &getclasslist('all','0');
  765:     
  766:     my $receiptparts=0;
  767:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  768: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  769:     my $parts=['0'];
  770:     if ($receiptparts) { ($parts)=&response_type($symb); }
  771:     
  772:     my $header = 
  773: 	&Apache::loncommon::start_data_table().
  774: 	&Apache::loncommon::start_data_table_header_row().
  775: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  776: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  777: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  778:     if ($receiptparts) {
  779: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  780:     }
  781:     $header.=
  782: 	&Apache::loncommon::end_data_table_header_row();
  783: 
  784:     foreach (sort 
  785: 	     {
  786: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  787: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  788: 		 }
  789: 		 return $a cmp $b;
  790: 	     } (keys(%$fullname))) {
  791: 	my ($uname,$udom)=split(/\:/);
  792: 	foreach my $part (@$parts) {
  793: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  794: 		$contents.=
  795: 		    &Apache::loncommon::start_data_table_row().
  796: 		    '<td>&nbsp;'."\n".
  797: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  798: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  799: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  800: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  801: 		if ($receiptparts) {
  802: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  803: 		}
  804: 		$contents.= 
  805: 		    &Apache::loncommon::end_data_table_row()."\n";
  806: 		
  807: 		$matches++;
  808: 	    }
  809: 	}
  810:     }
  811:     if ($matches == 0) {
  812: 	$string = $title.&mt('No match found for the above receipt.');
  813:     } else {
  814: 	$string = &jscriptNform($symb).$title.
  815: 	    '<p>'.
  816: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  817: 	    '</p>'.
  818: 	    $header.
  819: 	    $contents.
  820: 	    &Apache::loncommon::end_data_table()."\n";
  821:     }
  822:     return $string.&show_grading_menu_form($symb);
  823: }
  824: 
  825: #--- This is called by a number of programs.
  826: #--- Called from the Grading Menu - View/Grade an individual student
  827: #--- Also called directly when one clicks on the subm button 
  828: #    on the problem page.
  829: sub listStudents {
  830:     my ($request) = shift;
  831: 
  832:     my ($symb) = &get_symb($request);
  833:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  834:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  835:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  836:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  837:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  838:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  839:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  840: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  841: 
  842:     my $result='<h3><span class="LC_info">&nbsp;'
  843: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  844: 	.'</span></h3>';
  845: 
  846:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  847: 
  848:     my %lt = &Apache::lonlocal::texthash (
  849: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  850: 		'single'   => 'Please select the student before clicking on the Next button.',
  851: 	     );
  852:     $request->print(<<LISTJAVASCRIPT);
  853: <script type="text/javascript" language="javascript">
  854:     function checkSelect(checkBox) {
  855: 	var ctr=0;
  856: 	var sense="";
  857: 	if (checkBox.length > 1) {
  858: 	    for (var i=0; i<checkBox.length; i++) {
  859: 		if (checkBox[i].checked) {
  860: 		    ctr++;
  861: 		}
  862: 	    }
  863: 	    sense = '$lt{'multiple'}';
  864: 	} else {
  865: 	    if (checkBox.checked) {
  866: 		ctr = 1;
  867: 	    }
  868: 	    sense = '$lt{'single'}';
  869: 	}
  870: 	if (ctr == 0) {
  871: 	    alert(sense);
  872: 	    return false;
  873: 	}
  874: 	document.gradesub.submit();
  875:     }
  876: 
  877:     function reLoadList(formname) {
  878: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  879: 	formname.command.value = 'submission';
  880: 	formname.submit();
  881:     }
  882: </script>
  883: LISTJAVASCRIPT
  884: 
  885:     &commonJSfunctions($request);
  886:     $request->print($result);
  887: 
  888:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  889:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  890:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  891: 	"\n".$table;
  892: 	
  893:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  894:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  895:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  896:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  897:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  898:                   .&Apache::lonhtmlcommon::row_closure();
  899:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  900:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  901:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  902:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  903:                   .&Apache::lonhtmlcommon::row_closure();
  904: 
  905:     my $submission_options;
  906:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  907: 	$submission_options.=
  908: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  909:     }
  910:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  911:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  912:     $env{'form.Status'} = $saveStatus;
  913:     $submission_options.=
  914: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  915: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  916: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  917: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  918:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  919:                   .$submission_options
  920:                   .&Apache::lonhtmlcommon::row_closure();
  921: 
  922:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  923:                   .'<select name="increment">'
  924:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  925:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  926:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  927:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  928:                   .'</select>'
  929:                   .&Apache::lonhtmlcommon::row_closure();
  930: 
  931:     $gradeTable .= 
  932:         &build_section_inputs().
  933: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  934: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  935: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  936: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  937: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  938: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  939: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  940: 
  941:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  942: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  943:     } else {
  944:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  945:                       .&Apache::lonhtmlcommon::StatusOptions(
  946:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  947:                       .&Apache::lonhtmlcommon::row_closure();
  948:     }
  949: 
  950:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  951:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  952:                   .&Apache::lonhtmlcommon::row_closure(1)
  953:                   .&Apache::lonhtmlcommon::end_pick_box();
  954: 
  955:     $gradeTable .= '<p>'
  956:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
  957:                   .'<input type="hidden" name="command" value="processGroup" />'
  958:                   .'</p>';
  959: 
  960: # checkall buttons
  961:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  962:     $gradeTable.='<input type="button" '."\n".
  963: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  964: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  965:     $gradeTable.=&check_buttons();
  966:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  967:     $gradeTable.= &Apache::loncommon::start_data_table().
  968: 	&Apache::loncommon::start_data_table_header_row();
  969:     my $loop = 0;
  970:     while ($loop < 2) {
  971: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  972: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  973: 	if ($env{'form.showgrading'} eq 'yes' 
  974: 	    && $submitonly ne 'queued'
  975: 	    && $submitonly ne 'all') {
  976: 	    foreach my $part (sort(@$partlist)) {
  977: 		my $display_part=
  978: 		    &get_display_part((split(/_/,$part))[0],$symb);
  979: 		$gradeTable.=
  980: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  981: 	    }
  982: 	} elsif ($submitonly eq 'queued') {
  983: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  984: 	}
  985: 	$loop++;
  986: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  987:     }
  988:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  989: 
  990:     my $ctr = 0;
  991:     foreach my $student (sort 
  992: 			 {
  993: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  994: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  995: 			     }
  996: 			     return $a cmp $b;
  997: 			 }
  998: 			 (keys(%$fullname))) {
  999: 	my ($uname,$udom) = split(/:/,$student);
 1000: 
 1001: 	my %status = ();
 1002: 
 1003: 	if ($submitonly eq 'queued') {
 1004: 	    my %queue_status = 
 1005: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1006: 							$udom,$uname);
 1007: 	    next if (!defined($queue_status{'gradingqueue'}));
 1008: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1009: 	}
 1010: 
 1011: 	if ($env{'form.showgrading'} eq 'yes' 
 1012: 	    && $submitonly ne 'queued'
 1013: 	    && $submitonly ne 'all') {
 1014: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1015: 	    my $submitted = 0;
 1016: 	    my $graded = 0;
 1017: 	    my $incorrect = 0;
 1018: 	    foreach (keys(%status)) {
 1019: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1020: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1021: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1022: 		
 1023: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1024: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1025: 		    $submitted = 0;
 1026: 		    my ($part)=split(/\./,$partid);
 1027: 		    $gradeTable.='<input type="hidden" name="'.
 1028: 			$student.':'.$part.':submitted_by" value="'.
 1029: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1030: 		}
 1031: 	    }
 1032: 	    
 1033: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1034: 				     $submitonly eq 'incorrect' ||
 1035: 				     $submitonly eq 'graded'));
 1036: 	    next if (!$graded && ($submitonly eq 'graded'));
 1037: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1038: 	}
 1039: 
 1040: 	$ctr++;
 1041: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1042:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1043: 	if ( $perm{'vgr'} eq 'F' ) {
 1044: 	    if ($ctr%2 ==1) {
 1045: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1046: 	    }
 1047: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1048:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1049:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1050: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1051: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1052: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1053: 
 1054: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1055: 		foreach (sort(keys(%status))) {
 1056: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1057: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1058: 		}
 1059: 	    }
 1060: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1061: 	    if ($ctr%2 ==0) {
 1062: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1063: 	    }
 1064: 	}
 1065:     }
 1066:     if ($ctr%2 ==1) {
 1067: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1068: 	    if ($env{'form.showgrading'} eq 'yes' 
 1069: 		&& $submitonly ne 'queued'
 1070: 		&& $submitonly ne 'all') {
 1071: 		foreach (@$partlist) {
 1072: 		    $gradeTable.='<td>&nbsp;</td>';
 1073: 		}
 1074: 	    } elsif ($submitonly eq 'queued') {
 1075: 		$gradeTable.='<td>&nbsp;</td>';
 1076: 	    }
 1077: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1078:     }
 1079: 
 1080:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1081: 	'<input type="button" '.
 1082: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1083: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1084:     if ($ctr == 0) {
 1085: 	my $num_students=(scalar(keys(%$fullname)));
 1086: 	if ($num_students eq 0) {
 1087: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1088: 	} else {
 1089: 	    my $submissions='submissions';
 1090: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1091: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1092: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1093: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1094: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1095: 		    $num_students).
 1096: 		'</span><br />';
 1097: 	}
 1098:     } elsif ($ctr == 1) {
 1099: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1100:     }
 1101:     $gradeTable.=&show_grading_menu_form($symb);
 1102:     $request->print($gradeTable);
 1103:     return '';
 1104: }
 1105: 
 1106: #---- Called from the listStudents routine
 1107: 
 1108: sub check_script {
 1109:     my ($form, $type)=@_;
 1110:     my $chkallscript='<script type="text/javascript">
 1111:     function checkall() {
 1112:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1113:             ele = document.forms.'.$form.'.elements[i];
 1114:             if (ele.name == "'.$type.'") {
 1115:             document.forms.'.$form.'.elements[i].checked=true;
 1116:                                        }
 1117:         }
 1118:     }
 1119: 
 1120:     function checksec() {
 1121:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1122:             ele = document.forms.'.$form.'.elements[i];
 1123:            string = document.forms.'.$form.'.chksec.value;
 1124:            if
 1125:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1126:               document.forms.'.$form.'.elements[i].checked=true;
 1127:             }
 1128:         }
 1129:     }
 1130: 
 1131: 
 1132:     function uncheckall() {
 1133:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1134:             ele = document.forms.'.$form.'.elements[i];
 1135:             if (ele.name == "'.$type.'") {
 1136:             document.forms.'.$form.'.elements[i].checked=false;
 1137:                                        }
 1138:         }
 1139:     }
 1140: 
 1141: </script>'."\n";
 1142:     return $chkallscript;
 1143: }
 1144: 
 1145: sub check_buttons {
 1146:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1147:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1148:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1149:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1150:     return $buttons;
 1151: }
 1152: 
 1153: #     Displays the submissions for one student or a group of students
 1154: sub processGroup {
 1155:     my ($request)  = shift;
 1156:     my $ctr        = 0;
 1157:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1158:     my $total      = scalar(@stuchecked)-1;
 1159: 
 1160:     foreach my $student (@stuchecked) {
 1161: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1162: 	$env{'form.student'}        = $uname;
 1163: 	$env{'form.userdom'}        = $udom;
 1164: 	$env{'form.fullname'}       = $fullname;
 1165: 	&submission($request,$ctr,$total);
 1166: 	$ctr++;
 1167:     }
 1168:     return '';
 1169: }
 1170: 
 1171: #------------------------------------------------------------------------------------
 1172: #
 1173: #-------------------------- Next few routines handles grading by student, essentially
 1174: #                           handles essay response type problem/part
 1175: #
 1176: #--- Javascript to handle the submission page functionality ---
 1177: sub sub_page_js {
 1178:     my $request = shift;
 1179: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1180:     $request->print(<<SUBJAVASCRIPT);
 1181: <script type="text/javascript" language="javascript">
 1182:     function updateRadio(formname,id,weight) {
 1183: 	var gradeBox = formname["GD_BOX"+id];
 1184: 	var radioButton = formname["RADVAL"+id];
 1185: 	var oldpts = formname["oldpts"+id].value;
 1186: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1187: 	gradeBox.value = pts;
 1188: 	var resetbox = false;
 1189: 	if (isNaN(pts) || pts < 0) {
 1190: 	    alert("$alertmsg"+pts);
 1191: 	    for (var i=0; i<radioButton.length; i++) {
 1192: 		if (radioButton[i].checked) {
 1193: 		    gradeBox.value = i;
 1194: 		    resetbox = true;
 1195: 		}
 1196: 	    }
 1197: 	    if (!resetbox) {
 1198: 		formtextbox.value = "";
 1199: 	    }
 1200: 	    return;
 1201: 	}
 1202: 
 1203: 	if (pts > weight) {
 1204: 	    var resp = confirm("You entered a value ("+pts+
 1205: 			       ") greater than the weight for the part. Accept?");
 1206: 	    if (resp == false) {
 1207: 		gradeBox.value = oldpts;
 1208: 		return;
 1209: 	    }
 1210: 	}
 1211: 
 1212: 	for (var i=0; i<radioButton.length; i++) {
 1213: 	    radioButton[i].checked=false;
 1214: 	    if (pts == i && pts != "") {
 1215: 		radioButton[i].checked=true;
 1216: 	    }
 1217: 	}
 1218: 	updateSelect(formname,id);
 1219: 	formname["stores"+id].value = "0";
 1220:     }
 1221: 
 1222:     function writeBox(formname,id,pts) {
 1223: 	var gradeBox = formname["GD_BOX"+id];
 1224: 	if (checkSolved(formname,id) == 'update') {
 1225: 	    gradeBox.value = pts;
 1226: 	} else {
 1227: 	    var oldpts = formname["oldpts"+id].value;
 1228: 	    gradeBox.value = oldpts;
 1229: 	    var radioButton = formname["RADVAL"+id];
 1230: 	    for (var i=0; i<radioButton.length; i++) {
 1231: 		radioButton[i].checked=false;
 1232: 		if (i == oldpts) {
 1233: 		    radioButton[i].checked=true;
 1234: 		}
 1235: 	    }
 1236: 	}
 1237: 	formname["stores"+id].value = "0";
 1238: 	updateSelect(formname,id);
 1239: 	return;
 1240:     }
 1241: 
 1242:     function clearRadBox(formname,id) {
 1243: 	if (checkSolved(formname,id) == 'noupdate') {
 1244: 	    updateSelect(formname,id);
 1245: 	    return;
 1246: 	}
 1247: 	gradeSelect = formname["GD_SEL"+id];
 1248: 	for (var i=0; i<gradeSelect.length; i++) {
 1249: 	    if (gradeSelect[i].selected) {
 1250: 		var selectx=i;
 1251: 	    }
 1252: 	}
 1253: 	var stores = formname["stores"+id];
 1254: 	if (selectx == stores.value) { return };
 1255: 	var gradeBox = formname["GD_BOX"+id];
 1256: 	gradeBox.value = "";
 1257: 	var radioButton = formname["RADVAL"+id];
 1258: 	for (var i=0; i<radioButton.length; i++) {
 1259: 	    radioButton[i].checked=false;
 1260: 	}
 1261: 	stores.value = selectx;
 1262:     }
 1263: 
 1264:     function checkSolved(formname,id) {
 1265: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1266: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1267: 	    if (!reply) {return "noupdate";}
 1268: 	    formname.overRideScore.value = 'yes';
 1269: 	}
 1270: 	return "update";
 1271:     }
 1272: 
 1273:     function updateSelect(formname,id) {
 1274: 	formname["GD_SEL"+id][0].selected = true;
 1275: 	return;
 1276:     }
 1277: 
 1278: //=========== Check that a point is assigned for all the parts  ============
 1279:     function checksubmit(formname,val,total,parttot) {
 1280: 	formname.gradeOpt.value = val;
 1281: 	if (val == "Save & Next") {
 1282: 	    for (i=0;i<=total;i++) {
 1283: 		for (j=0;j<parttot;j++) {
 1284: 		    var partid = formname["partid"+i+"_"+j].value;
 1285: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1286: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1287: 			if (points == "") {
 1288: 			    var name = formname["name"+i].value;
 1289: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1290: 			    var resp = confirm("You did not assign a score for "+studentID+
 1291: 					       ", part "+partid+". Continue?");
 1292: 			    if (resp == false) {
 1293: 				formname["GD_BOX"+i+"_"+partid].focus();
 1294: 				return false;
 1295: 			    }
 1296: 			}
 1297: 		    }
 1298: 		    
 1299: 		}
 1300: 	    }
 1301: 	    
 1302: 	}
 1303: 	if (val == "Grade Student") {
 1304: 	    formname.showgrading.value = "yes";
 1305: 	    if (formname.Status.value == "") {
 1306: 		formname.Status.value = "Active";
 1307: 	    }
 1308: 	    formname.studentNo.value = total;
 1309: 	}
 1310: 	formname.submit();
 1311:     }
 1312: 
 1313: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1314:     function checkSubmitPage(formname,total) {
 1315: 	noscore = new Array(100);
 1316: 	var ptr = 0;
 1317: 	for (i=1;i<total;i++) {
 1318: 	    var partid = formname["q_"+i].value;
 1319: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1320: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1321: 		var status = formname["solved"+i+"_"+partid].value;
 1322: 		if (points == "" && status != "correct_by_student") {
 1323: 		    noscore[ptr] = i;
 1324: 		    ptr++;
 1325: 		}
 1326: 	    }
 1327: 	}
 1328: 	if (ptr != 0) {
 1329: 	    var sense = ptr == 1 ? ": " : "s: ";
 1330: 	    var prolist = "";
 1331: 	    if (ptr == 1) {
 1332: 		prolist = noscore[0];
 1333: 	    } else {
 1334: 		var i = 0;
 1335: 		while (i < ptr-1) {
 1336: 		    prolist += noscore[i]+", ";
 1337: 		    i++;
 1338: 		}
 1339: 		prolist += "and "+noscore[i];
 1340: 	    }
 1341: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1342: 	    if (resp == false) {
 1343: 		return false;
 1344: 	    }
 1345: 	}
 1346: 
 1347: 	formname.submit();
 1348:     }
 1349: </script>
 1350: SUBJAVASCRIPT
 1351: }
 1352: 
 1353: #--- javascript for essay type problem --
 1354: sub sub_page_kw_js {
 1355:     my $request = shift;
 1356:     my $iconpath = $request->dir_config('lonIconsURL');
 1357:     &commonJSfunctions($request);
 1358: 
 1359:     my $inner_js_msg_central=<<INNERJS;
 1360:     <script text="text/javascript">
 1361:     function checkInput() {
 1362:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1363:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1364:       var usrctr = document.msgcenter.usrctr.value;
 1365:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1366:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1367: 
 1368:       var msgchk = "";
 1369:       if (document.msgcenter.subchk.checked) {
 1370:          msgchk = "msgsub,";
 1371:       }
 1372:       var includemsg = 0;
 1373:       for (var i=1; i<=nmsg; i++) {
 1374:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1375:           var frmmsg = document.msgcenter["msg"+i];
 1376:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1377:           var showflg = opener.document.SCORE["shownOnce"+i];
 1378:           showflg.value = "1";
 1379:           var chkbox = document.msgcenter["msgn"+i];
 1380:           if (chkbox.checked) {
 1381:              msgchk += "savemsg"+i+",";
 1382:              includemsg = 1;
 1383:           }
 1384:       }
 1385:       if (document.msgcenter.newmsgchk.checked) {
 1386:          msgchk += "newmsg"+usrctr;
 1387:          includemsg = 1;
 1388:       }
 1389:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1390:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1391:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1392:       includemsg.value = msgchk;
 1393: 
 1394:       self.close()
 1395: 
 1396:     }
 1397:     </script>
 1398: INNERJS
 1399: 
 1400:     my $inner_js_highlight_central=<<INNERJS;
 1401:  <script type="text/javascript">
 1402:     function updateChoice(flag) {
 1403:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1404:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1405:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1406:       opener.document.SCORE.refresh.value = "on";
 1407:       if (opener.document.SCORE.keywords.value!=""){
 1408:          opener.document.SCORE.submit();
 1409:       }
 1410:       self.close()
 1411:     }
 1412: </script>
 1413: INNERJS
 1414: 
 1415:     my $start_page_msg_central = 
 1416:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1417: 				       {'js_ready'  => 1,
 1418: 					'only_body' => 1,
 1419: 					'bgcolor'   =>'#FFFFFF',});
 1420:     my $end_page_msg_central = 
 1421: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1422: 
 1423: 
 1424:     my $start_page_highlight_central = 
 1425:         &Apache::loncommon::start_page('Highlight Central',
 1426: 				       $inner_js_highlight_central,
 1427: 				       {'js_ready'  => 1,
 1428: 					'only_body' => 1,
 1429: 					'bgcolor'   =>'#FFFFFF',});
 1430:     my $end_page_highlight_central = 
 1431: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1432: 
 1433:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1434:     $docopen=~s/^document\.//;
 1435:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1436:     $request->print(<<SUBJAVASCRIPT);
 1437: <script type="text/javascript" language="javascript">
 1438: 
 1439: //===================== Show list of keywords ====================
 1440:   function keywords(formname) {
 1441:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1442:     if (nret==null) return;
 1443:     formname.keywords.value = nret;
 1444: 
 1445:     if (formname.keywords.value != "") {
 1446: 	formname.refresh.value = "on";
 1447: 	formname.submit();
 1448:     }
 1449:     return;
 1450:   }
 1451: 
 1452: //===================== Script to view submitted by ==================
 1453:   function viewSubmitter(submitter) {
 1454:     document.SCORE.refresh.value = "on";
 1455:     document.SCORE.NCT.value = "1";
 1456:     document.SCORE.unamedom0.value = submitter;
 1457:     document.SCORE.submit();
 1458:     return;
 1459:   }
 1460: 
 1461: //===================== Script to add keyword(s) ==================
 1462:   function getSel() {
 1463:     if (document.getSelection) txt = document.getSelection();
 1464:     else if (document.selection) txt = document.selection.createRange().text;
 1465:     else return;
 1466:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1467:     if (cleantxt=="") {
 1468: 	alert("$alertmsg");
 1469: 	return;
 1470:     }
 1471:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1472:     if (nret==null) return;
 1473:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1474:     if (document.SCORE.keywords.value != "") {
 1475: 	document.SCORE.refresh.value = "on";
 1476: 	document.SCORE.submit();
 1477:     }
 1478:     return;
 1479:   }
 1480: 
 1481: //====================== Script for composing message ==============
 1482:    // preload images
 1483:    img1 = new Image();
 1484:    img1.src = "$iconpath/mailbkgrd.gif";
 1485:    img2 = new Image();
 1486:    img2.src = "$iconpath/mailto.gif";
 1487: 
 1488:   function msgCenter(msgform,usrctr,fullname) {
 1489:     var Nmsg  = msgform.savemsgN.value;
 1490:     savedMsgHeader(Nmsg,usrctr,fullname);
 1491:     var subject = msgform.msgsub.value;
 1492:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1493:     re = /msgsub/;
 1494:     var shwsel = "";
 1495:     if (re.test(msgchk)) { shwsel = "checked" }
 1496:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1497:     displaySubject(checkEntities(subject),shwsel);
 1498:     for (var i=1; i<=Nmsg; i++) {
 1499: 	var testmsg = "savemsg"+i+",";
 1500: 	re = new RegExp(testmsg,"g");
 1501: 	shwsel = "";
 1502: 	if (re.test(msgchk)) { shwsel = "checked" }
 1503: 	var message = document.SCORE["savemsg"+i].value;
 1504: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1505: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1506: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1507:     }
 1508:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1509:     shwsel = "";
 1510:     re = /newmsg/;
 1511:     if (re.test(msgchk)) { shwsel = "checked" }
 1512:     newMsg(newmsg,shwsel);
 1513:     msgTail(); 
 1514:     return;
 1515:   }
 1516: 
 1517:   function checkEntities(strx) {
 1518:     if (strx.length == 0) return strx;
 1519:     var orgStr = ["&", "<", ">", '"']; 
 1520:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1521:     var counter = 0;
 1522:     while (counter < 4) {
 1523: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1524: 	counter++;
 1525:     }
 1526:     return strx;
 1527:   }
 1528: 
 1529:   function strReplace(strx, orgStr, newStr) {
 1530:     return strx.split(orgStr).join(newStr);
 1531:   }
 1532: 
 1533:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1534:     var height = 70*Nmsg+250;
 1535:     var scrollbar = "no";
 1536:     if (height > 600) {
 1537: 	height = 600;
 1538: 	scrollbar = "yes";
 1539:     }
 1540:     var xpos = (screen.width-600)/2;
 1541:     xpos = (xpos < 0) ? '0' : xpos;
 1542:     var ypos = (screen.height-height)/2-30;
 1543:     ypos = (ypos < 0) ? '0' : ypos;
 1544: 
 1545:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1546:     pWin.focus();
 1547:     pDoc = pWin.document;
 1548:     pDoc.$docopen;
 1549:     pDoc.write('$start_page_msg_central');
 1550: 
 1551:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1552:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1553:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1554: 
 1555:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1556:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1557:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1558: }
 1559:     function displaySubject(msg,shwsel) {
 1560:     pDoc = pWin.document;
 1561:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1562:     pDoc.write("<td>Subject<\\/td>");
 1563:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1564:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1565: }
 1566: 
 1567:   function displaySavedMsg(ctr,msg,shwsel) {
 1568:     pDoc = pWin.document;
 1569:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1570:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1571:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1572:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1573: }
 1574: 
 1575:   function newMsg(newmsg,shwsel) {
 1576:     pDoc = pWin.document;
 1577:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1578:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1579:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1580:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1581: }
 1582: 
 1583:   function msgTail() {
 1584:     pDoc = pWin.document;
 1585:     pDoc.write("<\\/table>");
 1586:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1587:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1588:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1589:     pDoc.write("<\\/form>");
 1590:     pDoc.write('$end_page_msg_central');
 1591:     pDoc.close();
 1592: }
 1593: 
 1594: //====================== Script for keyword highlight options ==============
 1595:   function kwhighlight() {
 1596:     var kwclr    = document.SCORE.kwclr.value;
 1597:     var kwsize   = document.SCORE.kwsize.value;
 1598:     var kwstyle  = document.SCORE.kwstyle.value;
 1599:     var redsel = "";
 1600:     var grnsel = "";
 1601:     var blusel = "";
 1602:     if (kwclr=="red")   {var redsel="checked"};
 1603:     if (kwclr=="green") {var grnsel="checked"};
 1604:     if (kwclr=="blue")  {var blusel="checked"};
 1605:     var sznsel = "";
 1606:     var sz1sel = "";
 1607:     var sz2sel = "";
 1608:     if (kwsize=="0")  {var sznsel="checked"};
 1609:     if (kwsize=="+1") {var sz1sel="checked"};
 1610:     if (kwsize=="+2") {var sz2sel="checked"};
 1611:     var synsel = "";
 1612:     var syisel = "";
 1613:     var sybsel = "";
 1614:     if (kwstyle=="")    {var synsel="checked"};
 1615:     if (kwstyle=="<i>") {var syisel="checked"};
 1616:     if (kwstyle=="<b>") {var sybsel="checked"};
 1617:     highlightCentral();
 1618:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1619:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1620:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1621:     highlightend();
 1622:     return;
 1623:   }
 1624: 
 1625:   function highlightCentral() {
 1626: //    if (window.hwdWin) window.hwdWin.close();
 1627:     var xpos = (screen.width-400)/2;
 1628:     xpos = (xpos < 0) ? '0' : xpos;
 1629:     var ypos = (screen.height-330)/2-30;
 1630:     ypos = (ypos < 0) ? '0' : ypos;
 1631: 
 1632:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1633:     hwdWin.focus();
 1634:     var hDoc = hwdWin.document;
 1635:     hDoc.$docopen;
 1636:     hDoc.write('$start_page_highlight_central');
 1637:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1638:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1639: 
 1640:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1641:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1642:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1643:   }
 1644: 
 1645:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1646:     var hDoc = hwdWin.document;
 1647:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1648:     hDoc.write("<td align=\\"left\\">");
 1649:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1650:     hDoc.write("<td align=\\"left\\">");
 1651:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1652:     hDoc.write("<td align=\\"left\\">");
 1653:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1654:     hDoc.write("<\\/tr>");
 1655:   }
 1656: 
 1657:   function highlightend() { 
 1658:     var hDoc = hwdWin.document;
 1659:     hDoc.write("<\\/table>");
 1660:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1661:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1662:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1663:     hDoc.write("<\\/form>");
 1664:     hDoc.write('$end_page_highlight_central');
 1665:     hDoc.close();
 1666:   }
 1667: 
 1668: </script>
 1669: SUBJAVASCRIPT
 1670: }
 1671: 
 1672: sub get_increment {
 1673:     my $increment = $env{'form.increment'};
 1674:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1675:         $increment != .1) {
 1676:         $increment = 1;
 1677:     }
 1678:     return $increment;
 1679: }
 1680: 
 1681: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1682: sub gradeBox {
 1683:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1684:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1685: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1686:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1687:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1688:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1689:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1690:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1691: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1692:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1693:     my $display_part= &get_display_part($partid,$symb);
 1694:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1695: 				       [$partid]);
 1696:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1697:     if ($last_resets{$partid}) {
 1698:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1699:     }
 1700:     $result.='<table border="0"><tr>';
 1701:     my $ctr = 0;
 1702:     my $thisweight = 0;
 1703:     my $increment = &get_increment();
 1704: 
 1705:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1706:     while ($thisweight<=$wgt) {
 1707: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1708: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1709: 	    $thisweight.')" value="'.$thisweight.'" '.
 1710: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1711: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1712:         $thisweight += $increment;
 1713: 	$ctr++;
 1714:     }
 1715:     $radio.='</tr></table>';
 1716: 
 1717:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1718: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1719: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1720: 	$wgt.')" /></td>'."\n";
 1721:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1722: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1723: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1724:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1725: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1726:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1727: 	$line.='<option></option>'.
 1728: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1729:     } else {
 1730: 	$line.='<option selected="selected"></option>'.
 1731: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1732:     }
 1733:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1734: 
 1735: 
 1736: 	#&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);
 1737:     $result .= 
 1738: 	    '<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>';
 1739:     $result.='</tr></table>'."\n";
 1740:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1741: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1742: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1743: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1744:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1745:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1746:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1747:         $aggtries.'" />'."\n";
 1748:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1749:     return $result;
 1750: }
 1751: 
 1752: sub handback_box {
 1753:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1754:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1755:     my (@respids);
 1756:      my @part_response_id = &flatten_responseType($responseType);
 1757:     foreach my $part_response_id (@part_response_id) {
 1758:     	my ($part,$resp) = @{ $part_response_id };
 1759:         if ($part eq $partid) {
 1760:             push(@respids,$resp);
 1761:         }
 1762:     }
 1763:     my $result;
 1764:     foreach my $respid (@respids) {
 1765: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1766: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1767: 	next if (!@$files);
 1768: 	my $file_counter = 1;
 1769: 	foreach my $file (@$files) {
 1770: 	    if ($file =~ /\/portfolio\//) {
 1771:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1772:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1773:     	        $file_disp = "$name.$ext";
 1774:     	        $file = $file_path.$file_disp;
 1775:     	        $result.=&mt('Return commented version of [_1] to student.',
 1776:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1777:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1778:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1779:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1780:     	        $file_counter++;
 1781: 	    }
 1782: 	}
 1783:     }
 1784:     return $result;    
 1785: }
 1786: 
 1787: sub show_problem {
 1788:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1789:     my $rendered;
 1790:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1791:     &Apache::lonxml::remember_problem_counter();
 1792:     if ($mode eq 'both' or $mode eq 'text') {
 1793: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1794: 						       $env{'request.course.id'},
 1795: 						       undef,\%form);
 1796:     }
 1797:     if ($removeform) {
 1798: 	$rendered=~s|<form(.*?)>||g;
 1799: 	$rendered=~s|</form>||g;
 1800: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1801:     }
 1802:     my $companswer;
 1803:     if ($mode eq 'both' or $mode eq 'answer') {
 1804: 	&Apache::lonxml::restore_problem_counter();
 1805: 	$companswer=
 1806: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1807: 						    $env{'request.course.id'},
 1808: 						    %form);
 1809:     }
 1810:     if ($removeform) {
 1811: 	$companswer=~s|<form(.*?)>||g;
 1812: 	$companswer=~s|</form>||g;
 1813: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1814:     }
 1815:     $rendered=
 1816: 	'<div class="LC_grade_show_problem_header">'.
 1817: 	&mt('View of the problem').
 1818: 	'</div><div class="LC_grade_show_problem_problem">'.
 1819: 	$rendered.
 1820: 	'</div>';
 1821:     $companswer=
 1822: 	'<div class="LC_grade_show_problem_header">'.
 1823: 	&mt('Correct answer').
 1824: 	'</div><div class="LC_grade_show_problem_problem">'.
 1825: 	$companswer.
 1826: 	'</div>';
 1827:     my $result;
 1828:     if ($mode eq 'both') {
 1829: 	$result=$rendered.$companswer;
 1830:     } elsif ($mode eq 'text') {
 1831: 	$result=$rendered;
 1832:     } elsif ($mode eq 'answer') {
 1833: 	$result=$companswer;
 1834:     }
 1835:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1836:     return $result;
 1837: }
 1838: 
 1839: sub files_exist {
 1840:     my ($r, $symb) = @_;
 1841:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1842: 
 1843:     foreach my $student (@students) {
 1844:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1845:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1846: 					      $udom,$uname);
 1847:         my ($string,$timestamp)= &get_last_submission(\%record);
 1848:         foreach my $submission (@$string) {
 1849:             my ($partid,$respid) =
 1850: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1851:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1852: 					   \%record);
 1853:             return 1 if (@$files);
 1854:         }
 1855:     }
 1856:     return 0;
 1857: }
 1858: 
 1859: sub download_all_link {
 1860:     my ($r,$symb) = @_;
 1861:     my $all_students = 
 1862: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1863: 
 1864:     my $parts =
 1865: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1866: 
 1867:     my $identifier = &Apache::loncommon::get_cgi_id();
 1868:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1869:                              'cgi.'.$identifier.'.symb' => $symb,
 1870:                              'cgi.'.$identifier.'.parts' => $parts,});
 1871:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1872: 	      &mt('Download All Submitted Documents').'</a>');
 1873:     return
 1874: }
 1875: 
 1876: sub build_section_inputs {
 1877:     my $section_inputs;
 1878:     if ($env{'form.section'} eq '') {
 1879:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1880:     } else {
 1881:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1882:         foreach my $section (@sections) {
 1883:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1884:         }
 1885:     }
 1886:     return $section_inputs;
 1887: }
 1888: 
 1889: # --------------------------- show submissions of a student, option to grade 
 1890: sub submission {
 1891:     my ($request,$counter,$total) = @_;
 1892:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1893:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1894:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1895:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1896:     my $symb = &get_symb($request); 
 1897:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1898: 
 1899:     if (!&canview($usec)) {
 1900: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1901: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1902: 			$env{'request.course.id'}.')</span>');
 1903: 	$request->print(&show_grading_menu_form($symb));
 1904: 	return;
 1905:     }
 1906: 
 1907:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1908:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1909:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1910:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1911:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1912: 	'" src="'.$request->dir_config('lonIconsURL').
 1913: 	'/check.gif" height="16" border="0" />';
 1914: 
 1915:     my %old_essays;
 1916:     # header info
 1917:     if ($counter == 0) {
 1918: 	&sub_page_js($request);
 1919: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1920: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1921: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1922: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1923: 	    &download_all_link($request, $symb);
 1924: 	}
 1925: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1926: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1927: 
 1928: 	# option to display problem, only once else it cause problems 
 1929:         # with the form later since the problem has a form.
 1930: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1931: 	    my $mode;
 1932: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1933: 		$mode='both';
 1934: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1935: 		$mode='text';
 1936: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1937: 		$mode='answer';
 1938: 	    }
 1939: 	    &Apache::lonxml::clear_problem_counter();
 1940: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1941: 	}
 1942: 
 1943: 	# kwclr is the only variable that is guaranteed to be non blank 
 1944:         # if this subroutine has been called once.
 1945: 	my %keyhash = ();
 1946: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1947: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1948: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1949: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1950: 
 1951: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1952: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1953: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1954: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1955: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1956: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1957: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1958: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1959: 	}
 1960: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1961: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1962: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1963: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1964: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1965: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1966: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1967: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1968: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1969: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1970: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1971: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1972: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1973: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1974: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1975: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1976: 			&build_section_inputs().
 1977: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1978: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1979: 			'<input type="hidden" name="NCT"'.
 1980: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1981: 	if ($env{'form.handgrade'} eq 'yes') {
 1982: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1983: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1984: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1985: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1986: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1987: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1988: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1989: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1990: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1991: 	    }
 1992: 	}
 1993: 	
 1994: 	my ($cts,$prnmsg) = (1,'');
 1995: 	while ($cts <= $env{'form.savemsgN'}) {
 1996: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1997: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1998: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1999: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2000: 		'" />'."\n".
 2001: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2002: 	    $cts++;
 2003: 	}
 2004: 	$request->print($prnmsg);
 2005: 
 2006: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2007: #
 2008: # Print out the keyword options line
 2009: #
 2010: 	    $request->print(<<KEYWORDS);
 2011: &nbsp;<b>Keyword Options:</b>&nbsp;
 2012: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2013: <a href="#" onMouseDown="javascript:getSel(); return false"
 2014:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2015: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2016: KEYWORDS
 2017: #
 2018: # Load the other essays for similarity check
 2019: #
 2020:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2021: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2022: 	    $apath=&escape($apath);
 2023: 	    $apath=~s/\W/\_/gs;
 2024: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2025:         }
 2026:     }
 2027: 
 2028: # This is where output for one specific student would start
 2029:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2030:     $request->print("\n\n".
 2031:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2032: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2033: 		    '<div class="LC_grade_show_user_body">'."\n");
 2034: 
 2035:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2036: 	my $mode;
 2037: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2038: 	    $mode='both';
 2039: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2040: 	    $mode='text';
 2041: 	} elsif ($env{'form.vAns'} eq 'all') {
 2042: 	    $mode='answer';
 2043: 	}
 2044: 	&Apache::lonxml::clear_problem_counter();
 2045: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2046:     }
 2047: 
 2048:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2050: 
 2051:     # Display student info
 2052:     $request->print(($counter == 0 ? '' : '<br />'));
 2053:     my $result='<div class="LC_grade_submissions">';
 2054:     
 2055:     $result.='<div class="LC_grade_submissions_header">';
 2056:     $result.= &mt('Submissions');
 2057:     $result.='<input type="hidden" name="name'.$counter.
 2058: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2059:     if ($env{'form.handgrade'} eq 'no') {
 2060: 	$result.='<span class="LC_grade_check_note">'.
 2061: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2062: 
 2063:     }
 2064: 
 2065: 
 2066: 
 2067:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2068:     my $fullname;
 2069:     my $col_fullnames = [];
 2070:     if ($env{'form.handgrade'} eq 'yes') {
 2071: 	(my $sub_result,$fullname,$col_fullnames)=
 2072: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2073: 				 $counter);
 2074: 	$result.=$sub_result;
 2075:     }
 2076:     $request->print($result."\n");
 2077:     $request->print('</div>'."\n");
 2078:     # print student answer/submission
 2079:     # Options are (1) Handgaded submission only
 2080:     #             (2) Last submission, includes submission that is not handgraded 
 2081:     #                  (for multi-response type part)
 2082:     #             (3) Last submission plus the parts info
 2083:     #             (4) The whole record for this student
 2084:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2085: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2086: 	
 2087: 	my $lastsubonly;
 2088: 
 2089: 	if ($$timestamp eq '') {
 2090: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2091: 	} else {
 2092: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2093: 
 2094: 	    my %seenparts;
 2095: 	    my @part_response_id = &flatten_responseType($responseType);
 2096: 	    foreach my $part (@part_response_id) {
 2097: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2098: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2099: 
 2100: 		my ($partid,$respid) = @{ $part };
 2101: 		my $display_part=&get_display_part($partid,$symb);
 2102: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2103: 		    if (exists($seenparts{$partid})) { next; }
 2104: 		    $seenparts{$partid}=1;
 2105: 		    my $submitby='<b>Part:</b> '.$display_part.
 2106: 			' <b>Collaborative submission by:</b> '.
 2107: 			'<a href="javascript:viewSubmitter(\''.
 2108: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2109: 			'\');" target="_self">'.
 2110: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2111: 		    $request->print($submitby);
 2112: 		    next;
 2113: 		}
 2114: 		my $responsetype = $responseType->{$partid}->{$respid};
 2115: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2116:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2117:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2118:                         ' <span class="LC_internal_info">'.
 2119:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
 2120:                         '</span>&nbsp; &nbsp;'.
 2121: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2122: 		    next;
 2123: 		}
 2124: 		foreach my $submission (@$string) {
 2125: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2126: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2127: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2128: 		    # Similarity check
 2129: 		    my $similar='';
 2130: 		    if($env{'form.checkPlag'}){
 2131: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2132: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2133: 			if ($osim) {
 2134: 			    $osim=int($osim*100.0);
 2135: 			    my %old_course_desc = 
 2136: 				&Apache::lonnet::coursedescription($ocrsid,
 2137: 								   {'one_time' => 1});
 2138: 
 2139: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2140: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2141: 				    $osim,
 2142: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2143: 				    $old_course_desc{'description'},
 2144: 				    $old_course_desc{'num'},
 2145: 				    $old_course_desc{'domain'}).
 2146: 				'</span></h3><blockquote><i>'.
 2147: 				&keywords_highlight($oessay).
 2148: 				'</i></blockquote><hr />';
 2149: 			}
 2150: 		    }
 2151: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2152: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2153: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2154: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2155: 			my $display_part=&get_display_part($partid,$symb);
 2156:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2157:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2158:                             ' <span class="LC_internal_info">'.
 2159:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2160:                             '</b></span>&nbsp; &nbsp;';
 2161: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2162: 			if (@$files) {
 2163: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2164: 			    my $file_counter = 0;
 2165: 			    foreach my $file (@$files) {
 2166: 			        $file_counter++;
 2167: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2168: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2169: 			    }
 2170: 			    $lastsubonly.='<br />';
 2171: 			}
 2172: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2173: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2174: 					 $respid,\%record,$order,undef,$uname,$udom);
 2175: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2176: 			$lastsubonly.='</div>';
 2177: 		    }
 2178: 		}
 2179: 	    }
 2180: 	    $lastsubonly.='</div>'."\n";
 2181: 	}
 2182: 	$request->print($lastsubonly);
 2183:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2184: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2185: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2186:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2187: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2188: 								 $env{'request.course.id'},
 2189: 								 $last,'.submission',
 2190: 								 'Apache::grades::keywords_highlight'));
 2191:     }
 2192: 
 2193:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2194: 	.$udom.'" />'."\n");
 2195:     # return if view submission with no grading option
 2196:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2197: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2198: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2199: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2200: 	$toGrade.='</div>'."\n";
 2201: 	if (($env{'form.command'} eq 'submission') || 
 2202: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2203: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2204: 	}
 2205: 	$request->print($toGrade);
 2206: 	return;
 2207:     } else {
 2208: 	$request->print('</div>'."\n");
 2209:     }
 2210: 
 2211:     # essay grading message center
 2212:     if ($env{'form.handgrade'} eq 'yes') {
 2213: 	my $result='<div class="LC_grade_message_center">';
 2214:     
 2215: 	$result.='<div class="LC_grade_message_center_header">'.
 2216: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2217: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2218: 	my $msgfor = $givenn.' '.$lastname;
 2219: 	if (scalar(@$col_fullnames) > 0) {
 2220: 	    my $lastone = pop(@$col_fullnames);
 2221: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2222: 	}
 2223: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2224: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2225: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2226: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2227: 	    ',\''.$msgfor.'\');" target="_self">'.
 2228: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2229: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2230: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2231: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2232: 	    '<br />&nbsp;('.
 2233: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2234: 	$result.='</div></div>';
 2235: 	$request->print($result);
 2236:     }
 2237: 
 2238:     my %seen = ();
 2239:     my @partlist;
 2240:     my @gradePartRespid;
 2241:     my @part_response_id = &flatten_responseType($responseType);
 2242:     $request->print('<div class="LC_grade_assign">'.
 2243: 		    
 2244: 		    '<div class="LC_grade_assign_header">'.
 2245: 		    &mt('Assign Grades').'</div>'.
 2246: 		    '<div class="LC_grade_assign_body">');
 2247:     foreach my $part_response_id (@part_response_id) {
 2248:     	my ($partid,$respid) = @{ $part_response_id };
 2249: 	my $part_resp = join('_',@{ $part_response_id });
 2250: 	next if ($seen{$partid} > 0);
 2251: 	$seen{$partid}++;
 2252: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2253: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2254: 	push(@partlist,$partid);
 2255: 	push(@gradePartRespid,$partid.'.'.$respid);
 2256: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2257:     }
 2258:     $request->print('</div></div>');
 2259: 
 2260:     $request->print('<div class="LC_grade_info_links">');
 2261:     if ($perm{'vgr'}) {
 2262: 	$request->print(
 2263: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2264: 						   $uname,$udom,'check'));
 2265:     }
 2266:     if ($perm{'opa'}) {
 2267: 	$request->print(
 2268: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2269: 					 $uname,$udom,$symb,'check'));
 2270:     }
 2271:     $request->print('</div>');
 2272: 
 2273:     $result='<input type="hidden" name="partlist'.$counter.
 2274: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2275:     $result.='<input type="hidden" name="gradePartRespid'.
 2276: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2277:     my $ctr = 0;
 2278:     while ($ctr < scalar(@partlist)) {
 2279: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2280: 	    $partlist[$ctr].'" />'."\n";
 2281: 	$ctr++;
 2282:     }
 2283:     $request->print($result.''."\n");
 2284: 
 2285: # Done with printing info for one student
 2286: 
 2287:     $request->print('</div>');#LC_grade_show_user_body
 2288:     $request->print('</div>');#LC_grade_show_user
 2289: 
 2290: 
 2291:     # print end of form
 2292:     if ($counter == $total) {
 2293: 	my $endform='<table border="0"><tr><td>'."\n";
 2294: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2295: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2296: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2297: 	my $ntstu ='<select name="NTSTU">'.
 2298: 	    '<option>1</option><option>2</option>'.
 2299: 	    '<option>3</option><option>5</option>'.
 2300: 	    '<option>7</option><option>10</option></select>'."\n";
 2301: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2302: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2303:         $endform.=&mt('[_1]student(s)',$ntstu);
 2304: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2305: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2306: 	    '<input type="button" value="'.&mt('Next').'" '.
 2307: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2308: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2309:         $endform.="<input type='hidden' value='".&get_increment().
 2310:             "' name='increment' />";
 2311: 	$endform.='</td></tr></table></form>';
 2312: 	$endform.=&show_grading_menu_form($symb);
 2313: 	$request->print($endform);
 2314:     }
 2315:     return '';
 2316: }
 2317: 
 2318: sub check_collaborators {
 2319:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2320:     my ($result,@col_fullnames);
 2321:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2322:     foreach my $part (keys(%$handgrade)) {
 2323: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2324: 					'.maxcollaborators',
 2325: 					$symb,$udom,$uname);
 2326: 	next if ($ncol <= 0);
 2327: 	$part =~ s/\_/\./g;
 2328: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2329: 	my (@good_collaborators, @bad_collaborators);
 2330: 	foreach my $possible_collaborator
 2331: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2332: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2333: 	    next if ($possible_collaborator eq '');
 2334: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2335: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2336: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2337: 	    # Doing this grep allows 'fuzzy' specification
 2338: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2339: 			       keys(%$classlist));
 2340: 	    if (! scalar(@matches)) {
 2341: 		push(@bad_collaborators, $possible_collaborator);
 2342: 	    } else {
 2343: 		push(@good_collaborators, @matches);
 2344: 	    }
 2345: 	}
 2346: 	if (scalar(@good_collaborators) != 0) {
 2347: 	    $result.='<br />'.&mt('Collaborators: ');
 2348: 	    foreach my $name (@good_collaborators) {
 2349: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2350: 		push(@col_fullnames, $givenn.' '.$lastname);
 2351: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2352: 	    }
 2353: 	    $result.='<br />'."\n";
 2354: 	    my ($part)=split(/\./,$part);
 2355: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2356: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2357: 		"\n";
 2358: 	}
 2359: 	if (scalar(@bad_collaborators) > 0) {
 2360: 	    $result.='<div class="LC_warning">';
 2361: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2362: 	    $result .= '</div>';
 2363: 	}         
 2364: 	if (scalar(@bad_collaborators > $ncol)) {
 2365: 	    $result .= '<div class="LC_warning">';
 2366: 	    $result .= &mt('This student has submitted too many '.
 2367: 		'collaborators.  Maximum is [_1].',$ncol);
 2368: 	    $result .= '</div>';
 2369: 	}
 2370:     }
 2371:     return ($result,$fullname,\@col_fullnames);
 2372: }
 2373: 
 2374: #--- Retrieve the last submission for all the parts
 2375: sub get_last_submission {
 2376:     my ($returnhash)=@_;
 2377:     my (@string,$timestamp);
 2378:     if ($$returnhash{'version'}) {
 2379: 	my %lasthash=();
 2380: 	my ($version);
 2381: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2382: 	    foreach my $key (sort(split(/\:/,
 2383: 					$$returnhash{$version.':keys'}))) {
 2384: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2385: 		$timestamp = 
 2386: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2387: 	    }
 2388: 	}
 2389: 	foreach my $key (keys(%lasthash)) {
 2390: 	    next if ($key !~ /\.submission$/);
 2391: 
 2392: 	    my ($partid,$foo) = split(/submission$/,$key);
 2393: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2394: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2395: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2396: 	}
 2397:     }
 2398:     if (!@string) {
 2399: 	$string[0] =
 2400: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2401:     }
 2402:     return (\@string,\$timestamp);
 2403: }
 2404: 
 2405: #--- High light keywords, with style choosen by user.
 2406: sub keywords_highlight {
 2407:     my $string    = shift;
 2408:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2409:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2410:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2411:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2412:     foreach my $keyword (@keylist) {
 2413: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2414:     }
 2415:     return $string;
 2416: }
 2417: 
 2418: #--- Called from submission routine
 2419: sub processHandGrade {
 2420:     my ($request) = shift;
 2421:     my $symb   = &get_symb($request);
 2422:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2423:     my $button = $env{'form.gradeOpt'};
 2424:     my $ngrade = $env{'form.NCT'};
 2425:     my $ntstu  = $env{'form.NTSTU'};
 2426:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2427:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2428: 
 2429:     if ($button eq 'Save & Next') {
 2430: 	my $ctr = 0;
 2431: 	while ($ctr < $ngrade) {
 2432: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2433: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2434: 	    if ($errorflag eq 'no_score') {
 2435: 		$ctr++;
 2436: 		next;
 2437: 	    }
 2438: 	    if ($errorflag eq 'not_allowed') {
 2439: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2440: 		$ctr++;
 2441: 		next;
 2442: 	    }
 2443: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2444: 	    my ($subject,$message,$msgstatus) = ('','','');
 2445: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2446:             my ($feedurl,$showsymb) =
 2447: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2448: 	    my $messagetail;
 2449: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2450: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2451: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2452: 		$subject.=' ['.$restitle.']';
 2453: 		my (@msgnum) = split(/,/,$includemsg);
 2454: 		foreach (@msgnum) {
 2455: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2456: 		}
 2457: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2458: 		if ($env{'form.withgrades'.$ctr}) {
 2459: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2460: 		    $messagetail = " for <a href=\"".
 2461: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2462: 		}
 2463: 		$msgstatus = 
 2464:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2465: 						     $message.$messagetail,
 2466:                                                      undef,$feedurl,undef,
 2467:                                                      undef,undef,$showsymb,
 2468:                                                      $restitle);
 2469: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2470: 				$msgstatus);
 2471: 	    }
 2472: 	    if ($env{'form.collaborator'.$ctr}) {
 2473: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2474: 		foreach my $collabstr (@collabstrs) {
 2475: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2476: 		    foreach my $collaborator (@collaborators) {
 2477: 			my ($errorflag,$pts,$wgt) = 
 2478: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2479: 					   $env{'form.unamedom'.$ctr},$part);
 2480: 			if ($errorflag eq 'not_allowed') {
 2481: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2482: 			    next;
 2483: 			} elsif ($message ne '') {
 2484: 			    my ($baseurl,$showsymb) = 
 2485: 				&get_feedurl_and_symb($symb,$collaborator,
 2486: 						      $udom);
 2487: 			    if ($env{'form.withgrades'.$ctr}) {
 2488: 				$messagetail = " for <a href=\"".
 2489:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2490: 			    }
 2491: 			    $msgstatus = 
 2492: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2493: 			}
 2494: 		    }
 2495: 		}
 2496: 	    }
 2497: 	    $ctr++;
 2498: 	}
 2499:     }
 2500: 
 2501:     if ($env{'form.handgrade'} eq 'yes') {
 2502: 	# Keywords sorted in alphabatical order
 2503: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2504: 	my %keyhash = ();
 2505: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2506: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2507: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2508: 	$env{'form.keywords'} = join(' ',@keywords);
 2509: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2510: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2511: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2512: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2513: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2514: 
 2515: 	# message center - Order of message gets changed. Blank line is eliminated.
 2516: 	# New messages are saved in env for the next student.
 2517: 	# All messages are saved in nohist_handgrade.db
 2518: 	my ($ctr,$idx) = (1,1);
 2519: 	while ($ctr <= $env{'form.savemsgN'}) {
 2520: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2521: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2522: 		$idx++;
 2523: 	    }
 2524: 	    $ctr++;
 2525: 	}
 2526: 	$ctr = 0;
 2527: 	while ($ctr < $ngrade) {
 2528: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2529: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2530: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2531: 		$idx++;
 2532: 	    }
 2533: 	    $ctr++;
 2534: 	}
 2535: 	$env{'form.savemsgN'} = --$idx;
 2536: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2537: 	my $putresult = &Apache::lonnet::put
 2538: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2539:     }
 2540:     # Called by Save & Refresh from Highlight Attribute Window
 2541:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2542:     if ($env{'form.refresh'} eq 'on') {
 2543: 	my ($ctr,$total) = (0,0);
 2544: 	while ($ctr < $ngrade) {
 2545: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2546: 	    $ctr++;
 2547: 	}
 2548: 	$env{'form.NTSTU'}=$ngrade;
 2549: 	$ctr = 0;
 2550: 	while ($ctr < $total) {
 2551: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2552: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2553: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2554: 	    &submission($request,$ctr,$total-1);
 2555: 	    $ctr++;
 2556: 	}
 2557: 	return '';
 2558:     }
 2559: 
 2560: # Go directly to grade student - from submission or link from chart page
 2561:     if ($button eq 'Grade Student') {
 2562: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2563: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2564: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2565: 	$env{'form.fullname'} = $$fullname{$processUser};
 2566: 	&submission($request,0,0);
 2567: 	return '';
 2568:     }
 2569: 
 2570:     # Get the next/previous one or group of students
 2571:     my $firststu = $env{'form.unamedom0'};
 2572:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2573:     my $ctr = 2;
 2574:     while ($laststu eq '') {
 2575: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2576: 	$ctr++;
 2577: 	$laststu = $firststu if ($ctr > $ngrade);
 2578:     }
 2579: 
 2580:     my (@parsedlist,@nextlist);
 2581:     my ($nextflg) = 0;
 2582:     foreach my $item (sort 
 2583: 	     {
 2584: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2585: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2586: 		 }
 2587: 		 return $a cmp $b;
 2588: 	     } (keys(%$fullname))) {
 2589: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2590: 	    push(@parsedlist,$item);
 2591: 	}
 2592: 	$nextflg = 1 if ($item eq $laststu);
 2593: 	if ($button eq 'Previous') {
 2594: 	    last if ($item eq $firststu);
 2595: 	    push(@parsedlist,$item);
 2596: 	}
 2597:     }
 2598:     $ctr = 0;
 2599:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2600:     my ($partlist) = &response_type($symb);
 2601:     foreach my $student (@parsedlist) {
 2602: 	my $submitonly=$env{'form.submitonly'};
 2603: 	my ($uname,$udom) = split(/:/,$student);
 2604: 	
 2605: 	if ($submitonly eq 'queued') {
 2606: 	    my %queue_status = 
 2607: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2608: 							$udom,$uname);
 2609: 	    next if (!defined($queue_status{'gradingqueue'}));
 2610: 	}
 2611: 
 2612: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2613: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2614: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2615: 	    my $submitted = 0;
 2616: 	    my $ungraded = 0;
 2617: 	    my $incorrect = 0;
 2618: 	    foreach my $item (keys(%status)) {
 2619: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2620: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2621: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2622: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2623: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2624: 		    $submitted = 0;
 2625: 		}
 2626: 	    }
 2627: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2628: 				     $submitonly eq 'incorrect' ||
 2629: 				     $submitonly eq 'graded'));
 2630: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2631: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2632: 	}
 2633: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2634: 	last if ($ctr == $ntstu);
 2635: 	$ctr++;
 2636:     }
 2637: 
 2638:     $ctr = 0;
 2639:     my $total = scalar(@nextlist)-1;
 2640: 
 2641:     foreach (sort(@nextlist)) {
 2642: 	my ($uname,$udom,$submitter) = split(/:/);
 2643: 	$env{'form.student'}  = $uname;
 2644: 	$env{'form.userdom'}  = $udom;
 2645: 	$env{'form.fullname'} = $$fullname{$_};
 2646: 	&submission($request,$ctr,$total);
 2647: 	$ctr++;
 2648:     }
 2649:     if ($total < 0) {
 2650: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2651: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2652: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2653: 	$the_end.=&show_grading_menu_form($symb);
 2654: 	$request->print($the_end);
 2655:     }
 2656:     return '';
 2657: }
 2658: 
 2659: #---- Save the score and award for each student, if changed
 2660: sub saveHandGrade {
 2661:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2662:     my @version_parts;
 2663:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2664: 					   $env{'request.course.id'});
 2665:     if (!&canmodify($usec)) { return('not_allowed'); }
 2666:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2667:     my @parts_graded;
 2668:     my %newrecord  = ();
 2669:     my ($pts,$wgt) = ('','');
 2670:     my %aggregate = ();
 2671:     my $aggregateflag = 0;
 2672:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2673:     foreach my $new_part (@parts) {
 2674: 	#collaborator ($submi may vary for different parts
 2675: 	if ($submitter && $new_part ne $part) { next; }
 2676: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2677: 	if ($dropMenu eq 'excused') {
 2678: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2679: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2680: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2681: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2682: 		}
 2683: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2684: 	    }
 2685: 	} elsif ($dropMenu eq 'reset status'
 2686: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2687: 	    foreach my $key (keys(%record)) {
 2688: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2689: 	    }
 2690: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2691: 		"$env{'user.name'}:$env{'user.domain'}";
 2692:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2693: 
 2694:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2695: 					       [$new_part]);
 2696:             my $aggtries =$totaltries;
 2697:             if ($last_resets{$new_part}) {
 2698:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2699: 					   $new_part);
 2700:             }
 2701: 
 2702:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2703:             if ($aggtries > 0) {
 2704:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2705:                 $aggregateflag = 1;
 2706:             }
 2707: 	} elsif ($dropMenu eq '') {
 2708: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2709: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2710: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2711: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2712: 		next;
 2713: 	    }
 2714: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2715: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2716: 	    my $partial= $pts/$wgt;
 2717: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2718: 		#do not update score for part if not changed.
 2719:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2720: 		next;
 2721: 	    } else {
 2722: 	        push(@parts_graded,$new_part);
 2723: 	    }
 2724: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2725: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2726: 	    }
 2727: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2728: 	    if ($partial == 0) {
 2729: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2730: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2731: 		}
 2732: 	    } else {
 2733: 		if ($record{$reckey} ne 'correct_by_override') {
 2734: 		    $newrecord{$reckey} = 'correct_by_override';
 2735: 		}
 2736: 	    }	    
 2737: 	    if ($submitter && 
 2738: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2739: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2740: 	    }
 2741: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2742: 		"$env{'user.name'}:$env{'user.domain'}";
 2743: 	}
 2744: 	# unless problem has been graded, set flag to version the submitted files
 2745: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2746: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2747: 	        $dropMenu eq 'reset status')
 2748: 	   {
 2749: 	    push(@version_parts,$new_part);
 2750: 	}
 2751:     }
 2752:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2753:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2754: 
 2755:     if (%newrecord) {
 2756:         if (@version_parts) {
 2757:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2758:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2759: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2760: 	    foreach my $new_part (@version_parts) {
 2761: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2762: 				$new_part,\%newrecord);
 2763: 	    }
 2764:         }
 2765: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2766: 				$env{'request.course.id'},$domain,$stuname);
 2767: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2768: 				     $cdom,$cnum,$domain,$stuname);
 2769:     }
 2770:     if ($aggregateflag) {
 2771:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2772: 			      $cdom,$cnum);
 2773:     }
 2774:     return ('',$pts,$wgt);
 2775: }
 2776: 
 2777: sub check_and_remove_from_queue {
 2778:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2779:     my @ungraded_parts;
 2780:     foreach my $part (@{$parts}) {
 2781: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2782: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2783: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2784: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2785: 		) {
 2786: 	    push(@ungraded_parts, $part);
 2787: 	}
 2788:     }
 2789:     if ( !@ungraded_parts ) {
 2790: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2791: 					       $cnum,$domain,$stuname);
 2792:     }
 2793: }
 2794: 
 2795: sub handback_files {
 2796:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2797:     my $portfolio_root = '/userfiles/portfolio';
 2798:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2799: 
 2800:     my @part_response_id = &flatten_responseType($responseType);
 2801:     foreach my $part_response_id (@part_response_id) {
 2802:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2803: 	my $part_resp = join('_',@{ $part_response_id });
 2804:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2805:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2806:                 my $file_counter = 1;
 2807: 		my $file_msg;
 2808:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2809:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2810:                     my ($directory,$answer_file) = 
 2811:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2812:                     my ($answer_name,$answer_ver,$answer_ext) =
 2813: 		        &file_name_version_ext($answer_file);
 2814: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2815:                     my $getpropath = 1;
 2816: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2817: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2818:                     # fix file name
 2819:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2820:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2821:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2822:             	                                $save_file_name);
 2823:                     if ($result !~ m|^/uploaded/|) {
 2824:                         $request->print('<br /><span class="LC_error">'.
 2825:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2826:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2827:                                         '</span>');
 2828:                     } else {
 2829:                         # mark the file as read only
 2830:                         my @files = ($save_file_name);
 2831:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2832:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2833: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2834: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2835: 			}
 2836:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2837: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2838: 
 2839:                     }
 2840:                     $request->print("<br />".$fname." will be the uploaded file name");
 2841:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2842:                     $file_counter++;
 2843:                 }
 2844: 		my $subject = "File Handed Back by Instructor ";
 2845: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2846: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2847: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2848: 		$message .= " and can be found in your portfolio space.";
 2849: 		my ($feedurl,$showsymb) = 
 2850: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2851:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2852: 		my $msgstatus = 
 2853:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2854: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2855:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2856:             }
 2857:         }
 2858:     return;
 2859: }
 2860: 
 2861: sub get_feedurl_and_symb {
 2862:     my ($symb,$uname,$udom) = @_;
 2863:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2864:     $url = &Apache::lonnet::clutter($url);
 2865:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2866: 					$symb,$udom,$uname);
 2867:     if ($encrypturl =~ /^yes$/i) {
 2868: 	&Apache::lonenc::encrypted(\$url,1);
 2869: 	&Apache::lonenc::encrypted(\$symb,1);
 2870:     }
 2871:     return ($url,$symb);
 2872: }
 2873: 
 2874: sub get_submitted_files {
 2875:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2876:     my @files;
 2877:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2878:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2879:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2880:     	    push(@files,$file_url.$file);
 2881:         }
 2882:     }
 2883:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2884:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2885:     }
 2886:     return (\@files);
 2887: }
 2888: 
 2889: # ----------- Provides number of tries since last reset.
 2890: sub get_num_tries {
 2891:     my ($record,$last_reset,$part) = @_;
 2892:     my $timestamp = '';
 2893:     my $num_tries = 0;
 2894:     if ($$record{'version'}) {
 2895:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2896:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2897:                 $timestamp = $$record{$version.':timestamp'};
 2898:                 if ($timestamp > $last_reset) {
 2899:                     $num_tries ++;
 2900:                 } else {
 2901:                     last;
 2902:                 }
 2903:             }
 2904:         }
 2905:     }
 2906:     return $num_tries;
 2907: }
 2908: 
 2909: # ----------- Determine decrements required in aggregate totals 
 2910: sub decrement_aggs {
 2911:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2912:     my %decrement = (
 2913:                         attempts => 0,
 2914:                         users => 0,
 2915:                         correct => 0
 2916:                     );
 2917:     $decrement{'attempts'} = $aggtries;
 2918:     if ($solvedstatus =~ /^correct/) {
 2919:         $decrement{'correct'} = 1;
 2920:     }
 2921:     if ($aggtries == $totaltries) {
 2922:         $decrement{'users'} = 1;
 2923:     }
 2924:     foreach my $type (keys(%decrement)) {
 2925:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2926:     }
 2927:     return;
 2928: }
 2929: 
 2930: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2931: sub get_last_resets {
 2932:     my ($symb,$courseid,$partids) =@_;
 2933:     my %last_resets;
 2934:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2935:     my $cname = $env{'course.'.$courseid.'.num'};
 2936:     my @keys;
 2937:     foreach my $part (@{$partids}) {
 2938: 	push(@keys,"$symb\0$part\0resettime");
 2939:     }
 2940:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2941: 				     $cdom,$cname);
 2942:     foreach my $part (@{$partids}) {
 2943: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2944:     }
 2945:     return %last_resets;
 2946: }
 2947: 
 2948: # ----------- Handles creating versions for portfolio files as answers
 2949: sub version_portfiles {
 2950:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2951:     my $version_parts = join('|',@$v_flag);
 2952:     my @returned_keys;
 2953:     my $parts = join('|', @$parts_graded);
 2954:     my $portfolio_root = '/userfiles/portfolio';
 2955:     foreach my $key (keys(%$record)) {
 2956:         my $new_portfiles;
 2957:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2958:             my @versioned_portfiles;
 2959:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2960:             foreach my $file (@portfiles) {
 2961:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2962:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2963: 		my ($answer_name,$answer_ver,$answer_ext) =
 2964: 		    &file_name_version_ext($answer_file);
 2965:                 my $getpropath = 1;    
 2966:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2967:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2968:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2969:                 if ($new_answer ne 'problem getting file') {
 2970:                     push(@versioned_portfiles, $directory.$new_answer);
 2971:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2972:                         [$directory.$new_answer],
 2973:                         [$symb,$env{'request.course.id'},'graded']);
 2974:                 }
 2975:             }
 2976:             $$record{$key} = join(',',@versioned_portfiles);
 2977:             push(@returned_keys,$key);
 2978:         }
 2979:     } 
 2980:     return (@returned_keys);   
 2981: }
 2982: 
 2983: sub get_next_version {
 2984:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2985:     my $version;
 2986:     foreach my $row (@$dir_list) {
 2987:         my ($file) = split(/\&/,$row,2);
 2988:         my ($file_name,$file_version,$file_ext) =
 2989: 	    &file_name_version_ext($file);
 2990:         if (($file_name eq $answer_name) && 
 2991: 	    ($file_ext eq $answer_ext)) {
 2992:                 # gets here if filename and extension match, regardless of version
 2993:                 if ($file_version ne '') {
 2994:                 # a versioned file is found  so save it for later
 2995:                 if ($file_version > $version) {
 2996: 		    $version = $file_version;
 2997: 	        }
 2998:             }
 2999:         }
 3000:     } 
 3001:     $version ++;
 3002:     return($version);
 3003: }
 3004: 
 3005: sub version_selected_portfile {
 3006:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3007:     my ($answer_name,$answer_ver,$answer_ext) =
 3008:         &file_name_version_ext($file_name);
 3009:     my $new_answer;
 3010:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3011:     if($env{'form.copy'} eq '-1') {
 3012:         $new_answer = 'problem getting file';
 3013:     } else {
 3014:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3015:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3016:                             $stu_name,$domain,'copy',
 3017: 		        '/portfolio'.$directory.$new_answer);
 3018:     }    
 3019:     return ($new_answer);
 3020: }
 3021: 
 3022: sub file_name_version_ext {
 3023:     my ($file)=@_;
 3024:     my @file_parts = split(/\./, $file);
 3025:     my ($name,$version,$ext);
 3026:     if (@file_parts > 1) {
 3027: 	$ext=pop(@file_parts);
 3028: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3029: 	    $version=pop(@file_parts);
 3030: 	}
 3031: 	$name=join('.',@file_parts);
 3032:     } else {
 3033: 	$name=join('.',@file_parts);
 3034:     }
 3035:     return($name,$version,$ext);
 3036: }
 3037: 
 3038: #--------------------------------------------------------------------------------------
 3039: #
 3040: #-------------------------- Next few routines handles grading by section or whole class
 3041: #
 3042: #--- Javascript to handle grading by section or whole class
 3043: sub viewgrades_js {
 3044:     my ($request) = shift;
 3045: 
 3046:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3047:     $request->print(<<VIEWJAVASCRIPT);
 3048: <script type="text/javascript" language="javascript">
 3049:    function writePoint(partid,weight,point) {
 3050: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3051: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3052: 	if (point == "textval") {
 3053: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3054: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3055: 		alert("$alertmsg"+parseFloat(point));
 3056: 		var resetbox = false;
 3057: 		for (var i=0; i<radioButton.length; i++) {
 3058: 		    if (radioButton[i].checked) {
 3059: 			textbox.value = i;
 3060: 			resetbox = true;
 3061: 		    }
 3062: 		}
 3063: 		if (!resetbox) {
 3064: 		    textbox.value = "";
 3065: 		}
 3066: 		return;
 3067: 	    }
 3068: 	    if (parseFloat(point) > parseFloat(weight)) {
 3069: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3070: 				   ") greater than the weight for the part. Accept?");
 3071: 		if (resp == false) {
 3072: 		    textbox.value = "";
 3073: 		    return;
 3074: 		}
 3075: 	    }
 3076: 	    for (var i=0; i<radioButton.length; i++) {
 3077: 		radioButton[i].checked=false;
 3078: 		if (parseFloat(point) == i) {
 3079: 		    radioButton[i].checked=true;
 3080: 		}
 3081: 	    }
 3082: 
 3083: 	} else {
 3084: 	    textbox.value = parseFloat(point);
 3085: 	}
 3086: 	for (i=0;i<document.classgrade.total.value;i++) {
 3087: 	    var user = document.classgrade["ctr"+i].value;
 3088: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3089: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3090: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3091: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3092: 	    if (saveval != "correct") {
 3093: 		scorename.value = point;
 3094: 		if (selname[0].selected != true) {
 3095: 		    selname[0].selected = true;
 3096: 		}
 3097: 	    }
 3098: 	}
 3099: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3100:     }
 3101: 
 3102:     function writeRadText(partid,weight) {
 3103: 	var selval   = document.classgrade["SELVAL_"+partid];
 3104: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3105:         var override = document.classgrade["FORCE_"+partid].checked;
 3106: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3107: 	if (selval[1].selected || selval[2].selected) {
 3108: 	    for (var i=0; i<radioButton.length; i++) {
 3109: 		radioButton[i].checked=false;
 3110: 
 3111: 	    }
 3112: 	    textbox.value = "";
 3113: 
 3114: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3115: 		var user = document.classgrade["ctr"+i].value;
 3116: 		user = user.replace(new RegExp(':', 'g'),"_");
 3117: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3118: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3119: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3120: 		if ((saveval != "correct") || override) {
 3121: 		    scorename.value = "";
 3122: 		    if (selval[1].selected) {
 3123: 			selname[1].selected = true;
 3124: 		    } else {
 3125: 			selname[2].selected = true;
 3126: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3127: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3128: 		    }
 3129: 		}
 3130: 	    }
 3131: 	} else {
 3132: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3133: 		var user = document.classgrade["ctr"+i].value;
 3134: 		user = user.replace(new RegExp(':', 'g'),"_");
 3135: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3136: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3137: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3138: 		if ((saveval != "correct") || override) {
 3139: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3140: 		    selname[0].selected = true;
 3141: 		}
 3142: 	    }
 3143: 	}	    
 3144:     }
 3145: 
 3146:     function changeSelect(partid,user) {
 3147: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3148: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3149: 	var point  = textbox.value;
 3150: 	var weight = document.classgrade["weight_"+partid].value;
 3151: 
 3152: 	if (isNaN(point) || parseFloat(point) < 0) {
 3153: 	    alert("$alertmsg"+parseFloat(point));
 3154: 	    textbox.value = "";
 3155: 	    return;
 3156: 	}
 3157: 	if (parseFloat(point) > parseFloat(weight)) {
 3158: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3159: 			       ") greater than the weight of the part. Accept?");
 3160: 	    if (resp == false) {
 3161: 		textbox.value = "";
 3162: 		return;
 3163: 	    }
 3164: 	}
 3165: 	selval[0].selected = true;
 3166:     }
 3167: 
 3168:     function changeOneScore(partid,user) {
 3169: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3170: 	if (selval[1].selected || selval[2].selected) {
 3171: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3172: 	    if (selval[2].selected) {
 3173: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3174: 	    }
 3175:         }
 3176:     }
 3177: 
 3178:     function resetEntry(numpart) {
 3179: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3180: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3181: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3182: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3183: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3184: 	    for (var i=0; i<radioButton.length; i++) {
 3185: 		radioButton[i].checked=false;
 3186: 
 3187: 	    }
 3188: 	    textbox.value = "";
 3189: 	    selval[0].selected = true;
 3190: 
 3191: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3192: 		var user = document.classgrade["ctr"+i].value;
 3193: 		user = user.replace(new RegExp(':', 'g'),"_");
 3194: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3195: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3196: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3197: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3198: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3199: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3200: 		if (saveselval == "excused") {
 3201: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3202: 		} else {
 3203: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3204: 		}
 3205: 	    }
 3206: 	}
 3207:     }
 3208: 
 3209: </script>
 3210: VIEWJAVASCRIPT
 3211: }
 3212: 
 3213: #--- show scores for a section or whole class w/ option to change/update a score
 3214: sub viewgrades {
 3215:     my ($request) = shift;
 3216:     &viewgrades_js($request);
 3217: 
 3218:     my ($symb) = &get_symb($request);
 3219:     #need to make sure we have the correct data for later EXT calls, 
 3220:     #thus invalidate the cache
 3221:     &Apache::lonnet::devalidatecourseresdata(
 3222:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3223:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3224:     &Apache::lonnet::clear_EXT_cache_status();
 3225: 
 3226:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3227:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3228: 
 3229:     #view individual student submission form - called using Javascript viewOneStudent
 3230:     $result.=&jscriptNform($symb);
 3231: 
 3232:     #beginning of class grading form
 3233:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3234:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3235: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3236: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3237: 	&build_section_inputs().
 3238: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3239: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3240: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3241: 
 3242:     my ($common_header,$specific_header);
 3243:     if ($env{'form.section'} eq 'all') {
 3244: 	$common_header = &mt('Assign Common Grade to Class');
 3245:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3246:     } elsif ($env{'form.section'} eq 'none') {
 3247:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3248: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3249:     } else {
 3250:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3251:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3252: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3253:     }
 3254:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3255:     #radio buttons/text box for assigning points for a section or class.
 3256:     #handles different parts of a problem
 3257:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3258:     my %weight = ();
 3259:     my $ctsparts = 0;
 3260:     my %seen = ();
 3261:     my @part_response_id = &flatten_responseType($responseType);
 3262:     foreach my $part_response_id (@part_response_id) {
 3263:     	my ($partid,$respid) = @{ $part_response_id };
 3264: 	my $part_resp = join('_',@{ $part_response_id });
 3265: 	next if $seen{$partid};
 3266: 	$seen{$partid}++;
 3267: 	my $handgrade=$$handgrade{$part_resp};
 3268: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3269: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3270: 
 3271: 	my $display_part=&get_display_part($partid,$symb);
 3272: 	my $radio.='<table border="0"><tr>';  
 3273: 	my $ctr = 0;
 3274: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3275: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3276: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3277: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3278: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3279: 	    $ctr++;
 3280: 	}
 3281: 	$radio.='</tr></table>';
 3282: 	my $line = '<input type="text" name="TEXTVAL_'.
 3283: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3284: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3285: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3286: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3287: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3288: 		$weight{$partid}.')"> '.
 3289: 	    '<option selected="selected"> </option>'.
 3290: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3291: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3292: 	    '</select></td>'.
 3293:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3294: 	$line.='<input type="hidden" name="partid_'.
 3295: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3296: 	$line.='<input type="hidden" name="weight_'.
 3297: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3298: 
 3299: 	$result.=
 3300: 	    &Apache::loncommon::start_data_table_row()."\n".
 3301: 	    '<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>'.
 3302: 	    &Apache::loncommon::end_data_table_row()."\n";
 3303: 	$ctsparts++;
 3304:     }
 3305:     $result.=&Apache::loncommon::end_data_table()."\n".
 3306: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3307:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3308: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3309: 
 3310:     #table listing all the students in a section/class
 3311:     #header of table
 3312:     $result.= '<h3>'.$specific_header.'</h3>'.
 3313:               &Apache::loncommon::start_data_table().
 3314: 	      &Apache::loncommon::start_data_table_header_row().
 3315: 	      '<th>'.&mt('No.').'</th>'.
 3316: 	      '<th>'.&nameUserString('header')."</th>\n";
 3317:     my (@parts) = sort(&getpartlist($symb));
 3318:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3319:     my @partids = ();
 3320:     foreach my $part (@parts) {
 3321: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3322:         my $narrowtext = &mt('Tries');
 3323: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3324: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3325: 	my ($partid) = &split_part_type($part);
 3326:         push(@partids,$partid);
 3327: 	my $display_part=&get_display_part($partid,$symb);
 3328: 	if ($display =~ /^Partial Credit Factor/) {
 3329: 	    $result.='<th>'.
 3330: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3331: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3332: 	    next;
 3333: 	    
 3334: 	} else {
 3335: 	    if ($display =~ /Problem Status/) {
 3336: 		my $grade_status_mt = &mt('Grade Status');
 3337: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3338: 	    }
 3339: 	    my $part_mt = &mt('Part:');
 3340: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3341: 	}
 3342: 
 3343: 	$result.='<th>'.$display.'</th>'."\n";
 3344:     }
 3345:     $result.=&Apache::loncommon::end_data_table_header_row();
 3346: 
 3347:     my %last_resets = 
 3348: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3349: 
 3350:     #get info for each student
 3351:     #list all the students - with points and grade status
 3352:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3353:     my $ctr = 0;
 3354:     foreach (sort 
 3355: 	     {
 3356: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3357: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3358: 		 }
 3359: 		 return $a cmp $b;
 3360: 	     } (keys(%$fullname))) {
 3361: 	$ctr++;
 3362: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3363: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3364:     }
 3365:     $result.=&Apache::loncommon::end_data_table();
 3366:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3367:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3368: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3369:     if (scalar(%$fullname) eq 0) {
 3370: 	my $colspan=3+scalar(@parts);
 3371: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3372:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3373: 	$result='<span class="LC_warning">'.
 3374: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3375: 	        $section_display, $stu_status).
 3376: 	    '</span>';
 3377:     }
 3378:     $result.=&show_grading_menu_form($symb);
 3379:     return $result;
 3380: }
 3381: 
 3382: #--- call by previous routine to display each student
 3383: sub viewstudentgrade {
 3384:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3385:     my ($uname,$udom) = split(/:/,$student);
 3386:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3387:     my %aggregates = (); 
 3388:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3389: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3390: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3391: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3392: 	'\');" target="_self">'.$fullname.'</a> '.
 3393: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3394:     $student=~s/:/_/; # colon doen't work in javascript for names
 3395:     foreach my $apart (@$parts) {
 3396: 	my ($part,$type) = &split_part_type($apart);
 3397: 	my $score=$record{"resource.$part.$type"};
 3398:         $result.='<td align="center">';
 3399:         my ($aggtries,$totaltries);
 3400:         unless (exists($aggregates{$part})) {
 3401: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3402: 
 3403: 	    $aggtries = $totaltries;
 3404:             if ($$last_resets{$part}) {  
 3405:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3406: 					   $part);
 3407:             }
 3408:             $result.='<input type="hidden" name="'.
 3409:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3410:             $result.='<input type="hidden" name="'.
 3411:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3412:             $aggregates{$part} = 1;
 3413:         }
 3414: 	if ($type eq 'awarded') {
 3415: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3416: 	    $result.='<input type="hidden" name="'.
 3417: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3418: 	    $result.='<input type="text" name="'.
 3419: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3420: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3421: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3422: 	} elsif ($type eq 'solved') {
 3423: 	    my ($status,$foo)=split(/_/,$score,2);
 3424: 	    $status = 'nothing' if ($status eq '');
 3425: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3426: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3427: 	    $result.='&nbsp;<select name="'.
 3428: 		'GD_'.$student.'_'.$part.'_solved" '.
 3429: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3430: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3431: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3432: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3433: 	    $result.="</select>&nbsp;</td>\n";
 3434: 	} else {
 3435: 	    $result.='<input type="hidden" name="'.
 3436: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3437: 		    "\n";
 3438: 	    $result.='<input type="text" name="'.
 3439: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3440: 		'value="'.$score.'" size="4" /></td>'."\n";
 3441: 	}
 3442:     }
 3443:     $result.=&Apache::loncommon::end_data_table_row();
 3444:     return $result;
 3445: }
 3446: 
 3447: #--- change scores for all the students in a section/class
 3448: #    record does not get update if unchanged
 3449: sub editgrades {
 3450:     my ($request) = @_;
 3451: 
 3452:     my $symb=&get_symb($request);
 3453:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3454:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3455:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3456:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3457: 
 3458:     my $result= &Apache::loncommon::start_data_table().
 3459: 	&Apache::loncommon::start_data_table_header_row().
 3460: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3461: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3462:     my %scoreptr = (
 3463: 		    'correct'  =>'correct_by_override',
 3464: 		    'incorrect'=>'incorrect_by_override',
 3465: 		    'excused'  =>'excused',
 3466: 		    'ungraded' =>'ungraded_attempted',
 3467: 		    'nothing'  => '',
 3468: 		    );
 3469:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3470: 
 3471:     my (@partid);
 3472:     my %weight = ();
 3473:     my %columns = ();
 3474:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3475: 
 3476:     my (@parts) = sort(&getpartlist($symb));
 3477:     my $header;
 3478:     while ($ctr < $env{'form.totalparts'}) {
 3479: 	my $partid = $env{'form.partid_'.$ctr};
 3480: 	push(@partid,$partid);
 3481: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3482: 	$ctr++;
 3483:     }
 3484:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3485:     foreach my $partid (@partid) {
 3486: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3487: 	    '<th align="center">'.&mt('New Score').'</th>';
 3488: 	$columns{$partid}=2;
 3489: 	foreach my $stores (@parts) {
 3490: 	    my ($part,$type) = &split_part_type($stores);
 3491: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3492: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3493: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3494: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3495:             my $narrowtext = &mt('Tries');
 3496: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3497: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3498: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3499: 	    $columns{$partid}+=2;
 3500: 	}
 3501:     }
 3502:     foreach my $partid (@partid) {
 3503: 	my $display_part=&get_display_part($partid,$symb);
 3504: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3505: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3506: 	    '</th>';
 3507: 
 3508:     }
 3509:     $result .= &Apache::loncommon::end_data_table_header_row().
 3510: 	&Apache::loncommon::start_data_table_header_row().
 3511: 	$header.
 3512: 	&Apache::loncommon::end_data_table_header_row();
 3513:     my @noupdate;
 3514:     my ($updateCtr,$noupdateCtr) = (1,1);
 3515:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3516: 	my $line;
 3517: 	my $user = $env{'form.ctr'.$i};
 3518: 	my ($uname,$udom)=split(/:/,$user);
 3519: 	my %newrecord;
 3520: 	my $updateflag = 0;
 3521: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3522: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3523: 	if (!&canmodify($usec)) {
 3524: 	    my $numcols=scalar(@partid)*4+2;
 3525: 	    push(@noupdate,
 3526: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3527: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3528: 	    next;
 3529: 	}
 3530:         my %aggregate = ();
 3531:         my $aggregateflag = 0;
 3532: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3533: 	foreach (@partid) {
 3534: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3535: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3536: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3537: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3538: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3539: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3540: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3541: 	    my $score;
 3542: 	    if ($partial eq '') {
 3543: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3544: 	    } elsif ($partial > 0) {
 3545: 		$score = 'correct_by_override';
 3546: 	    } elsif ($partial == 0) {
 3547: 		$score = 'incorrect_by_override';
 3548: 	    }
 3549: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3550: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3551: 
 3552: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3553: 		"$env{'user.name'}:$env{'user.domain'}";
 3554: 	    if ($dropMenu eq 'reset status' &&
 3555: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3556: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3557: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3558: 		$newrecord{'resource.'.$_.'.award'} = '';
 3559: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3560: 		$updateflag = 1;
 3561:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3562:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3563:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3564:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3565:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3566:                     $aggregateflag = 1;
 3567:                 }
 3568: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3569: 		$updateflag = 1;
 3570: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3571: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3572: 		$rec_update++;
 3573: 	    }
 3574: 
 3575: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3576: 		'<td align="center">'.$awarded.
 3577: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3578: 
 3579: 
 3580: 	    my $partid=$_;
 3581: 	    foreach my $stores (@parts) {
 3582: 		my ($part,$type) = &split_part_type($stores);
 3583: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3584: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3585: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3586: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3587: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3588: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3589: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3590: 		    $updateflag=1;
 3591: 		}
 3592: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3593: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3594: 	    }
 3595: 	}
 3596: 	$line.="\n";
 3597: 
 3598: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3599: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3600: 
 3601: 	if ($updateflag) {
 3602: 	    $count++;
 3603: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3604: 				    $udom,$uname);
 3605: 
 3606: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3607: 					      $cnum,$udom,$uname)) {
 3608: 		# need to figure out if should be in queue.
 3609: 		my %record =  
 3610: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3611: 					     $udom,$uname);
 3612: 		my $all_graded = 1;
 3613: 		my $none_graded = 1;
 3614: 		foreach my $part (@parts) {
 3615: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3616: 			$all_graded = 0;
 3617: 		    } else {
 3618: 			$none_graded = 0;
 3619: 		    }
 3620: 		}
 3621: 
 3622: 		if ($all_graded || $none_graded) {
 3623: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3624: 							   $symb,$cdom,$cnum,
 3625: 							   $udom,$uname);
 3626: 		}
 3627: 	    }
 3628: 
 3629: 	    $result.=&Apache::loncommon::start_data_table_row().
 3630: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3631: 		&Apache::loncommon::end_data_table_row();
 3632: 	    $updateCtr++;
 3633: 	} else {
 3634: 	    push(@noupdate,
 3635: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3636: 	    $noupdateCtr++;
 3637: 	}
 3638:         if ($aggregateflag) {
 3639:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3640: 				  $cdom,$cnum);
 3641:         }
 3642:     }
 3643:     if (@noupdate) {
 3644: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3645: 	my $numcols=scalar(@partid)*4+2;
 3646: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3647: 	    '<td align="center" colspan="'.$numcols.'">'.
 3648: 	    &mt('No Changes Occurred For the Students Below').
 3649: 	    '</td>'.
 3650: 	    &Apache::loncommon::end_data_table_row();
 3651: 	foreach my $line (@noupdate) {
 3652: 	    $result.=
 3653: 		&Apache::loncommon::start_data_table_row().
 3654: 		$line.
 3655: 		&Apache::loncommon::end_data_table_row();
 3656: 	}
 3657:     }
 3658:     $result .= &Apache::loncommon::end_data_table().
 3659: 	&show_grading_menu_form($symb);
 3660:     my $msg = '<p><b>'.
 3661: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3662: 	    $rec_update,$count).'</b><br />'.
 3663: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3664: 	'</b></p>';
 3665:     return $title.$msg.$result;
 3666: }
 3667: 
 3668: sub split_part_type {
 3669:     my ($partstr) = @_;
 3670:     my ($temp,@allparts)=split(/_/,$partstr);
 3671:     my $type=pop(@allparts);
 3672:     my $part=join('_',@allparts);
 3673:     return ($part,$type);
 3674: }
 3675: 
 3676: #------------- end of section for handling grading by section/class ---------
 3677: #
 3678: #----------------------------------------------------------------------------
 3679: 
 3680: 
 3681: #----------------------------------------------------------------------------
 3682: #
 3683: #-------------------------- Next few routines handles grading by csv upload
 3684: #
 3685: #--- Javascript to handle csv upload
 3686: sub csvupload_javascript_reverse_associate {
 3687:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3688:     my $error2=&mt('You need to specify at least one grading field');
 3689:   return(<<ENDPICK);
 3690:   function verify(vf) {
 3691:     var foundsomething=0;
 3692:     var founduname=0;
 3693:     var foundID=0;
 3694:     for (i=0;i<=vf.nfields.value;i++) {
 3695:       tw=eval('vf.f'+i+'.selectedIndex');
 3696:       if (i==0 && tw!=0) { foundID=1; }
 3697:       if (i==1 && tw!=0) { founduname=1; }
 3698:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3699:     }
 3700:     if (founduname==0 && foundID==0) {
 3701: 	alert('$error1');
 3702: 	return;
 3703:     }
 3704:     if (foundsomething==0) {
 3705: 	alert('$error2');
 3706: 	return;
 3707:     }
 3708:     vf.submit();
 3709:   }
 3710:   function flip(vf,tf) {
 3711:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3712:     var i;
 3713:     for (i=0;i<=vf.nfields.value;i++) {
 3714:       //can not pick the same destination field for both name and domain
 3715:       if (((i ==0)||(i ==1)) && 
 3716:           ((tf==0)||(tf==1)) && 
 3717:           (i!=tf) &&
 3718:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3719:         eval('vf.f'+i+'.selectedIndex=0;')
 3720:       }
 3721:     }
 3722:   }
 3723: ENDPICK
 3724: }
 3725: 
 3726: sub csvupload_javascript_forward_associate {
 3727:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3728:     my $error2=&mt('You need to specify at least one grading field');
 3729:   return(<<ENDPICK);
 3730:   function verify(vf) {
 3731:     var foundsomething=0;
 3732:     var founduname=0;
 3733:     var foundID=0;
 3734:     for (i=0;i<=vf.nfields.value;i++) {
 3735:       tw=eval('vf.f'+i+'.selectedIndex');
 3736:       if (tw==1) { foundID=1; }
 3737:       if (tw==2) { founduname=1; }
 3738:       if (tw>3) { foundsomething=1; }
 3739:     }
 3740:     if (founduname==0 && foundID==0) {
 3741: 	alert('$error1');
 3742: 	return;
 3743:     }
 3744:     if (foundsomething==0) {
 3745: 	alert('$error2');
 3746: 	return;
 3747:     }
 3748:     vf.submit();
 3749:   }
 3750:   function flip(vf,tf) {
 3751:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3752:     var i;
 3753:     //can not pick the same destination field twice
 3754:     for (i=0;i<=vf.nfields.value;i++) {
 3755:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3756:         eval('vf.f'+i+'.selectedIndex=0;')
 3757:       }
 3758:     }
 3759:   }
 3760: ENDPICK
 3761: }
 3762: 
 3763: sub csvuploadmap_header {
 3764:     my ($request,$symb,$datatoken,$distotal)= @_;
 3765:     my $javascript;
 3766:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3767: 	$javascript=&csvupload_javascript_reverse_associate();
 3768:     } else {
 3769: 	$javascript=&csvupload_javascript_forward_associate();
 3770:     }
 3771: 
 3772:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3773:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3774:     my $ignore=&mt('Ignore First Line');
 3775:     $symb = &Apache::lonenc::check_encrypt($symb);
 3776:     $request->print(<<ENDPICK);
 3777: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3778: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3779: $result
 3780: <hr />
 3781: <h3>Identify fields</h3>
 3782: Total number of records found in file: $distotal <hr />
 3783: Enter as many fields as you can. The system will inform you and bring you back
 3784: to this page if the data selected is insufficient to run your class.<hr />
 3785: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3786: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3787: <input type="hidden" name="associate"  value="" />
 3788: <input type="hidden" name="phase"      value="three" />
 3789: <input type="hidden" name="datatoken"  value="$datatoken" />
 3790: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3791: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3792: <input type="hidden" name="upfile_associate" 
 3793:                                        value="$env{'form.upfile_associate'}" />
 3794: <input type="hidden" name="symb"       value="$symb" />
 3795: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3796: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3797: <input type="hidden" name="command"    value="csvuploadoptions" />
 3798: <hr />
 3799: <script type="text/javascript" language="Javascript">
 3800: $javascript
 3801: </script>
 3802: ENDPICK
 3803:     return '';
 3804: 
 3805: }
 3806: 
 3807: sub csvupload_fields {
 3808:     my ($symb) = @_;
 3809:     my (@parts) = &getpartlist($symb);
 3810:     my @fields=(['ID','Student/Employee ID'],
 3811: 		['username','Student Username'],
 3812: 		['domain','Student Domain']);
 3813:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3814:     foreach my $part (sort(@parts)) {
 3815: 	my @datum;
 3816: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3817: 	my $name=$part;
 3818: 	if  (!$display) { $display = $name; }
 3819: 	@datum=($name,$display);
 3820: 	if ($name=~/^stores_(.*)_awarded/) {
 3821: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3822: 	}
 3823: 	push(@fields,\@datum);
 3824:     }
 3825:     return (@fields);
 3826: }
 3827: 
 3828: sub csvuploadmap_footer {
 3829:     my ($request,$i,$keyfields) =@_;
 3830:     $request->print(<<ENDPICK);
 3831: </table>
 3832: <input type="hidden" name="nfields" value="$i" />
 3833: <input type="hidden" name="keyfields" value="$keyfields" />
 3834: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3835: </form>
 3836: ENDPICK
 3837: }
 3838: 
 3839: sub checkforfile_js {
 3840:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3841:     my $result =<<CSVFORMJS;
 3842: <script type="text/javascript" language="javascript">
 3843:     function checkUpload(formname) {
 3844: 	if (formname.upfile.value == "") {
 3845: 	    alert("$alertmsg");
 3846: 	    return false;
 3847: 	}
 3848: 	formname.submit();
 3849:     }
 3850:     </script>
 3851: CSVFORMJS
 3852:     return $result;
 3853: }
 3854: 
 3855: sub upcsvScores_form {
 3856:     my ($request) = shift;
 3857:     my ($symb)=&get_symb($request);
 3858:     if (!$symb) {return '';}
 3859:     my $result=&checkforfile_js();
 3860:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3861:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3862:     $result.=$table;
 3863:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3864:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3865:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3866: 	'</b></td></tr>'."\n";
 3867:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3868:     my $upload=&mt("Upload Scores");
 3869:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3870:     my $ignore=&mt('Ignore First Line');
 3871:     $symb = &Apache::lonenc::check_encrypt($symb);
 3872:     $result.=<<ENDUPFORM;
 3873: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3874: <input type="hidden" name="symb" value="$symb" />
 3875: <input type="hidden" name="command" value="csvuploadmap" />
 3876: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3877: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3878: $upfile_select
 3879: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3880: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3881: </form>
 3882: ENDUPFORM
 3883:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3884:                            &mt("How do I create a CSV file from a spreadsheet"))
 3885:     .'</td></tr></table>'."\n";
 3886:     $result.='</td></tr></table><br /><br />'."\n";
 3887:     $result.=&show_grading_menu_form($symb);
 3888:     return $result;
 3889: }
 3890: 
 3891: 
 3892: sub csvuploadmap {
 3893:     my ($request)= @_;
 3894:     my ($symb)=&get_symb($request);
 3895:     if (!$symb) {return '';}
 3896: 
 3897:     my $datatoken;
 3898:     if (!$env{'form.datatoken'}) {
 3899: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3900:     } else {
 3901: 	$datatoken=$env{'form.datatoken'};
 3902: 	&Apache::loncommon::load_tmp_file($request);
 3903:     }
 3904:     my @records=&Apache::loncommon::upfile_record_sep();
 3905:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3906:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3907:     my ($i,$keyfields);
 3908:     if (@records) {
 3909: 	my @fields=&csvupload_fields($symb);
 3910: 
 3911: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3912: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3913: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3914: 							  \@fields);
 3915: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3916: 	    chop($keyfields);
 3917: 	} else {
 3918: 	    unshift(@fields,['none','']);
 3919: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3920: 							    \@fields);
 3921:             foreach my $rec (@records) {
 3922:                 my %temp = &Apache::loncommon::record_sep($rec);
 3923:                 if (%temp) {
 3924:                     $keyfields=join(',',sort(keys(%temp)));
 3925:                     last;
 3926:                 }
 3927:             }
 3928: 	}
 3929:     }
 3930:     &csvuploadmap_footer($request,$i,$keyfields);
 3931:     $request->print(&show_grading_menu_form($symb));
 3932: 
 3933:     return '';
 3934: }
 3935: 
 3936: sub csvuploadoptions {
 3937:     my ($request)= @_;
 3938:     my ($symb)=&get_symb($request);
 3939:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3940:     my $ignore=&mt('Ignore First Line');
 3941:     $request->print(<<ENDPICK);
 3942: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3943: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3944: <input type="hidden" name="command"    value="csvuploadassign" />
 3945: <!--
 3946: <p>
 3947: <label>
 3948:    <input type="checkbox" name="show_full_results" />
 3949:    Show a table of all changes
 3950: </label>
 3951: </p>
 3952: -->
 3953: <p>
 3954: <label>
 3955:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3956:    Overwrite any existing score
 3957: </label>
 3958: </p>
 3959: ENDPICK
 3960:     my %fields=&get_fields();
 3961:     if (!defined($fields{'domain'})) {
 3962: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3963: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3964:     }
 3965:     foreach my $key (sort(keys(%env))) {
 3966: 	if ($key !~ /^form\.(.*)$/) { next; }
 3967: 	my $cleankey=$1;
 3968: 	if ($cleankey eq 'command') { next; }
 3969: 	$request->print('<input type="hidden" name="'.$cleankey.
 3970: 			'"  value="'.$env{$key}.'" />'."\n");
 3971:     }
 3972:     # FIXME do a check for any duplicated user ids...
 3973:     # FIXME do a check for any invalid user ids?...
 3974:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3975: <hr /></form>'."\n");
 3976:     $request->print(&show_grading_menu_form($symb));
 3977:     return '';
 3978: }
 3979: 
 3980: sub get_fields {
 3981:     my %fields;
 3982:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3983:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3984: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3985: 	    if ($env{'form.f'.$i} ne 'none') {
 3986: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3987: 	    }
 3988: 	} else {
 3989: 	    if ($env{'form.f'.$i} ne 'none') {
 3990: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3991: 	    }
 3992: 	}
 3993:     }
 3994:     return %fields;
 3995: }
 3996: 
 3997: sub csvuploadassign {
 3998:     my ($request)= @_;
 3999:     my ($symb)=&get_symb($request);
 4000:     if (!$symb) {return '';}
 4001:     my $error_msg = '';
 4002:     &Apache::loncommon::load_tmp_file($request);
 4003:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4004:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4005:     my %fields=&get_fields();
 4006:     $request->print('<h3>Assigning Grades</h3>');
 4007:     my $courseid=$env{'request.course.id'};
 4008:     my ($classlist) = &getclasslist('all',0);
 4009:     my @notallowed;
 4010:     my @skipped;
 4011:     my $countdone=0;
 4012:     foreach my $grade (@gradedata) {
 4013: 	my %entries=&Apache::loncommon::record_sep($grade);
 4014: 	my $domain;
 4015: 	if ($entries{$fields{'domain'}}) {
 4016: 	    $domain=$entries{$fields{'domain'}};
 4017: 	} else {
 4018: 	    $domain=$env{'form.default_domain'};
 4019: 	}
 4020: 	$domain=~s/\s//g;
 4021: 	my $username=$entries{$fields{'username'}};
 4022: 	$username=~s/\s//g;
 4023: 	if (!$username) {
 4024: 	    my $id=$entries{$fields{'ID'}};
 4025: 	    $id=~s/\s//g;
 4026: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4027: 	    $username=$ids{$id};
 4028: 	}
 4029: 	if (!exists($$classlist{"$username:$domain"})) {
 4030: 	    my $id=$entries{$fields{'ID'}};
 4031: 	    $id=~s/\s//g;
 4032: 	    if ($id) {
 4033: 		push(@skipped,"$id:$domain");
 4034: 	    } else {
 4035: 		push(@skipped,"$username:$domain");
 4036: 	    }
 4037: 	    next;
 4038: 	}
 4039: 	my $usec=$classlist->{"$username:$domain"}[5];
 4040: 	if (!&canmodify($usec)) {
 4041: 	    push(@notallowed,"$username:$domain");
 4042: 	    next;
 4043: 	}
 4044: 	my %points;
 4045: 	my %grades;
 4046: 	foreach my $dest (keys(%fields)) {
 4047: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4048: 		$dest eq 'domain') { next; }
 4049: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4050: 	    if ($dest=~/stores_(.*)_points/) {
 4051: 		my $part=$1;
 4052: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4053: 					      $symb,$domain,$username);
 4054:                 if ($wgt) {
 4055:                     $entries{$fields{$dest}}=~s/\s//g;
 4056:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4057:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4058:                                           : 'correct_by_override';
 4059:                     $grades{"resource.$part.awarded"}=$pcr;
 4060:                     $grades{"resource.$part.solved"}=$award;
 4061:                     $points{$part}=1;
 4062:                 } else {
 4063:                     $error_msg = "<br />" .
 4064:                         &mt("Some point values were assigned"
 4065:                             ." for problems with a weight "
 4066:                             ."of zero. These values were "
 4067:                             ."ignored.");
 4068:                 }
 4069: 	    } else {
 4070: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4071: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4072: 		my $store_key=$dest;
 4073: 		$store_key=~s/^stores/resource/;
 4074: 		$store_key=~s/_/\./g;
 4075: 		$grades{$store_key}=$entries{$fields{$dest}};
 4076: 	    }
 4077: 	}
 4078: 	if (! %grades) { 
 4079:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4080:         } else {
 4081: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4082: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4083: 					   $env{'request.course.id'},
 4084: 					   $domain,$username);
 4085: 	   if ($result eq 'ok') {
 4086: 	      $request->print('.');
 4087: 	   } else {
 4088: 	      $request->print("<p><span class=\"LC_error\">".
 4089:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4090:                                   "$username:$domain",$result)."</span></p>");
 4091: 	   }
 4092: 	   $request->rflush();
 4093: 	   $countdone++;
 4094:         }
 4095:     }
 4096:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4097:     if (@skipped) {
 4098: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4099:         $request->print(join(', ',@skipped));
 4100:     }
 4101:     if (@notallowed) {
 4102: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4103: 	$request->print(join(', ',@notallowed));
 4104:     }
 4105:     $request->print("<br />\n");
 4106:     $request->print(&show_grading_menu_form($symb));
 4107:     return $error_msg;
 4108: }
 4109: #------------- end of section for handling csv file upload ---------
 4110: #
 4111: #-------------------------------------------------------------------
 4112: #
 4113: #-------------- Next few routines handle grading by page/sequence
 4114: #
 4115: #--- Select a page/sequence and a student to grade
 4116: sub pickStudentPage {
 4117:     my ($request) = shift;
 4118: 
 4119:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4120:     $request->print(<<LISTJAVASCRIPT);
 4121: <script type="text/javascript" language="javascript">
 4122: 
 4123: function checkPickOne(formname) {
 4124:     if (radioSelection(formname.student) == null) {
 4125: 	alert("$alertmsg");
 4126: 	return;
 4127:     }
 4128:     ptr = pullDownSelection(formname.selectpage);
 4129:     formname.page.value = formname["page"+ptr].value;
 4130:     formname.title.value = formname["title"+ptr].value;
 4131:     formname.submit();
 4132: }
 4133: 
 4134: </script>
 4135: LISTJAVASCRIPT
 4136:     &commonJSfunctions($request);
 4137:     my ($symb) = &get_symb($request);
 4138:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4139:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4140:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4141: 
 4142:     my $result='<h3><span class="LC_info">&nbsp;'.
 4143: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4144: 
 4145:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4146:     my ($titles,$symbx) = &getSymbMap();
 4147:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4148: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4149: #    my $type=($curpage =~ /\.(page|sequence)/);
 4150:     my $select = '<select name="selectpage">'."\n";
 4151:     my $ctr=0;
 4152:     foreach (@$titles) {
 4153: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4154: 	$select.='<option value="'.$ctr.'" '.
 4155: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4156: 	    '>'.$showtitle.'</option>'."\n";
 4157: 	$ctr++;
 4158:     }
 4159:     $select.= '</select>';
 4160:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4161: 
 4162:     $ctr=0;
 4163:     foreach (@$titles) {
 4164: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4165: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4166: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4167: 	$ctr++;
 4168:     }
 4169:     $result.='<input type="hidden" name="page" />'."\n".
 4170: 	'<input type="hidden" name="title" />'."\n";
 4171: 
 4172:     my $options =
 4173: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4174: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4175:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4176: 
 4177:     $options =
 4178: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4179: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4180: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4181:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4182:     
 4183:     $result.=&build_section_inputs();
 4184:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4185:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4186: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4187: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4188: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4189: 
 4190:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4191: 
 4192:     $result.='&nbsp;<input type="button" '.
 4193: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4194: 
 4195:     $request->print($result);
 4196: 
 4197:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4198: 	&Apache::loncommon::start_data_table().
 4199: 	&Apache::loncommon::start_data_table_header_row().
 4200: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4201: 	'<th>'.&nameUserString('header').'</th>'.
 4202: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4203: 	'<th>'.&nameUserString('header').'</th>'.
 4204: 	&Apache::loncommon::end_data_table_header_row();
 4205:  
 4206:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4207:     my $ptr = 1;
 4208:     foreach my $student (sort 
 4209: 			 {
 4210: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4211: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4212: 			     }
 4213: 			     return $a cmp $b;
 4214: 			 } (keys(%$fullname))) {
 4215: 	my ($uname,$udom) = split(/:/,$student);
 4216: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4217:                                   : '</td>');
 4218: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4219: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4220: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4221: 	$studentTable.=
 4222: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4223:                          : '');
 4224: 	$ptr++;
 4225:     }
 4226:     if ($ptr%2 == 0) {
 4227: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4228: 	    &Apache::loncommon::end_data_table_row();
 4229:     }
 4230:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4231:     $studentTable.='<input type="button" '.
 4232: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4233: 
 4234:     $studentTable.=&show_grading_menu_form($symb);
 4235:     $request->print($studentTable);
 4236: 
 4237:     return '';
 4238: }
 4239: 
 4240: sub getSymbMap {
 4241:     my $navmap = Apache::lonnavmaps::navmap->new();
 4242: 
 4243:     my %symbx = ();
 4244:     my @titles = ();
 4245:     my $minder = 0;
 4246: 
 4247:     # Gather every sequence that has problems.
 4248:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4249: 					       1,0,1);
 4250:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4251: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4252: 	    my $title = $minder.'.'.
 4253: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4254: 	    push(@titles, $title); # minder in case two titles are identical
 4255: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4256: 	    $minder++;
 4257: 	}
 4258:     }
 4259:     return \@titles,\%symbx;
 4260: }
 4261: 
 4262: #
 4263: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4264: sub displayPage {
 4265:     my ($request) = shift;
 4266: 
 4267:     my ($symb) = &get_symb($request);
 4268:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4269:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4270:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4271:     my $pageTitle = $env{'form.page'};
 4272:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4273:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4274:     my $usec=$classlist->{$env{'form.student'}}[5];
 4275: 
 4276:     #need to make sure we have the correct data for later EXT calls, 
 4277:     #thus invalidate the cache
 4278:     &Apache::lonnet::devalidatecourseresdata(
 4279:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4280:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4281:     &Apache::lonnet::clear_EXT_cache_status();
 4282: 
 4283:     if (!&canview($usec)) {
 4284: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4285: 	$request->print(&show_grading_menu_form($symb));
 4286: 	return;
 4287:     }
 4288:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4289:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4290: 	'</h3>'."\n";
 4291:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4292:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4293: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4294:     } else {
 4295: 	delete($env{'form.CODE'});
 4296:     }
 4297:     &sub_page_js($request);
 4298:     $request->print($result);
 4299: 
 4300:     my $navmap = Apache::lonnavmaps::navmap->new();
 4301:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4302:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4303:     if (!$map) {
 4304: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4305: 	$request->print(&show_grading_menu_form($symb));
 4306: 	return; 
 4307:     }
 4308:     my $iterator = $navmap->getIterator($map->map_start(),
 4309: 					$map->map_finish());
 4310: 
 4311:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4312: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4313: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4314: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4315: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4316: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4317: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4318: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4319: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4320: 
 4321:     if (defined($env{'form.CODE'})) {
 4322: 	$studentTable.=
 4323: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4324:     }
 4325:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4326: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4327: 
 4328:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4329: 	&Apache::loncommon::start_data_table().
 4330: 	&Apache::loncommon::start_data_table_header_row().
 4331: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4332: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4333: 	&Apache::loncommon::end_data_table_header_row();
 4334: 
 4335:     &Apache::lonxml::clear_problem_counter();
 4336:     my ($depth,$question,$prob) = (1,1,1);
 4337:     $iterator->next(); # skip the first BEGIN_MAP
 4338:     my $curRes = $iterator->next(); # for "current resource"
 4339:     while ($depth > 0) {
 4340:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4341:         if($curRes == $iterator->END_MAP) { $depth--; }
 4342: 
 4343:         if (ref($curRes) && $curRes->is_problem()) {
 4344: 	    my $parts = $curRes->parts();
 4345:             my $title = $curRes->compTitle();
 4346: 	    my $symbx = $curRes->symb();
 4347: 	    $studentTable.=
 4348: 		&Apache::loncommon::start_data_table_row().
 4349: 		'<td align="center" valign="top" >'.$prob.
 4350: 		(scalar(@{$parts}) == 1 ? '' 
 4351: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4352: 							scalar(@{$parts}))
 4353: 		 ).
 4354: 		 '</td>';
 4355: 	    $studentTable.='<td valign="top">';
 4356: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4357: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4358: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4359: 					     undef,'both',\%form);
 4360: 	    } else {
 4361: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4362: 		$companswer =~ s|<form(.*?)>||g;
 4363: 		$companswer =~ s|</form>||g;
 4364: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4365: #		    $companswer =~ s/$1/ /ms;
 4366: #		    $request->print('match='.$1."<br />\n");
 4367: #		}
 4368: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4369: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4370: 	    }
 4371: 
 4372: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4373: 
 4374: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4375: 		if ($record{'version'} eq '') {
 4376: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4377: 		} else {
 4378: 		    my %responseType = ();
 4379: 		    foreach my $partid (@{$parts}) {
 4380: 			my @responseIds =$curRes->responseIds($partid);
 4381: 			my @responseType =$curRes->responseType($partid);
 4382: 			my %responseIds;
 4383: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4384: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4385: 			}
 4386: 			$responseType{$partid} = \%responseIds;
 4387: 		    }
 4388: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4389: 
 4390: 		}
 4391: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4392: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4393: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4394: 									$env{'request.course.id'},
 4395: 									'','.submission');
 4396:  
 4397: 	    }
 4398: 	    if (&canmodify($usec)) {
 4399: 		foreach my $partid (@{$parts}) {
 4400: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4401: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4402: 		    $question++;
 4403: 		}
 4404: 		$prob++;
 4405: 	    }
 4406: 	    $studentTable.='</td></tr>';
 4407: 
 4408: 	}
 4409:         $curRes = $iterator->next();
 4410:     }
 4411: 
 4412:     $studentTable.='</table>'."\n".
 4413: 	'<input type="button" value="'.&mt('Save').'" '.
 4414: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4415: 	'</form>'."\n";
 4416:     $studentTable.=&show_grading_menu_form($symb);
 4417:     $request->print($studentTable);
 4418: 
 4419:     return '';
 4420: }
 4421: 
 4422: sub displaySubByDates {
 4423:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4424:     my $isCODE=0;
 4425:     my $isTask = ($symb =~/\.task$/);
 4426:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4427:     my $studentTable=&Apache::loncommon::start_data_table().
 4428: 	&Apache::loncommon::start_data_table_header_row().
 4429: 	'<th>'.&mt('Date/Time').'</th>'.
 4430: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4431: 	'<th>'.&mt('Submission').'</th>'.
 4432: 	'<th>'.&mt('Status').'</th>'.
 4433: 	&Apache::loncommon::end_data_table_header_row();
 4434:     my ($version);
 4435:     my %mark;
 4436:     my %orders;
 4437:     $mark{'correct_by_student'} = $checkIcon;
 4438:     if (!exists($$record{'1:timestamp'})) {
 4439: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4440:     }
 4441: 
 4442:     my $interaction;
 4443:     my $no_increment = 1;
 4444:     for ($version=1;$version<=$$record{'version'};$version++) {
 4445: 	my $timestamp = 
 4446: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4447: 	if (exists($$record{$version.':resource.0.version'})) {
 4448: 	    $interaction = $$record{$version.':resource.0.version'};
 4449: 	}
 4450: 
 4451: 	my $where = ($isTask ? "$version:resource.$interaction"
 4452: 		             : "$version:resource");
 4453: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4454: 	    '<td>'.$timestamp.'</td>';
 4455: 	if ($isCODE) {
 4456: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4457: 	}
 4458: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4459: 	my @displaySub = ();
 4460: 	foreach my $partid (@{$parts}) {
 4461: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4462: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4463: 	    
 4464: 
 4465: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4466: 	    my $display_part=&get_display_part($partid,$symb);
 4467: 	    foreach my $matchKey (@matchKey) {
 4468: 		if (exists($$record{$version.':'.$matchKey}) &&
 4469: 		    $$record{$version.':'.$matchKey} ne '') {
 4470: 
 4471: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4472: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4473:                     $displaySub[0].='<span class="LC_nobreak"';
 4474:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4475:                                    .' <span class="LC_internal_info">'
 4476:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4477:                                    .'</span>'
 4478:                                    .' <b>';
 4479: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4480: 			$displaySub[0].=&mt('Trial not counted');
 4481: 		    } else {
 4482: 			$displaySub[0].=&mt('Trial: [_1]',
 4483: 					    $$record{"$where.$partid.tries"});
 4484: 		    }
 4485: 		    my $responseType=($isTask ? 'Task'
 4486:                                               : $responseType->{$partid}->{$responseId});
 4487: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4488: 		    if (!exists($orders{$partid}->{$responseId})) {
 4489: 			$orders{$partid}->{$responseId}=
 4490: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4491:                                        $no_increment);
 4492: 		    }
 4493: 		    $displaySub[0].='</b></span>'; # /nobreak
 4494: 		    $displaySub[0].='&nbsp; '.
 4495: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4496: 		}
 4497: 	    }
 4498: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4499: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4500: 				    $$record{"$where.$partid.checkedin"},
 4501: 				    $$record{"$where.$partid.checkedin.slot"}).
 4502: 					'<br />';
 4503: 	    }
 4504: 	    if (exists $$record{"$where.$partid.award"}) {
 4505: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4506: 		    lc($$record{"$where.$partid.award"}).' '.
 4507: 		    $mark{$$record{"$where.$partid.solved"}}.
 4508: 		    '<br />';
 4509: 	    }
 4510: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4511: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4512: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4513: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4514: 		$displaySub[2].=
 4515: 		    $$record{"$version:resource.$partid.regrader"}.
 4516: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4517: 	    }
 4518: 	}
 4519: 	# needed because old essay regrader has not parts info
 4520: 	if (exists $$record{"$version:resource.regrader"}) {
 4521: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4522: 	}
 4523: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4524: 	if ($displaySub[2]) {
 4525: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4526: 	}
 4527: 	$studentTable.='&nbsp;</td>'.
 4528: 	    &Apache::loncommon::end_data_table_row();
 4529:     }
 4530:     $studentTable.=&Apache::loncommon::end_data_table();
 4531:     return $studentTable;
 4532: }
 4533: 
 4534: sub updateGradeByPage {
 4535:     my ($request) = shift;
 4536: 
 4537:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4538:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4539:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4540:     my $pageTitle = $env{'form.page'};
 4541:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4542:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4543:     my $usec=$classlist->{$env{'form.student'}}[5];
 4544:     if (!&canmodify($usec)) {
 4545: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4546: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4547: 	return;
 4548:     }
 4549:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4550:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4551: 	'</h3>'."\n";
 4552: 
 4553:     $request->print($result);
 4554: 
 4555:     my $navmap = Apache::lonnavmaps::navmap->new();
 4556:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4557:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4558:     if (!$map) {
 4559: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4560: 	my ($symb)=&get_symb($request);
 4561: 	$request->print(&show_grading_menu_form($symb));
 4562: 	return; 
 4563:     }
 4564:     my $iterator = $navmap->getIterator($map->map_start(),
 4565: 					$map->map_finish());
 4566: 
 4567:     my $studentTable=
 4568: 	&Apache::loncommon::start_data_table().
 4569: 	&Apache::loncommon::start_data_table_header_row().
 4570: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4571: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4572: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4573: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4574: 	&Apache::loncommon::end_data_table_header_row();
 4575: 
 4576:     $iterator->next(); # skip the first BEGIN_MAP
 4577:     my $curRes = $iterator->next(); # for "current resource"
 4578:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4579:     while ($depth > 0) {
 4580:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4581:         if($curRes == $iterator->END_MAP) { $depth--; }
 4582: 
 4583:         if (ref($curRes) && $curRes->is_problem()) {
 4584: 	    my $parts = $curRes->parts();
 4585:             my $title = $curRes->compTitle();
 4586: 	    my $symbx = $curRes->symb();
 4587: 	    $studentTable.=
 4588: 		&Apache::loncommon::start_data_table_row().
 4589: 		'<td align="center" valign="top" >'.$prob.
 4590: 		(scalar(@{$parts}) == 1 ? '' 
 4591:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4592: 		.')').'</td>';
 4593: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4594: 
 4595: 	    my %newrecord=();
 4596: 	    my @displayPts=();
 4597:             my %aggregate = ();
 4598:             my $aggregateflag = 0;
 4599: 	    foreach my $partid (@{$parts}) {
 4600: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4601: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4602: 
 4603: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4604: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4605: 		my $partial = $newpts/$wgt;
 4606: 		my $score;
 4607: 		if ($partial > 0) {
 4608: 		    $score = 'correct_by_override';
 4609: 		} elsif ($newpts ne '') { #empty is taken as 0
 4610: 		    $score = 'incorrect_by_override';
 4611: 		}
 4612: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4613: 		if ($dropMenu eq 'excused') {
 4614: 		    $partial = '';
 4615: 		    $score = 'excused';
 4616: 		} elsif ($dropMenu eq 'reset status'
 4617: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4618: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4619: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4620: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4621: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4622: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4623: 		    $changeflag++;
 4624: 		    $newpts = '';
 4625:                     
 4626:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4627:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4628:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4629:                     if ($aggtries > 0) {
 4630:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4631:                         $aggregateflag = 1;
 4632:                     }
 4633: 		}
 4634: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4635: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4636: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4637: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4638: 		    '&nbsp;<br />';
 4639: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4640: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4641: 		    '&nbsp;<br />';
 4642: 		$question++;
 4643: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4644: 
 4645: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4646: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4647: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4648: 		    if (scalar(keys(%newrecord)) > 0);
 4649: 
 4650: 		$changeflag++;
 4651: 	    }
 4652: 	    if (scalar(keys(%newrecord)) > 0) {
 4653: 		my %record = 
 4654: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4655: 					     $udom,$uname);
 4656: 
 4657: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4658: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4659: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4660: 		    $newrecord{'resource.CODE'} = '';
 4661: 		}
 4662: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4663: 					$udom,$uname);
 4664: 		%record = &Apache::lonnet::restore($symbx,
 4665: 						   $env{'request.course.id'},
 4666: 						   $udom,$uname);
 4667: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4668: 					     $cdom,$cnum,$udom,$uname);
 4669: 	    }
 4670: 	    
 4671:             if ($aggregateflag) {
 4672:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4673:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4674:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4675:             }
 4676: 
 4677: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4678: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4679: 		&Apache::loncommon::end_data_table_row();
 4680: 
 4681: 	    $prob++;
 4682: 	}
 4683:         $curRes = $iterator->next();
 4684:     }
 4685: 
 4686:     $studentTable.=&Apache::loncommon::end_data_table();
 4687:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4688:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4689: 		  &mt('The scores were changed for [quant,_1,problem].',
 4690: 		  $changeflag));
 4691:     $request->print($grademsg.$studentTable);
 4692: 
 4693:     return '';
 4694: }
 4695: 
 4696: #-------- end of section for handling grading by page/sequence ---------
 4697: #
 4698: #-------------------------------------------------------------------
 4699: 
 4700: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4701: #
 4702: #------ start of section for handling grading by page/sequence ---------
 4703: 
 4704: =pod
 4705: 
 4706: =head1 Bubble sheet grading routines
 4707: 
 4708:   For this documentation:
 4709: 
 4710:    'scanline' refers to the full line of characters
 4711:    from the file that we are parsing that represents one entire sheet
 4712: 
 4713:    'bubble line' refers to the data
 4714:    representing the line of bubbles that are on the physical bubble sheet
 4715: 
 4716: 
 4717: The overall process is that a scanned in bubble sheet data is uploaded
 4718: into a course. When a user wants to grade, they select a
 4719: sequence/folder of resources, a file of bubble sheet info, and pick
 4720: one of the predefined configurations for what each scanline looks
 4721: like.
 4722: 
 4723: Next each scanline is checked for any errors of either 'missing
 4724: bubbles' (it's an error because it may have been mis-scanned
 4725: because too light bubbling), 'double bubble' (each bubble line should
 4726: have no more that one letter picked), invalid or duplicated CODE,
 4727: invalid student/employee ID
 4728: 
 4729: If the CODE option is used that determines the randomization of the
 4730: homework problems, either way the student/employee ID is looked up into a
 4731: username:domain.
 4732: 
 4733: During the validation phase the instructor can choose to skip scanlines. 
 4734: 
 4735: After the validation phase, there are now 3 bubble sheet files
 4736: 
 4737:   scantron_original_filename (unmodified original file)
 4738:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4739:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4740: 
 4741: Also there is a separate hash nohist_scantrondata that contains extra
 4742: correction information that isn't representable in the bubble sheet
 4743: file (see &scantron_getfile() for more information)
 4744: 
 4745: After all scanlines are either valid, marked as valid or skipped, then
 4746: foreach line foreach problem in the picked sequence, an ssi request is
 4747: made that simulates a user submitting their selected letter(s) against
 4748: the homework problem.
 4749: 
 4750: =over 4
 4751: 
 4752: 
 4753: 
 4754: =item defaultFormData
 4755: 
 4756:   Returns html hidden inputs used to hold context/default values.
 4757: 
 4758:  Arguments:
 4759:   $symb - $symb of the current resource 
 4760: 
 4761: =cut
 4762: 
 4763: sub defaultFormData {
 4764:     my ($symb)=@_;
 4765:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4766:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4767:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4768: }
 4769: 
 4770: 
 4771: =pod 
 4772: 
 4773: =item getSequenceDropDown
 4774: 
 4775:    Return html dropdown of possible sequences to grade
 4776:  
 4777:  Arguments:
 4778:    $symb - $symb of the current resource 
 4779: 
 4780: =cut
 4781: 
 4782: sub getSequenceDropDown {
 4783:     my ($symb)=@_;
 4784:     my $result='<select name="selectpage">'."\n";
 4785:     my ($titles,$symbx) = &getSymbMap();
 4786:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4787:     my $ctr=0;
 4788:     foreach (@$titles) {
 4789: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4790: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4791: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4792: 	    '>'.$showtitle.'</option>'."\n";
 4793: 	$ctr++;
 4794:     }
 4795:     $result.= '</select>';
 4796:     return $result;
 4797: }
 4798: 
 4799: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4800:                                    # key is zero-based index - 0, 1, 2 ...
 4801: 
 4802: my %first_bubble_line;             # First bubble line no. for each bubble.
 4803: 
 4804: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4805:                                    # matchresponse or rankresponse, where 
 4806:                                    # an individual response can have multiple 
 4807:                                    # lines
 4808: 
 4809: my %responsetype_per_response;     # responsetype for each response
 4810: 
 4811: # Save and restore the bubble lines array to the form env.
 4812: 
 4813: 
 4814: sub save_bubble_lines {
 4815:     foreach my $line (keys(%bubble_lines_per_response)) {
 4816: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4817: 	$env{"form.scantron.first_bubble_line.$line"} =
 4818: 	    $first_bubble_line{$line};
 4819:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4820:             $subdivided_bubble_lines{$line};
 4821:         $env{"form.scantron.responsetype.$line"} =
 4822:             $responsetype_per_response{$line};
 4823:     }
 4824: }
 4825: 
 4826: 
 4827: sub restore_bubble_lines {
 4828:     my $line = 0;
 4829:     %bubble_lines_per_response = ();
 4830:     while ($env{"form.scantron.bubblelines.$line"}) {
 4831: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4832: 	$bubble_lines_per_response{$line} = $value;
 4833: 	$first_bubble_line{$line}  =
 4834: 	    $env{"form.scantron.first_bubble_line.$line"};
 4835:         $subdivided_bubble_lines{$line} =
 4836:             $env{"form.scantron.sub_bubblelines.$line"};
 4837:         $responsetype_per_response{$line} =
 4838:             $env{"form.scantron.responsetype.$line"};
 4839: 	$line++;
 4840:     }
 4841: }
 4842: 
 4843: #  Given the parsed scanline, get the response for 
 4844: #  'answer' number n:
 4845: 
 4846: sub get_response_bubbles {
 4847:     my ($parsed_line, $response)  = @_;
 4848: 
 4849:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4850:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4851:     
 4852:     my $selected = "";
 4853: 
 4854:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4855: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4856: 	$bubble_line++;
 4857:     }
 4858:     return $selected;
 4859: }
 4860: 
 4861: =pod 
 4862: 
 4863: =item scantron_filenames
 4864: 
 4865:    Returns a list of the scantron files in the current course 
 4866: 
 4867: =cut
 4868: 
 4869: sub scantron_filenames {
 4870:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4871:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4872:     my $getpropath = 1;
 4873:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4874:                                        $getpropath);
 4875:     my @possiblenames;
 4876:     foreach my $filename (sort(@files)) {
 4877: 	($filename)=split(/&/,$filename);
 4878: 	if ($filename!~/^scantron_orig_/) { next ; }
 4879: 	$filename=~s/^scantron_orig_//;
 4880: 	push(@possiblenames,$filename);
 4881:     }
 4882:     return @possiblenames;
 4883: }
 4884: 
 4885: =pod 
 4886: 
 4887: =item scantron_uploads
 4888: 
 4889:    Returns  html drop-down list of scantron files in current course.
 4890: 
 4891:  Arguments:
 4892:    $file2grade - filename to set as selected in the dropdown
 4893: 
 4894: =cut
 4895: 
 4896: sub scantron_uploads {
 4897:     my ($file2grade) = @_;
 4898:     my $result=	'<select name="scantron_selectfile">';
 4899:     $result.="<option></option>";
 4900:     foreach my $filename (sort(&scantron_filenames())) {
 4901: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4902:     }
 4903:     $result.="</select>";
 4904:     return $result;
 4905: }
 4906: 
 4907: =pod 
 4908: 
 4909: =item scantron_scantab
 4910: 
 4911:   Returns html drop down of the scantron formats in the scantronformat.tab
 4912:   file.
 4913: 
 4914: =cut
 4915: 
 4916: sub scantron_scantab {
 4917:     my $result='<select name="scantron_format">'."\n";
 4918:     $result.='<option></option>'."\n";
 4919:     my @lines = &get_scantronformat_file();
 4920:     if (@lines > 0) {
 4921:         foreach my $line (@lines) {
 4922:             next if (($line =~ /^\#/) || ($line eq ''));
 4923: 	    my ($name,$descrip)=split(/:/,$line);
 4924: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4925:         }
 4926:     }
 4927:     $result.='</select>'."\n";
 4928:     return $result;
 4929: }
 4930: 
 4931: =pod
 4932: 
 4933: =item get_scantronformat_file
 4934: 
 4935:   Returns an array containing lines from the scantron format file for
 4936:   the domain of the course.
 4937: 
 4938:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4939:   lines are from this file.
 4940: 
 4941:   Otherwise, if a default.tab has been published in RES space by the 
 4942:   domainconfig user, lines are from this file.
 4943: 
 4944:   Otherwise, fall back to getting lines from the legacy file on the
 4945:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4946: 
 4947: =cut
 4948: 
 4949: sub get_scantronformat_file {
 4950:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4951:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4952:     my $gottab = 0;
 4953:     my @lines;
 4954:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4955:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4956:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4957:             if ($formatfile ne '-1') {
 4958:                 @lines = split("\n",$formatfile,-1);
 4959:                 $gottab = 1;
 4960:             }
 4961:         }
 4962:     }
 4963:     if (!$gottab) {
 4964:         my $confname = $cdom.'-domainconfig';
 4965:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4966:         my $formatfile =  &Apache::lonnet::getfile($default);
 4967:         if ($formatfile ne '-1') {
 4968:             @lines = split("\n",$formatfile,-1);
 4969:             $gottab = 1;
 4970:         }
 4971:     }
 4972:     if (!$gottab) {
 4973:         my @domains = &Apache::lonnet::current_machine_domains();
 4974:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4975:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4976:             @lines = <$fh>;
 4977:             close($fh);
 4978:         } else {
 4979:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4980:             @lines = <$fh>;
 4981:             close($fh);
 4982:         }
 4983:     }
 4984:     return @lines;
 4985: }
 4986: 
 4987: =pod 
 4988: 
 4989: =item scantron_CODElist
 4990: 
 4991:   Returns html drop down of the saved CODE lists from current course,
 4992:   generated from earlier printings.
 4993: 
 4994: =cut
 4995: 
 4996: sub scantron_CODElist {
 4997:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4998:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4999:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5000:     my $namechoice='<option></option>';
 5001:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5002: 	if ($name =~ /^error: 2 /) { next; }
 5003: 	if ($name =~ /^type\0/) { next; }
 5004: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5005:     }
 5006:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5007:     return $namechoice;
 5008: }
 5009: 
 5010: =pod 
 5011: 
 5012: =item scantron_CODEunique
 5013: 
 5014:   Returns the html for "Each CODE to be used once" radio.
 5015: 
 5016: =cut
 5017: 
 5018: sub scantron_CODEunique {
 5019:     my $result='<span class="LC_nobreak">
 5020:                  <label><input type="radio" name="scantron_CODEunique"
 5021:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5022:                 </span>
 5023:                 <span class="LC_nobreak">
 5024:                  <label><input type="radio" name="scantron_CODEunique"
 5025:                         value="no" />'.&mt('No').' </label>
 5026:                 </span>';
 5027:     return $result;
 5028: }
 5029: 
 5030: =pod 
 5031: 
 5032: =item scantron_selectphase
 5033: 
 5034:   Generates the initial screen to start the bubble sheet process.
 5035:   Allows for - starting a grading run.
 5036:              - downloading existing scan data (original, corrected
 5037:                                                 or skipped info)
 5038: 
 5039:              - uploading new scan data
 5040: 
 5041:  Arguments:
 5042:   $r          - The Apache request object
 5043:   $file2grade - name of the file that contain the scanned data to score
 5044: 
 5045: =cut
 5046: 
 5047: sub scantron_selectphase {
 5048:     my ($r,$file2grade) = @_;
 5049:     my ($symb)=&get_symb($r);
 5050:     if (!$symb) {return '';}
 5051:     my $sequence_selector=&getSequenceDropDown($symb);
 5052:     my $default_form_data=&defaultFormData($symb);
 5053:     my $grading_menu_button=&show_grading_menu_form($symb);
 5054:     my $file_selector=&scantron_uploads($file2grade);
 5055:     my $format_selector=&scantron_scantab();
 5056:     my $CODE_selector=&scantron_CODElist();
 5057:     my $CODE_unique=&scantron_CODEunique();
 5058:     my $result;
 5059: 
 5060:     $ssi_error = 0;
 5061: 
 5062:     # Chunk of form to prompt for a file to grade and how:
 5063: 
 5064:     $result.= '
 5065:     <br />
 5066:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5067:     <input type="hidden" name="command" value="scantron_warning" />
 5068:     '.$default_form_data.'
 5069:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5070:        '.&Apache::loncommon::start_data_table_header_row().'
 5071:             <th colspan="2">
 5072:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5073:             </th>
 5074:        '.&Apache::loncommon::end_data_table_header_row().'
 5075:        '.&Apache::loncommon::start_data_table_row().'
 5076:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5077:        '.&Apache::loncommon::end_data_table_row().'
 5078:        '.&Apache::loncommon::start_data_table_row().'
 5079:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5080:        '.&Apache::loncommon::end_data_table_row().'
 5081:        '.&Apache::loncommon::start_data_table_row().'
 5082:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5083:        '.&Apache::loncommon::end_data_table_row().'
 5084:        '.&Apache::loncommon::start_data_table_row().'
 5085:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5086:        '.&Apache::loncommon::end_data_table_row().'
 5087:        '.&Apache::loncommon::start_data_table_row().'
 5088:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5089:        '.&Apache::loncommon::end_data_table_row().'
 5090:        '.&Apache::loncommon::start_data_table_row().'
 5091: 	    <td> '.&mt('Options:').' </td>
 5092:             <td>
 5093: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5094:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5095:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5096: 	    </td>
 5097:        '.&Apache::loncommon::end_data_table_row().'
 5098:        '.&Apache::loncommon::start_data_table_row().'
 5099:             <td colspan="2">
 5100:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5101:             </td>
 5102:        '.&Apache::loncommon::end_data_table_row().'
 5103:     '.&Apache::loncommon::end_data_table().'
 5104:     </form>
 5105: ';
 5106:    
 5107:     $r->print($result);
 5108: 
 5109:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5110:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5111: 
 5112: 	# Chunk of form to prompt for a scantron file upload.
 5113: 
 5114:         $r->print('
 5115:     <br />
 5116:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5117:        '.&Apache::loncommon::start_data_table_header_row().'
 5118:             <th>
 5119:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5120:             </th>
 5121:        '.&Apache::loncommon::end_data_table_header_row().'
 5122:        '.&Apache::loncommon::start_data_table_row().'
 5123:             <td>
 5124: ');
 5125:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5126:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5127:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5128:     $r->print('
 5129:               <script type="text/javascript" language="javascript">
 5130:     function checkUpload(formname) {
 5131: 	if (formname.upfile.value == "") {
 5132: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5133: 	    return false;
 5134: 	}
 5135: 	formname.submit();
 5136:     }
 5137:               </script>
 5138: 
 5139:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5140:                 '.$default_form_data.'
 5141:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5142:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5143:                 <input name="command" value="scantronupload_save" type="hidden" />
 5144:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5145:                 <br />
 5146:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5147:               </form>
 5148: ');
 5149: 
 5150:         $r->print('
 5151:             </td>
 5152:        '.&Apache::loncommon::end_data_table_row().'
 5153:        '.&Apache::loncommon::end_data_table().'
 5154: ');
 5155:     }
 5156: 
 5157:     # Chunk of the form that prompts to view a scoring office file,
 5158:     # corrected file, skipped records in a file.
 5159: 
 5160:     $r->print('
 5161:    <br />
 5162:    <form action="/adm/grades" name="scantron_download">
 5163:      '.$default_form_data.'
 5164:      <input type="hidden" name="command" value="scantron_download" />
 5165:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5166:        '.&Apache::loncommon::start_data_table_header_row().'
 5167:               <th>
 5168:                 &nbsp;'.&mt('Download a scoring office file').'
 5169:               </th>
 5170:        '.&Apache::loncommon::end_data_table_header_row().'
 5171:        '.&Apache::loncommon::start_data_table_row().'
 5172:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5173:                 <br />
 5174:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5175:        '.&Apache::loncommon::end_data_table_row().'
 5176:      '.&Apache::loncommon::end_data_table().'
 5177:    </form>
 5178:    <br />
 5179: ');
 5180: 
 5181:     &Apache::lonpickcode::code_list($r,2);
 5182: 
 5183:     $r->print('<br /><form method="post" name="checkscantron">'.
 5184:              $default_form_data."\n".
 5185:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5186:              &Apache::loncommon::start_data_table_header_row()."\n".
 5187:              '<th colspan="2">
 5188:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5189:              '</th>'."\n".
 5190:               &Apache::loncommon::end_data_table_header_row()."\n".
 5191:               &Apache::loncommon::start_data_table_row()."\n".
 5192:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5193:               '<td> '.$sequence_selector.' </td>'.
 5194:               &Apache::loncommon::end_data_table_row()."\n".
 5195:               &Apache::loncommon::start_data_table_row()."\n".
 5196:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5197:               '<td> '.$file_selector.' </td>'."\n".
 5198:               &Apache::loncommon::end_data_table_row()."\n".
 5199:               &Apache::loncommon::start_data_table_row()."\n".
 5200:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5201:               '<td> '.$format_selector.' </td>'."\n".
 5202:               &Apache::loncommon::end_data_table_row()."\n".
 5203:               &Apache::loncommon::start_data_table_row()."\n".
 5204:               '<td> '.&mt('Options').' </td>'."\n".
 5205:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5206:               &Apache::loncommon::end_data_table_row()."\n".
 5207:               &Apache::loncommon::start_data_table_row()."\n".
 5208:               '<td colspan="2">'."\n".
 5209:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5210:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5211:               '</td>'."\n".
 5212:               &Apache::loncommon::end_data_table_row()."\n".
 5213:               &Apache::loncommon::end_data_table()."\n".
 5214:               '</form><br />');
 5215:     $r->print($grading_menu_button);
 5216:     return;
 5217: }
 5218: 
 5219: =pod
 5220: 
 5221: =item get_scantron_config
 5222: 
 5223:    Parse and return the scantron configuration line selected as a
 5224:    hash of configuration file fields.
 5225: 
 5226:  Arguments:
 5227:     which - the name of the configuration to parse from the file.
 5228: 
 5229: 
 5230:  Returns:
 5231:             If the named configuration is not in the file, an empty
 5232:             hash is returned.
 5233:     a hash with the fields
 5234:       name         - internal name for the this configuration setup
 5235:       description  - text to display to operator that describes this config
 5236:       CODElocation - if 0 or the string 'none'
 5237:                           - no CODE exists for this config
 5238:                      if -1 || the string 'letter'
 5239:                           - a CODE exists for this config and is
 5240:                             a string of letters
 5241:                      Unsupported value (but planned for future support)
 5242:                           if a positive integer
 5243:                                - The CODE exists as the first n items from
 5244:                                  the question section of the form
 5245:                           if the string 'number'
 5246:                                - The CODE exists for this config and is
 5247:                                  a string of numbers
 5248:       CODEstart   - (only matter if a CODE exists) column in the line where
 5249:                      the CODE starts
 5250:       CODElength  - length of the CODE
 5251:       IDstart     - column where the student/employee ID starts
 5252:       IDlength    - length of the student/employee ID info
 5253:       Qstart      - column where the information from the bubbled
 5254:                     'questions' start
 5255:       Qlength     - number of columns comprising a single bubble line from
 5256:                     the sheet. (usually either 1 or 10)
 5257:       Qon         - either a single character representing the character used
 5258:                     to signal a bubble was chosen in the positional setup, or
 5259:                     the string 'letter' if the letter of the chosen bubble is
 5260:                     in the final, or 'number' if a number representing the
 5261:                     chosen bubble is in the file (1->A 0->J)
 5262:       Qoff        - the character used to represent that a bubble was
 5263:                     left blank
 5264:       PaperID     - if the scanning process generates a unique number for each
 5265:                     sheet scanned the column that this ID number starts in
 5266:       PaperIDlength - number of columns that comprise the unique ID number
 5267:                       for the sheet of paper
 5268:       FirstName   - column that the first name starts in
 5269:       FirstNameLength - number of columns that the first name spans
 5270:  
 5271:       LastName    - column that the last name starts in
 5272:       LastNameLength - number of columns that the last name spans
 5273: 
 5274: =cut
 5275: 
 5276: sub get_scantron_config {
 5277:     my ($which) = @_;
 5278:     my @lines = &get_scantronformat_file();
 5279:     my %config;
 5280:     #FIXME probably should move to XML it has already gotten a bit much now
 5281:     foreach my $line (@lines) {
 5282: 	my ($name,$descrip)=split(/:/,$line);
 5283: 	if ($name ne $which ) { next; }
 5284: 	chomp($line);
 5285: 	my @config=split(/:/,$line);
 5286: 	$config{'name'}=$config[0];
 5287: 	$config{'description'}=$config[1];
 5288: 	$config{'CODElocation'}=$config[2];
 5289: 	$config{'CODEstart'}=$config[3];
 5290: 	$config{'CODElength'}=$config[4];
 5291: 	$config{'IDstart'}=$config[5];
 5292: 	$config{'IDlength'}=$config[6];
 5293: 	$config{'Qstart'}=$config[7];
 5294:  	$config{'Qlength'}=$config[8];
 5295: 	$config{'Qoff'}=$config[9];
 5296: 	$config{'Qon'}=$config[10];
 5297: 	$config{'PaperID'}=$config[11];
 5298: 	$config{'PaperIDlength'}=$config[12];
 5299: 	$config{'FirstName'}=$config[13];
 5300: 	$config{'FirstNamelength'}=$config[14];
 5301: 	$config{'LastName'}=$config[15];
 5302: 	$config{'LastNamelength'}=$config[16];
 5303: 	last;
 5304:     }
 5305:     return %config;
 5306: }
 5307: 
 5308: =pod 
 5309: 
 5310: =item username_to_idmap
 5311: 
 5312:     creates a hash keyed by student/employee ID with values of the corresponding
 5313:     student username:domain.
 5314: 
 5315:   Arguments:
 5316: 
 5317:     $classlist - reference to the class list hash. This is a hash
 5318:                  keyed by student name:domain  whose elements are references
 5319:                  to arrays containing various chunks of information
 5320:                  about the student. (See loncoursedata for more info).
 5321: 
 5322:   Returns
 5323:     %idmap - the constructed hash
 5324: 
 5325: =cut
 5326: 
 5327: sub username_to_idmap {
 5328:     my ($classlist)= @_;
 5329:     my %idmap;
 5330:     foreach my $student (keys(%$classlist)) {
 5331: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5332: 	    $student;
 5333:     }
 5334:     return %idmap;
 5335: }
 5336: 
 5337: =pod
 5338: 
 5339: =item scantron_fixup_scanline
 5340: 
 5341:    Process a requested correction to a scanline.
 5342: 
 5343:   Arguments:
 5344:     $scantron_config   - hash from &get_scantron_config()
 5345:     $scan_data         - hash of correction information 
 5346:                           (see &scantron_getfile())
 5347:     $line              - existing scanline
 5348:     $whichline         - line number of the passed in scanline
 5349:     $field             - type of change to process 
 5350:                          (either 
 5351:                           'ID'     -> correct the student/employee ID
 5352:                           'CODE'   -> correct the CODE
 5353:                           'answer' -> fixup the submitted answers)
 5354:     
 5355:    $args               - hash of additional info,
 5356:                           - 'ID' 
 5357:                                'newid' -> studentID to use in replacement
 5358:                                           of existing one
 5359:                           - 'CODE' 
 5360:                                'CODE_ignore_dup' - set to true if duplicates
 5361:                                                    should be ignored.
 5362: 	                       'CODE' - is new code or 'use_unfound'
 5363:                                         if the existing unfound code should
 5364:                                         be used as is
 5365:                           - 'answer'
 5366:                                'response' - new answer or 'none' if blank
 5367:                                'question' - the bubble line to change
 5368:                                'questionnum' - the question identifier,
 5369:                                                may include subquestion. 
 5370: 
 5371:   Returns:
 5372:     $line - the modified scanline
 5373: 
 5374:   Side effects: 
 5375:     $scan_data - may be updated
 5376: 
 5377: =cut
 5378: 
 5379: 
 5380: sub scantron_fixup_scanline {
 5381:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5382:     if ($field eq 'ID') {
 5383: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5384: 	    return ($line,1,'New value too large');
 5385: 	}
 5386: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5387: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5388: 				     $args->{'newid'});
 5389: 	}
 5390: 	substr($line,$$scantron_config{'IDstart'}-1,
 5391: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5392: 	if ($args->{'newid'}=~/^\s*$/) {
 5393: 	    &scan_data($scan_data,"$whichline.user",
 5394: 		       $args->{'username'}.':'.$args->{'domain'});
 5395: 	}
 5396:     } elsif ($field eq 'CODE') {
 5397: 	if ($args->{'CODE_ignore_dup'}) {
 5398: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5399: 	}
 5400: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5401: 	if ($args->{'CODE'} ne 'use_unfound') {
 5402: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5403: 		return ($line,1,'New CODE value too large');
 5404: 	    }
 5405: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5406: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5407: 	    }
 5408: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5409: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5410: 	}
 5411:     } elsif ($field eq 'answer') {
 5412: 	my $length=$scantron_config->{'Qlength'};
 5413: 	my $off=$scantron_config->{'Qoff'};
 5414: 	my $on=$scantron_config->{'Qon'};
 5415: 	my $answer=${off}x$length;
 5416: 	if ($args->{'response'} eq 'none') {
 5417: 	    &scan_data($scan_data,
 5418: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5419: 	} else {
 5420: 	    if ($on eq 'letter') {
 5421: 		my @alphabet=('A'..'Z');
 5422: 		$answer=$alphabet[$args->{'response'}];
 5423: 	    } elsif ($on eq 'number') {
 5424: 		$answer=$args->{'response'}+1;
 5425: 		if ($answer == 10) { $answer = '0'; }
 5426: 	    } else {
 5427: 		substr($answer,$args->{'response'},1)=$on;
 5428: 	    }
 5429: 	    &scan_data($scan_data,
 5430: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5431: 	}
 5432: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5433: 	substr($line,$where-1,$length)=$answer;
 5434:     }
 5435:     return $line;
 5436: }
 5437: 
 5438: =pod
 5439: 
 5440: =item scan_data
 5441: 
 5442:     Edit or look up  an item in the scan_data hash.
 5443: 
 5444:   Arguments:
 5445:     $scan_data  - The hash (see scantron_getfile)
 5446:     $key        - shorthand of the key to edit (actual key is
 5447:                   scantronfilename_key).
 5448:     $data        - New value of the hash entry.
 5449:     $delete      - If true, the entry is removed from the hash.
 5450: 
 5451:   Returns:
 5452:     The new value of the hash table field (undefined if deleted).
 5453: 
 5454: =cut
 5455: 
 5456: 
 5457: sub scan_data {
 5458:     my ($scan_data,$key,$value,$delete)=@_;
 5459:     my $filename=$env{'form.scantron_selectfile'};
 5460:     if (defined($value)) {
 5461: 	$scan_data->{$filename.'_'.$key} = $value;
 5462:     }
 5463:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5464:     return $scan_data->{$filename.'_'.$key};
 5465: }
 5466: 
 5467: # ----- These first few routines are general use routines.----
 5468: 
 5469: # Return the number of occurences of a pattern in a string.
 5470: 
 5471: sub occurence_count {
 5472:     my ($string, $pattern) = @_;
 5473: 
 5474:     my @matches = ($string =~ /$pattern/g);
 5475: 
 5476:     return scalar(@matches);
 5477: }
 5478: 
 5479: 
 5480: # Take a string known to have digits and convert all the
 5481: # digits into letters in the range J,A..I.
 5482: 
 5483: sub digits_to_letters {
 5484:     my ($input) = @_;
 5485: 
 5486:     my @alphabet = ('J', 'A'..'I');
 5487: 
 5488:     my @input    = split(//, $input);
 5489:     my $output ='';
 5490:     for (my $i = 0; $i < scalar(@input); $i++) {
 5491: 	if ($input[$i] =~ /\d/) {
 5492: 	    $output .= $alphabet[$input[$i]];
 5493: 	} else {
 5494: 	    $output .= $input[$i];
 5495: 	}
 5496:     }
 5497:     return $output;
 5498: }
 5499: 
 5500: =pod 
 5501: 
 5502: =item scantron_parse_scanline
 5503: 
 5504:   Decodes a scanline from the selected scantron file
 5505: 
 5506:  Arguments:
 5507:     line             - The text of the scantron file line to process
 5508:     whichline        - Line number
 5509:     scantron_config  - Hash describing the format of the scantron lines.
 5510:     scan_data        - Hash of extra information about the scanline
 5511:                        (see scantron_getfile for more information)
 5512:     just_header      - True if should not process question answers but only
 5513:                        the stuff to the left of the answers.
 5514:  Returns:
 5515:    Hash containing the result of parsing the scanline
 5516: 
 5517:    Keys are all proceeded by the string 'scantron.'
 5518: 
 5519:        CODE    - the CODE in use for this scanline
 5520:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5521:                  by the operator
 5522:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5523:                             CODEs were selected, but the usage has been
 5524:                             forced by the operator
 5525:        ID  - student/employee ID
 5526:        PaperID - if used, the ID number printed on the sheet when the 
 5527:                  paper was scanned
 5528:        FirstName - first name from the sheet
 5529:        LastName  - last name from the sheet
 5530: 
 5531:      if just_header was not true these key may also exist
 5532: 
 5533:        missingerror - a list of bubble ranges that are considered to be answers
 5534:                       to a single question that don't have any bubbles filled in.
 5535:                       Of the form questionnumber:firstbubblenumber:count.
 5536:        doubleerror  - a list of bubble ranges that are considered to be answers
 5537:                       to a single question that have more than one bubble filled in.
 5538:                       Of the form questionnumber::firstbubblenumber:count
 5539:    
 5540:                 In the above, count is the number of bubble responses in the
 5541:                 input line needed to represent the possible answers to the question.
 5542:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5543:                 per line would have count = 2.
 5544: 
 5545:        maxquest     - the number of the last bubble line that was parsed
 5546: 
 5547:        (<number> starts at 1)
 5548:        <number>.answer - zero or more letters representing the selected
 5549:                          letters from the scanline for the bubble line 
 5550:                          <number>.
 5551:                          if blank there was either no bubble or there where
 5552:                          multiple bubbles, (consult the keys missingerror and
 5553:                          doubleerror if this is an error condition)
 5554: 
 5555: =cut
 5556: 
 5557: sub scantron_parse_scanline {
 5558:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5559: 
 5560:     my %record;
 5561:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5562:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5563:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5564:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5565: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5566: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5567: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5568: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5569: 	    $record{'scantron.CODE'}=substr($data,
 5570: 					    $$scantron_config{'CODEstart'}-1,
 5571: 					    $$scantron_config{'CODElength'});
 5572: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5573: 		$record{'scantron.useCODE'}=1;
 5574: 	    }
 5575: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5576: 		$record{'scantron.CODE_ignore_dup'}=1;
 5577: 	    }
 5578: 	} else {
 5579: 	    #FIXME interpret first N questions
 5580: 	}
 5581:     }
 5582:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5583: 				  $$scantron_config{'IDlength'});
 5584:     $record{'scantron.PaperID'}=
 5585: 	substr($data,$$scantron_config{'PaperID'}-1,
 5586: 	       $$scantron_config{'PaperIDlength'});
 5587:     $record{'scantron.FirstName'}=
 5588: 	substr($data,$$scantron_config{'FirstName'}-1,
 5589: 	       $$scantron_config{'FirstNamelength'});
 5590:     $record{'scantron.LastName'}=
 5591: 	substr($data,$$scantron_config{'LastName'}-1,
 5592: 	       $$scantron_config{'LastNamelength'});
 5593:     if ($just_header) { return \%record; }
 5594: 
 5595:     my @alphabet=('A'..'Z');
 5596:     my $questnum=0;
 5597:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5598: 
 5599:     chomp($questions);		# Get rid of any trailing \n.
 5600:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5601:     while (length($questions)) {
 5602: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5603:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5604:                              || 1;
 5605:         $questnum++;
 5606:         my $quest_id = $questnum;
 5607:         my $currentquest = substr($questions,0,$answer_length);
 5608:         $questions       = substr($questions,$answer_length);
 5609:         if (length($currentquest) < $answer_length) { next; }
 5610: 
 5611:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5612:             my $subquestnum = 1;
 5613:             my $subquestions = $currentquest;
 5614:             my @subanswers_needed = 
 5615:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5616:             foreach my $subans (@subanswers_needed) {
 5617:                 my $subans_length =
 5618:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5619:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5620:                 $subquestions   = substr($subquestions,$subans_length);
 5621:                 $quest_id = "$questnum.$subquestnum";
 5622:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5623:                     ($$scantron_config{'Qon'} eq 'number')) {
 5624:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5625:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5626:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5627:                 } else {
 5628:                     $ansnum = &scantron_validator_positional($ansnum,
 5629:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5630:                 }
 5631:                 $subquestnum ++;
 5632:             }
 5633:         } else {
 5634:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5635:                 ($$scantron_config{'Qon'} eq 'number')) {
 5636:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5637:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5638:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5639:             } else {
 5640:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5641:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5642:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5643:             }
 5644:         }
 5645:     }
 5646:     $record{'scantron.maxquest'}=$questnum;
 5647:     return \%record;
 5648: }
 5649: 
 5650: sub scantron_validator_lettnum {
 5651:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5652:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5653: 
 5654:     # Qon 'letter' implies for each slot in currquest we have:
 5655:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5656:     #    about anything else (esp. a value of Qoff) for missing
 5657:     #    bubbles.
 5658:     #
 5659:     # Qon 'number' implies each slot gives a digit that indexes the
 5660:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5661:     #    and * or ? for double bubbles on a single line.
 5662:     #
 5663: 
 5664:     my $matchon;
 5665:     if ($$scantron_config{'Qon'} eq 'letter') {
 5666:         $matchon = '[A-Z]';
 5667:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5668:         $matchon = '\d';
 5669:     }
 5670:     my $occurrences = 0;
 5671:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5672:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5673:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5674:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5675:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5676:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5677:         my @singlelines = split('',$currquest);
 5678:         foreach my $entry (@singlelines) {
 5679:             $occurrences = &occurence_count($entry,$matchon);
 5680:             if ($occurrences > 1) {
 5681:                 last;
 5682:             }
 5683:         } 
 5684:     } else {
 5685:         $occurrences = &occurence_count($currquest,$matchon); 
 5686:     }
 5687:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5688:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5689:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5690:             my $bubble = substr($currquest,$ans,1);
 5691:             if ($bubble =~ /$matchon/ ) {
 5692:                 if ($$scantron_config{'Qon'} eq 'number') {
 5693:                     if ($bubble == 0) {
 5694:                         $bubble = 10; 
 5695:                     }
 5696:                     $record->{"scantron.$ansnum.answer"} = 
 5697:                         $alphabet->[$bubble-1];
 5698:                 } else {
 5699:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5700:                 }
 5701:             } else {
 5702:                 $record->{"scantron.$ansnum.answer"}='';
 5703:             }
 5704:             $ansnum++;
 5705:         }
 5706:     } elsif (!defined($currquest)
 5707:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5708:             || (&occurence_count($currquest,$matchon) == 0)) {
 5709:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5710:             $record->{"scantron.$ansnum.answer"}='';
 5711:             $ansnum++;
 5712:         }
 5713:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5714:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5715:         }
 5716:     } else {
 5717:         if ($$scantron_config{'Qon'} eq 'number') {
 5718:             $currquest = &digits_to_letters($currquest);            
 5719:         }
 5720:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5721:             my $bubble = substr($currquest,$ans,1);
 5722:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5723:             $ansnum++;
 5724:         }
 5725:     }
 5726:     return $ansnum;
 5727: }
 5728: 
 5729: sub scantron_validator_positional {
 5730:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5731:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5732: 
 5733:     # Otherwise there's a positional notation;
 5734:     # each bubble line requires Qlength items, and there are filled in
 5735:     # bubbles for each case where there 'Qon' characters.
 5736:     #
 5737: 
 5738:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5739: 
 5740:     # If the split only gives us one element.. the full length of the
 5741:     # answer string, no bubbles are filled in:
 5742: 
 5743:     if ($answers_needed eq '') {
 5744:         return;
 5745:     }
 5746: 
 5747:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5748:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5749:             $record->{"scantron.$ansnum.answer"}='';
 5750:             $ansnum++;
 5751:         }
 5752:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5753:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5754:         }
 5755:     } elsif (scalar(@array) == 2) {
 5756:         my $location = length($array[0]);
 5757:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5758:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5759:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5760:             if ($ans eq $line_num) {
 5761:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5762:             } else {
 5763:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5764:             }
 5765:             $ansnum++;
 5766:          }
 5767:     } else {
 5768:         #  If there's more than one instance of a bubble character
 5769:         #  That's a double bubble; with positional notation we can
 5770:         #  record all the bubbles filled in as well as the
 5771:         #  fact this response consists of multiple bubbles.
 5772:         #
 5773:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5774:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5775:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5776:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5777:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5778:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5779:             my $doubleerror = 0;
 5780:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5781:                    (!$doubleerror)) {
 5782:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5783:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5784:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5785:                if (length(@currarray) > 2) {
 5786:                    $doubleerror = 1;
 5787:                } 
 5788:             }
 5789:             if ($doubleerror) {
 5790:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5791:             }
 5792:         } else {
 5793:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5794:         }
 5795:         my $item = $ansnum;
 5796:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5797:             $record->{"scantron.$item.answer"} = '';
 5798:             $item ++;
 5799:         }
 5800: 
 5801:         my @ans=@array;
 5802:         my $i=0;
 5803:         my $increment = 0;
 5804:         while ($#ans) {
 5805:             $i+=length($ans[0]) + $increment;
 5806:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5807:             my $bubble = $i%$$scantron_config{'Qlength'};
 5808:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5809:             shift(@ans);
 5810:             $increment = 1;
 5811:         }
 5812:         $ansnum += $answers_needed;
 5813:     }
 5814:     return $ansnum;
 5815: }
 5816: 
 5817: =pod
 5818: 
 5819: =item scantron_add_delay
 5820: 
 5821:    Adds an error message that occurred during the grading phase to a
 5822:    queue of messages to be shown after grading pass is complete
 5823: 
 5824:  Arguments:
 5825:    $delayqueue  - arrary ref of hash ref of error messages
 5826:    $scanline    - the scanline that caused the error
 5827:    $errormesage - the error message
 5828:    $errorcode   - a numeric code for the error
 5829: 
 5830:  Side Effects:
 5831:    updates the $delayqueue to have a new hash ref of the error
 5832: 
 5833: =cut
 5834: 
 5835: sub scantron_add_delay {
 5836:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5837:     push(@$delayqueue,
 5838: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5839: 	  'ecode' => $errorcode }
 5840: 	 );
 5841: }
 5842: 
 5843: =pod
 5844: 
 5845: =item scantron_find_student
 5846: 
 5847:    Finds the username for the current scanline
 5848: 
 5849:   Arguments:
 5850:    $scantron_record - hash result from scantron_parse_scanline
 5851:    $scan_data       - hash of correction information 
 5852:                       (see &scantron_getfile() form more information)
 5853:    $idmap           - hash from &username_to_idmap()
 5854:    $line            - number of current scanline
 5855:  
 5856:   Returns:
 5857:    Either 'username:domain' or undef if unknown
 5858: 
 5859: =cut
 5860: 
 5861: sub scantron_find_student {
 5862:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5863:     my $scanID=$$scantron_record{'scantron.ID'};
 5864:     if ($scanID =~ /^\s*$/) {
 5865:  	return &scan_data($scan_data,"$line.user");
 5866:     }
 5867:     foreach my $id (keys(%$idmap)) {
 5868:  	if (lc($id) eq lc($scanID)) {
 5869:  	    return $$idmap{$id};
 5870:  	}
 5871:     }
 5872:     return undef;
 5873: }
 5874: 
 5875: =pod
 5876: 
 5877: =item scantron_filter
 5878: 
 5879:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5880:    hidden resources was selected
 5881: 
 5882: =cut
 5883: 
 5884: sub scantron_filter {
 5885:     my ($curres)=@_;
 5886: 
 5887:     if (ref($curres) && $curres->is_problem()) {
 5888: 	# if the user has asked to not have either hidden
 5889: 	# or 'randomout' controlled resources to be graded
 5890: 	# don't include them
 5891: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5892: 	    && $curres->randomout) {
 5893: 	    return 0;
 5894: 	}
 5895: 	return 1;
 5896:     }
 5897:     return 0;
 5898: }
 5899: 
 5900: =pod
 5901: 
 5902: =item scantron_process_corrections
 5903: 
 5904:    Gets correction information out of submitted form data and corrects
 5905:    the scanline
 5906: 
 5907: =cut
 5908: 
 5909: sub scantron_process_corrections {
 5910:     my ($r) = @_;
 5911:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5912:     my ($scanlines,$scan_data)=&scantron_getfile();
 5913:     my $classlist=&Apache::loncoursedata::get_classlist();
 5914:     my $which=$env{'form.scantron_line'};
 5915:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5916:     my ($skip,$err,$errmsg);
 5917:     if ($env{'form.scantron_skip_record'}) {
 5918: 	$skip=1;
 5919:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5920: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5921: 	    $env{'form.scantron_domain'};
 5922: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5923: 	($line,$err,$errmsg)=
 5924: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5925: 				     'ID',{'newid'=>$newid,
 5926: 				    'username'=>$env{'form.scantron_username'},
 5927: 				    'domain'=>$env{'form.scantron_domain'}});
 5928:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5929: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5930: 	my $newCODE;
 5931: 	my %args;
 5932: 	if      ($resolution eq 'use_unfound') {
 5933: 	    $newCODE='use_unfound';
 5934: 	} elsif ($resolution eq 'use_found') {
 5935: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5936: 	} elsif ($resolution eq 'use_typed') {
 5937: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5938: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5939: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5940: 	}
 5941: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5942: 	    $args{'CODE_ignore_dup'}=1;
 5943: 	}
 5944: 	$args{'CODE'}=$newCODE;
 5945: 	($line,$err,$errmsg)=
 5946: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5947: 				     'CODE',\%args);
 5948:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5949: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5950: 	    ($line,$err,$errmsg)=
 5951: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5952: 					 $which,'answer',
 5953: 					 { 'question'=>$question,
 5954: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5955:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5956: 	    if ($err) { last; }
 5957: 	}
 5958:     }
 5959:     if ($err) {
 5960: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5961:     } else {
 5962: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5963: 	&scantron_putfile($scanlines,$scan_data);
 5964:     }
 5965: }
 5966: 
 5967: =pod
 5968: 
 5969: =item reset_skipping_status
 5970: 
 5971:    Forgets the current set of remember skipped scanlines (and thus
 5972:    reverts back to considering all lines in the
 5973:    scantron_skipped_<filename> file)
 5974: 
 5975: =cut
 5976: 
 5977: sub reset_skipping_status {
 5978:     my ($scanlines,$scan_data)=&scantron_getfile();
 5979:     &scan_data($scan_data,'remember_skipping',undef,1);
 5980:     &scantron_putfile(undef,$scan_data);
 5981: }
 5982: 
 5983: =pod
 5984: 
 5985: =item start_skipping
 5986: 
 5987:    Marks a scanline to be skipped. 
 5988: 
 5989: =cut
 5990: 
 5991: sub start_skipping {
 5992:     my ($scan_data,$i)=@_;
 5993:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5994:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5995: 	$remembered{$i}=2;
 5996:     } else {
 5997: 	$remembered{$i}=1;
 5998:     }
 5999:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6000: }
 6001: 
 6002: =pod
 6003: 
 6004: =item should_be_skipped
 6005: 
 6006:    Checks whether a scanline should be skipped.
 6007: 
 6008: =cut
 6009: 
 6010: sub should_be_skipped {
 6011:     my ($scanlines,$scan_data,$i)=@_;
 6012:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6013: 	# not redoing old skips
 6014: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6015: 	return 0;
 6016:     }
 6017:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6018: 
 6019:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6020: 	return 0;
 6021:     }
 6022:     return 1;
 6023: }
 6024: 
 6025: =pod
 6026: 
 6027: =item remember_current_skipped
 6028: 
 6029:    Discovers what scanlines are in the scantron_skipped_<filename>
 6030:    file and remembers them into scan_data for later use.
 6031: 
 6032: =cut
 6033: 
 6034: sub remember_current_skipped {
 6035:     my ($scanlines,$scan_data)=&scantron_getfile();
 6036:     my %to_remember;
 6037:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6038: 	if ($scanlines->{'skipped'}[$i]) {
 6039: 	    $to_remember{$i}=1;
 6040: 	}
 6041:     }
 6042: 
 6043:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6044:     &scantron_putfile(undef,$scan_data);
 6045: }
 6046: 
 6047: =pod
 6048: 
 6049: =item check_for_error
 6050: 
 6051:     Checks if there was an error when attempting to remove a specific
 6052:     scantron_.. bubble sheet data file. Prints out an error if
 6053:     something went wrong.
 6054: 
 6055: =cut
 6056: 
 6057: sub check_for_error {
 6058:     my ($r,$result)=@_;
 6059:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6060: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6061:     }
 6062: }
 6063: 
 6064: =pod
 6065: 
 6066: =item scantron_warning_screen
 6067: 
 6068:    Interstitial screen to make sure the operator has selected the
 6069:    correct options before we start the validation phase.
 6070: 
 6071: =cut
 6072: 
 6073: sub scantron_warning_screen {
 6074:     my ($button_text)=@_;
 6075:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6076:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6077:     my $CODElist;
 6078:     if ($scantron_config{'CODElocation'} &&
 6079: 	$scantron_config{'CODEstart'} &&
 6080: 	$scantron_config{'CODElength'}) {
 6081: 	$CODElist=$env{'form.scantron_CODElist'};
 6082: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6083: 	$CODElist=
 6084: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6085: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6086:     }
 6087:     return ('
 6088: <p>
 6089: <span class="LC_warning">
 6090: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6091: </p>
 6092: <table>
 6093: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6094: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6095: '.$CODElist.'
 6096: </table>
 6097: <br />
 6098: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6099: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6100: 
 6101: <br />
 6102: ');
 6103: }
 6104: 
 6105: =pod
 6106: 
 6107: =item scantron_do_warning
 6108: 
 6109:    Check if the operator has picked something for all required
 6110:    fields. Error out if something is missing.
 6111: 
 6112: =cut
 6113: 
 6114: sub scantron_do_warning {
 6115:     my ($r)=@_;
 6116:     my ($symb)=&get_symb($r);
 6117:     if (!$symb) {return '';}
 6118:     my $default_form_data=&defaultFormData($symb);
 6119:     $r->print(&scantron_form_start().$default_form_data);
 6120:     if ( $env{'form.selectpage'} eq '' ||
 6121: 	 $env{'form.scantron_selectfile'} eq '' ||
 6122: 	 $env{'form.scantron_format'} eq '' ) {
 6123: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6124: 	if ( $env{'form.selectpage'} eq '') {
 6125: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6126: 	} 
 6127: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6128: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6129: 	} 
 6130: 	if ( $env{'form.scantron_format'} eq '') {
 6131: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6132: 	} 
 6133:     } else {
 6134: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6135: 	$r->print('
 6136: '.$warning.'
 6137: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6138: <input type="hidden" name="command" value="scantron_validate" />
 6139: ');
 6140:     }
 6141:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6142:     return '';
 6143: }
 6144: 
 6145: =pod
 6146: 
 6147: =item scantron_form_start
 6148: 
 6149:     html hidden input for remembering all selected grading options
 6150: 
 6151: =cut
 6152: 
 6153: sub scantron_form_start {
 6154:     my ($max_bubble)=@_;
 6155:     my $result= <<SCANTRONFORM;
 6156: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6157:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6158:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6159:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6160:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6161:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6162:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6163:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6164:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6165:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6166: SCANTRONFORM
 6167: 
 6168:   my $line = 0;
 6169:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6170:        my $chunk =
 6171: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6172:        $chunk .=
 6173: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6174:        $chunk .= 
 6175:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6176:        $chunk .=
 6177:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6178:        $result .= $chunk;
 6179:        $line++;
 6180:    }
 6181:     return $result;
 6182: }
 6183: 
 6184: =pod
 6185: 
 6186: =item scantron_validate_file
 6187: 
 6188:     Dispatch routine for doing validation of a bubble sheet data file.
 6189: 
 6190:     Also processes any necessary information resets that need to
 6191:     occur before validation begins (ignore previous corrections,
 6192:     restarting the skipped records processing)
 6193: 
 6194: =cut
 6195: 
 6196: sub scantron_validate_file {
 6197:     my ($r) = @_;
 6198:     my ($symb)=&get_symb($r);
 6199:     if (!$symb) {return '';}
 6200:     my $default_form_data=&defaultFormData($symb);
 6201:     
 6202:     # do the detection of only doing skipped records first befroe we delete
 6203:     # them when doing the corrections reset
 6204:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6205: 	&reset_skipping_status();
 6206:     }
 6207:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6208: 	&remember_current_skipped();
 6209: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6210:     }
 6211: 
 6212:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6213: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6214: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6215: 	&check_for_error($r,&scantron_remove_scan_data());
 6216: 	$env{'form.scantron_options_ignore'}='done';
 6217:     }
 6218: 
 6219:     if ($env{'form.scantron_corrections'}) {
 6220: 	&scantron_process_corrections($r);
 6221:     }
 6222:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6223:     #get the student pick code ready
 6224:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6225:     my $max_bubble=&scantron_get_maxbubble();
 6226:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6227:     $r->print($result);
 6228:     
 6229:     my @validate_phases=( 'sequence',
 6230: 			  'ID',
 6231: 			  'CODE',
 6232: 			  'doublebubble',
 6233: 			  'missingbubbles');
 6234:     if (!$env{'form.validatepass'}) {
 6235: 	$env{'form.validatepass'} = 0;
 6236:     }
 6237:     my $currentphase=$env{'form.validatepass'};
 6238: 
 6239: 
 6240:     my $stop=0;
 6241:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6242: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6243: 	$r->rflush();
 6244: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6245: 	{
 6246: 	    no strict 'refs';
 6247: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6248: 	}
 6249:     }
 6250:     if (!$stop) {
 6251: 	my $warning=&scantron_warning_screen('Start Grading');
 6252: 	$r->print(&mt('Validation process complete.').'<br />'.
 6253:                   $warning.
 6254:                   &mt('Perform verification for each student after storage of submissions?').
 6255:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6256:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6257:                   ('&nbsp;'x3).'<label>'.
 6258:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6259:                   '</label></span><br />'.
 6260:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6261:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6262:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6263:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6264:     } else {
 6265: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6266: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6267:     }
 6268:     if ($stop) {
 6269: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6270: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6271: 	    $r->print(' '.&mt('this error').' <br />');
 6272: 
 6273: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6274: 	} else {
 6275:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6276: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6277:             } else {
 6278:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6279:             }
 6280: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6281: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6282: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6283: 	}
 6284:     }
 6285:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6286:     return '';
 6287: }
 6288: 
 6289: 
 6290: =pod
 6291: 
 6292: =item scantron_remove_file
 6293: 
 6294:    Removes the requested bubble sheet data file, makes sure that
 6295:    scantron_original_<filename> is never removed
 6296: 
 6297: 
 6298: =cut
 6299: 
 6300: sub scantron_remove_file {
 6301:     my ($which)=@_;
 6302:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6303:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6304:     my $file='scantron_';
 6305:     if ($which eq 'corrected' || $which eq 'skipped') {
 6306: 	$file.=$which.'_';
 6307:     } else {
 6308: 	return 'refused';
 6309:     }
 6310:     $file.=$env{'form.scantron_selectfile'};
 6311:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6312: }
 6313: 
 6314: 
 6315: =pod
 6316: 
 6317: =item scantron_remove_scan_data
 6318: 
 6319:    Removes all scan_data correction for the requested bubble sheet
 6320:    data file.  (In the case that both the are doing skipped records we need
 6321:    to remember the old skipped lines for the time being so that element
 6322:    persists for a while.)
 6323: 
 6324: =cut
 6325: 
 6326: sub scantron_remove_scan_data {
 6327:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6328:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6329:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6330:     my @todelete;
 6331:     my $filename=$env{'form.scantron_selectfile'};
 6332:     foreach my $key (@keys) {
 6333: 	if ($key=~/^\Q$filename\E_/) {
 6334: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6335: 		$key=~/remember_skipping/) {
 6336: 		next;
 6337: 	    }
 6338: 	    push(@todelete,$key);
 6339: 	}
 6340:     }
 6341:     my $result;
 6342:     if (@todelete) {
 6343: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6344: 				       \@todelete,$cdom,$cname);
 6345:     } else {
 6346: 	$result = 'ok';
 6347:     }
 6348:     return $result;
 6349: }
 6350: 
 6351: 
 6352: =pod
 6353: 
 6354: =item scantron_getfile
 6355: 
 6356:     Fetches the requested bubble sheet data file (all 3 versions), and
 6357:     the scan_data hash
 6358:   
 6359:   Arguments:
 6360:     None
 6361: 
 6362:   Returns:
 6363:     2 hash references
 6364: 
 6365:      - first one has 
 6366:          orig      -
 6367:          corrected -
 6368:          skipped   -  each of which points to an array ref of the specified
 6369:                       file broken up into individual lines
 6370:          count     - number of scanlines
 6371:  
 6372:      - second is the scan_data hash possible keys are
 6373:        ($number refers to scanline numbered $number and thus the key affects
 6374:         only that scanline
 6375:         $bubline refers to the specific bubble line element and the aspects
 6376:         refers to that specific bubble line element)
 6377: 
 6378:        $number.user - username:domain to use
 6379:        $number.CODE_ignore_dup 
 6380:                     - ignore the duplicate CODE error 
 6381:        $number.useCODE
 6382:                     - use the CODE in the scanline as is
 6383:        $number.no_bubble.$bubline
 6384:                     - it is valid that there is no bubbled in bubble
 6385:                       at $number $bubline
 6386:        remember_skipping
 6387:                     - a frozen hash containing keys of $number and values
 6388:                       of either 
 6389:                         1 - we are on a 'do skipped records pass' and plan
 6390:                             on processing this line
 6391:                         2 - we are on a 'do skipped records pass' and this
 6392:                             scanline has been marked to skip yet again
 6393: 
 6394: =cut
 6395: 
 6396: sub scantron_getfile {
 6397:     #FIXME really would prefer a scantron directory
 6398:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6399:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6400:     my $lines;
 6401:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6402: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6403:     my %scanlines;
 6404:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6405:     my $temp=$scanlines{'orig'};
 6406:     $scanlines{'count'}=$#$temp;
 6407: 
 6408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6409: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6410:     if ($lines eq '-1') {
 6411: 	$scanlines{'corrected'}=[];
 6412:     } else {
 6413: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6414:     }
 6415:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6416: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6417:     if ($lines eq '-1') {
 6418: 	$scanlines{'skipped'}=[];
 6419:     } else {
 6420: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6421:     }
 6422:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6423:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6424:     my %scan_data = @tmp;
 6425:     return (\%scanlines,\%scan_data);
 6426: }
 6427: 
 6428: =pod
 6429: 
 6430: =item lonnet_putfile
 6431: 
 6432:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6433: 
 6434:  Arguments:
 6435:    $contents - data to store
 6436:    $filename - filename to store $contents into
 6437: 
 6438:  Returns:
 6439:    result value from &Apache::lonnet::finishuserfileupload
 6440: 
 6441: =cut
 6442: 
 6443: sub lonnet_putfile {
 6444:     my ($contents,$filename)=@_;
 6445:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6446:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6447:     $env{'form.sillywaytopassafilearound'}=$contents;
 6448:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6449: 
 6450: }
 6451: 
 6452: =pod
 6453: 
 6454: =item scantron_putfile
 6455: 
 6456:     Stores the current version of the bubble sheet data files, and the
 6457:     scan_data hash. (Does not modify the original version only the
 6458:     corrected and skipped versions.
 6459: 
 6460:  Arguments:
 6461:     $scanlines - hash ref that looks like the first return value from
 6462:                  &scantron_getfile()
 6463:     $scan_data - hash ref that looks like the second return value from
 6464:                  &scantron_getfile()
 6465: 
 6466: =cut
 6467: 
 6468: sub scantron_putfile {
 6469:     my ($scanlines,$scan_data) = @_;
 6470:     #FIXME really would prefer a scantron directory
 6471:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6473:     if ($scanlines) {
 6474: 	my $prefix='scantron_';
 6475: # no need to update orig, shouldn't change
 6476: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6477: #		    $env{'form.scantron_selectfile'});
 6478: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6479: 			$prefix.'corrected_'.
 6480: 			$env{'form.scantron_selectfile'});
 6481: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6482: 			$prefix.'skipped_'.
 6483: 			$env{'form.scantron_selectfile'});
 6484:     }
 6485:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6486: }
 6487: 
 6488: =pod
 6489: 
 6490: =item scantron_get_line
 6491: 
 6492:    Returns the correct version of the scanline
 6493: 
 6494:  Arguments:
 6495:     $scanlines - hash ref that looks like the first return value from
 6496:                  &scantron_getfile()
 6497:     $scan_data - hash ref that looks like the second return value from
 6498:                  &scantron_getfile()
 6499:     $i         - number of the requested line (starts at 0)
 6500: 
 6501:  Returns:
 6502:    A scanline, (either the original or the corrected one if it
 6503:    exists), or undef if the requested scanline should be
 6504:    skipped. (Either because it's an skipped scanline, or it's an
 6505:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6506:    pass.
 6507: 
 6508: =cut
 6509: 
 6510: sub scantron_get_line {
 6511:     my ($scanlines,$scan_data,$i)=@_;
 6512:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6513:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6514:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6515:     return $scanlines->{'orig'}[$i]; 
 6516: }
 6517: 
 6518: =pod
 6519: 
 6520: =item scantron_todo_count
 6521: 
 6522:     Counts the number of scanlines that need processing.
 6523: 
 6524:  Arguments:
 6525:     $scanlines - hash ref that looks like the first return value from
 6526:                  &scantron_getfile()
 6527:     $scan_data - hash ref that looks like the second return value from
 6528:                  &scantron_getfile()
 6529: 
 6530:  Returns:
 6531:     $count - number of scanlines to process
 6532: 
 6533: =cut
 6534: 
 6535: sub get_todo_count {
 6536:     my ($scanlines,$scan_data)=@_;
 6537:     my $count=0;
 6538:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6539: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6540: 	if ($line=~/^[\s\cz]*$/) { next; }
 6541: 	$count++;
 6542:     }
 6543:     return $count;
 6544: }
 6545: 
 6546: =pod
 6547: 
 6548: =item scantron_put_line
 6549: 
 6550:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6551:     data file.
 6552: 
 6553:  Arguments:
 6554:     $scanlines - hash ref that looks like the first return value from
 6555:                  &scantron_getfile()
 6556:     $scan_data - hash ref that looks like the second return value from
 6557:                  &scantron_getfile()
 6558:     $i         - line number to update
 6559:     $newline   - contents of the updated scanline
 6560:     $skip      - if true make the line for skipping and update the
 6561:                  'skipped' file
 6562: 
 6563: =cut
 6564: 
 6565: sub scantron_put_line {
 6566:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6567:     if ($skip) {
 6568: 	$scanlines->{'skipped'}[$i]=$newline;
 6569: 	&start_skipping($scan_data,$i);
 6570: 	return;
 6571:     }
 6572:     $scanlines->{'corrected'}[$i]=$newline;
 6573: }
 6574: 
 6575: =pod
 6576: 
 6577: =item scantron_clear_skip
 6578: 
 6579:    Remove a line from the 'skipped' file
 6580: 
 6581:  Arguments:
 6582:     $scanlines - hash ref that looks like the first return value from
 6583:                  &scantron_getfile()
 6584:     $scan_data - hash ref that looks like the second return value from
 6585:                  &scantron_getfile()
 6586:     $i         - line number to update
 6587: 
 6588: =cut
 6589: 
 6590: sub scantron_clear_skip {
 6591:     my ($scanlines,$scan_data,$i)=@_;
 6592:     if (exists($scanlines->{'skipped'}[$i])) {
 6593: 	undef($scanlines->{'skipped'}[$i]);
 6594: 	return 1;
 6595:     }
 6596:     return 0;
 6597: }
 6598: 
 6599: =pod
 6600: 
 6601: =item scantron_filter_not_exam
 6602: 
 6603:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6604:    filter out resources that are not marked as 'exam' mode
 6605: 
 6606: =cut
 6607: 
 6608: sub scantron_filter_not_exam {
 6609:     my ($curres)=@_;
 6610:     
 6611:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6612: 	# if the user has asked to not have either hidden
 6613: 	# or 'randomout' controlled resources to be graded
 6614: 	# don't include them
 6615: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6616: 	    && $curres->randomout) {
 6617: 	    return 0;
 6618: 	}
 6619: 	return 1;
 6620:     }
 6621:     return 0;
 6622: }
 6623: 
 6624: =pod
 6625: 
 6626: =item scantron_validate_sequence
 6627: 
 6628:     Validates the selected sequence, checking for resource that are
 6629:     not set to exam mode.
 6630: 
 6631: =cut
 6632: 
 6633: sub scantron_validate_sequence {
 6634:     my ($r,$currentphase) = @_;
 6635: 
 6636:     my $navmap=Apache::lonnavmaps::navmap->new();
 6637:     my (undef,undef,$sequence)=
 6638: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6639: 
 6640:     my $map=$navmap->getResourceByUrl($sequence);
 6641: 
 6642:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6643:                                     value="ignore" />');
 6644:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6645: 	my @resources=
 6646: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6647: 	if (@resources) {
 6648: 	    $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>");
 6649: 	    return (1,$currentphase);
 6650: 	}
 6651:     }
 6652: 
 6653:     return (0,$currentphase+1);
 6654: }
 6655: 
 6656: 
 6657: 
 6658: sub scantron_validate_ID {
 6659:     my ($r,$currentphase) = @_;
 6660:     
 6661:     #get student info
 6662:     my $classlist=&Apache::loncoursedata::get_classlist();
 6663:     my %idmap=&username_to_idmap($classlist);
 6664: 
 6665:     #get scantron line setup
 6666:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6667:     my ($scanlines,$scan_data)=&scantron_getfile();
 6668:     
 6669:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6670: 
 6671:     my %found=('ids'=>{},'usernames'=>{});
 6672:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6673: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6674: 	if ($line=~/^[\s\cz]*$/) { next; }
 6675: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6676: 						 $scan_data);
 6677: 	my $id=$$scan_record{'scantron.ID'};
 6678: 	my $found;
 6679: 	foreach my $checkid (keys(%idmap)) {
 6680: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6681: 	}
 6682: 	if ($found) {
 6683: 	    my $username=$idmap{$found};
 6684: 	    if ($found{'ids'}{$found}) {
 6685: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6686: 					 $line,'duplicateID',$found);
 6687: 		return(1,$currentphase);
 6688: 	    } elsif ($found{'usernames'}{$username}) {
 6689: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6690: 					 $line,'duplicateID',$username);
 6691: 		return(1,$currentphase);
 6692: 	    }
 6693: 	    #FIXME store away line we previously saw the ID on to use above
 6694: 	    $found{'ids'}{$found}++;
 6695: 	    $found{'usernames'}{$username}++;
 6696: 	} else {
 6697: 	    if ($id =~ /^\s*$/) {
 6698: 		my $username=&scan_data($scan_data,"$i.user");
 6699: 		if (defined($username) && $found{'usernames'}{$username}) {
 6700: 		    &scantron_get_correction($r,$i,$scan_record,
 6701: 					     \%scantron_config,
 6702: 					     $line,'duplicateID',$username);
 6703: 		    return(1,$currentphase);
 6704: 		} elsif (!defined($username)) {
 6705: 		    &scantron_get_correction($r,$i,$scan_record,
 6706: 					     \%scantron_config,
 6707: 					     $line,'incorrectID');
 6708: 		    return(1,$currentphase);
 6709: 		}
 6710: 		$found{'usernames'}{$username}++;
 6711: 	    } else {
 6712: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6713: 					 $line,'incorrectID');
 6714: 		return(1,$currentphase);
 6715: 	    }
 6716: 	}
 6717:     }
 6718: 
 6719:     return (0,$currentphase+1);
 6720: }
 6721: 
 6722: 
 6723: sub scantron_get_correction {
 6724:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6725: #FIXME in the case of a duplicated ID the previous line, probably need
 6726: #to show both the current line and the previous one and allow skipping
 6727: #the previous one or the current one
 6728: 
 6729:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6730: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6731: 			    " for PaperID <tt>[_1]</tt>",
 6732: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6733:     } else {
 6734: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6735: 			    " in scanline [_1] <pre>[_2]</pre>",
 6736: 			    $i,$line)."</p> \n");
 6737:     }
 6738:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6739: 			  "The name on the paper is [_2],[_3]",
 6740: 			  $$scan_record{'scantron.ID'},
 6741: 			  $$scan_record{'scantron.LastName'},
 6742: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6743: 
 6744:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6745:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6746:                            # Array populated for doublebubble or
 6747:     my @lines_to_correct;  # missingbubble errors to build javascript
 6748:                            # to validate radio button checking   
 6749: 
 6750:     if ($error =~ /ID$/) {
 6751: 	if ($error eq 'incorrectID') {
 6752: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6753: 		      "</p>\n");
 6754: 	} elsif ($error eq 'duplicateID') {
 6755: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6756: 	}
 6757: 	$r->print($message);
 6758: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6759: 	$r->print("\n<ul><li> ");
 6760: 	#FIXME it would be nice if this sent back the user ID and
 6761: 	#could do partial userID matches
 6762: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6763: 				       'scantron_username','scantron_domain'));
 6764: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6765: 	$r->print("\n@".
 6766: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6767: 
 6768: 	$r->print('</li>');
 6769:     } elsif ($error =~ /CODE$/) {
 6770: 	if ($error eq 'incorrectCODE') {
 6771: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6772: 	} elsif ($error eq 'duplicateCODE') {
 6773: 	    $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");
 6774: 	}
 6775: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6776: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6777: 	$r->print($message);
 6778: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6779: 	$r->print("\n<br /> ");
 6780: 	my $i=0;
 6781: 	if ($error eq 'incorrectCODE' 
 6782: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6783: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6784: 	    if ($closest > 0) {
 6785: 		foreach my $testcode (@{$closest}) {
 6786: 		    my $checked='';
 6787: 		    if (!$i) { $checked=' checked="checked"'; }
 6788: 		    $r->print("
 6789:    <label>
 6790:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6791:        ".&mt("Use the similar CODE [_1] instead.",
 6792: 	    "<b><tt>".$testcode."</tt></b>")."
 6793:     </label>
 6794:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6795: 		    $r->print("\n<br />");
 6796: 		    $i++;
 6797: 		}
 6798: 	    }
 6799: 	}
 6800: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6801: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6802: 	    $r->print("
 6803:     <label>
 6804:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6805:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6806: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6807:     </label>");
 6808: 	    $r->print("\n<br />");
 6809: 	}
 6810: 
 6811: 	$r->print(<<ENDSCRIPT);
 6812: <script type="text/javascript">
 6813: function change_radio(field) {
 6814:     var slct=document.scantronupload.scantron_CODE_resolution;
 6815:     var i;
 6816:     for (i=0;i<slct.length;i++) {
 6817:         if (slct[i].value==field) { slct[i].checked=true; }
 6818:     }
 6819: }
 6820: </script>
 6821: ENDSCRIPT
 6822: 	my $href="/adm/pickcode?".
 6823: 	   "form=".&escape("scantronupload").
 6824: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6825: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6826: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6827: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6828: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6829: 	    $r->print("
 6830:     <label>
 6831:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6832:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6833: 	     "<a target='_blank' href='$href'>","</a>")."
 6834:     </label> 
 6835:     ".&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\')" />'));
 6836: 	    $r->print("\n<br />");
 6837: 	}
 6838: 	$r->print("
 6839:     <label>
 6840:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6841:        ".&mt("Use [_1] as the CODE.",
 6842: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6843: 	$r->print("\n<br /><br />");
 6844:     } elsif ($error eq 'doublebubble') {
 6845: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6846: 
 6847: 	# The form field scantron_questions is acutally a list of line numbers.
 6848: 	# represented by this form so:
 6849: 
 6850: 	my $line_list = &questions_to_line_list($arg);
 6851: 
 6852: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6853: 		  $line_list.'" />');
 6854: 	$r->print($message);
 6855: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6856: 	foreach my $question (@{$arg}) {
 6857: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6858:                                                    $scan_record, $error);
 6859:             push(@lines_to_correct,@linenums);
 6860: 	}
 6861:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6862:     } elsif ($error eq 'missingbubble') {
 6863: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6864: 	$r->print($message);
 6865: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6866: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6867: 
 6868: 	# The form field scantron_questions is actually a list of line numbers not
 6869: 	# a list of question numbers. Therefore:
 6870: 	#
 6871: 	
 6872: 	my $line_list = &questions_to_line_list($arg);
 6873: 
 6874: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6875: 		  $line_list.'" />');
 6876: 	foreach my $question (@{$arg}) {
 6877: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6878:                                                    $scan_record, $error);
 6879:             push(@lines_to_correct,@linenums);
 6880: 	}
 6881:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6882:     } else {
 6883: 	$r->print("\n<ul>");
 6884:     }
 6885:     $r->print("\n</li></ul>");
 6886: }
 6887: 
 6888: sub verify_bubbles_checked {
 6889:     my (@ansnums) = @_;
 6890:     my $ansnumstr = join('","',@ansnums);
 6891:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6892:     my $output = (<<ENDSCRIPT);
 6893: <script type="text/javascript">
 6894: function verify_bubble_radio(form) {
 6895:     var ansnumArray = new Array ("$ansnumstr");
 6896:     var need_bubble_count = 0;
 6897:     for (var i=0; i<ansnumArray.length; i++) {
 6898:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6899:             var bubble_picked = 0; 
 6900:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6901:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6902:                     bubble_picked = 1;
 6903:                 }
 6904:             }
 6905:             if (bubble_picked == 0) {
 6906:                 need_bubble_count ++;
 6907:             }
 6908:         }
 6909:     }
 6910:     if (need_bubble_count) {
 6911:         alert("$warning");
 6912:         return;
 6913:     }
 6914:     form.submit(); 
 6915: }
 6916: </script>
 6917: ENDSCRIPT
 6918:     return $output;
 6919: }
 6920: 
 6921: =pod
 6922: 
 6923: =item  questions_to_line_list
 6924: 
 6925: Converts a list of questions into a string of comma separated
 6926: line numbers in the answer sheet used by the questions.  This is
 6927: used to fill in the scantron_questions form field.
 6928: 
 6929:   Arguments:
 6930:      questions    - Reference to an array of questions.
 6931: 
 6932: =cut
 6933: 
 6934: 
 6935: sub questions_to_line_list {
 6936:     my ($questions) = @_;
 6937:     my @lines;
 6938: 
 6939:     foreach my $item (@{$questions}) {
 6940:         my $question = $item;
 6941:         my ($first,$count,$last);
 6942:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6943:             $question = $1;
 6944:             my $subquestion = $2;
 6945:             $first = $first_bubble_line{$question-1} + 1;
 6946:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6947:             my $subcount = 1;
 6948:             while ($subcount<$subquestion) {
 6949:                 $first += $subans[$subcount-1];
 6950:                 $subcount ++;
 6951:             }
 6952:             $count = $subans[$subquestion-1];
 6953:         } else {
 6954: 	    $first   = $first_bubble_line{$question-1} + 1;
 6955: 	    $count   = $bubble_lines_per_response{$question-1};
 6956:         }
 6957:         $last = $first+$count-1;
 6958:         push(@lines, ($first..$last));
 6959:     }
 6960:     return join(',', @lines);
 6961: }
 6962: 
 6963: =pod 
 6964: 
 6965: =item prompt_for_corrections
 6966: 
 6967: Prompts for a potentially multiline correction to the
 6968: user's bubbling (factors out common code from scantron_get_correction
 6969: for multi and missing bubble cases).
 6970: 
 6971:  Arguments:
 6972:    $r           - Apache request object.
 6973:    $question    - The question number to prompt for.
 6974:    $scan_config - The scantron file configuration hash.
 6975:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6976:    $error       - Type of error
 6977: 
 6978:  Implicit inputs:
 6979:    %bubble_lines_per_response   - Starting line numbers for each question.
 6980:                                   Numbered from 0 (but question numbers are from
 6981:                                   1.
 6982:    %first_bubble_line           - Starting bubble line for each question.
 6983:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6984:                                   type problems render as separate sub-questions, 
 6985:                                   in exam mode. This hash contains a 
 6986:                                   comma-separated list of the lines per 
 6987:                                   sub-question.
 6988:    %responsetype_per_response   - essayresponse, formularesponse,
 6989:                                   stringresponse, imageresponse, reactionresponse,
 6990:                                   and organicresponse type problem parts can have
 6991:                                   multiple lines per response if the weight
 6992:                                   assigned exceeds 10.  In this case, only
 6993:                                   one bubble per line is permitted, but more 
 6994:                                   than one line might contain bubbles, e.g.
 6995:                                   bubbling of: line 1 - J, line 2 - J, 
 6996:                                   line 3 - B would assign 22 points.  
 6997: 
 6998: =cut
 6999: 
 7000: sub prompt_for_corrections {
 7001:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7002:     my ($current_line,$lines);
 7003:     my @linenums;
 7004:     my $questionnum = $question;
 7005:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7006:         $question = $1;
 7007:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7008:         my $subquestion = $2;
 7009:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7010:         my $subcount = 1;
 7011:         while ($subcount<$subquestion) {
 7012:             $current_line += $subans[$subcount-1];
 7013:             $subcount ++;
 7014:         }
 7015:         $lines = $subans[$subquestion-1];
 7016:     } else {
 7017:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7018:         $lines        = $bubble_lines_per_response{$question-1};
 7019:     }
 7020:     if ($lines > 1) {
 7021:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7022:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7023:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7024:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7025:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7026:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7027:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7028:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7029:         } else {
 7030:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7031:         }
 7032:     }
 7033:     for (my $i =0; $i < $lines; $i++) {
 7034:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7035: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7036: 	        		  $questionnum,$error,split('', $selected));
 7037:         push(@linenums,$current_line);
 7038: 	$current_line++;
 7039:     }
 7040:     if ($lines > 1) {
 7041: 	$r->print("<hr /><br />");
 7042:     }
 7043:     return @linenums;
 7044: }
 7045: 
 7046: =pod
 7047: 
 7048: =item scantron_bubble_selector
 7049:   
 7050:    Generates the html radiobuttons to correct a single bubble line
 7051:    possibly showing the existing the selected bubbles if known
 7052: 
 7053:  Arguments:
 7054:     $r           - Apache request object
 7055:     $scan_config - hash from &get_scantron_config()
 7056:     $line        - Number of the line being displayed.
 7057:     $questionnum - Question number (may include subquestion)
 7058:     $error       - Type of error.
 7059:     @selected    - Array of bubbles picked on this line.
 7060: 
 7061: =cut
 7062: 
 7063: sub scantron_bubble_selector {
 7064:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7065:     my $max=$$scan_config{'Qlength'};
 7066: 
 7067:     my $scmode=$$scan_config{'Qon'};
 7068:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7069: 
 7070:     my @alphabet=('A'..'Z');
 7071:     $r->print(&Apache::loncommon::start_data_table().
 7072:               &Apache::loncommon::start_data_table_row());
 7073:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7074:     for (my $i=0;$i<$max+1;$i++) {
 7075: 	$r->print("\n".'<td align="center">');
 7076: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7077: 	else { $r->print('&nbsp;'); }
 7078: 	$r->print('</td>');
 7079:     }
 7080:     $r->print(&Apache::loncommon::end_data_table_row().
 7081:               &Apache::loncommon::start_data_table_row());
 7082:     for (my $i=0;$i<$max;$i++) {
 7083: 	$r->print("\n".
 7084: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7085: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7086:     }
 7087:     my $nobub_checked = ' ';
 7088:     if ($error eq 'missingbubble') {
 7089:         $nobub_checked = ' checked = "checked" ';
 7090:     }
 7091:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7092: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7093:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7094:               $line.'" value="'.$questionnum.'" /></td>');
 7095:     $r->print(&Apache::loncommon::end_data_table_row().
 7096:               &Apache::loncommon::end_data_table());
 7097: }
 7098: 
 7099: =pod
 7100: 
 7101: =item num_matches
 7102: 
 7103:    Counts the number of characters that are the same between the two arguments.
 7104: 
 7105:  Arguments:
 7106:    $orig - CODE from the scanline
 7107:    $code - CODE to match against
 7108: 
 7109:  Returns:
 7110:    $count - integer count of the number of same characters between the
 7111:             two arguments
 7112: 
 7113: =cut
 7114: 
 7115: sub num_matches {
 7116:     my ($orig,$code) = @_;
 7117:     my @code=split(//,$code);
 7118:     my @orig=split(//,$orig);
 7119:     my $same=0;
 7120:     for (my $i=0;$i<scalar(@code);$i++) {
 7121: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7122:     }
 7123:     return $same;
 7124: }
 7125: 
 7126: =pod
 7127: 
 7128: =item scantron_get_closely_matching_CODEs
 7129: 
 7130:    Cycles through all CODEs and finds the set that has the greatest
 7131:    number of same characters as the provided CODE
 7132: 
 7133:  Arguments:
 7134:    $allcodes - hash ref returned by &get_codes()
 7135:    $CODE     - CODE from the current scanline
 7136: 
 7137:  Returns:
 7138:    2 element list
 7139:     - first elements is number of how closely matching the best fit is 
 7140:       (5 means best set has 5 matching characters)
 7141:     - second element is an arrary ref containing the set of valid CODEs
 7142:       that best fit the passed in CODE
 7143: 
 7144: =cut
 7145: 
 7146: sub scantron_get_closely_matching_CODEs {
 7147:     my ($allcodes,$CODE)=@_;
 7148:     my @CODEs;
 7149:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7150: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7151:     }
 7152: 
 7153:     return ($#CODEs,$CODEs[-1]);
 7154: }
 7155: 
 7156: =pod
 7157: 
 7158: =item get_codes
 7159: 
 7160:    Builds a hash which has keys of all of the valid CODEs from the selected
 7161:    set of remembered CODEs.
 7162: 
 7163:  Arguments:
 7164:   $old_name - name of the set of remembered CODEs
 7165:   $cdom     - domain of the course
 7166:   $cnum     - internal course name
 7167: 
 7168:  Returns:
 7169:   %allcodes - keys are the valid CODEs, values are all 1
 7170: 
 7171: =cut
 7172: 
 7173: sub get_codes {
 7174:     my ($old_name, $cdom, $cnum) = @_;
 7175:     if (!$old_name) {
 7176: 	$old_name=$env{'form.scantron_CODElist'};
 7177:     }
 7178:     if (!$cdom) {
 7179: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7180:     }
 7181:     if (!$cnum) {
 7182: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7183:     }
 7184:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7185: 				    $cdom,$cnum);
 7186:     my %allcodes;
 7187:     if ($result{"type\0$old_name"} eq 'number') {
 7188: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7189:     } else {
 7190: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7191:     }
 7192:     return %allcodes;
 7193: }
 7194: 
 7195: =pod
 7196: 
 7197: =item scantron_validate_CODE
 7198: 
 7199:    Validates all scanlines in the selected file to not have any
 7200:    invalid or underspecified CODEs and that none of the codes are
 7201:    duplicated if this was requested.
 7202: 
 7203: =cut
 7204: 
 7205: sub scantron_validate_CODE {
 7206:     my ($r,$currentphase) = @_;
 7207:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7208:     if ($scantron_config{'CODElocation'} &&
 7209: 	$scantron_config{'CODEstart'} &&
 7210: 	$scantron_config{'CODElength'}) {
 7211: 	if (!defined($env{'form.scantron_CODElist'})) {
 7212: 	    &FIXME_blow_up()
 7213: 	}
 7214:     } else {
 7215: 	return (0,$currentphase+1);
 7216:     }
 7217:     
 7218:     my %usedCODEs;
 7219: 
 7220:     my %allcodes=&get_codes();
 7221: 
 7222:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7223: 
 7224:     my ($scanlines,$scan_data)=&scantron_getfile();
 7225:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7226: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7227: 	if ($line=~/^[\s\cz]*$/) { next; }
 7228: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7229: 						 $scan_data);
 7230: 	my $CODE=$$scan_record{'scantron.CODE'};
 7231: 	my $error=0;
 7232: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7233: 	    &scantron_get_correction($r,$i,$scan_record,
 7234: 				     \%scantron_config,
 7235: 				     $line,'incorrectCODE',\%allcodes);
 7236: 	    return(1,$currentphase);
 7237: 	}
 7238: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7239: 	    && !$$scan_record{'scantron.useCODE'}) {
 7240: 	    &scantron_get_correction($r,$i,$scan_record,
 7241: 				     \%scantron_config,
 7242: 				     $line,'incorrectCODE',\%allcodes);
 7243: 	    return(1,$currentphase);
 7244: 	}
 7245: 	if (exists($usedCODEs{$CODE}) 
 7246: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7247: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7248: 	    &scantron_get_correction($r,$i,$scan_record,
 7249: 				     \%scantron_config,
 7250: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7251: 	    return(1,$currentphase);
 7252: 	}
 7253: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7254:     }
 7255:     return (0,$currentphase+1);
 7256: }
 7257: 
 7258: =pod
 7259: 
 7260: =item scantron_validate_doublebubble
 7261: 
 7262:    Validates all scanlines in the selected file to not have any
 7263:    bubble lines with multiple bubbles marked.
 7264: 
 7265: =cut
 7266: 
 7267: sub scantron_validate_doublebubble {
 7268:     my ($r,$currentphase) = @_;
 7269:     #get student info
 7270:     my $classlist=&Apache::loncoursedata::get_classlist();
 7271:     my %idmap=&username_to_idmap($classlist);
 7272: 
 7273:     #get scantron line setup
 7274:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7275:     my ($scanlines,$scan_data)=&scantron_getfile();
 7276:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7277: 
 7278:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7279: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7280: 	if ($line=~/^[\s\cz]*$/) { next; }
 7281: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7282: 						 $scan_data);
 7283: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7284: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7285: 				 'doublebubble',
 7286: 				 $$scan_record{'scantron.doubleerror'});
 7287:     	return (1,$currentphase);
 7288:     }
 7289:     return (0,$currentphase+1);
 7290: }
 7291: 
 7292: 
 7293: sub scantron_get_maxbubble {
 7294:     if (defined($env{'form.scantron_maxbubble'}) &&
 7295: 	$env{'form.scantron_maxbubble'}) {
 7296: 	&restore_bubble_lines();
 7297: 	return $env{'form.scantron_maxbubble'};
 7298:     }
 7299: 
 7300:     my (undef, undef, $sequence) =
 7301: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7302: 
 7303:     my $navmap=Apache::lonnavmaps::navmap->new();
 7304:     my $map=$navmap->getResourceByUrl($sequence);
 7305:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7306: 
 7307:     &Apache::lonxml::clear_problem_counter();
 7308: 
 7309:     my $uname       = $env{'user.name'};
 7310:     my $udom        = $env{'user.domain'};
 7311:     my $cid         = $env{'request.course.id'};
 7312:     my $total_lines = 0;
 7313:     %bubble_lines_per_response = ();
 7314:     %first_bubble_line         = ();
 7315:     %subdivided_bubble_lines   = ();
 7316:     %responsetype_per_response = ();
 7317: 
 7318:     my $response_number = 0;
 7319:     my $bubble_line     = 0;
 7320:     foreach my $resource (@resources) {
 7321:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7322:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7323: 	    foreach my $part_id (@{$parts}) {
 7324:                 my $lines;
 7325: 
 7326: 	        # TODO - make this a persistent hash not an array.
 7327: 
 7328:                 # optionresponse, matchresponse and rankresponse type items 
 7329:                 # render as separate sub-questions in exam mode.
 7330:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7331:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7332:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7333:                     my ($numbub,$numshown);
 7334:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7335:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7336:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7337:                         }
 7338:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7339:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7340:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7341:                         }
 7342:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7343:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7344:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7345:                         }
 7346:                     }
 7347:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7348:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7349:                     }
 7350:                     my $bubbles_per_line = 10;
 7351:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7352:                     if (($numbub % $bubbles_per_line) != 0) {
 7353:                         $inner_bubble_lines++;
 7354:                     }
 7355:                     for (my $i=0; $i<$numshown; $i++) {
 7356:                         $subdivided_bubble_lines{$response_number} .= 
 7357:                             $inner_bubble_lines.',';
 7358:                     }
 7359:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7360:                     $lines = $numshown * $inner_bubble_lines;
 7361:                 } else {
 7362:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7363:                 } 
 7364: 
 7365:                 $first_bubble_line{$response_number} = $bubble_line;
 7366: 	        $bubble_lines_per_response{$response_number} = $lines;
 7367:                 $responsetype_per_response{$response_number} = 
 7368:                     $analysis->{$part_id.'.type'};
 7369: 	        $response_number++;
 7370: 
 7371: 	        $bubble_line +=  $lines;
 7372: 	        $total_lines +=  $lines;
 7373: 	    }
 7374:         }
 7375:     }
 7376:     &Apache::lonnet::delenv('scantron.');
 7377: 
 7378:     &save_bubble_lines();
 7379:     $env{'form.scantron_maxbubble'} =
 7380: 	$total_lines;
 7381:     return $env{'form.scantron_maxbubble'};
 7382: }
 7383: 
 7384: sub scantron_validate_missingbubbles {
 7385:     my ($r,$currentphase) = @_;
 7386:     #get student info
 7387:     my $classlist=&Apache::loncoursedata::get_classlist();
 7388:     my %idmap=&username_to_idmap($classlist);
 7389: 
 7390:     #get scantron line setup
 7391:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7392:     my ($scanlines,$scan_data)=&scantron_getfile();
 7393:     my $max_bubble=&scantron_get_maxbubble();
 7394:     if (!$max_bubble) { $max_bubble=2**31; }
 7395:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7396: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7397: 	if ($line=~/^[\s\cz]*$/) { next; }
 7398: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7399: 						 $scan_data);
 7400: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7401: 	my @to_correct;
 7402: 	
 7403: 	# Probably here's where the error is...
 7404: 
 7405: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7406:             my $lastbubble;
 7407:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7408:                my $question = $1;
 7409:                my $subquestion = $2;
 7410:                if (!defined($first_bubble_line{$question -1})) { next; }
 7411:                my $first = $first_bubble_line{$question-1};
 7412:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7413:                my $subcount = 1;
 7414:                while ($subcount<$subquestion) {
 7415:                    $first += $subans[$subcount-1];
 7416:                    $subcount ++;
 7417:                }
 7418:                my $count = $subans[$subquestion-1];
 7419:                $lastbubble = $first + $count;
 7420:             } else {
 7421:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7422:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7423:             }
 7424:             if ($lastbubble > $max_bubble) { next; }
 7425: 	    push(@to_correct,$missing);
 7426: 	}
 7427: 	if (@to_correct) {
 7428: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7429: 				     $line,'missingbubble',\@to_correct);
 7430: 	    return (1,$currentphase);
 7431: 	}
 7432: 
 7433:     }
 7434:     return (0,$currentphase+1);
 7435: }
 7436: 
 7437: 
 7438: sub scantron_process_students {
 7439:     my ($r) = @_;
 7440: 
 7441:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7442:     my ($symb)=&get_symb($r);
 7443:     if (!$symb) {
 7444: 	return '';
 7445:     }
 7446:     my $default_form_data=&defaultFormData($symb);
 7447: 
 7448:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7449:     my ($scanlines,$scan_data)=&scantron_getfile();
 7450:     my $classlist=&Apache::loncoursedata::get_classlist();
 7451:     my %idmap=&username_to_idmap($classlist);
 7452:     my $navmap=Apache::lonnavmaps::navmap->new();
 7453:     my $map=$navmap->getResourceByUrl($sequence);
 7454:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7455:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7456:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7457:                             \%grader_randomlists_by_symb);
 7458:     foreach my $resource (@resources) {
 7459:         my $ressymb = $resource->symb();
 7460:         my ($analysis,$parts) =
 7461:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7462:                                       $env{'user.name'},$env{'user.domain'},1);
 7463:         $grader_partids_by_symb{$ressymb} = $parts;
 7464:         if (ref($analysis) eq 'HASH') {
 7465:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7466:                 $grader_randomlists_by_symb{$ressymb} = 
 7467:                     $analysis->{'parts_withrandomlist'};
 7468:             }
 7469:         }
 7470:     }
 7471: 
 7472:     my ($uname,$udom);
 7473:     my $result= <<SCANTRONFORM;
 7474: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7475:   <input type="hidden" name="command" value="scantron_configphase" />
 7476:   $default_form_data
 7477: SCANTRONFORM
 7478:     $r->print($result);
 7479: 
 7480:     my @delayqueue;
 7481:     my (%completedstudents,%scandata);
 7482:     
 7483:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7484:     my $count=&get_todo_count($scanlines,$scan_data);
 7485:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7486:  				    'Bubblesheet Progress',$count,
 7487: 				    'inline',undef,'scantronupload');
 7488:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7489: 					  'Processing first student');
 7490:     $r->print('<br />');
 7491:     my $start=&Time::HiRes::time();
 7492:     my $i=-1;
 7493:     my $started;
 7494: 
 7495:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7496: 
 7497:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7498:     # the user and return.
 7499: 
 7500:     if ($ssi_error) {
 7501: 	$r->print("</form>");
 7502: 	&ssi_print_error($r);
 7503: 	$r->print(&show_grading_menu_form($symb));
 7504:         &Apache::lonnet::remove_lock($lock);
 7505: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7506:     }
 7507: 
 7508:     my %lettdig = &letter_to_digits();
 7509:     my $numletts = scalar(keys(%lettdig));
 7510: 
 7511:     while ($i<$scanlines->{'count'}) {
 7512:  	($uname,$udom)=('','');
 7513:  	$i++;
 7514:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7515:  	if ($line=~/^[\s\cz]*$/) { next; }
 7516: 	if ($started) {
 7517: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7518: 						     'last student');
 7519: 	}
 7520: 	$started=1;
 7521:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7522:  						 $scan_data);
 7523:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7524:  					      \%idmap,$i)) {
 7525:   	    &scantron_add_delay(\@delayqueue,$line,
 7526:  				'Unable to find a student that matches',1);
 7527:  	    next;
 7528:   	}
 7529:  	if (exists $completedstudents{$uname}) {
 7530:  	    &scantron_add_delay(\@delayqueue,$line,
 7531:  				'Student '.$uname.' has multiple sheets',2);
 7532:  	    next;
 7533:  	}
 7534:   	($uname,$udom)=split(/:/,$uname);
 7535: 
 7536:         my %partids_by_symb;
 7537:         foreach my $resource (@resources) {
 7538:             my $ressymb = $resource->symb();
 7539:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7540:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7541:                 my ($analysis,$parts) =
 7542:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7543:                 $partids_by_symb{$ressymb} = $parts;
 7544:             } else {
 7545:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7546:             }
 7547:         }
 7548: 
 7549: 	&Apache::lonxml::clear_problem_counter();
 7550:   	&Apache::lonnet::appenv($scan_record);
 7551: 
 7552: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7553: 	    &scantron_putfile($scanlines,$scan_data);
 7554: 	}
 7555: 	
 7556:         my $scancode;
 7557:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7558:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7559:             $scancode = $scan_record->{'scantron.CODE'};
 7560:         } else {
 7561:             $scancode = '';
 7562:         }
 7563: 
 7564:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7565:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7566:             $ssi_error = 0; # So end of handler error message does not trigger.
 7567:             $r->print("</form>");
 7568:             &ssi_print_error($r);
 7569:             $r->print(&show_grading_menu_form($symb));
 7570:             &Apache::lonnet::remove_lock($lock);
 7571:             return '';      # Why return ''?  Beats me.
 7572:         }
 7573: 
 7574: 	$completedstudents{$uname}={'line'=>$line};
 7575:         if ($env{'form.verifyrecord'}) {
 7576:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7577:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7578:             chomp($studentdata);
 7579:             $studentdata =~ s/\r$//;
 7580:             my $studentrecord = '';
 7581:             my $counter = -1;
 7582:             foreach my $resource (@resources) {
 7583:                 my $ressymb = $resource->symb();
 7584:                 ($counter,my $recording) =
 7585:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7586:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7587:                                              \%scantron_config,\%lettdig,$numletts);
 7588:                 $studentrecord .= $recording;
 7589:             }
 7590:             if ($studentrecord ne $studentdata) {
 7591:                 &Apache::lonxml::clear_problem_counter();
 7592:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7593:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7594:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7595:                     $r->print("</form>");
 7596:                     &ssi_print_error($r);
 7597:                     $r->print(&show_grading_menu_form($symb));
 7598:                     &Apache::lonnet::remove_lock($lock);
 7599:                     delete($completedstudents{$uname});
 7600:                     return '';
 7601:                 }
 7602:                 $counter = -1;
 7603:                 $studentrecord = '';
 7604:                 foreach my $resource (@resources) {
 7605:                     my $ressymb = $resource->symb();
 7606:                     ($counter,my $recording) =
 7607:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7608:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7609:                                                  \%scantron_config,\%lettdig,$numletts);
 7610:                     $studentrecord .= $recording;
 7611:                 }
 7612:                 if ($studentrecord ne $studentdata) {
 7613:                     $r->print('<p><span class="LC_error">');
 7614:                     if ($scancode eq '') {
 7615:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7616:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7617:                     } else {
 7618:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7619:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7620:                     }
 7621:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7622:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7623:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7624:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7625:                               &Apache::loncommon::start_data_table_row().
 7626:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7627:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7628:                               &Apache::loncommon::end_data_table_row().
 7629:                               &Apache::loncommon::start_data_table_row().
 7630:                               '<td>Stored submissions</td>'.
 7631:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7632:                               &Apache::loncommon::end_data_table_row().
 7633:                               &Apache::loncommon::end_data_table().'</p>');
 7634:                 } else {
 7635:                     $r->print('<br /><span class="LC_warning">'.
 7636:                              &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 />'.
 7637:                              &mt("As a consequence, this user's submission history records two tries.").
 7638:                                  '</span><br />');
 7639:                 }
 7640:             }
 7641:         }
 7642:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7643:     } continue {
 7644: 	&Apache::lonxml::clear_problem_counter();
 7645: 	&Apache::lonnet::delenv('scantron.');
 7646:     }
 7647:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7648:     &Apache::lonnet::remove_lock($lock);
 7649: #    my $lasttime = &Time::HiRes::time()-$start;
 7650: #    $r->print("<p>took $lasttime</p>");
 7651: 
 7652:     $r->print("</form>");
 7653:     $r->print(&show_grading_menu_form($symb));
 7654:     return '';
 7655: }
 7656: 
 7657: sub graders_resources_pass {
 7658:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7659:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7660:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7661:         foreach my $resource (@{$resources}) {
 7662:             my $ressymb = $resource->symb();
 7663:             my ($analysis,$parts) =
 7664:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7665:                                           $env{'user.name'},$env{'user.domain'},1);
 7666:             $grader_partids_by_symb->{$ressymb} = $parts;
 7667:             if (ref($analysis) eq 'HASH') {
 7668:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7669:                     $grader_randomlists_by_symb->{$ressymb} =
 7670:                         $analysis->{'parts_withrandomlist'};
 7671:                 }
 7672:             }
 7673:         }
 7674:     }
 7675:     return;
 7676: }
 7677: 
 7678: sub grade_student_bubbles {
 7679:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7680:     if (ref($resources) eq 'ARRAY') {
 7681:         my $count = 0;
 7682:         foreach my $resource (@{$resources}) {
 7683:             my $ressymb = $resource->symb();
 7684:             my %form = ('submitted'      => 'scantron',
 7685:                         'grade_target'   => 'grade',
 7686:                         'grade_username' => $uname,
 7687:                         'grade_domain'   => $udom,
 7688:                         'grade_courseid' => $env{'request.course.id'},
 7689:                         'grade_symb'     => $ressymb,
 7690:                         'CODE'           => $scancode
 7691:                        );
 7692:             if (ref($parts) eq 'HASH') {
 7693:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7694:                     foreach my $part (@{$parts->{$ressymb}}) {
 7695:                         $form{'scantron_questnum_start.'.$part} =
 7696:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7697:                         $count++;
 7698:                     }
 7699:                 }
 7700:             }
 7701:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7702:             return 'ssi_error' if ($ssi_error);
 7703:             last if (&Apache::loncommon::connection_aborted($r));
 7704:         }
 7705:     }
 7706:     return;
 7707: }
 7708: 
 7709: sub scantron_upload_scantron_data {
 7710:     my ($r)=@_;
 7711:     my $dom = $env{'request.role.domain'};
 7712:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7713:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7714:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7715: 							  'domainid',
 7716: 							  'coursename',$dom);
 7717:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7718:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7719:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7720:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7721:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
 7722:     $r->print('
 7723: <script type="text/javascript" language="javascript">
 7724:     function checkUpload(formname) {
 7725: 	if (formname.upfile.value == "") {
 7726: 	    alert("'.$nofile_alert.'");
 7727: 	    return false;
 7728: 	}
 7729:         if (formname.courseid.value == "") {
 7730:             alert("'.$nocourseid_alert.'");
 7731:             return false;
 7732:         }
 7733: 	formname.submit();
 7734:     }
 7735: 
 7736:     function ToSyllabus() {
 7737:         var cdom = '."'$dom'".';
 7738:         var cnum = document.rules.courseid.value;
 7739:         if (cdom == "" || cdom == null) {
 7740:             return;
 7741:         }
 7742:         if (cnum == "" || cnum == null) {
 7743:            return;
 7744:         }
 7745:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7746:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7747:         return;
 7748:     }
 7749: 
 7750: </script>
 7751: 
 7752: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7753: 
 7754: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7755: '.$default_form_data.
 7756:   &Apache::lonhtmlcommon::start_pick_box().
 7757:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7758:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7759:   &Apache::lonhtmlcommon::row_closure().
 7760:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7761:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7762:   &Apache::lonhtmlcommon::row_closure().
 7763:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7764:   '<input name="domainid" type="hidden" />'.$domdesc.
 7765:   &Apache::lonhtmlcommon::row_closure().
 7766:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7767:   '<input type="file" name="upfile" size="50" />'.
 7768:   &Apache::lonhtmlcommon::row_closure(1).
 7769:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7770: 
 7771: <input name="command" value="scantronupload_save" type="hidden" />
 7772: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7773: </form>
 7774: ');
 7775:     return '';
 7776: }
 7777: 
 7778: 
 7779: sub scantron_upload_scantron_data_save {
 7780:     my($r)=@_;
 7781:     my ($symb)=&get_symb($r,1);
 7782:     my $doanotherupload=
 7783: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7784: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7785: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7786: 	'</form>'."\n";
 7787:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7788: 	!&Apache::lonnet::allowed('usc',
 7789: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7790: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7791: 	if ($symb) {
 7792: 	    $r->print(&show_grading_menu_form($symb));
 7793: 	} else {
 7794: 	    $r->print($doanotherupload);
 7795: 	}
 7796: 	return '';
 7797:     }
 7798:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7799:     my $uploadedfile;
 7800:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7801:     if (length($env{'form.upfile'}) < 2) {
 7802:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7803:     } else {
 7804:         my $result = 
 7805:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7806:                                             $env{'form.courseid'},$env{'form.domainid'});
 7807: 	if ($result =~ m{^/uploaded/}) {
 7808: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7809:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7810: 			  '<span class="LC_filename">'.$result.'</span>'));
 7811:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7812:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7813:                                                        $env{'form.courseid'},$uploadedfile));
 7814: 	} else {
 7815: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7816:                           '<span class="LC_error">','</span>',$result,
 7817: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7818: 	}
 7819:     }
 7820:     if ($symb) {
 7821: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7822:     } else {
 7823: 	$r->print($doanotherupload);
 7824:     }
 7825:     return '';
 7826: }
 7827: 
 7828: sub validate_uploaded_scantron_file {
 7829:     my ($cdom,$cname,$fname) = @_;
 7830:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7831:     my @lines;
 7832:     if ($scanlines ne '-1') {
 7833:         @lines=split("\n",$scanlines,-1);
 7834:     }
 7835:     my $output;
 7836:     if (@lines) {
 7837:         my (%counts,$max_match_format);
 7838:         my ($max_match_count,$max_match_pct) = (0,0);
 7839:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7840:         my %idmap = &username_to_idmap($classlist);
 7841:         foreach my $key (keys(%idmap)) {
 7842:             my $lckey = lc($key);
 7843:             $idmap{$lckey} = $idmap{$key};
 7844:         }
 7845:         my %unique_formats;
 7846:         my @formatlines = &get_scantronformat_file();
 7847:         foreach my $line (@formatlines) {
 7848:             chomp($line);
 7849:             my @config = split(/:/,$line);
 7850:             my $idstart = $config[5];
 7851:             my $idlength = $config[6];
 7852:             if (($idstart ne '') && ($idlength > 0)) {
 7853:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7854:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7855:                 } else {
 7856:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7857:                 }
 7858:             }
 7859:         }
 7860:         foreach my $key (keys(%unique_formats)) {
 7861:             my ($idstart,$idlength) = split(':',$key);
 7862:             %{$counts{$key}} = (
 7863:                                'found'   => 0,
 7864:                                'total'   => 0,
 7865:                               );
 7866:             foreach my $line (@lines) {
 7867:                 next if ($line =~ /^#/);
 7868:                 next if ($line =~ /^[\s\cz]*$/);
 7869:                 my $id = substr($line,$idstart-1,$idlength);
 7870:                 $id = lc($id);
 7871:                 if (exists($idmap{$id})) {
 7872:                     $counts{$key}{'found'} ++;
 7873:                 }
 7874:                 $counts{$key}{'total'} ++;
 7875:             }
 7876:             if ($counts{$key}{'total'}) {
 7877:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 7878:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 7879:                     $max_match_pct = $percent_match;
 7880:                     $max_match_format = $key;
 7881:                     $max_match_count = $counts{$key}{'total'};
 7882:                 }
 7883:             }
 7884:         }
 7885:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 7886:             my $format_descs;
 7887:             my $numwithformat = @{$unique_formats{$max_match_format}};
 7888:             for (my $i=0; $i<$numwithformat; $i++) {
 7889:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 7890:                 if ($i<$numwithformat-2) {
 7891:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 7892:                 } elsif ($i==$numwithformat-2) {
 7893:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 7894:                 } elsif ($i==$numwithformat-1) {
 7895:                     $format_descs .= '"<i>'.$desc.'</i>"';
 7896:                 }
 7897:             }
 7898:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 7899:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 7900:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 7901:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 7902:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 7903:                                   '<i>'.$cdom.'</i>').'</li>'.
 7904:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 7905:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 7906:                        '</ul>';
 7907:         }
 7908:     } else {
 7909:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 7910:     }
 7911:     return $output;
 7912: }
 7913: 
 7914: sub valid_file {
 7915:     my ($requested_file)=@_;
 7916:     foreach my $filename (sort(&scantron_filenames())) {
 7917: 	if ($requested_file eq $filename) { return 1; }
 7918:     }
 7919:     return 0;
 7920: }
 7921: 
 7922: sub scantron_download_scantron_data {
 7923:     my ($r)=@_;
 7924:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7925:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7926:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7927:     my $file=$env{'form.scantron_selectfile'};
 7928:     if (! &valid_file($file)) {
 7929: 	$r->print('
 7930: 	<p>
 7931: 	    '.&mt('The requested file name was invalid.').'
 7932:         </p>
 7933: ');
 7934: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7935: 	return;
 7936:     }
 7937:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7938:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7939:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7940:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7941:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7942:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7943:     $r->print('
 7944:     <p>
 7945: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7946: 	      '<a href="'.$orig.'">','</a>').'
 7947:     </p>
 7948:     <p>
 7949: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7950: 	      '<a href="'.$corrected.'">','</a>').'
 7951:     </p>
 7952:     <p>
 7953: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7954: 	      '<a href="'.$skipped.'">','</a>').'
 7955:     </p>
 7956: ');
 7957:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7958:     return '';
 7959: }
 7960: 
 7961: sub checkscantron_results {
 7962:     my ($r) = @_;
 7963:     my ($symb)=&get_symb($r);
 7964:     if (!$symb) {return '';}
 7965:     my $grading_menu_button=&show_grading_menu_form($symb);
 7966:     my $cid = $env{'request.course.id'};
 7967:     my %lettdig = &letter_to_digits();
 7968:     my $numletts = scalar(keys(%lettdig));
 7969:     my $cnum = $env{'course.'.$cid.'.num'};
 7970:     my $cdom = $env{'course.'.$cid.'.domain'};
 7971:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7972:     my %record;
 7973:     my %scantron_config =
 7974:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7975:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7976:     my $classlist=&Apache::loncoursedata::get_classlist();
 7977:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7978:     my $navmap=Apache::lonnavmaps::navmap->new();
 7979:     my $map=$navmap->getResourceByUrl($sequence);
 7980:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7981:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7982:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 7983: 
 7984:     my ($uname,$udom);
 7985:     my (%scandata,%lastname,%bylast);
 7986:     $r->print('
 7987: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7988: 
 7989:     my @delayqueue;
 7990:     my %completedstudents;
 7991: 
 7992:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7993:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 7994:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 7995:                                     'inline',undef,'checkscantron');
 7996:     my ($username,$domain,$started);
 7997: 
 7998:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7999: 
 8000:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8001:                                           'Processing first student');
 8002:     my $start=&Time::HiRes::time();
 8003:     my $i=-1;
 8004: 
 8005:     while ($i<$scanlines->{'count'}) {
 8006:         ($username,$domain,$uname)=('','','');
 8007:         $i++;
 8008:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8009:         if ($line=~/^[\s\cz]*$/) { next; }
 8010:         if ($started) {
 8011:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8012:                                                      'last student');
 8013:         }
 8014:         $started=1;
 8015:         my $scan_record=
 8016:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8017:                                                      $scan_data);
 8018:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8019:                                                               \%idmap,$i)) {
 8020:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8021:                                 'Unable to find a student that matches',1);
 8022:             next;
 8023:         }
 8024:         if (exists $completedstudents{$uname}) {
 8025:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8026:                                 'Student '.$uname.' has multiple sheets',2);
 8027:             next;
 8028:         }
 8029:         my $pid = $scan_record->{'scantron.ID'};
 8030:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8031:         push(@{$bylast{$lastname{$pid}}},$pid);
 8032:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8033:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8034:         chomp($scandata{$pid});
 8035:         $scandata{$pid} =~ s/\r$//;
 8036:         ($username,$domain)=split(/:/,$uname);
 8037:         my $counter = -1;
 8038:         foreach my $resource (@resources) {
 8039:             my $parts;
 8040:             my $ressymb = $resource->symb();
 8041:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8042:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8043:                 (my $analysis,$parts) =
 8044:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8045:             } else {
 8046:                 $parts = $grader_partids_by_symb{$ressymb};
 8047:             }
 8048:             ($counter,my $recording) =
 8049:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8050:                                          $scandata{$pid},$parts,
 8051:                                          \%scantron_config,\%lettdig,$numletts);
 8052:             $record{$pid} .= $recording;
 8053:         }
 8054:     }
 8055:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8056:     $r->print('<br />');
 8057:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8058:     $passed = 0;
 8059:     $failed = 0;
 8060:     $numstudents = 0;
 8061:     foreach my $last (sort(keys(%bylast))) {
 8062:         if (ref($bylast{$last}) eq 'ARRAY') {
 8063:             foreach my $pid (sort(@{$bylast{$last}})) {
 8064:                 my $showscandata = $scandata{$pid};
 8065:                 my $showrecord = $record{$pid};
 8066:                 $showscandata =~ s/\s/&nbsp;/g;
 8067:                 $showrecord =~ s/\s/&nbsp;/g;
 8068:                 if ($scandata{$pid} eq $record{$pid}) {
 8069:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8070:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8071: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8072: '</tr>'."\n".
 8073: '<tr class="'.$css_class.'">'."\n".
 8074: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8075:                     $passed ++;
 8076:                 } else {
 8077:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8078:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8079: '</tr>'."\n".
 8080: '<tr class="'.$css_class.'">'."\n".
 8081: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8082: '</tr>'."\n";
 8083:                     $failed ++;
 8084:                 }
 8085:                 $numstudents ++;
 8086:             }
 8087:         }
 8088:     }
 8089:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 8090:     $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>');
 8091:     if ($passed) {
 8092:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8093:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8094:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8095:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8096:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8097:                  $okstudents."\n".
 8098:                  &Apache::loncommon::end_data_table().'<br />');
 8099:     }
 8100:     if ($failed) {
 8101:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8102:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8103:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8104:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8105:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8106:                  $badstudents."\n".
 8107:                  &Apache::loncommon::end_data_table()).'<br />'.
 8108:                  &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');  
 8109:     }
 8110:     $r->print('</form><br />'.$grading_menu_button);
 8111:     return;
 8112: }
 8113: 
 8114: sub verify_scantron_grading {
 8115:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8116:         $scantron_config,$lettdig,$numletts) = @_;
 8117:     my ($record,%expected,%startpos);
 8118:     return ($counter,$record) if (!ref($resource));
 8119:     return ($counter,$record) if (!$resource->is_problem());
 8120:     my $symb = $resource->symb();
 8121:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8122:     foreach my $part_id (@{$partids}) {
 8123:         $counter ++;
 8124:         $expected{$part_id} = 0;
 8125:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8126:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8127:             foreach my $item (@sub_lines) {
 8128:                 $expected{$part_id} += $item;
 8129:             }
 8130:         } else {
 8131:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8132:         }
 8133:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8134:     }
 8135:     if ($symb) {
 8136:         my %recorded;
 8137:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8138:         if ($returnhash{'version'}) {
 8139:             my %lasthash=();
 8140:             my $version;
 8141:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8142:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8143:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8144:                 }
 8145:             }
 8146:             foreach my $key (keys(%lasthash)) {
 8147:                 if ($key =~ /\.scantron$/) {
 8148:                     my $value = &unescape($lasthash{$key});
 8149:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8150:                     if ($value eq '') {
 8151:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8152:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8153:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8154:                             }
 8155:                         }
 8156:                     } else {
 8157:                         my @tocheck;
 8158:                         my @items = split(//,$value);
 8159:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8160:                             ($scantron_config->{'Qon'} eq 'number')) {
 8161:                             if (@items < $expected{$part_id}) {
 8162:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8163:                                 my @singles = split(//,$fragment);
 8164:                                 foreach my $pos (@singles) {
 8165:                                     if ($pos eq ' ') {
 8166:                                         push(@tocheck,$pos);
 8167:                                     } else {
 8168:                                         my $next = shift(@items);
 8169:                                         push(@tocheck,$next);
 8170:                                     }
 8171:                                 }
 8172:                             } else {
 8173:                                 @tocheck = @items;
 8174:                             }
 8175:                             foreach my $letter (@tocheck) {
 8176:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8177:                                     if ($letter !~ /^[A-J]$/) {
 8178:                                         $letter = $scantron_config->{'Qoff'};
 8179:                                     }
 8180:                                     $recorded{$part_id} .= $letter;
 8181:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8182:                                     my $digit;
 8183:                                     if ($letter !~ /^[A-J]$/) {
 8184:                                         $digit = $scantron_config->{'Qoff'};
 8185:                                     } else {
 8186:                                         $digit = $lettdig->{$letter};
 8187:                                     }
 8188:                                     $recorded{$part_id} .= $digit;
 8189:                                 }
 8190:                             }
 8191:                         } else {
 8192:                             @tocheck = @items;
 8193:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8194:                                 my $curr_sub = shift(@tocheck);
 8195:                                 my $digit;
 8196:                                 if ($curr_sub =~ /^[A-J]$/) {
 8197:                                     $digit = $lettdig->{$curr_sub}-1;
 8198:                                 }
 8199:                                 if ($curr_sub eq 'J') {
 8200:                                     $digit += scalar($numletts);
 8201:                                 }
 8202:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8203:                                     if ($j == $digit) {
 8204:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8205:                                     } else {
 8206:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8207:                                     }
 8208:                                 }
 8209:                             }
 8210:                         }
 8211:                     }
 8212:                 }
 8213:             }
 8214:         }
 8215:         foreach my $part_id (@{$partids}) {
 8216:             if ($recorded{$part_id} eq '') {
 8217:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8218:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8219:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8220:                     }
 8221:                 }
 8222:             }
 8223:             $record .= $recorded{$part_id};
 8224:         }
 8225:     }
 8226:     return ($counter,$record);
 8227: }
 8228: 
 8229: sub letter_to_digits { 
 8230:     my %lettdig = (
 8231:                     A => 1,
 8232:                     B => 2,
 8233:                     C => 3,
 8234:                     D => 4,
 8235:                     E => 5,
 8236:                     F => 6,
 8237:                     G => 7,
 8238:                     H => 8,
 8239:                     I => 9,
 8240:                     J => 0,
 8241:                   );
 8242:     return %lettdig;
 8243: }
 8244: 
 8245: 
 8246: #-------- end of section for handling grading scantron forms -------
 8247: #
 8248: #-------------------------------------------------------------------
 8249: 
 8250: #-------------------------- Menu interface -------------------------
 8251: #
 8252: #--- Show a Grading Menu button - Calls the next routine ---
 8253: sub show_grading_menu_form {
 8254:     my ($symb)=@_;
 8255:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8256: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8257: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8258: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8259: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8260: 	'</form>'."\n";
 8261:     return $result;
 8262: }
 8263: 
 8264: # -- Retrieve choices for grading form
 8265: sub savedState {
 8266:     my %savedState = ();
 8267:     if ($env{'form.saveState'}) {
 8268: 	foreach (split(/:/,$env{'form.saveState'})) {
 8269: 	    my ($key,$value) = split(/=/,$_,2);
 8270: 	    $savedState{$key} = $value;
 8271: 	}
 8272:     }
 8273:     return \%savedState;
 8274: }
 8275: 
 8276: sub grading_menu {
 8277:     my ($request) = @_;
 8278:     my ($symb)=&get_symb($request);
 8279:     if (!$symb) {return '';}
 8280:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8281:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8282: 
 8283:     $request->print($table);
 8284:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8285:                   'handgrade'=>$hdgrade,
 8286:                   'probTitle'=>$probTitle,
 8287:                   'command'=>'submit_options',
 8288:                   'saveState'=>"",
 8289:                   'gradingMenu'=>1,
 8290:                   'showgrading'=>"yes");
 8291:     
 8292:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8293:     
 8294:     $fields{'command'} = 'csvform';
 8295:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8296:     
 8297:     $fields{'command'} = 'processclicker';
 8298:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8299:     
 8300:     $fields{'command'} = 'scantron_selectphase';
 8301:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8302:     
 8303:     my @menu = ({	categorytitle=>'Course Grading',
 8304:             items =>[
 8305:                         {	linktext => 'Manual Grading/View Submissions',
 8306:                     		url => $url1,
 8307:                     		permission => 'F',
 8308:                     		icon => 'edit-find-replace.png',
 8309:                     		linktitle => 'Start the process of hand grading submissions.'
 8310:                         },
 8311:                 	    {	linktext => 'Upload Scores',
 8312:                     		url => $url2,
 8313:                     		permission => 'F',
 8314:                     		icon => 'uploadscores.png',
 8315:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8316:                 	    },
 8317:                 	    {	linktext => 'Process Clicker',
 8318:                     		url => $url3,
 8319:                     		permission => 'F',
 8320:                     		icon => 'addClickerInfoFile.png',
 8321:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8322:                 	    },
 8323:                 	    {	linktext => 'Grade/Manage/Review Bubblesheet Forms',
 8324:                     		url => $url4,
 8325:                     		permission => 'F',
 8326:                     		icon => 'stat.png',
 8327:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8328:                 	    }
 8329:                     ]
 8330:             });
 8331: 
 8332:     #$fields{'command'} = 'verify';
 8333:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8334:     #
 8335:     # Create the menu
 8336:     my $Str;
 8337:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8338:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8339:     $Str .= '<input type="hidden" name="command" value="" />'.
 8340:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8341: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8342: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8343: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8344: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8345: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8346: 
 8347:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8348:     #$menudata->{'jscript'}
 8349:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8350:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8351:         ' /> '.
 8352:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8353:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8354: 
 8355:     $Str .="</form>\n";
 8356:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8357:     $request->print(<<GRADINGMENUJS);
 8358: <script type="text/javascript" language="javascript">
 8359:     function checkChoice(formname,val,cmdx) {
 8360: 	if (val <= 2) {
 8361: 	    var cmd = radioSelection(formname.radioChoice);
 8362: 	    var cmdsave = cmd;
 8363: 	} else {
 8364: 	    cmd = cmdx;
 8365: 	    cmdsave = 'submission';
 8366: 	}
 8367: 	formname.command.value = cmd;
 8368: 	if (val < 5) formname.submit();
 8369: 	if (val == 5) {
 8370: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8371: 	        return false;
 8372: 	    } else {
 8373: 	        formname.submit();
 8374: 	    }
 8375: 	}
 8376:     }
 8377: 
 8378:     function checkReceiptNo(formname,nospace) {
 8379: 	var receiptNo = formname.receipt.value;
 8380: 	var checkOpt = false;
 8381: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8382: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8383: 	if (checkOpt) {
 8384: 	    alert("$receiptalert");
 8385: 	    formname.receipt.value = "";
 8386: 	    formname.receipt.focus();
 8387: 	    return false;
 8388: 	}
 8389: 	return true;
 8390:     }
 8391: </script>
 8392: GRADINGMENUJS
 8393:     &commonJSfunctions($request);
 8394:     return $Str;    
 8395: }
 8396: 
 8397: 
 8398: #--- Displays the submissions first page -------
 8399: sub submit_options {
 8400:     my ($request) = @_;
 8401:     my ($symb)=&get_symb($request);
 8402:     if (!$symb) {return '';}
 8403:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8404: 
 8405:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8406:     $request->print(<<GRADINGMENUJS);
 8407: <script type="text/javascript" language="javascript">
 8408:     function checkChoice(formname,val,cmdx) {
 8409: 	if (val <= 2) {
 8410: 	    var cmd = radioSelection(formname.radioChoice);
 8411: 	    var cmdsave = cmd;
 8412: 	} else {
 8413: 	    cmd = cmdx;
 8414: 	    cmdsave = 'submission';
 8415: 	}
 8416: 	formname.command.value = cmd;
 8417: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8418: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8419: 	if (val < 5) formname.submit();
 8420: 	if (val == 5) {
 8421: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8422: 	    formname.submit();
 8423: 	}
 8424: 	if (val < 7) formname.submit();
 8425:     }
 8426: 
 8427:     function checkReceiptNo(formname,nospace) {
 8428: 	var receiptNo = formname.receipt.value;
 8429: 	var checkOpt = false;
 8430: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8431: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8432: 	if (checkOpt) {
 8433: 	    alert("$receiptalert");
 8434: 	    formname.receipt.value = "";
 8435: 	    formname.receipt.focus();
 8436: 	    return false;
 8437: 	}
 8438: 	return true;
 8439:     }
 8440: </script>
 8441: GRADINGMENUJS
 8442:     &commonJSfunctions($request);
 8443:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8444:     my $result;
 8445:     my (undef,$sections) = &getclasslist('all','0');
 8446:     my $savedState = &savedState();
 8447:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8448:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8449:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8450:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8451: 
 8452:     # Preselect sections
 8453:     my $selsec="";
 8454:     if (ref($sections)) {
 8455:         foreach my $section (sort(@$sections)) {
 8456:             $selsec.='<option value="'.$section.'" '.
 8457:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8458:         }
 8459:     }
 8460: 
 8461:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8462: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8463: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8464: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8465: 	'<input type="hidden" name="command"     value="" />'."\n".
 8466: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8467: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8468: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8469: 
 8470:     $result.='
 8471: <h2>
 8472:   '.&mt('Grade Current Resource').'
 8473: </h2>
 8474: <div>
 8475:   '.$table.'
 8476: </div>
 8477: 
 8478: <div class="LC_columnSection">
 8479:   
 8480:     <fieldset>
 8481:       <legend>
 8482:        '.&mt('Sections').'
 8483:       </legend>
 8484:       <select name="section" multiple="multiple" size="5">'."\n";
 8485:     $result.= $selsec;
 8486:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8487:     $result.='
 8488:     </fieldset>
 8489:   
 8490:     <fieldset>
 8491:       <legend>
 8492:         '.&mt('Groups').'
 8493:       </legend>
 8494:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8495:     </fieldset>
 8496:   
 8497:     <fieldset>
 8498:       <legend>
 8499:         '.&mt('Access Status').'
 8500:       </legend>
 8501:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8502:     </fieldset>
 8503:   
 8504:     <fieldset>
 8505:       <legend>
 8506:         '.&mt('Submission Status').'
 8507:       </legend>
 8508:       <select name="submitonly" size="5">
 8509: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8510: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8511: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8512: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8513:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8514:       </select>
 8515:     </fieldset>
 8516:   
 8517: </div>
 8518: 
 8519: <br />
 8520:           <div>
 8521:             <div>
 8522:               <label>
 8523:                 <input type="radio" name="radioChoice" value="submission" '.
 8524:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8525:              &mt('Select individual students to grade and view submissions.').'
 8526: 	      </label> 
 8527:             </div>
 8528:             <div>
 8529: 	      <label>
 8530:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8531:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8532:                     &mt('Grade all selected students in a grading table.').'
 8533:               </label>
 8534:             </div>
 8535:             <div>
 8536: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8537:             </div>
 8538:           </div>
 8539: 
 8540: 
 8541:         <h2>
 8542:          '.&mt('Grade Complete Folder for One Student').'
 8543:         </h2>
 8544:         <div>
 8545:             <div>
 8546:               <label>
 8547:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8548: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8549:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8550:               </label>
 8551:             </div>
 8552:             <div>
 8553: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8554:             </div>
 8555:         </div>
 8556:   </form>';
 8557:     $result .= &show_grading_menu_form($symb);
 8558:     return $result;
 8559: }
 8560: 
 8561: sub reset_perm {
 8562:     undef(%perm);
 8563: }
 8564: 
 8565: sub init_perm {
 8566:     &reset_perm();
 8567:     foreach my $test_perm ('vgr','mgr','opa') {
 8568: 
 8569: 	my $scope = $env{'request.course.id'};
 8570: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8571: 
 8572: 	    $scope .= '/'.$env{'request.course.sec'};
 8573: 	    if ( $perm{$test_perm}=
 8574: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8575: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8576: 	    } else {
 8577: 		delete($perm{$test_perm});
 8578: 	    }
 8579: 	}
 8580:     }
 8581: }
 8582: 
 8583: sub gather_clicker_ids {
 8584:     my %clicker_ids;
 8585: 
 8586:     my $classlist = &Apache::loncoursedata::get_classlist();
 8587: 
 8588:     # Set up a couple variables.
 8589:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8590:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8591:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8592: 
 8593:     foreach my $student (keys(%$classlist)) {
 8594:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8595:         my $username = $classlist->{$student}->[$username_idx];
 8596:         my $domain   = $classlist->{$student}->[$domain_idx];
 8597:         my $clickers =
 8598: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8599:         foreach my $id (split(/\,/,$clickers)) {
 8600:             $id=~s/^[\#0]+//;
 8601:             $id=~s/[\-\:]//g;
 8602:             if (exists($clicker_ids{$id})) {
 8603: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8604:             } else {
 8605: 		$clicker_ids{$id}=$username.':'.$domain;
 8606:             }
 8607:         }
 8608:     }
 8609:     return %clicker_ids;
 8610: }
 8611: 
 8612: sub gather_adv_clicker_ids {
 8613:     my %clicker_ids;
 8614:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8615:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8616:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8617:     foreach my $element (sort(keys(%coursepersonnel))) {
 8618:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8619:             my ($puname,$pudom)=split(/\:/,$person);
 8620:             my $clickers =
 8621: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8622:             foreach my $id (split(/\,/,$clickers)) {
 8623: 		$id=~s/^[\#0]+//;
 8624:                 $id=~s/[\-\:]//g;
 8625: 		if (exists($clicker_ids{$id})) {
 8626: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8627: 		} else {
 8628: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8629: 		}
 8630:             }
 8631:         }
 8632:     }
 8633:     return %clicker_ids;
 8634: }
 8635: 
 8636: sub clicker_grading_parameters {
 8637:     return ('gradingmechanism' => 'scalar',
 8638:             'upfiletype' => 'scalar',
 8639:             'specificid' => 'scalar',
 8640:             'pcorrect' => 'scalar',
 8641:             'pincorrect' => 'scalar');
 8642: }
 8643: 
 8644: sub process_clicker {
 8645:     my ($r)=@_;
 8646:     my ($symb)=&get_symb($r);
 8647:     if (!$symb) {return '';}
 8648:     my $result=&checkforfile_js();
 8649:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8650:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8651:     $result.=$table;
 8652:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8653:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8654:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8655:         '</b></td></tr>'."\n";
 8656:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8657: # Attempt to restore parameters from last session, set defaults if not present
 8658:     my %Saveable_Parameters=&clicker_grading_parameters();
 8659:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8660:                                                  \%Saveable_Parameters);
 8661:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8662:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8663:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8664:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8665: 
 8666:     my %checked;
 8667:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8668:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8669:           $checked{$gradingmechanism}=' checked="checked"';
 8670:        }
 8671:     }
 8672: 
 8673:     my $upload=&mt("Upload File");
 8674:     my $type=&mt("Type");
 8675:     my $attendance=&mt("Award points just for participation");
 8676:     my $personnel=&mt("Correctness determined from response by course personnel");
 8677:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8678:     my $given=&mt("Correctness determined from given list of answers").' '.
 8679:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8680:     my $pcorrect=&mt("Percentage points for correct solution");
 8681:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8682:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8683: 						   ('iclicker' => 'i>clicker',
 8684:                                                     'interwrite' => 'interwrite PRS'));
 8685:     $symb = &Apache::lonenc::check_encrypt($symb);
 8686:     $result.=<<ENDUPFORM;
 8687: <script type="text/javascript">
 8688: function sanitycheck() {
 8689: // Accept only integer percentages
 8690:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8691:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8692: // Find out grading choice
 8693:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8694:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8695:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8696:       }
 8697:    }
 8698: // By default, new choice equals user selection
 8699:    newgradingchoice=gradingchoice;
 8700: // Not good to give more points for false answers than correct ones
 8701:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8702:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8703:    }
 8704: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8705:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8706:       document.forms.gradesupload.pcorrect.value=100;
 8707:       document.forms.gradesupload.pincorrect.value=100;
 8708:    }
 8709: // If the values are different, cannot be attendance only
 8710:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8711:        (gradingchoice=='attendance')) {
 8712:        newgradingchoice='personnel';
 8713:    }
 8714: // Change grading choice to new one
 8715:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8716:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8717:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8718:       } else {
 8719:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8720:       }
 8721:    }
 8722: // Remember the old state
 8723:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8724: }
 8725: </script>
 8726: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8727: <input type="hidden" name="symb" value="$symb" />
 8728: <input type="hidden" name="command" value="processclickerfile" />
 8729: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8730: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8731: <input type="file" name="upfile" size="50" />
 8732: <br /><label>$type: $selectform</label>
 8733: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8734: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8735: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8736: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8737: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
 8738: <br />&nbsp;&nbsp;&nbsp;
 8739: <input type="text" name="givenanswer" size="50" />
 8740: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8741: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8742: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8743: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8744: </form>
 8745: ENDUPFORM
 8746:     $result.='</td></tr></table>'."\n".
 8747:              '</td></tr></table><br /><br />'."\n";
 8748:     $result.=&show_grading_menu_form($symb);
 8749:     return $result;
 8750: }
 8751: 
 8752: sub process_clicker_file {
 8753:     my ($r)=@_;
 8754:     my ($symb)=&get_symb($r);
 8755:     if (!$symb) {return '';}
 8756: 
 8757:     my %Saveable_Parameters=&clicker_grading_parameters();
 8758:     &Apache::loncommon::store_course_settings('grades_clicker',
 8759:                                               \%Saveable_Parameters);
 8760: 
 8761:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8762:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8763: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8764: 	return $result.&show_grading_menu_form($symb);
 8765:     }
 8766:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8767:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8768:         return $result.&show_grading_menu_form($symb);
 8769:     }
 8770:     my $foundgiven=0;
 8771:     if ($env{'form.gradingmechanism'} eq 'given') {
 8772:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8773:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8774:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8775:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8776:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8777:         $foundgiven=$#answers+1;
 8778:     }
 8779:     my %clicker_ids=&gather_clicker_ids();
 8780:     my %correct_ids;
 8781:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8782: 	%correct_ids=&gather_adv_clicker_ids();
 8783:     }
 8784:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8785: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8786: 	   $correct_id=~tr/a-z/A-Z/;
 8787: 	   $correct_id=~s/\s//gs;
 8788: 	   $correct_id=~s/^[\#0]+//;
 8789:            $correct_id=~s/[\-\:]//g;
 8790:            if ($correct_id) {
 8791: 	      $correct_ids{$correct_id}='specified';
 8792:            }
 8793:         }
 8794:     }
 8795:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8796: 	$result.=&mt('Score based on attendance only');
 8797:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8798:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8799:     } else {
 8800: 	my $number=0;
 8801: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8802: 	foreach my $id (sort(keys(%correct_ids))) {
 8803: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8804: 	    if ($correct_ids{$id} eq 'specified') {
 8805: 		$result.=&mt('specified');
 8806: 	    } else {
 8807: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8808: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8809: 	    }
 8810: 	    $number++;
 8811: 	}
 8812:         $result.="</p>\n";
 8813: 	if ($number==0) {
 8814: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8815: 	    return $result.&show_grading_menu_form($symb);
 8816: 	}
 8817:     }
 8818:     if (length($env{'form.upfile'}) < 2) {
 8819:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8820: 		     '<span class="LC_error">',
 8821: 		     '</span>',
 8822: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8823:         return $result.&show_grading_menu_form($symb);
 8824:     }
 8825: 
 8826: # Were able to get all the info needed, now analyze the file
 8827: 
 8828:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8829:     $symb = &Apache::lonenc::check_encrypt($symb);
 8830:     my $heading=&mt('Scanning clicker file');
 8831:     $result.=(<<ENDHEADER);
 8832: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8833: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8834: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8835: <form method="post" action="/adm/grades" name="clickeranalysis">
 8836: <input type="hidden" name="symb" value="$symb" />
 8837: <input type="hidden" name="command" value="assignclickergrades" />
 8838: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8839: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8840: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8841: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8842: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8843: ENDHEADER
 8844:     if ($env{'form.gradingmechanism'} eq 'given') {
 8845:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8846:     } 
 8847:     my %responses;
 8848:     my @questiontitles;
 8849:     my $errormsg='';
 8850:     my $number=0;
 8851:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8852: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8853:     }
 8854:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8855:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8856:     }
 8857:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8858:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8859:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8860:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8861:              '<br />';
 8862:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8863:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8864:        return $result.&show_grading_menu_form($symb);
 8865:     } 
 8866: # Remember Question Titles
 8867: # FIXME: Possibly need delimiter other than ":"
 8868:     for (my $i=0;$i<$number;$i++) {
 8869:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8870:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8871:     }
 8872:     my $correct_count=0;
 8873:     my $student_count=0;
 8874:     my $unknown_count=0;
 8875: # Match answers with usernames
 8876: # FIXME: Possibly need delimiter other than ":"
 8877:     foreach my $id (keys(%responses)) {
 8878:        if ($correct_ids{$id}) {
 8879:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8880:           $correct_count++;
 8881:        } elsif ($clicker_ids{$id}) {
 8882:           if ($clicker_ids{$id}=~/\,/) {
 8883: # More than one user with the same clicker!
 8884:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8885:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8886:                            "<select name='multi".$id."'>";
 8887:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8888:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8889:              }
 8890:              $result.='</select>';
 8891:              $unknown_count++;
 8892:           } else {
 8893: # Good: found one and only one user with the right clicker
 8894:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8895:              $student_count++;
 8896:           }
 8897:        } else {
 8898:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8899:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8900:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8901:                    "\n".&mt("Domain").": ".
 8902:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8903:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8904:           $unknown_count++;
 8905:        }
 8906:     }
 8907:     $result.='<hr />'.
 8908:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8909:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8910:        if ($correct_count==0) {
 8911:           $errormsg.="Found no correct answers answers for grading!";
 8912:        } elsif ($correct_count>1) {
 8913:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8914:        }
 8915:     }
 8916:     if ($number<1) {
 8917:        $errormsg.="Found no questions.";
 8918:     }
 8919:     if ($errormsg) {
 8920:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8921:     } else {
 8922:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8923:     }
 8924:     $result.='</form></td></tr></table>'."\n".
 8925:              '</td></tr></table><br /><br />'."\n";
 8926:     return $result.&show_grading_menu_form($symb);
 8927: }
 8928: 
 8929: sub iclicker_eval {
 8930:     my ($questiontitles,$responses)=@_;
 8931:     my $number=0;
 8932:     my $errormsg='';
 8933:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8934:         my %components=&Apache::loncommon::record_sep($line);
 8935:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8936: 	if ($entries[0] eq 'Question') {
 8937: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8938: 		$$questiontitles[$number]=$entries[$i];
 8939: 		$number++;
 8940: 	    }
 8941: 	}
 8942: 	if ($entries[0]=~/^\#/) {
 8943: 	    my $id=$entries[0];
 8944: 	    my @idresponses;
 8945: 	    $id=~s/^[\#0]+//;
 8946: 	    for (my $i=0;$i<$number;$i++) {
 8947: 		my $idx=3+$i*6;
 8948: 		push(@idresponses,$entries[$idx]);
 8949: 	    }
 8950: 	    $$responses{$id}=join(',',@idresponses);
 8951: 	}
 8952:     }
 8953:     return ($errormsg,$number);
 8954: }
 8955: 
 8956: sub interwrite_eval {
 8957:     my ($questiontitles,$responses)=@_;
 8958:     my $number=0;
 8959:     my $errormsg='';
 8960:     my $skipline=1;
 8961:     my $questionnumber=0;
 8962:     my %idresponses=();
 8963:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8964:         my %components=&Apache::loncommon::record_sep($line);
 8965:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8966:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8967:         if ($entries[1] eq 'Response') { $skipline=1; }
 8968:         next if $skipline;
 8969:         if ($entries[0]!=$questionnumber) {
 8970:            $questionnumber=$entries[0];
 8971:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8972:            $number++;
 8973:         }
 8974:         my $id=$entries[4];
 8975:         $id=~s/^[\#0]+//;
 8976:         $id=~s/^v\d*\://i;
 8977:         $id=~s/[\-\:]//g;
 8978:         $idresponses{$id}[$number]=$entries[6];
 8979:     }
 8980:     foreach my $id (keys(%idresponses)) {
 8981:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8982:        $$responses{$id}=~s/^\s*\,//;
 8983:     }
 8984:     return ($errormsg,$number);
 8985: }
 8986: 
 8987: sub assign_clicker_grades {
 8988:     my ($r)=@_;
 8989:     my ($symb)=&get_symb($r);
 8990:     if (!$symb) {return '';}
 8991: # See which part we are saving to
 8992:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8993: # FIXME: This should probably look for the first handgradeable part
 8994:     my $part=$$partlist[0];
 8995: # Start screen output
 8996:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8997: 
 8998:     my $heading=&mt('Assigning grades based on clicker file');
 8999:     $result.=(<<ENDHEADER);
 9000: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9001: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9002: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9003: ENDHEADER
 9004: # Get correct result
 9005: # FIXME: Possibly need delimiter other than ":"
 9006:     my @correct=();
 9007:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9008:     my $number=$env{'form.number'};
 9009:     if ($gradingmechanism ne 'attendance') {
 9010:        foreach my $key (keys(%env)) {
 9011:           if ($key=~/^form\.correct\:/) {
 9012:              my @input=split(/\,/,$env{$key});
 9013:              for (my $i=0;$i<=$#input;$i++) {
 9014:                  if (($correct[$i]) && ($input[$i]) &&
 9015:                      ($correct[$i] ne $input[$i])) {
 9016:                     $result.='<br /><span class="LC_warning">'.
 9017:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9018:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9019:                  } elsif ($input[$i]) {
 9020:                     $correct[$i]=$input[$i];
 9021:                  }
 9022:              }
 9023:           }
 9024:        }
 9025:        for (my $i=0;$i<$number;$i++) {
 9026:           if (!$correct[$i]) {
 9027:              $result.='<br /><span class="LC_error">'.
 9028:                       &mt('No correct result given for question "[_1]"!',
 9029:                           $env{'form.question:'.$i}).'</span>';
 9030:           }
 9031:        }
 9032:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9033:     }
 9034: # Start grading
 9035:     my $pcorrect=$env{'form.pcorrect'};
 9036:     my $pincorrect=$env{'form.pincorrect'};
 9037:     my $storecount=0;
 9038:     foreach my $key (keys(%env)) {
 9039:        my $user='';
 9040:        if ($key=~/^form\.student\:(.*)$/) {
 9041:           $user=$1;
 9042:        }
 9043:        if ($key=~/^form\.unknown\:(.*)$/) {
 9044:           my $id=$1;
 9045:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9046:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9047:           } elsif ($env{'form.multi'.$id}) {
 9048:              $user=$env{'form.multi'.$id};
 9049:           }
 9050:        }
 9051:        if ($user) { 
 9052:           my @answer=split(/\,/,$env{$key});
 9053:           my $sum=0;
 9054:           my $realnumber=$number;
 9055:           for (my $i=0;$i<$number;$i++) {
 9056:              if  ($correct[$i] eq '-') {
 9057:                 $realnumber--;
 9058:              } elsif ($answer[$i]) {
 9059:                 if ($gradingmechanism eq 'attendance') {
 9060:                    $sum+=$pcorrect;
 9061:                 } elsif ($correct[$i] eq '*') {
 9062:                    $sum+=$pcorrect;
 9063:                 } else {
 9064:                    if ($answer[$i] eq $correct[$i]) {
 9065:                       $sum+=$pcorrect;
 9066:                    } else {
 9067:                       $sum+=$pincorrect;
 9068:                    }
 9069:                 }
 9070:              }
 9071:           }
 9072:           my $ave=$sum/(100*$realnumber);
 9073: # Store
 9074:           my ($username,$domain)=split(/\:/,$user);
 9075:           my %grades=();
 9076:           $grades{"resource.$part.solved"}='correct_by_override';
 9077:           $grades{"resource.$part.awarded"}=$ave;
 9078:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9079:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9080:                                                  $env{'request.course.id'},
 9081:                                                  $domain,$username);
 9082:           if ($returncode ne 'ok') {
 9083:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9084:           } else {
 9085:              $storecount++;
 9086:           }
 9087:        }
 9088:     }
 9089: # We are done
 9090:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9091:              '</td></tr></table>'."\n".
 9092:              '</td></tr></table><br /><br />'."\n";
 9093:     return $result.&show_grading_menu_form($symb);
 9094: }
 9095: 
 9096: sub handler {
 9097:     my $request=$_[0];
 9098:     &reset_caches();
 9099:     if ($env{'browser.mathml'}) {
 9100: 	&Apache::loncommon::content_type($request,'text/xml');
 9101:     } else {
 9102: 	&Apache::loncommon::content_type($request,'text/html');
 9103:     }
 9104:     $request->send_http_header;
 9105:     return '' if $request->header_only;
 9106:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9107:     my $symb=&get_symb($request,1);
 9108:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9109:     my $command=$commands[0];
 9110: 
 9111:     if ($#commands > 0) {
 9112: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9113:     }
 9114: 
 9115:     $ssi_error = 0;
 9116:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9117:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9118:                                           {'bread_crumbs' => $brcrum}));
 9119:     if (&Apache::loncommon::needs_gci_custom()) {
 9120:         $request->print('<h3>'.&mt('Grading screens are unavailable for GCI Concept Tests').'</h3>'.&Apache::loncommon::end_page());
 9121:         &reset_caches();
 9122:         return '';
 9123:     }
 9124:     if ($symb eq '' && $command eq '') {
 9125: 	if ($env{'user.adv'}) {
 9126: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9127: 		($env{'form.codethree'})) {
 9128: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9129: 		    $env{'form.codethree'};
 9130: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9131: 		    &Apache::lonnet::checkin($token);
 9132: 		if ($tsymb) {
 9133: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9134: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9135: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9136: 					  ('grade_username' => $tuname,
 9137: 					   'grade_domain' => $tudom,
 9138: 					   'grade_courseid' => $tcrsid,
 9139: 					   'grade_symb' => $tsymb)));
 9140: 		    } else {
 9141: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9142: 		    }
 9143: 		} else {
 9144: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9145: 		}
 9146: 	    } else {
 9147: 		$request->print(&Apache::lonxml::tokeninputfield());
 9148: 	    }
 9149: 	}
 9150:     } else {
 9151: 	&init_perm();
 9152: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9153: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9154: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9155: 	    &pickStudentPage($request);
 9156: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9157: 	    &displayPage($request);
 9158: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9159: 	    &updateGradeByPage($request);
 9160: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9161: 	    &processGroup($request);
 9162: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9163: 	    $request->print(&grading_menu($request));
 9164: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9165: 	    $request->print(&submit_options($request));
 9166: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9167: 	    $request->print(&viewgrades($request));
 9168: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9169: 	    $request->print(&processHandGrade($request));
 9170: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9171: 	    $request->print(&editgrades($request));
 9172: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9173: 	    $request->print(&verifyreceipt($request));
 9174:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9175:             $request->print(&process_clicker($request));
 9176:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9177:             $request->print(&process_clicker_file($request));
 9178:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9179:             $request->print(&assign_clicker_grades($request));
 9180: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9181: 	    $request->print(&upcsvScores_form($request));
 9182: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9183: 	    $request->print(&csvupload($request));
 9184: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9185: 	    $request->print(&csvuploadmap($request));
 9186: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9187: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9188: 		$request->print(&csvuploadoptions($request));
 9189: 	    } else {
 9190: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9191: 		    $env{'form.upfile_associate'} = 'reverse';
 9192: 		} else {
 9193: 		    $env{'form.upfile_associate'} = 'forward';
 9194: 		}
 9195: 		$request->print(&csvuploadmap($request));
 9196: 	    }
 9197: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9198: 	    $request->print(&csvuploadassign($request));
 9199: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9200: 	    $request->print(&scantron_selectphase($request));
 9201:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9202:  	    $request->print(&scantron_do_warning($request));
 9203: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9204: 	    $request->print(&scantron_validate_file($request));
 9205: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9206: 	    $request->print(&scantron_process_students($request));
 9207:  	} elsif ($command eq 'scantronupload' && 
 9208:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9209: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9210:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9211:  	} elsif ($command eq 'scantronupload_save' &&
 9212:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9213: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9214:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9215:  	} elsif ($command eq 'scantron_download' &&
 9216: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9217:  	    $request->print(&scantron_download_scantron_data($request));
 9218:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9219:             $request->print(&checkscantron_results($request));     
 9220: 	} elsif ($command) {
 9221: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9222: 	}
 9223:     }
 9224:     if ($ssi_error) {
 9225: 	&ssi_print_error($request);
 9226:     }
 9227:     $request->print(&Apache::loncommon::end_page());
 9228:     &reset_caches();
 9229:     return '';
 9230: }
 9231: 
 9232: 1;
 9233: 
 9234: __END__;
 9235: 
 9236: 
 9237: =head1 NAME
 9238: 
 9239: Apache::grades
 9240: 
 9241: =head1 SYNOPSIS
 9242: 
 9243: Handles the viewing of grades.
 9244: 
 9245: This is part of the LearningOnline Network with CAPA project
 9246: described at http://www.lon-capa.org.
 9247: 
 9248: =head1 OVERVIEW
 9249: 
 9250: Do an ssi with retries:
 9251: While I'd love to factor out this with the vesrion in lonprintout,
 9252: 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
 9253: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9254: 
 9255: At least the logic that drives this has been pulled out into loncommon.
 9256: 
 9257: 
 9258: 
 9259: ssi_with_retries - Does the server side include of a resource.
 9260:                      if the ssi call returns an error we'll retry it up to
 9261:                      the number of times requested by the caller.
 9262:                      If we still have a proble, no text is appended to the
 9263:                      output and we set some global variables.
 9264:                      to indicate to the caller an SSI error occurred.  
 9265:                      All of this is supposed to deal with the issues described
 9266:                      in LonCAPA BZ 5631 see:
 9267:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9268:                      by informing the user that this happened.
 9269: 
 9270: Parameters:
 9271:   resource   - The resource to include.  This is passed directly, without
 9272:                interpretation to lonnet::ssi.
 9273:   form       - The form hash parameters that guide the interpretation of the resource
 9274:                
 9275:   retries    - Number of retries allowed before giving up completely.
 9276: Returns:
 9277:   On success, returns the rendered resource identified by the resource parameter.
 9278: Side Effects:
 9279:   The following global variables can be set:
 9280:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9281:                               It is up to the caller to initialize this to false
 9282:                               if desired.
 9283:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9284:                               of the resource that could not be rendered by the ssi
 9285:                               call.
 9286:    ssi_error_message   - The error string fetched from the ssi response
 9287:                               in the event of an error.
 9288: 
 9289: 
 9290: =head1 HANDLER SUBROUTINE
 9291: 
 9292: ssi_with_retries()
 9293: 
 9294: =head1 SUBROUTINES
 9295: 
 9296: =over
 9297: 
 9298: =item scantron_get_correction() : 
 9299: 
 9300:    Builds the interface screen to interact with the operator to fix a
 9301:    specific error condition in a specific scanline
 9302: 
 9303:  Arguments:
 9304:     $r           - Apache request object
 9305:     $i           - number of the current scanline
 9306:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9307:     $scan_config - hash ref as returned from &get_scantron_config()
 9308:     $line        - full contents of the current scanline
 9309:     $error       - error condition, valid values are
 9310:                    'incorrectCODE', 'duplicateCODE',
 9311:                    'doublebubble', 'missingbubble',
 9312:                    'duplicateID', 'incorrectID'
 9313:     $arg         - extra information needed
 9314:        For errors:
 9315:          - duplicateID   - paper number that this studentID was seen before on
 9316:          - duplicateCODE - array ref of the paper numbers this CODE was
 9317:                            seen on before
 9318:          - incorrectCODE - current incorrect CODE 
 9319:          - doublebubble  - array ref of the bubble lines that have double
 9320:                            bubble errors
 9321:          - missingbubble - array ref of the bubble lines that have missing
 9322:                            bubble errors
 9323: 
 9324: =item  scantron_get_maxbubble() : 
 9325: 
 9326:    Returns the maximum number of bubble lines that are expected to
 9327:    occur. Does this by walking the selected sequence rendering the
 9328:    resource and then checking &Apache::lonxml::get_problem_counter()
 9329:    for what the current value of the problem counter is.
 9330: 
 9331:    Caches the results to $env{'form.scantron_maxbubble'},
 9332:    $env{'form.scantron.bubble_lines.n'}, 
 9333:    $env{'form.scantron.first_bubble_line.n'} and
 9334:    $env{"form.scantron.sub_bubblelines.n"}
 9335:    which are the total number of bubble, lines, the number of bubble
 9336:    lines for response n and number of the first bubble line for response n,
 9337:    and a comma separated list of numbers of bubble lines for sub-questions
 9338:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9339: 
 9340: 
 9341: =item  scantron_validate_missingbubbles() : 
 9342: 
 9343:    Validates all scanlines in the selected file to not have any
 9344:     answers that don't have bubbles that have not been verified
 9345:     to be bubble free.
 9346: 
 9347: =item  scantron_process_students() : 
 9348: 
 9349:    Routine that does the actual grading of the bubble sheet information.
 9350: 
 9351:    The parsed scanline hash is added to %env 
 9352: 
 9353:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9354:    foreach resource , with the form data of
 9355: 
 9356: 	'submitted'     =>'scantron' 
 9357: 	'grade_target'  =>'grade',
 9358: 	'grade_username'=> username of student
 9359: 	'grade_domain'  => domain of student
 9360: 	'grade_courseid'=> of course
 9361: 	'grade_symb'    => symb of resource to grade
 9362: 
 9363:     This triggers a grading pass. The problem grading code takes care
 9364:     of converting the bubbled letter information (now in %env) into a
 9365:     valid submission.
 9366: 
 9367: =item  scantron_upload_scantron_data() :
 9368: 
 9369:     Creates the screen for adding a new bubble sheet data file to a course.
 9370: 
 9371: =item  scantron_upload_scantron_data_save() : 
 9372: 
 9373:    Adds a provided bubble information data file to the course if user
 9374:    has the correct privileges to do so. 
 9375: 
 9376: =item  valid_file() :
 9377: 
 9378:    Validates that the requested bubble data file exists in the course.
 9379: 
 9380: =item  scantron_download_scantron_data() : 
 9381: 
 9382:    Shows a list of the three internal files (original, corrected,
 9383:    skipped) for a specific bubble sheet data file that exists in the
 9384:    course.
 9385: 
 9386: =item  scantron_validate_ID() : 
 9387: 
 9388:    Validates all scanlines in the selected file to not have any
 9389:    invalid or underspecified student/employee IDs
 9390: 
 9391: =back
 9392: 
 9393: =cut

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