File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.554: download - view: text, annotated - select for diffs
Fri Mar 6 16:13:29 2009 UTC (15 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Verification of Scantron grading for problems containing randomlists
  - &scantron_partids_tograde()
    - changed to use &get_analyze() to retrieve partIDs/responseIDs
    - subroutine moved to be within scope of %analyze_cache.
    - needs to be called for each user (randomlist -> possibly different responseIDs for different users).

- Robustness against changes to lonxml::counter being made by multitasking instructors.
  - scantron_questnum_start.$part.$id form element passed in ssi call for scantron grading.
    - where available, this value is used within response::getresponse() instead of lonxml::counter to determine starting column for scantron line.

- Second pass (if optional inbuilt verification enabled during scantron grading).
  - Added missing call to repeat &grade_student_bubbles() when anomaly is detected during first pass.

****
Work-in-progress - possible performance hit - perhaps check if resource includes <randomlist></randomlist> before calling &scantron_partids_tograde() for each user?

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.554 2009/03/06 16:13:29 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: sub getpartlist {
  100:     my ($symb) = @_;
  101: 
  102:     my $navmap   = Apache::lonnavmaps::navmap->new();
  103:     my $res      = $navmap->getBySymb($symb);
  104:     my $partlist = $res->parts();
  105:     my $url      = $res->src();
  106:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  107: 
  108:     my @stores;
  109:     foreach my $part (@{ $partlist }) {
  110: 	foreach my $key (@metakeys) {
  111: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  112: 	}
  113:     }
  114:     return @stores;
  115: }
  116: 
  117: # --- Get the symbolic name of a problem and the url
  118: sub get_symb {
  119:     my ($request,$silent) = @_;
  120:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  121:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  122:     if ($symb eq '') { 
  123: 	if (!$silent) {
  124: 	    $request->print("Unable to handle ambiguous references:$url:.");
  125: 	    return ();
  126: 	}
  127:     }
  128:     &Apache::lonenc::check_decrypt(\$symb);
  129:     return ($symb);
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: sub response_type {
  147:     my ($symb) = shift;
  148: 
  149:     my $navmap = Apache::lonnavmaps::navmap->new();
  150:     my $res = $navmap->getBySymb($symb);
  151:     my $partlist = $res->parts();
  152:     my %vPart = 
  153: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  154:     my (%response_types,%handgrade);
  155:     foreach my $part (@{ $partlist }) {
  156: 	next if (%vPart && !exists($vPart{$part}));
  157: 
  158: 	my @types = $res->responseType($part);
  159: 	my @ids = $res->responseIds($part);
  160: 	for (my $i=0; $i < scalar(@ids); $i++) {
  161: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  162: 	    $handgrade{$part.'_'.$ids[$i]} = 
  163: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  164: 				     '.handgrade',$symb);
  165: 	}
  166:     }
  167:     return ($partlist,\%handgrade,\%response_types);
  168: }
  169: 
  170: sub flatten_responseType {
  171:     my ($responseType) = @_;
  172:     my @part_response_id =
  173: 	map { 
  174: 	    my $part = $_;
  175: 	    map {
  176: 		[$part,$_]
  177: 		} sort(keys(%{ $responseType->{$part} }));
  178: 	} sort(keys(%$responseType));
  179:     return @part_response_id;
  180: }
  181: 
  182: sub get_display_part {
  183:     my ($partID,$symb)=@_;
  184:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  185:     if (defined($display) and $display ne '') {
  186: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  187:     } else {
  188: 	$display=$partID;
  189:     }
  190:     return $display;
  191: }
  192: 
  193: #--- Show resource title
  194: #--- and parts and response type
  195: sub showResourceInfo {
  196:     my ($symb,$probTitle,$checkboxes) = @_;
  197:     my $col=3;
  198:     if ($checkboxes) { $col=4; }
  199:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  200:     $result .='<table border="0">';
  201:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  202:     my %resptype = ();
  203:     my $hdgrade='no';
  204:     my %partsseen;
  205:     foreach my $partID (sort(keys(%$responseType))) {
  206: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  207: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  208: 	    my $responsetype = $responseType->{$partID}->{$resID};
  209: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  210: 	    $result.='<tr>';
  211: 	    if ($checkboxes) {
  212: 		if (exists($partsseen{$partID})) {
  213: 		    $result.="<td>&nbsp;</td>";
  214: 		} else {
  215: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  216: 		}
  217: 		$partsseen{$partID}=1;
  218: 	    }
  219: 	    my $display_part=&get_display_part($partID,$symb);
  220: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
  221:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  222: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
  223: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  224: 	}
  225:     }
  226:     $result.='</table>'."\n";
  227:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  228: }
  229: 
  230: sub reset_caches {
  231:     &reset_analyze_cache();
  232:     &reset_perm();
  233: }
  234: 
  235: {
  236:     my %analyze_cache;
  237: 
  238:     sub reset_analyze_cache {
  239: 	undef(%analyze_cache);
  240:     }
  241: 
  242:     sub get_analyze {
  243: 	my ($symb,$uname,$udom,$no_increment)=@_;
  244: 	my $key = "$symb\0$uname\0$udom";
  245: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  246: 
  247: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  248: 	$url=&Apache::lonnet::clutter($url);
  249: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  250: 					   ('grade_target' => 'analyze',
  251: 					    'grade_domain' => $udom,
  252: 					    'grade_symb' => $symb,
  253: 					    'grade_courseid' => 
  254: 					    $env{'request.course.id'},
  255: 					    'grade_username' => $uname,
  256:                                             'grade_noincrement' => $no_increment));
  257: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  258: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  259: 	return $analyze_cache{$key} = \%analyze;
  260:     }
  261: 
  262:     sub get_order {
  263: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  264: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  265: 	return $analyze->{"$partid.$respid.shown"};
  266:     }
  267: 
  268:     sub get_radiobutton_correct_foil {
  269: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  270: 	my $analyze = &get_analyze($symb,$uname,$udom);
  271: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  272: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  273: 		return $foil;
  274: 	    }
  275: 	}
  276:     }
  277: 
  278:     sub scantron_partids_tograde {
  279:         my ($resource,$cid,$uname,$udom) = @_;
  280:         my (%analysis,@parts);
  281:         if (ref($resource)) {
  282:             my $symb = $resource->symb();
  283:             my $analyze = &get_analyze($symb,$uname,$udom);
  284:             if (ref($analyze) eq 'HASH') {
  285:                 %analysis = %{$analyze};
  286:             }
  287:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  288:                 foreach my $part (@{$analysis{'parts'}}) {
  289:                     my ($id,$respid) = split(/\./,$part);
  290:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  291:                         push(@parts,$part);
  292:                     }
  293:                 }
  294:             }
  295:         }
  296:         return (\%analysis,\@parts);
  297:     }
  298: 
  299: }
  300: 
  301: #--- Clean response type for display
  302: #--- Currently filters option/rank/radiobutton/match/essay/Task
  303: #        response types only.
  304: sub cleanRecord {
  305:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  306: 	$uname,$udom) = @_;
  307:     my $grayFont = '<span class="LC_internal_info">';
  308:     if ($response =~ /^(option|rank)$/) {
  309: 	my %answer=&Apache::lonnet::str2hash($answer);
  310: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  311: 	my ($toprow,$bottomrow);
  312: 	foreach my $foil (@$order) {
  313: 	    if ($grading{$foil} == 1) {
  314: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  315: 	    } else {
  316: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  317: 	    }
  318: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  319: 	}
  320: 	return '<blockquote><table border="1">'.
  321: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  322: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  323: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  324:     } elsif ($response eq 'match') {
  325: 	my %answer=&Apache::lonnet::str2hash($answer);
  326: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  327: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  328: 	my ($toprow,$middlerow,$bottomrow);
  329: 	foreach my $foil (@$order) {
  330: 	    my $item=shift(@items);
  331: 	    if ($grading{$foil} == 1) {
  332: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  333: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  334: 	    } else {
  335: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  336: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  337: 	    }
  338: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  339: 	}
  340: 	return '<blockquote><table border="1">'.
  341: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  342: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  343: 	    $middlerow.'</tr>'.
  344: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  345: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  346:     } elsif ($response eq 'radiobutton') {
  347: 	my %answer=&Apache::lonnet::str2hash($answer);
  348: 	my ($toprow,$bottomrow);
  349: 	my $correct = 
  350: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  351: 	foreach my $foil (@$order) {
  352: 	    if (exists($answer{$foil})) {
  353: 		if ($foil eq $correct) {
  354: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  355: 		} else {
  356: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  357: 		}
  358: 	    } else {
  359: 		$toprow.='<td>'.&mt('false').'</td>';
  360: 	    }
  361: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  362: 	}
  363: 	return '<blockquote><table border="1">'.
  364: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  366: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  367:     } elsif ($response eq 'essay') {
  368: 	if (! exists ($env{'form.'.$symb})) {
  369: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  370: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  371: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  372: 
  373: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  374: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  375: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  376: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  377: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  378: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  379: 	}
  380: 	$answer =~ s-\n-<br />-g;
  381: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  382:     } elsif ( $response eq 'organic') {
  383: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  384: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  385: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  386: 	return $result;
  387:     } elsif ( $response eq 'Task') {
  388: 	if ( $answer eq 'SUBMITTED') {
  389: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  390: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  391: 	    return $result;
  392: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  393: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  394: 			       keys(%{$record}));
  395: 	    return join('<br />',($version,@matches));
  396: 			       
  397: 			       
  398: 	} else {
  399: 	    my $result =
  400: 		'<p>'
  401: 		.&mt('Overall result: [_1]',
  402: 		     $record->{$version."resource.$respid.$partid.status"})
  403: 		.'</p>';
  404: 	    
  405: 	    $result .= '<ul>';
  406: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  407: 			     keys(%{$record}));
  408: 	    foreach my $grade (sort(@grade)) {
  409: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  410: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  411: 				     $dim, $record->{$grade}).
  412: 			  '</li>';
  413: 	    }
  414: 	    $result.='</ul>';
  415: 	    return $result;
  416: 	}
  417:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  418: 	$answer = 
  419: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  420: 							      $answer);
  421:     }
  422:     return $answer;
  423: }
  424: 
  425: #-- A couple of common js functions
  426: sub commonJSfunctions {
  427:     my $request = shift;
  428:     $request->print(<<COMMONJSFUNCTIONS);
  429: <script type="text/javascript" language="javascript">
  430:     function radioSelection(radioButton) {
  431: 	var selection=null;
  432: 	if (radioButton.length > 1) {
  433: 	    for (var i=0; i<radioButton.length; i++) {
  434: 		if (radioButton[i].checked) {
  435: 		    return radioButton[i].value;
  436: 		}
  437: 	    }
  438: 	} else {
  439: 	    if (radioButton.checked) return radioButton.value;
  440: 	}
  441: 	return selection;
  442:     }
  443: 
  444:     function pullDownSelection(selectOne) {
  445: 	var selection="";
  446: 	if (selectOne.length > 1) {
  447: 	    for (var i=0; i<selectOne.length; i++) {
  448: 		if (selectOne[i].selected) {
  449: 		    return selectOne[i].value;
  450: 		}
  451: 	    }
  452: 	} else {
  453:             // only one value it must be the selected one
  454: 	    return selectOne.value;
  455: 	}
  456:     }
  457: </script>
  458: COMMONJSFUNCTIONS
  459: }
  460: 
  461: #--- Dumps the class list with usernames,list of sections,
  462: #--- section, ids and fullnames for each user.
  463: sub getclasslist {
  464:     my ($getsec,$filterlist,$getgroup) = @_;
  465:     my @getsec;
  466:     my @getgroup;
  467:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  468:     if (!ref($getsec)) {
  469: 	if ($getsec ne '' && $getsec ne 'all') {
  470: 	    @getsec=($getsec);
  471: 	}
  472:     } else {
  473: 	@getsec=@{$getsec};
  474:     }
  475:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  476:     if (!ref($getgroup)) {
  477: 	if ($getgroup ne '' && $getgroup ne 'all') {
  478: 	    @getgroup=($getgroup);
  479: 	}
  480:     } else {
  481: 	@getgroup=@{$getgroup};
  482:     }
  483:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  484: 
  485:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  486:     # Bail out if we were unable to get the classlist
  487:     return if (! defined($classlist));
  488:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  489:     #
  490:     my %sections;
  491:     my %fullnames;
  492:     foreach my $student (keys(%$classlist)) {
  493:         my $end      = 
  494:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  495:         my $start    = 
  496:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  497:         my $id       = 
  498:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  499:         my $section  = 
  500:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  501:         my $fullname = 
  502:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  503:         my $status   = 
  504:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  505:         my $group   = 
  506:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  507: 	# filter students according to status selected
  508: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  509: 	    if (!($stu_status =~ $status)) {
  510: 		delete($classlist->{$student});
  511: 		next;
  512: 	    }
  513: 	}
  514: 	# filter students according to groups selected
  515: 	my @stu_groups = split(/,/,$group);
  516: 	if (@getgroup) {
  517: 	    my $exclude = 1;
  518: 	    foreach my $grp (@getgroup) {
  519: 	        foreach my $stu_group (@stu_groups) {
  520: 	            if ($stu_group eq $grp) {
  521: 	                $exclude = 0;
  522:     	            } 
  523: 	        }
  524:     	        if (($grp eq 'none') && !$group) {
  525:         	        $exclude = 0;
  526:         	}
  527: 	    }
  528: 	    if ($exclude) {
  529: 	        delete($classlist->{$student});
  530: 	    }
  531: 	}
  532: 	$section = ($section ne '' ? $section : 'none');
  533: 	if (&canview($section)) {
  534: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  535: 		$sections{$section}++;
  536: 		if ($classlist->{$student}) {
  537: 		    $fullnames{$student}=$fullname;
  538: 		}
  539: 	    } else {
  540: 		delete($classlist->{$student});
  541: 	    }
  542: 	} else {
  543: 	    delete($classlist->{$student});
  544: 	}
  545:     }
  546:     my %seen = ();
  547:     my @sections = sort(keys(%sections));
  548:     return ($classlist,\@sections,\%fullnames);
  549: }
  550: 
  551: sub canmodify {
  552:     my ($sec)=@_;
  553:     if ($perm{'mgr'}) {
  554: 	if (!defined($perm{'mgr_section'})) {
  555: 	    # can modify whole class
  556: 	    return 1;
  557: 	} else {
  558: 	    if ($sec eq $perm{'mgr_section'}) {
  559: 		#can modify the requested section
  560: 		return 1;
  561: 	    } else {
  562: 		# can't modify the request section
  563: 		return 0;
  564: 	    }
  565: 	}
  566:     }
  567:     #can't modify
  568:     return 0;
  569: }
  570: 
  571: sub canview {
  572:     my ($sec)=@_;
  573:     if ($perm{'vgr'}) {
  574: 	if (!defined($perm{'vgr_section'})) {
  575: 	    # can modify whole class
  576: 	    return 1;
  577: 	} else {
  578: 	    if ($sec eq $perm{'vgr_section'}) {
  579: 		#can modify the requested section
  580: 		return 1;
  581: 	    } else {
  582: 		# can't modify the request section
  583: 		return 0;
  584: 	    }
  585: 	}
  586:     }
  587:     #can't modify
  588:     return 0;
  589: }
  590: 
  591: #--- Retrieve the grade status of a student for all the parts
  592: sub student_gradeStatus {
  593:     my ($symb,$udom,$uname,$partlist) = @_;
  594:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  595:     my %partstatus = ();
  596:     foreach (@$partlist) {
  597: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  598: 	$status              = 'nothing' if ($status eq '');
  599: 	$partstatus{$_}      = $status;
  600: 	my $subkey           = "resource.$_.submitted_by";
  601: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  602:     }
  603:     return %partstatus;
  604: }
  605: 
  606: # hidden form and javascript that calls the form
  607: # Use by verifyscript and viewgrades
  608: # Shows a student's view of problem and submission
  609: sub jscriptNform {
  610:     my ($symb) = @_;
  611:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  612:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  613: 	'    function viewOneStudent(user,domain) {'."\n".
  614: 	'	document.onestudent.student.value = user;'."\n".
  615: 	'	document.onestudent.userdom.value = domain;'."\n".
  616: 	'	document.onestudent.submit();'."\n".
  617: 	'    }'."\n".
  618: 	'</script>'."\n";
  619:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  620: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  621: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  622: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  623: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  624: 	'<input type="hidden" name="command" value="submission" />'."\n".
  625: 	'<input type="hidden" name="student" value="" />'."\n".
  626: 	'<input type="hidden" name="userdom" value="" />'."\n".
  627: 	'</form>'."\n";
  628:     return $jscript;
  629: }
  630: 
  631: 
  632: 
  633: # Given the score (as a number [0-1] and the weight) what is the final
  634: # point value? This function will round to the nearest tenth, third,
  635: # or quarter if one of those is within the tolerance of .00001.
  636: sub compute_points {
  637:     my ($score, $weight) = @_;
  638:     
  639:     my $tolerance = .00001;
  640:     my $points = $score * $weight;
  641: 
  642:     # Check for nearness to 1/x.
  643:     my $check_for_nearness = sub {
  644:         my ($factor) = @_;
  645:         my $num = ($points * $factor) + $tolerance;
  646:         my $floored_num = floor($num);
  647:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  648:             return $floored_num / $factor;
  649:         }
  650:         return $points;
  651:     };
  652: 
  653:     $points = $check_for_nearness->(10);
  654:     $points = $check_for_nearness->(3);
  655:     $points = $check_for_nearness->(4);
  656:     
  657:     return $points;
  658: }
  659: 
  660: #------------------ End of general use routines --------------------
  661: 
  662: #
  663: # Find most similar essay
  664: #
  665: 
  666: sub most_similar {
  667:     my ($uname,$udom,$uessay,$old_essays)=@_;
  668: 
  669: # ignore spaces and punctuation
  670: 
  671:     $uessay=~s/\W+/ /gs;
  672: 
  673: # ignore empty submissions (occuring when only files are sent)
  674: 
  675:     unless ($uessay=~/\w+/) { return ''; }
  676: 
  677: # these will be returned. Do not care if not at least 50 percent similar
  678:     my $limit=0.6;
  679:     my $sname='';
  680:     my $sdom='';
  681:     my $scrsid='';
  682:     my $sessay='';
  683: # go through all essays ...
  684:     foreach my $tkey (keys(%$old_essays)) {
  685: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  686: # ... except the same student
  687:         next if (($tname eq $uname) && ($tdom eq $udom));
  688: 	my $tessay=$old_essays->{$tkey};
  689: 	$tessay=~s/\W+/ /gs;
  690: # String similarity gives up if not even limit
  691: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  692: # Found one
  693: 	if ($tsimilar>$limit) {
  694: 	    $limit=$tsimilar;
  695: 	    $sname=$tname;
  696: 	    $sdom=$tdom;
  697: 	    $scrsid=$tcrsid;
  698: 	    $sessay=$old_essays->{$tkey};
  699: 	}
  700:     }
  701:     if ($limit>0.6) {
  702:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  703:     } else {
  704:        return ('','','','',0);
  705:     }
  706: }
  707: 
  708: #-------------------------------------------------------------------
  709: 
  710: #------------------------------------ Receipt Verification Routines
  711: #
  712: #--- Check whether a receipt number is valid.---
  713: sub verifyreceipt {
  714:     my $request  = shift;
  715: 
  716:     my $courseid = $env{'request.course.id'};
  717:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  718: 	$env{'form.receipt'};
  719:     $receipt     =~ s/[^\-\d]//g;
  720:     my ($symb)   = &get_symb($request);
  721: 
  722:     my $title.=
  723: 	'<h3><span class="LC_info">'.
  724: 	&mt('Verifying  Receipt No. [_1]',$receipt).
  725: 	'</span></h3>'."\n".
  726: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  727: 	'</h4>'."\n";
  728: 
  729:     my ($string,$contents,$matches) = ('','',0);
  730:     my (undef,undef,$fullname) = &getclasslist('all','0');
  731:     
  732:     my $receiptparts=0;
  733:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  734: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  735:     my $parts=['0'];
  736:     if ($receiptparts) { ($parts)=&response_type($symb); }
  737:     
  738:     my $header = 
  739: 	&Apache::loncommon::start_data_table().
  740: 	&Apache::loncommon::start_data_table_header_row().
  741: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  742: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  743: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  744:     if ($receiptparts) {
  745: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  746:     }
  747:     $header.=
  748: 	&Apache::loncommon::end_data_table_header_row();
  749: 
  750:     foreach (sort 
  751: 	     {
  752: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  753: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  754: 		 }
  755: 		 return $a cmp $b;
  756: 	     } (keys(%$fullname))) {
  757: 	my ($uname,$udom)=split(/\:/);
  758: 	foreach my $part (@$parts) {
  759: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  760: 		$contents.=
  761: 		    &Apache::loncommon::start_data_table_row().
  762: 		    '<td>&nbsp;'."\n".
  763: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  764: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  765: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  766: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  767: 		if ($receiptparts) {
  768: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  769: 		}
  770: 		$contents.= 
  771: 		    &Apache::loncommon::end_data_table_row()."\n";
  772: 		
  773: 		$matches++;
  774: 	    }
  775: 	}
  776:     }
  777:     if ($matches == 0) {
  778: 	$string = $title.&mt('No match found for the above receipt.');
  779:     } else {
  780: 	$string = &jscriptNform($symb).$title.
  781: 	    '<p>'.
  782: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  783: 	    '</p>'.
  784: 	    $header.
  785: 	    $contents.
  786: 	    &Apache::loncommon::end_data_table()."\n";
  787:     }
  788:     return $string.&show_grading_menu_form($symb);
  789: }
  790: 
  791: #--- This is called by a number of programs.
  792: #--- Called from the Grading Menu - View/Grade an individual student
  793: #--- Also called directly when one clicks on the subm button 
  794: #    on the problem page.
  795: sub listStudents {
  796:     my ($request) = shift;
  797: 
  798:     my ($symb) = &get_symb($request);
  799:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  800:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  801:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  802:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  803:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  804:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  805:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  806: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  807: 
  808:     my $result='<h3><span class="LC_info">&nbsp;'
  809: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  810: 	.'</span></h3>';
  811: 
  812:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  813: 
  814:     my %lt = ( 'multiple' =>
  815: 	       &mt("Please select a student or group of students before clicking on the Next button."),
  816: 	       'single'   =>
  817: 	       &mt("Please select the student before clicking on the Next button."),
  818: 	       );
  819:     %lt = &Apache::lonlocal::texthash(%lt);
  820:     $request->print(<<LISTJAVASCRIPT);
  821: <script type="text/javascript" language="javascript">
  822:     function checkSelect(checkBox) {
  823: 	var ctr=0;
  824: 	var sense="";
  825: 	if (checkBox.length > 1) {
  826: 	    for (var i=0; i<checkBox.length; i++) {
  827: 		if (checkBox[i].checked) {
  828: 		    ctr++;
  829: 		}
  830: 	    }
  831: 	    sense = '$lt{'multiple'}';
  832: 	} else {
  833: 	    if (checkBox.checked) {
  834: 		ctr = 1;
  835: 	    }
  836: 	    sense = '$lt{'single'}';
  837: 	}
  838: 	if (ctr == 0) {
  839: 	    alert(sense);
  840: 	    return false;
  841: 	}
  842: 	document.gradesub.submit();
  843:     }
  844: 
  845:     function reLoadList(formname) {
  846: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  847: 	formname.command.value = 'submission';
  848: 	formname.submit();
  849:     }
  850: </script>
  851: LISTJAVASCRIPT
  852: 
  853:     &commonJSfunctions($request);
  854:     $request->print($result);
  855: 
  856:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  857:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  858:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  859: 	"\n".$table;
  860: 	
  861:     $gradeTable .= 
  862: 	'&nbsp;<b>'.&mt('View Problem Text').': </b>'.
  863: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  864: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  865: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n";
  866:     $gradeTable .= 
  867: 	'&nbsp;<b>'.&mt('View Answer').': </b>'.
  868: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  869: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  870: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n";
  871: 
  872:     my $submission_options;
  873:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  874: 	$submission_options.=
  875: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  876:     }
  877:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  878:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  879:     $env{'form.Status'} = $saveStatus;
  880:     $submission_options.=
  881: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  882: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  883: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  884: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  885:     $gradeTable .= 
  886: 	'&nbsp;<b>'.&mt('Submissions').': </b>'.$submission_options.'<br />'."\n";
  887: 
  888:     $gradeTable .= 
  889:         '&nbsp;<b>'.&mt('Grading Increments').': </b>'.
  890: 	    '<select name="increment">'.
  891: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  892: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  893: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  894: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  895: 	    '</select>';
  896:     
  897:     $gradeTable .= 
  898:         &build_section_inputs().
  899: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  900: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  901: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  902: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  903: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  904: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  905: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  906: 
  907:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  908: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  909:     } else {
  910: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  911: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  912:     }
  913: 
  914:     $gradeTable.=&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.").'<br />'."\n".
  915: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  916: 
  917: # checkall buttons
  918:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  919:     $gradeTable.='<input type="button" '."\n".
  920: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  921: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  922:     $gradeTable.=&check_buttons();
  923:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  924:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  925:     $gradeTable.= &Apache::loncommon::start_data_table().
  926: 	&Apache::loncommon::start_data_table_header_row();
  927:     my $loop = 0;
  928:     while ($loop < 2) {
  929: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  930: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  931: 	if ($env{'form.showgrading'} eq 'yes' 
  932: 	    && $submitonly ne 'queued'
  933: 	    && $submitonly ne 'all') {
  934: 	    foreach my $part (sort(@$partlist)) {
  935: 		my $display_part=
  936: 		    &get_display_part((split(/_/,$part))[0],$symb);
  937: 		$gradeTable.=
  938: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  939: 	    }
  940: 	} elsif ($submitonly eq 'queued') {
  941: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  942: 	}
  943: 	$loop++;
  944: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  945:     }
  946:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  947: 
  948:     my $ctr = 0;
  949:     foreach my $student (sort 
  950: 			 {
  951: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  952: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  953: 			     }
  954: 			     return $a cmp $b;
  955: 			 }
  956: 			 (keys(%$fullname))) {
  957: 	my ($uname,$udom) = split(/:/,$student);
  958: 
  959: 	my %status = ();
  960: 
  961: 	if ($submitonly eq 'queued') {
  962: 	    my %queue_status = 
  963: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  964: 							$udom,$uname);
  965: 	    next if (!defined($queue_status{'gradingqueue'}));
  966: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  967: 	}
  968: 
  969: 	if ($env{'form.showgrading'} eq 'yes' 
  970: 	    && $submitonly ne 'queued'
  971: 	    && $submitonly ne 'all') {
  972: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  973: 	    my $submitted = 0;
  974: 	    my $graded = 0;
  975: 	    my $incorrect = 0;
  976: 	    foreach (keys(%status)) {
  977: 		$submitted = 1 if ($status{$_} ne 'nothing');
  978: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  979: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  980: 		
  981: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  982: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  983: 		    $submitted = 0;
  984: 		    my ($part)=split(/\./,$partid);
  985: 		    $gradeTable.='<input type="hidden" name="'.
  986: 			$student.':'.$part.':submitted_by" value="'.
  987: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  988: 		}
  989: 	    }
  990: 	    
  991: 	    next if (!$submitted && ($submitonly eq 'yes' ||
  992: 				     $submitonly eq 'incorrect' ||
  993: 				     $submitonly eq 'graded'));
  994: 	    next if (!$graded && ($submitonly eq 'graded'));
  995: 	    next if (!$incorrect && $submitonly eq 'incorrect');
  996: 	}
  997: 
  998: 	$ctr++;
  999: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1000:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1001: 	if ( $perm{'vgr'} eq 'F' ) {
 1002: 	    if ($ctr%2 ==1) {
 1003: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1004: 	    }
 1005: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1006:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1007:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1008: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1009: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1010: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1011: 
 1012: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1013: 		foreach (sort(keys(%status))) {
 1014: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1015: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1016: 		}
 1017: 	    }
 1018: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1019: 	    if ($ctr%2 ==0) {
 1020: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1021: 	    }
 1022: 	}
 1023:     }
 1024:     if ($ctr%2 ==1) {
 1025: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1026: 	    if ($env{'form.showgrading'} eq 'yes' 
 1027: 		&& $submitonly ne 'queued'
 1028: 		&& $submitonly ne 'all') {
 1029: 		foreach (@$partlist) {
 1030: 		    $gradeTable.='<td>&nbsp;</td>';
 1031: 		}
 1032: 	    } elsif ($submitonly eq 'queued') {
 1033: 		$gradeTable.='<td>&nbsp;</td>';
 1034: 	    }
 1035: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1036:     }
 1037: 
 1038:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1039: 	'<input type="button" '.
 1040: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1041: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1042:     if ($ctr == 0) {
 1043: 	my $num_students=(scalar(keys(%$fullname)));
 1044: 	if ($num_students eq 0) {
 1045: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1046: 	} else {
 1047: 	    my $submissions='submissions';
 1048: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1049: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1050: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1051: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1052: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1053: 		    $num_students).
 1054: 		'</span><br />';
 1055: 	}
 1056:     } elsif ($ctr == 1) {
 1057: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1058:     }
 1059:     $gradeTable.=&show_grading_menu_form($symb);
 1060:     $request->print($gradeTable);
 1061:     return '';
 1062: }
 1063: 
 1064: #---- Called from the listStudents routine
 1065: 
 1066: sub check_script {
 1067:     my ($form, $type)=@_;
 1068:     my $chkallscript='<script type="text/javascript">
 1069:     function checkall() {
 1070:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1071:             ele = document.forms.'.$form.'.elements[i];
 1072:             if (ele.name == "'.$type.'") {
 1073:             document.forms.'.$form.'.elements[i].checked=true;
 1074:                                        }
 1075:         }
 1076:     }
 1077: 
 1078:     function checksec() {
 1079:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1080:             ele = document.forms.'.$form.'.elements[i];
 1081:            string = document.forms.'.$form.'.chksec.value;
 1082:            if
 1083:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1084:               document.forms.'.$form.'.elements[i].checked=true;
 1085:             }
 1086:         }
 1087:     }
 1088: 
 1089: 
 1090:     function uncheckall() {
 1091:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1092:             ele = document.forms.'.$form.'.elements[i];
 1093:             if (ele.name == "'.$type.'") {
 1094:             document.forms.'.$form.'.elements[i].checked=false;
 1095:                                        }
 1096:         }
 1097:     }
 1098: 
 1099: </script>'."\n";
 1100:     return $chkallscript;
 1101: }
 1102: 
 1103: sub check_buttons {
 1104:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1105:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1106:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1107:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1108:     return $buttons;
 1109: }
 1110: 
 1111: #     Displays the submissions for one student or a group of students
 1112: sub processGroup {
 1113:     my ($request)  = shift;
 1114:     my $ctr        = 0;
 1115:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1116:     my $total      = scalar(@stuchecked)-1;
 1117: 
 1118:     foreach my $student (@stuchecked) {
 1119: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1120: 	$env{'form.student'}        = $uname;
 1121: 	$env{'form.userdom'}        = $udom;
 1122: 	$env{'form.fullname'}       = $fullname;
 1123: 	&submission($request,$ctr,$total);
 1124: 	$ctr++;
 1125:     }
 1126:     return '';
 1127: }
 1128: 
 1129: #------------------------------------------------------------------------------------
 1130: #
 1131: #-------------------------- Next few routines handles grading by student, essentially
 1132: #                           handles essay response type problem/part
 1133: #
 1134: #--- Javascript to handle the submission page functionality ---
 1135: sub sub_page_js {
 1136:     my $request = shift;
 1137: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1138:     $request->print(<<SUBJAVASCRIPT);
 1139: <script type="text/javascript" language="javascript">
 1140:     function updateRadio(formname,id,weight) {
 1141: 	var gradeBox = formname["GD_BOX"+id];
 1142: 	var radioButton = formname["RADVAL"+id];
 1143: 	var oldpts = formname["oldpts"+id].value;
 1144: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1145: 	gradeBox.value = pts;
 1146: 	var resetbox = false;
 1147: 	if (isNaN(pts) || pts < 0) {
 1148: 	    alert("$alertmsg"+pts);
 1149: 	    for (var i=0; i<radioButton.length; i++) {
 1150: 		if (radioButton[i].checked) {
 1151: 		    gradeBox.value = i;
 1152: 		    resetbox = true;
 1153: 		}
 1154: 	    }
 1155: 	    if (!resetbox) {
 1156: 		formtextbox.value = "";
 1157: 	    }
 1158: 	    return;
 1159: 	}
 1160: 
 1161: 	if (pts > weight) {
 1162: 	    var resp = confirm("You entered a value ("+pts+
 1163: 			       ") greater than the weight for the part. Accept?");
 1164: 	    if (resp == false) {
 1165: 		gradeBox.value = oldpts;
 1166: 		return;
 1167: 	    }
 1168: 	}
 1169: 
 1170: 	for (var i=0; i<radioButton.length; i++) {
 1171: 	    radioButton[i].checked=false;
 1172: 	    if (pts == i && pts != "") {
 1173: 		radioButton[i].checked=true;
 1174: 	    }
 1175: 	}
 1176: 	updateSelect(formname,id);
 1177: 	formname["stores"+id].value = "0";
 1178:     }
 1179: 
 1180:     function writeBox(formname,id,pts) {
 1181: 	var gradeBox = formname["GD_BOX"+id];
 1182: 	if (checkSolved(formname,id) == 'update') {
 1183: 	    gradeBox.value = pts;
 1184: 	} else {
 1185: 	    var oldpts = formname["oldpts"+id].value;
 1186: 	    gradeBox.value = oldpts;
 1187: 	    var radioButton = formname["RADVAL"+id];
 1188: 	    for (var i=0; i<radioButton.length; i++) {
 1189: 		radioButton[i].checked=false;
 1190: 		if (i == oldpts) {
 1191: 		    radioButton[i].checked=true;
 1192: 		}
 1193: 	    }
 1194: 	}
 1195: 	formname["stores"+id].value = "0";
 1196: 	updateSelect(formname,id);
 1197: 	return;
 1198:     }
 1199: 
 1200:     function clearRadBox(formname,id) {
 1201: 	if (checkSolved(formname,id) == 'noupdate') {
 1202: 	    updateSelect(formname,id);
 1203: 	    return;
 1204: 	}
 1205: 	gradeSelect = formname["GD_SEL"+id];
 1206: 	for (var i=0; i<gradeSelect.length; i++) {
 1207: 	    if (gradeSelect[i].selected) {
 1208: 		var selectx=i;
 1209: 	    }
 1210: 	}
 1211: 	var stores = formname["stores"+id];
 1212: 	if (selectx == stores.value) { return };
 1213: 	var gradeBox = formname["GD_BOX"+id];
 1214: 	gradeBox.value = "";
 1215: 	var radioButton = formname["RADVAL"+id];
 1216: 	for (var i=0; i<radioButton.length; i++) {
 1217: 	    radioButton[i].checked=false;
 1218: 	}
 1219: 	stores.value = selectx;
 1220:     }
 1221: 
 1222:     function checkSolved(formname,id) {
 1223: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1224: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1225: 	    if (!reply) {return "noupdate";}
 1226: 	    formname.overRideScore.value = 'yes';
 1227: 	}
 1228: 	return "update";
 1229:     }
 1230: 
 1231:     function updateSelect(formname,id) {
 1232: 	formname["GD_SEL"+id][0].selected = true;
 1233: 	return;
 1234:     }
 1235: 
 1236: //=========== Check that a point is assigned for all the parts  ============
 1237:     function checksubmit(formname,val,total,parttot) {
 1238: 	formname.gradeOpt.value = val;
 1239: 	if (val == "Save & Next") {
 1240: 	    for (i=0;i<=total;i++) {
 1241: 		for (j=0;j<parttot;j++) {
 1242: 		    var partid = formname["partid"+i+"_"+j].value;
 1243: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1244: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1245: 			if (points == "") {
 1246: 			    var name = formname["name"+i].value;
 1247: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1248: 			    var resp = confirm("You did not assign a score for "+studentID+
 1249: 					       ", part "+partid+". Continue?");
 1250: 			    if (resp == false) {
 1251: 				formname["GD_BOX"+i+"_"+partid].focus();
 1252: 				return false;
 1253: 			    }
 1254: 			}
 1255: 		    }
 1256: 		    
 1257: 		}
 1258: 	    }
 1259: 	    
 1260: 	}
 1261: 	if (val == "Grade Student") {
 1262: 	    formname.showgrading.value = "yes";
 1263: 	    if (formname.Status.value == "") {
 1264: 		formname.Status.value = "Active";
 1265: 	    }
 1266: 	    formname.studentNo.value = total;
 1267: 	}
 1268: 	formname.submit();
 1269:     }
 1270: 
 1271: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1272:     function checkSubmitPage(formname,total) {
 1273: 	noscore = new Array(100);
 1274: 	var ptr = 0;
 1275: 	for (i=1;i<total;i++) {
 1276: 	    var partid = formname["q_"+i].value;
 1277: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1278: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1279: 		var status = formname["solved"+i+"_"+partid].value;
 1280: 		if (points == "" && status != "correct_by_student") {
 1281: 		    noscore[ptr] = i;
 1282: 		    ptr++;
 1283: 		}
 1284: 	    }
 1285: 	}
 1286: 	if (ptr != 0) {
 1287: 	    var sense = ptr == 1 ? ": " : "s: ";
 1288: 	    var prolist = "";
 1289: 	    if (ptr == 1) {
 1290: 		prolist = noscore[0];
 1291: 	    } else {
 1292: 		var i = 0;
 1293: 		while (i < ptr-1) {
 1294: 		    prolist += noscore[i]+", ";
 1295: 		    i++;
 1296: 		}
 1297: 		prolist += "and "+noscore[i];
 1298: 	    }
 1299: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1300: 	    if (resp == false) {
 1301: 		return false;
 1302: 	    }
 1303: 	}
 1304: 
 1305: 	formname.submit();
 1306:     }
 1307: </script>
 1308: SUBJAVASCRIPT
 1309: }
 1310: 
 1311: #--- javascript for essay type problem --
 1312: sub sub_page_kw_js {
 1313:     my $request = shift;
 1314:     my $iconpath = $request->dir_config('lonIconsURL');
 1315:     &commonJSfunctions($request);
 1316: 
 1317:     my $inner_js_msg_central=<<INNERJS;
 1318:     <script text="text/javascript">
 1319:     function checkInput() {
 1320:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1321:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1322:       var usrctr = document.msgcenter.usrctr.value;
 1323:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1324:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1325: 
 1326:       var msgchk = "";
 1327:       if (document.msgcenter.subchk.checked) {
 1328:          msgchk = "msgsub,";
 1329:       }
 1330:       var includemsg = 0;
 1331:       for (var i=1; i<=nmsg; i++) {
 1332:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1333:           var frmmsg = document.msgcenter["msg"+i];
 1334:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1335:           var showflg = opener.document.SCORE["shownOnce"+i];
 1336:           showflg.value = "1";
 1337:           var chkbox = document.msgcenter["msgn"+i];
 1338:           if (chkbox.checked) {
 1339:              msgchk += "savemsg"+i+",";
 1340:              includemsg = 1;
 1341:           }
 1342:       }
 1343:       if (document.msgcenter.newmsgchk.checked) {
 1344:          msgchk += "newmsg"+usrctr;
 1345:          includemsg = 1;
 1346:       }
 1347:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1348:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1349:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1350:       includemsg.value = msgchk;
 1351: 
 1352:       self.close()
 1353: 
 1354:     }
 1355:     </script>
 1356: INNERJS
 1357: 
 1358:     my $inner_js_highlight_central=<<INNERJS;
 1359:  <script type="text/javascript">
 1360:     function updateChoice(flag) {
 1361:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1362:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1363:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1364:       opener.document.SCORE.refresh.value = "on";
 1365:       if (opener.document.SCORE.keywords.value!=""){
 1366:          opener.document.SCORE.submit();
 1367:       }
 1368:       self.close()
 1369:     }
 1370: </script>
 1371: INNERJS
 1372: 
 1373:     my $start_page_msg_central = 
 1374:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1375: 				       {'js_ready'  => 1,
 1376: 					'only_body' => 1,
 1377: 					'bgcolor'   =>'#FFFFFF',});
 1378:     my $end_page_msg_central = 
 1379: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1380: 
 1381: 
 1382:     my $start_page_highlight_central = 
 1383:         &Apache::loncommon::start_page('Highlight Central',
 1384: 				       $inner_js_highlight_central,
 1385: 				       {'js_ready'  => 1,
 1386: 					'only_body' => 1,
 1387: 					'bgcolor'   =>'#FFFFFF',});
 1388:     my $end_page_highlight_central = 
 1389: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1390: 
 1391:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1392:     $docopen=~s/^document\.//;
 1393:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1394:     $request->print(<<SUBJAVASCRIPT);
 1395: <script type="text/javascript" language="javascript">
 1396: 
 1397: //===================== Show list of keywords ====================
 1398:   function keywords(formname) {
 1399:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1400:     if (nret==null) return;
 1401:     formname.keywords.value = nret;
 1402: 
 1403:     if (formname.keywords.value != "") {
 1404: 	formname.refresh.value = "on";
 1405: 	formname.submit();
 1406:     }
 1407:     return;
 1408:   }
 1409: 
 1410: //===================== Script to view submitted by ==================
 1411:   function viewSubmitter(submitter) {
 1412:     document.SCORE.refresh.value = "on";
 1413:     document.SCORE.NCT.value = "1";
 1414:     document.SCORE.unamedom0.value = submitter;
 1415:     document.SCORE.submit();
 1416:     return;
 1417:   }
 1418: 
 1419: //===================== Script to add keyword(s) ==================
 1420:   function getSel() {
 1421:     if (document.getSelection) txt = document.getSelection();
 1422:     else if (document.selection) txt = document.selection.createRange().text;
 1423:     else return;
 1424:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1425:     if (cleantxt=="") {
 1426: 	alert("$alertmsg");
 1427: 	return;
 1428:     }
 1429:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1430:     if (nret==null) return;
 1431:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1432:     if (document.SCORE.keywords.value != "") {
 1433: 	document.SCORE.refresh.value = "on";
 1434: 	document.SCORE.submit();
 1435:     }
 1436:     return;
 1437:   }
 1438: 
 1439: //====================== Script for composing message ==============
 1440:    // preload images
 1441:    img1 = new Image();
 1442:    img1.src = "$iconpath/mailbkgrd.gif";
 1443:    img2 = new Image();
 1444:    img2.src = "$iconpath/mailto.gif";
 1445: 
 1446:   function msgCenter(msgform,usrctr,fullname) {
 1447:     var Nmsg  = msgform.savemsgN.value;
 1448:     savedMsgHeader(Nmsg,usrctr,fullname);
 1449:     var subject = msgform.msgsub.value;
 1450:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1451:     re = /msgsub/;
 1452:     var shwsel = "";
 1453:     if (re.test(msgchk)) { shwsel = "checked" }
 1454:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1455:     displaySubject(checkEntities(subject),shwsel);
 1456:     for (var i=1; i<=Nmsg; i++) {
 1457: 	var testmsg = "savemsg"+i+",";
 1458: 	re = new RegExp(testmsg,"g");
 1459: 	shwsel = "";
 1460: 	if (re.test(msgchk)) { shwsel = "checked" }
 1461: 	var message = document.SCORE["savemsg"+i].value;
 1462: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1463: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1464: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1465:     }
 1466:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1467:     shwsel = "";
 1468:     re = /newmsg/;
 1469:     if (re.test(msgchk)) { shwsel = "checked" }
 1470:     newMsg(newmsg,shwsel);
 1471:     msgTail(); 
 1472:     return;
 1473:   }
 1474: 
 1475:   function checkEntities(strx) {
 1476:     if (strx.length == 0) return strx;
 1477:     var orgStr = ["&", "<", ">", '"']; 
 1478:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1479:     var counter = 0;
 1480:     while (counter < 4) {
 1481: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1482: 	counter++;
 1483:     }
 1484:     return strx;
 1485:   }
 1486: 
 1487:   function strReplace(strx, orgStr, newStr) {
 1488:     return strx.split(orgStr).join(newStr);
 1489:   }
 1490: 
 1491:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1492:     var height = 70*Nmsg+250;
 1493:     var scrollbar = "no";
 1494:     if (height > 600) {
 1495: 	height = 600;
 1496: 	scrollbar = "yes";
 1497:     }
 1498:     var xpos = (screen.width-600)/2;
 1499:     xpos = (xpos < 0) ? '0' : xpos;
 1500:     var ypos = (screen.height-height)/2-30;
 1501:     ypos = (ypos < 0) ? '0' : ypos;
 1502: 
 1503:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1504:     pWin.focus();
 1505:     pDoc = pWin.document;
 1506:     pDoc.$docopen;
 1507:     pDoc.write('$start_page_msg_central');
 1508: 
 1509:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1510:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1511:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1512: 
 1513:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1514:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1515:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1516: }
 1517:     function displaySubject(msg,shwsel) {
 1518:     pDoc = pWin.document;
 1519:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1520:     pDoc.write("<td>Subject<\\/td>");
 1521:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1522:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1523: }
 1524: 
 1525:   function displaySavedMsg(ctr,msg,shwsel) {
 1526:     pDoc = pWin.document;
 1527:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1528:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1529:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1530:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1531: }
 1532: 
 1533:   function newMsg(newmsg,shwsel) {
 1534:     pDoc = pWin.document;
 1535:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1536:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1537:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1538:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1539: }
 1540: 
 1541:   function msgTail() {
 1542:     pDoc = pWin.document;
 1543:     pDoc.write("<\\/table>");
 1544:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1545:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1546:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1547:     pDoc.write("<\\/form>");
 1548:     pDoc.write('$end_page_msg_central');
 1549:     pDoc.close();
 1550: }
 1551: 
 1552: //====================== Script for keyword highlight options ==============
 1553:   function kwhighlight() {
 1554:     var kwclr    = document.SCORE.kwclr.value;
 1555:     var kwsize   = document.SCORE.kwsize.value;
 1556:     var kwstyle  = document.SCORE.kwstyle.value;
 1557:     var redsel = "";
 1558:     var grnsel = "";
 1559:     var blusel = "";
 1560:     if (kwclr=="red")   {var redsel="checked"};
 1561:     if (kwclr=="green") {var grnsel="checked"};
 1562:     if (kwclr=="blue")  {var blusel="checked"};
 1563:     var sznsel = "";
 1564:     var sz1sel = "";
 1565:     var sz2sel = "";
 1566:     if (kwsize=="0")  {var sznsel="checked"};
 1567:     if (kwsize=="+1") {var sz1sel="checked"};
 1568:     if (kwsize=="+2") {var sz2sel="checked"};
 1569:     var synsel = "";
 1570:     var syisel = "";
 1571:     var sybsel = "";
 1572:     if (kwstyle=="")    {var synsel="checked"};
 1573:     if (kwstyle=="<i>") {var syisel="checked"};
 1574:     if (kwstyle=="<b>") {var sybsel="checked"};
 1575:     highlightCentral();
 1576:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1577:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1578:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1579:     highlightend();
 1580:     return;
 1581:   }
 1582: 
 1583:   function highlightCentral() {
 1584: //    if (window.hwdWin) window.hwdWin.close();
 1585:     var xpos = (screen.width-400)/2;
 1586:     xpos = (xpos < 0) ? '0' : xpos;
 1587:     var ypos = (screen.height-330)/2-30;
 1588:     ypos = (ypos < 0) ? '0' : ypos;
 1589: 
 1590:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1591:     hwdWin.focus();
 1592:     var hDoc = hwdWin.document;
 1593:     hDoc.$docopen;
 1594:     hDoc.write('$start_page_highlight_central');
 1595:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1596:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1597: 
 1598:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1599:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1600:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1601:   }
 1602: 
 1603:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1604:     var hDoc = hwdWin.document;
 1605:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1606:     hDoc.write("<td align=\\"left\\">");
 1607:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1608:     hDoc.write("<td align=\\"left\\">");
 1609:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1610:     hDoc.write("<td align=\\"left\\">");
 1611:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1612:     hDoc.write("<\\/tr>");
 1613:   }
 1614: 
 1615:   function highlightend() { 
 1616:     var hDoc = hwdWin.document;
 1617:     hDoc.write("<\\/table>");
 1618:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1619:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1620:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1621:     hDoc.write("<\\/form>");
 1622:     hDoc.write('$end_page_highlight_central');
 1623:     hDoc.close();
 1624:   }
 1625: 
 1626: </script>
 1627: SUBJAVASCRIPT
 1628: }
 1629: 
 1630: sub get_increment {
 1631:     my $increment = $env{'form.increment'};
 1632:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1633:         $increment != .1) {
 1634:         $increment = 1;
 1635:     }
 1636:     return $increment;
 1637: }
 1638: 
 1639: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1640: sub gradeBox {
 1641:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1642:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1643: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1644:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1645:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1646:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1647:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1648:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1649: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1650:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1651:     my $display_part= &get_display_part($partid,$symb);
 1652:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1653: 				       [$partid]);
 1654:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1655:     if ($last_resets{$partid}) {
 1656:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1657:     }
 1658:     $result.='<table border="0"><tr>';
 1659:     my $ctr = 0;
 1660:     my $thisweight = 0;
 1661:     my $increment = &get_increment();
 1662: 
 1663:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1664:     while ($thisweight<=$wgt) {
 1665: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1666: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1667: 	    $thisweight.')" value="'.$thisweight.'" '.
 1668: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1669: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1670:         $thisweight += $increment;
 1671: 	$ctr++;
 1672:     }
 1673:     $radio.='</tr></table>';
 1674: 
 1675:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1676: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1677: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1678: 	$wgt.')" /></td>'."\n";
 1679:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1680: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1681: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1682:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1683: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1684:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1685: 	$line.='<option></option>'.
 1686: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1687:     } else {
 1688: 	$line.='<option selected="selected"></option>'.
 1689: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1690:     }
 1691:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1692: 
 1693: 
 1694: 	#&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);
 1695:     $result .= 
 1696: 	    '<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>'.
 1697:     
 1698:     $result.='</tr></table>'."\n";
 1699:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1700: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1701: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1702: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1703:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1704:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1705:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1706:         $aggtries.'" />'."\n";
 1707:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1708:     return $result;
 1709: }
 1710: 
 1711: sub handback_box {
 1712:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1713:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1714:     my (@respids);
 1715:      my @part_response_id = &flatten_responseType($responseType);
 1716:     foreach my $part_response_id (@part_response_id) {
 1717:     	my ($part,$resp) = @{ $part_response_id };
 1718:         if ($part eq $partid) {
 1719:             push(@respids,$resp);
 1720:         }
 1721:     }
 1722:     my $result;
 1723:     foreach my $respid (@respids) {
 1724: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1725: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1726: 	next if (!@$files);
 1727: 	my $file_counter = 1;
 1728: 	foreach my $file (@$files) {
 1729: 	    if ($file =~ /\/portfolio\//) {
 1730:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1731:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1732:     	        $file_disp = "$name.$ext";
 1733:     	        $file = $file_path.$file_disp;
 1734:     	        $result.=&mt('Return commented version of [_1] to student.',
 1735:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1736:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1737:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1738:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1739:     	        $file_counter++;
 1740: 	    }
 1741: 	}
 1742:     }
 1743:     return $result;    
 1744: }
 1745: 
 1746: sub show_problem {
 1747:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1748:     my $rendered;
 1749:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1750:     &Apache::lonxml::remember_problem_counter();
 1751:     if ($mode eq 'both' or $mode eq 'text') {
 1752: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1753: 						       $env{'request.course.id'},
 1754: 						       undef,\%form);
 1755:     }
 1756:     if ($removeform) {
 1757: 	$rendered=~s|<form(.*?)>||g;
 1758: 	$rendered=~s|</form>||g;
 1759: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1760:     }
 1761:     my $companswer;
 1762:     if ($mode eq 'both' or $mode eq 'answer') {
 1763: 	&Apache::lonxml::restore_problem_counter();
 1764: 	$companswer=
 1765: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1766: 						    $env{'request.course.id'},
 1767: 						    %form);
 1768:     }
 1769:     if ($removeform) {
 1770: 	$companswer=~s|<form(.*?)>||g;
 1771: 	$companswer=~s|</form>||g;
 1772: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1773:     }
 1774:     $rendered=
 1775: 	'<div class="LC_grade_show_problem_header">'.
 1776: 	&mt('View of the problem').
 1777: 	'</div><div class="LC_grade_show_problem_problem">'.
 1778: 	$rendered.
 1779: 	'</div>';
 1780:     $companswer=
 1781: 	'<div class="LC_grade_show_problem_header">'.
 1782: 	&mt('Correct answer').
 1783: 	'</div><div class="LC_grade_show_problem_problem">'.
 1784: 	$companswer.
 1785: 	'</div>';
 1786:     my $result;
 1787:     if ($mode eq 'both') {
 1788: 	$result=$rendered.$companswer;
 1789:     } elsif ($mode eq 'text') {
 1790: 	$result=$rendered;
 1791:     } elsif ($mode eq 'answer') {
 1792: 	$result=$companswer;
 1793:     }
 1794:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1795:     return $result;
 1796: }
 1797: 
 1798: sub files_exist {
 1799:     my ($r, $symb) = @_;
 1800:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1801: 
 1802:     foreach my $student (@students) {
 1803:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1804:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1805: 					      $udom,$uname);
 1806:         my ($string,$timestamp)= &get_last_submission(\%record);
 1807:         foreach my $submission (@$string) {
 1808:             my ($partid,$respid) =
 1809: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1810:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1811: 					   \%record);
 1812:             return 1 if (@$files);
 1813:         }
 1814:     }
 1815:     return 0;
 1816: }
 1817: 
 1818: sub download_all_link {
 1819:     my ($r,$symb) = @_;
 1820:     my $all_students = 
 1821: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1822: 
 1823:     my $parts =
 1824: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1825: 
 1826:     my $identifier = &Apache::loncommon::get_cgi_id();
 1827:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1828:                              'cgi.'.$identifier.'.symb' => $symb,
 1829:                              'cgi.'.$identifier.'.parts' => $parts,});
 1830:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1831: 	      &mt('Download All Submitted Documents').'</a>');
 1832:     return
 1833: }
 1834: 
 1835: sub build_section_inputs {
 1836:     my $section_inputs;
 1837:     if ($env{'form.section'} eq '') {
 1838:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1839:     } else {
 1840:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1841:         foreach my $section (@sections) {
 1842:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1843:         }
 1844:     }
 1845:     return $section_inputs;
 1846: }
 1847: 
 1848: # --------------------------- show submissions of a student, option to grade 
 1849: sub submission {
 1850:     my ($request,$counter,$total) = @_;
 1851:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1852:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1853:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1854:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1855:     my $symb = &get_symb($request); 
 1856:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1857: 
 1858:     if (!&canview($usec)) {
 1859: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1860: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1861: 			$env{'request.course.id'}.')</span>');
 1862: 	$request->print(&show_grading_menu_form($symb));
 1863: 	return;
 1864:     }
 1865: 
 1866:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1867:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1868:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1869:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1870:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1871: 	'" src="'.$request->dir_config('lonIconsURL').
 1872: 	'/check.gif" height="16" border="0" />';
 1873: 
 1874:     my %old_essays;
 1875:     # header info
 1876:     if ($counter == 0) {
 1877: 	&sub_page_js($request);
 1878: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1879: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1880: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1881: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1882: 	    &download_all_link($request, $symb);
 1883: 	}
 1884: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1885: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1886: 
 1887: 	# option to display problem, only once else it cause problems 
 1888:         # with the form later since the problem has a form.
 1889: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1890: 	    my $mode;
 1891: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1892: 		$mode='both';
 1893: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1894: 		$mode='text';
 1895: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1896: 		$mode='answer';
 1897: 	    }
 1898: 	    &Apache::lonxml::clear_problem_counter();
 1899: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1900: 	}
 1901: 
 1902: 	# kwclr is the only variable that is guaranteed to be non blank 
 1903:         # if this subroutine has been called once.
 1904: 	my %keyhash = ();
 1905: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1906: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1907: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1908: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1909: 
 1910: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1911: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1912: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1913: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1914: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1915: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1916: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1917: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1918: 	}
 1919: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1920: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1921: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1922: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1923: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1924: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1925: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1926: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1927: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1928: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1929: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1930: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1931: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1932: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1933: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1934: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1935: 			&build_section_inputs().
 1936: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1937: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1938: 			'<input type="hidden" name="NCT"'.
 1939: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1940: 	if ($env{'form.handgrade'} eq 'yes') {
 1941: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1942: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1943: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1944: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1945: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1946: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1947: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1948: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1949: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1950: 	    }
 1951: 	}
 1952: 	
 1953: 	my ($cts,$prnmsg) = (1,'');
 1954: 	while ($cts <= $env{'form.savemsgN'}) {
 1955: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1956: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1957: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1958: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1959: 		'" />'."\n".
 1960: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1961: 	    $cts++;
 1962: 	}
 1963: 	$request->print($prnmsg);
 1964: 
 1965: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1966: #
 1967: # Print out the keyword options line
 1968: #
 1969: 	    $request->print(<<KEYWORDS);
 1970: &nbsp;<b>Keyword Options:</b>&nbsp;
 1971: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1972: <a href="#" onMouseDown="javascript:getSel(); return false"
 1973:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1974: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1975: KEYWORDS
 1976: #
 1977: # Load the other essays for similarity check
 1978: #
 1979:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1980: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1981: 	    $apath=&escape($apath);
 1982: 	    $apath=~s/\W/\_/gs;
 1983: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1984:         }
 1985:     }
 1986: 
 1987: # This is where output for one specific student would start
 1988:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 1989:     $request->print("\n\n".
 1990:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 1991: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 1992: 		    '<div class="LC_grade_show_user_body">'."\n");
 1993: 
 1994:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 1995: 	my $mode;
 1996: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 1997: 	    $mode='both';
 1998: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 1999: 	    $mode='text';
 2000: 	} elsif ($env{'form.vAns'} eq 'all') {
 2001: 	    $mode='answer';
 2002: 	}
 2003: 	&Apache::lonxml::clear_problem_counter();
 2004: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2005:     }
 2006: 
 2007:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2008:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2009: 
 2010:     # Display student info
 2011:     $request->print(($counter == 0 ? '' : '<br />'));
 2012:     my $result='<div class="LC_grade_submissions">';
 2013:     
 2014:     $result.='<div class="LC_grade_submissions_header">';
 2015:     $result.= &mt('Submissions');
 2016:     $result.='<input type="hidden" name="name'.$counter.
 2017: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2018:     if ($env{'form.handgrade'} eq 'no') {
 2019: 	$result.='<span class="LC_grade_check_note">'.
 2020: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2021: 
 2022:     }
 2023: 
 2024: 
 2025: 
 2026:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2027:     my $fullname;
 2028:     my $col_fullnames = [];
 2029:     if ($env{'form.handgrade'} eq 'yes') {
 2030: 	(my $sub_result,$fullname,$col_fullnames)=
 2031: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2032: 				 $counter);
 2033: 	$result.=$sub_result;
 2034:     }
 2035:     $request->print($result."\n");
 2036:     $request->print('</div>'."\n");
 2037:     # print student answer/submission
 2038:     # Options are (1) Handgaded submission only
 2039:     #             (2) Last submission, includes submission that is not handgraded 
 2040:     #                  (for multi-response type part)
 2041:     #             (3) Last submission plus the parts info
 2042:     #             (4) The whole record for this student
 2043:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2044: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2045: 	
 2046: 	my $lastsubonly;
 2047: 
 2048: 	if ($$timestamp eq '') {
 2049: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2050: 	} else {
 2051: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2052: 
 2053: 	    my %seenparts;
 2054: 	    my @part_response_id = &flatten_responseType($responseType);
 2055: 	    foreach my $part (@part_response_id) {
 2056: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2057: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2058: 
 2059: 		my ($partid,$respid) = @{ $part };
 2060: 		my $display_part=&get_display_part($partid,$symb);
 2061: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2062: 		    if (exists($seenparts{$partid})) { next; }
 2063: 		    $seenparts{$partid}=1;
 2064: 		    my $submitby='<b>Part:</b> '.$display_part.
 2065: 			' <b>Collaborative submission by:</b> '.
 2066: 			'<a href="javascript:viewSubmitter(\''.
 2067: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2068: 			'\');" target="_self">'.
 2069: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2070: 		    $request->print($submitby);
 2071: 		    next;
 2072: 		}
 2073: 		my $responsetype = $responseType->{$partid}->{$respid};
 2074: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2075: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2076: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2077: 			' )</span>&nbsp; &nbsp;'.
 2078: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2079: 		    next;
 2080: 		}
 2081: 		foreach my $submission (@$string) {
 2082: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2083: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2084: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2085: 		    # Similarity check
 2086: 		    my $similar='';
 2087: 		    if($env{'form.checkPlag'}){
 2088: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2089: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2090: 			if ($osim) {
 2091: 			    $osim=int($osim*100.0);
 2092: 			    my %old_course_desc = 
 2093: 				&Apache::lonnet::coursedescription($ocrsid,
 2094: 								   {'one_time' => 1});
 2095: 
 2096: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2097: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2098: 				    $osim,
 2099: 				    &Apache::loncommon::plainname($oname,$odom),
 2100: 				    $oname,$odom,
 2101: 				    $old_course_desc{'description'},
 2102: 				    $old_course_desc{'num'},
 2103: 				    $old_course_desc{'domain'}).
 2104: 				'</span></h3><blockquote><i>'.
 2105: 				&keywords_highlight($oessay).
 2106: 				'</i></blockquote><hr />';
 2107: 			}
 2108: 		    }
 2109: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2110: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2111: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2112: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2113: 			my $display_part=&get_display_part($partid,$symb);
 2114: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2115: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2116: 			    ' )</span>&nbsp; &nbsp;';
 2117: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2118: 			if (@$files) {
 2119: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2120: 			    my $file_counter = 0;
 2121: 			    foreach my $file (@$files) {
 2122: 			        $file_counter++;
 2123: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2124: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2125: 			    }
 2126: 			    $lastsubonly.='<br />';
 2127: 			}
 2128: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2129: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2130: 					 $respid,\%record,$order);
 2131: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2132: 			$lastsubonly.='</div>';
 2133: 		    }
 2134: 		}
 2135: 	    }
 2136: 	    $lastsubonly.='</div>'."\n";
 2137: 	}
 2138: 	$request->print($lastsubonly);
 2139:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2140: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2141: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2142:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2143: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2144: 								 $env{'request.course.id'},
 2145: 								 $last,'.submission',
 2146: 								 'Apache::grades::keywords_highlight'));
 2147:     }
 2148: 
 2149:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2150: 	.$udom.'" />'."\n");
 2151:     # return if view submission with no grading option
 2152:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2153: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2154: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2155: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2156: 	$toGrade.='</div>'."\n";
 2157: 	if (($env{'form.command'} eq 'submission') || 
 2158: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2159: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2160: 	}
 2161: 	$request->print($toGrade);
 2162: 	return;
 2163:     } else {
 2164: 	$request->print('</div>'."\n");
 2165:     }
 2166: 
 2167:     # essay grading message center
 2168:     if ($env{'form.handgrade'} eq 'yes') {
 2169: 	my $result='<div class="LC_grade_message_center">';
 2170:     
 2171: 	$result.='<div class="LC_grade_message_center_header">'.
 2172: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2173: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2174: 	my $msgfor = $givenn.' '.$lastname;
 2175: 	if (scalar(@$col_fullnames) > 0) {
 2176: 	    my $lastone = pop(@$col_fullnames);
 2177: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2178: 	}
 2179: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2180: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2181: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2182: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2183: 	    ',\''.$msgfor.'\');" target="_self">'.
 2184: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2185: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2186: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2187: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2188: 	    '<br />&nbsp;('.
 2189: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2190: 	$result.='</div></div>';
 2191: 	$request->print($result);
 2192:     }
 2193: 
 2194:     my %seen = ();
 2195:     my @partlist;
 2196:     my @gradePartRespid;
 2197:     my @part_response_id = &flatten_responseType($responseType);
 2198:     $request->print('<div class="LC_grade_assign">'.
 2199: 		    
 2200: 		    '<div class="LC_grade_assign_header">'.
 2201: 		    &mt('Assign Grades').'</div>'.
 2202: 		    '<div class="LC_grade_assign_body">');
 2203:     foreach my $part_response_id (@part_response_id) {
 2204:     	my ($partid,$respid) = @{ $part_response_id };
 2205: 	my $part_resp = join('_',@{ $part_response_id });
 2206: 	next if ($seen{$partid} > 0);
 2207: 	$seen{$partid}++;
 2208: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2209: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2210: 	push(@partlist,$partid);
 2211: 	push(@gradePartRespid,$partid.'.'.$respid);
 2212: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2213:     }
 2214:     $request->print('</div></div>');
 2215: 
 2216:     $request->print('<div class="LC_grade_info_links">');
 2217:     if ($perm{'vgr'}) {
 2218: 	$request->print(
 2219: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2220: 						   $uname,$udom,'check'));
 2221:     }
 2222:     if ($perm{'opa'}) {
 2223: 	$request->print(
 2224: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2225: 					 $uname,$udom,$symb,'check'));
 2226:     }
 2227:     $request->print('</div>');
 2228: 
 2229:     $result='<input type="hidden" name="partlist'.$counter.
 2230: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2231:     $result.='<input type="hidden" name="gradePartRespid'.
 2232: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2233:     my $ctr = 0;
 2234:     while ($ctr < scalar(@partlist)) {
 2235: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2236: 	    $partlist[$ctr].'" />'."\n";
 2237: 	$ctr++;
 2238:     }
 2239:     $request->print($result.''."\n");
 2240: 
 2241: # Done with printing info for one student
 2242: 
 2243:     $request->print('</div>');#LC_grade_show_user_body
 2244:     $request->print('</div>');#LC_grade_show_user
 2245: 
 2246: 
 2247:     # print end of form
 2248:     if ($counter == $total) {
 2249: 	my $endform='<table border="0"><tr><td>'."\n";
 2250: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2251: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2252: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2253: 	my $ntstu ='<select name="NTSTU">'.
 2254: 	    '<option>1</option><option>2</option>'.
 2255: 	    '<option>3</option><option>5</option>'.
 2256: 	    '<option>7</option><option>10</option></select>'."\n";
 2257: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2258: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2259: 	$endform.=&mt('[quant,_1,student]',$ntstu);
 2260: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2261: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2262: 	    '<input type="button" value="'.&mt('Next').'" '.
 2263: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2264: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2265:         $endform.="<input type='hidden' value='".&get_increment().
 2266:             "' name='increment' />";
 2267: 	$endform.='</td></tr></table></form>';
 2268: 	$endform.=&show_grading_menu_form($symb);
 2269: 	$request->print($endform);
 2270:     }
 2271:     return '';
 2272: }
 2273: 
 2274: sub check_collaborators {
 2275:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2276:     my ($result,@col_fullnames);
 2277:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2278:     foreach my $part (keys(%$handgrade)) {
 2279: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2280: 					'.maxcollaborators',
 2281: 					$symb,$udom,$uname);
 2282: 	next if ($ncol <= 0);
 2283: 	$part =~ s/\_/\./g;
 2284: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2285: 	my (@good_collaborators, @bad_collaborators);
 2286: 	foreach my $possible_collaborator
 2287: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2288: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2289: 	    next if ($possible_collaborator eq '');
 2290: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2291: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2292: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2293: 	    # Doing this grep allows 'fuzzy' specification
 2294: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2295: 			       keys(%$classlist));
 2296: 	    if (! scalar(@matches)) {
 2297: 		push(@bad_collaborators, $possible_collaborator);
 2298: 	    } else {
 2299: 		push(@good_collaborators, @matches);
 2300: 	    }
 2301: 	}
 2302: 	if (scalar(@good_collaborators) != 0) {
 2303: 	    $result.='<br />'.&mt('Collaborators: ');
 2304: 	    foreach my $name (@good_collaborators) {
 2305: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2306: 		push(@col_fullnames, $givenn.' '.$lastname);
 2307: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2308: 	    }
 2309: 	    $result.='<br />'."\n";
 2310: 	    my ($part)=split(/\./,$part);
 2311: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2312: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2313: 		"\n";
 2314: 	}
 2315: 	if (scalar(@bad_collaborators) > 0) {
 2316: 	    $result.='<div class="LC_warning">';
 2317: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2318: 	    $result .= '</div>';
 2319: 	}         
 2320: 	if (scalar(@bad_collaborators > $ncol)) {
 2321: 	    $result .= '<div class="LC_warning">';
 2322: 	    $result .= &mt('This student has submitted too many '.
 2323: 		'collaborators.  Maximum is [_1].',$ncol);
 2324: 	    $result .= '</div>';
 2325: 	}
 2326:     }
 2327:     return ($result,$fullname,\@col_fullnames);
 2328: }
 2329: 
 2330: #--- Retrieve the last submission for all the parts
 2331: sub get_last_submission {
 2332:     my ($returnhash)=@_;
 2333:     my (@string,$timestamp);
 2334:     if ($$returnhash{'version'}) {
 2335: 	my %lasthash=();
 2336: 	my ($version);
 2337: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2338: 	    foreach my $key (sort(split(/\:/,
 2339: 					$$returnhash{$version.':keys'}))) {
 2340: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2341: 		$timestamp = 
 2342: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2343: 	    }
 2344: 	}
 2345: 	foreach my $key (keys(%lasthash)) {
 2346: 	    next if ($key !~ /\.submission$/);
 2347: 
 2348: 	    my ($partid,$foo) = split(/submission$/,$key);
 2349: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2350: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2351: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2352: 	}
 2353:     }
 2354:     if (!@string) {
 2355: 	$string[0] =
 2356: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2357:     }
 2358:     return (\@string,\$timestamp);
 2359: }
 2360: 
 2361: #--- High light keywords, with style choosen by user.
 2362: sub keywords_highlight {
 2363:     my $string    = shift;
 2364:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2365:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2366:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2367:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2368:     foreach my $keyword (@keylist) {
 2369: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2370:     }
 2371:     return $string;
 2372: }
 2373: 
 2374: #--- Called from submission routine
 2375: sub processHandGrade {
 2376:     my ($request) = shift;
 2377:     my $symb   = &get_symb($request);
 2378:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2379:     my $button = $env{'form.gradeOpt'};
 2380:     my $ngrade = $env{'form.NCT'};
 2381:     my $ntstu  = $env{'form.NTSTU'};
 2382:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2383:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2384: 
 2385:     if ($button eq 'Save & Next') {
 2386: 	my $ctr = 0;
 2387: 	while ($ctr < $ngrade) {
 2388: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2389: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2390: 	    if ($errorflag eq 'no_score') {
 2391: 		$ctr++;
 2392: 		next;
 2393: 	    }
 2394: 	    if ($errorflag eq 'not_allowed') {
 2395: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2396: 		$ctr++;
 2397: 		next;
 2398: 	    }
 2399: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2400: 	    my ($subject,$message,$msgstatus) = ('','','');
 2401: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2402:             my ($feedurl,$showsymb) =
 2403: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2404: 	    my $messagetail;
 2405: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2406: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2407: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2408: 		$subject.=' ['.$restitle.']';
 2409: 		my (@msgnum) = split(/,/,$includemsg);
 2410: 		foreach (@msgnum) {
 2411: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2412: 		}
 2413: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2414: 		if ($env{'form.withgrades'.$ctr}) {
 2415: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2416: 		    $messagetail = " for <a href=\"".
 2417: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2418: 		}
 2419: 		$msgstatus = 
 2420:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2421: 						     $message.$messagetail,
 2422:                                                      undef,$feedurl,undef,
 2423:                                                      undef,undef,$showsymb,
 2424:                                                      $restitle);
 2425: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2426: 				$msgstatus);
 2427: 	    }
 2428: 	    if ($env{'form.collaborator'.$ctr}) {
 2429: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2430: 		foreach my $collabstr (@collabstrs) {
 2431: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2432: 		    foreach my $collaborator (@collaborators) {
 2433: 			my ($errorflag,$pts,$wgt) = 
 2434: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2435: 					   $env{'form.unamedom'.$ctr},$part);
 2436: 			if ($errorflag eq 'not_allowed') {
 2437: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2438: 			    next;
 2439: 			} elsif ($message ne '') {
 2440: 			    my ($baseurl,$showsymb) = 
 2441: 				&get_feedurl_and_symb($symb,$collaborator,
 2442: 						      $udom);
 2443: 			    if ($env{'form.withgrades'.$ctr}) {
 2444: 				$messagetail = " for <a href=\"".
 2445:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2446: 			    }
 2447: 			    $msgstatus = 
 2448: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2449: 			}
 2450: 		    }
 2451: 		}
 2452: 	    }
 2453: 	    $ctr++;
 2454: 	}
 2455:     }
 2456: 
 2457:     if ($env{'form.handgrade'} eq 'yes') {
 2458: 	# Keywords sorted in alphabatical order
 2459: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2460: 	my %keyhash = ();
 2461: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2462: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2463: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2464: 	$env{'form.keywords'} = join(' ',@keywords);
 2465: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2466: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2467: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2468: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2469: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2470: 
 2471: 	# message center - Order of message gets changed. Blank line is eliminated.
 2472: 	# New messages are saved in env for the next student.
 2473: 	# All messages are saved in nohist_handgrade.db
 2474: 	my ($ctr,$idx) = (1,1);
 2475: 	while ($ctr <= $env{'form.savemsgN'}) {
 2476: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2477: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2478: 		$idx++;
 2479: 	    }
 2480: 	    $ctr++;
 2481: 	}
 2482: 	$ctr = 0;
 2483: 	while ($ctr < $ngrade) {
 2484: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2485: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2486: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2487: 		$idx++;
 2488: 	    }
 2489: 	    $ctr++;
 2490: 	}
 2491: 	$env{'form.savemsgN'} = --$idx;
 2492: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2493: 	my $putresult = &Apache::lonnet::put
 2494: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2495:     }
 2496:     # Called by Save & Refresh from Highlight Attribute Window
 2497:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2498:     if ($env{'form.refresh'} eq 'on') {
 2499: 	my ($ctr,$total) = (0,0);
 2500: 	while ($ctr < $ngrade) {
 2501: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2502: 	    $ctr++;
 2503: 	}
 2504: 	$env{'form.NTSTU'}=$ngrade;
 2505: 	$ctr = 0;
 2506: 	while ($ctr < $total) {
 2507: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2508: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2509: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2510: 	    &submission($request,$ctr,$total-1);
 2511: 	    $ctr++;
 2512: 	}
 2513: 	return '';
 2514:     }
 2515: 
 2516: # Go directly to grade student - from submission or link from chart page
 2517:     if ($button eq 'Grade Student') {
 2518: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2519: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2520: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2521: 	$env{'form.fullname'} = $$fullname{$processUser};
 2522: 	&submission($request,0,0);
 2523: 	return '';
 2524:     }
 2525: 
 2526:     # Get the next/previous one or group of students
 2527:     my $firststu = $env{'form.unamedom0'};
 2528:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2529:     my $ctr = 2;
 2530:     while ($laststu eq '') {
 2531: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2532: 	$ctr++;
 2533: 	$laststu = $firststu if ($ctr > $ngrade);
 2534:     }
 2535: 
 2536:     my (@parsedlist,@nextlist);
 2537:     my ($nextflg) = 0;
 2538:     foreach my $item (sort 
 2539: 	     {
 2540: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2541: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2542: 		 }
 2543: 		 return $a cmp $b;
 2544: 	     } (keys(%$fullname))) {
 2545: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2546: 	    push(@parsedlist,$item);
 2547: 	}
 2548: 	$nextflg = 1 if ($item eq $laststu);
 2549: 	if ($button eq 'Previous') {
 2550: 	    last if ($item eq $firststu);
 2551: 	    push(@parsedlist,$item);
 2552: 	}
 2553:     }
 2554:     $ctr = 0;
 2555:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2556:     my ($partlist) = &response_type($symb);
 2557:     foreach my $student (@parsedlist) {
 2558: 	my $submitonly=$env{'form.submitonly'};
 2559: 	my ($uname,$udom) = split(/:/,$student);
 2560: 	
 2561: 	if ($submitonly eq 'queued') {
 2562: 	    my %queue_status = 
 2563: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2564: 							$udom,$uname);
 2565: 	    next if (!defined($queue_status{'gradingqueue'}));
 2566: 	}
 2567: 
 2568: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2569: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2570: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2571: 	    my $submitted = 0;
 2572: 	    my $ungraded = 0;
 2573: 	    my $incorrect = 0;
 2574: 	    foreach my $item (keys(%status)) {
 2575: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2576: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2577: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2578: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2579: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2580: 		    $submitted = 0;
 2581: 		}
 2582: 	    }
 2583: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2584: 				     $submitonly eq 'incorrect' ||
 2585: 				     $submitonly eq 'graded'));
 2586: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2587: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2588: 	}
 2589: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2590: 	last if ($ctr == $ntstu);
 2591: 	$ctr++;
 2592:     }
 2593: 
 2594:     $ctr = 0;
 2595:     my $total = scalar(@nextlist)-1;
 2596: 
 2597:     foreach (sort(@nextlist)) {
 2598: 	my ($uname,$udom,$submitter) = split(/:/);
 2599: 	$env{'form.student'}  = $uname;
 2600: 	$env{'form.userdom'}  = $udom;
 2601: 	$env{'form.fullname'} = $$fullname{$_};
 2602: 	&submission($request,$ctr,$total);
 2603: 	$ctr++;
 2604:     }
 2605:     if ($total < 0) {
 2606: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2607: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2608: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2609: 	$the_end.=&show_grading_menu_form($symb);
 2610: 	$request->print($the_end);
 2611:     }
 2612:     return '';
 2613: }
 2614: 
 2615: #---- Save the score and award for each student, if changed
 2616: sub saveHandGrade {
 2617:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2618:     my @version_parts;
 2619:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2620: 					   $env{'request.course.id'});
 2621:     if (!&canmodify($usec)) { return('not_allowed'); }
 2622:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2623:     my @parts_graded;
 2624:     my %newrecord  = ();
 2625:     my ($pts,$wgt) = ('','');
 2626:     my %aggregate = ();
 2627:     my $aggregateflag = 0;
 2628:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2629:     foreach my $new_part (@parts) {
 2630: 	#collaborator ($submi may vary for different parts
 2631: 	if ($submitter && $new_part ne $part) { next; }
 2632: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2633: 	if ($dropMenu eq 'excused') {
 2634: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2635: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2636: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2637: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2638: 		}
 2639: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2640: 	    }
 2641: 	} elsif ($dropMenu eq 'reset status'
 2642: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2643: 	    foreach my $key (keys(%record)) {
 2644: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2645: 	    }
 2646: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2647: 		"$env{'user.name'}:$env{'user.domain'}";
 2648:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2649: 
 2650:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2651: 					       [$new_part]);
 2652:             my $aggtries =$totaltries;
 2653:             if ($last_resets{$new_part}) {
 2654:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2655: 					   $new_part);
 2656:             }
 2657: 
 2658:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2659:             if ($aggtries > 0) {
 2660:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2661:                 $aggregateflag = 1;
 2662:             }
 2663: 	} elsif ($dropMenu eq '') {
 2664: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2665: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2666: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2667: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2668: 		next;
 2669: 	    }
 2670: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2671: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2672: 	    my $partial= $pts/$wgt;
 2673: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2674: 		#do not update score for part if not changed.
 2675:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2676: 		next;
 2677: 	    } else {
 2678: 	        push(@parts_graded,$new_part);
 2679: 	    }
 2680: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2681: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2682: 	    }
 2683: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2684: 	    if ($partial == 0) {
 2685: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2686: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2687: 		}
 2688: 	    } else {
 2689: 		if ($record{$reckey} ne 'correct_by_override') {
 2690: 		    $newrecord{$reckey} = 'correct_by_override';
 2691: 		}
 2692: 	    }	    
 2693: 	    if ($submitter && 
 2694: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2695: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2696: 	    }
 2697: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2698: 		"$env{'user.name'}:$env{'user.domain'}";
 2699: 	}
 2700: 	# unless problem has been graded, set flag to version the submitted files
 2701: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2702: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2703: 	        $dropMenu eq 'reset status')
 2704: 	   {
 2705: 	    push(@version_parts,$new_part);
 2706: 	}
 2707:     }
 2708:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2709:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2710: 
 2711:     if (%newrecord) {
 2712:         if (@version_parts) {
 2713:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2714:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2715: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2716: 	    foreach my $new_part (@version_parts) {
 2717: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2718: 				$new_part,\%newrecord);
 2719: 	    }
 2720:         }
 2721: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2722: 				$env{'request.course.id'},$domain,$stuname);
 2723: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2724: 				     $cdom,$cnum,$domain,$stuname);
 2725:     }
 2726:     if ($aggregateflag) {
 2727:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2728: 			      $cdom,$cnum);
 2729:     }
 2730:     return ('',$pts,$wgt);
 2731: }
 2732: 
 2733: sub check_and_remove_from_queue {
 2734:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2735:     my @ungraded_parts;
 2736:     foreach my $part (@{$parts}) {
 2737: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2738: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2739: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2740: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2741: 		) {
 2742: 	    push(@ungraded_parts, $part);
 2743: 	}
 2744:     }
 2745:     if ( !@ungraded_parts ) {
 2746: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2747: 					       $cnum,$domain,$stuname);
 2748:     }
 2749: }
 2750: 
 2751: sub handback_files {
 2752:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2753:     my $portfolio_root = '/userfiles/portfolio';
 2754:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2755: 
 2756:     my @part_response_id = &flatten_responseType($responseType);
 2757:     foreach my $part_response_id (@part_response_id) {
 2758:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2759: 	my $part_resp = join('_',@{ $part_response_id });
 2760:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2761:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2762:                 my $file_counter = 1;
 2763: 		my $file_msg;
 2764:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2765:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2766:                     my ($directory,$answer_file) = 
 2767:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2768:                     my ($answer_name,$answer_ver,$answer_ext) =
 2769: 		        &file_name_version_ext($answer_file);
 2770: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2771:                     my $getpropath = 1;
 2772: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2773: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2774:                     # fix file name
 2775:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2776:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2777:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2778:             	                                $save_file_name);
 2779:                     if ($result !~ m|^/uploaded/|) {
 2780:                         $request->print('<br /><span class="LC_error">'.
 2781:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2782:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2783:                                         '</span>');
 2784:                     } else {
 2785:                         # mark the file as read only
 2786:                         my @files = ($save_file_name);
 2787:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2788:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2789: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2790: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2791: 			}
 2792:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2793: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2794: 
 2795:                     }
 2796:                     $request->print("<br />".$fname." will be the uploaded file name");
 2797:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2798:                     $file_counter++;
 2799:                 }
 2800: 		my $subject = "File Handed Back by Instructor ";
 2801: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2802: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2803: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2804: 		$message .= " and can be found in your portfolio space.";
 2805: 		my ($feedurl,$showsymb) = 
 2806: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2807:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2808: 		my $msgstatus = 
 2809:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2810: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2811:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2812:             }
 2813:         }
 2814:     return;
 2815: }
 2816: 
 2817: sub get_feedurl_and_symb {
 2818:     my ($symb,$uname,$udom) = @_;
 2819:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2820:     $url = &Apache::lonnet::clutter($url);
 2821:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2822: 					$symb,$udom,$uname);
 2823:     if ($encrypturl =~ /^yes$/i) {
 2824: 	&Apache::lonenc::encrypted(\$url,1);
 2825: 	&Apache::lonenc::encrypted(\$symb,1);
 2826:     }
 2827:     return ($url,$symb);
 2828: }
 2829: 
 2830: sub get_submitted_files {
 2831:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2832:     my @files;
 2833:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2834:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2835:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2836:     	    push(@files,$file_url.$file);
 2837:         }
 2838:     }
 2839:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2840:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2841:     }
 2842:     return (\@files);
 2843: }
 2844: 
 2845: # ----------- Provides number of tries since last reset.
 2846: sub get_num_tries {
 2847:     my ($record,$last_reset,$part) = @_;
 2848:     my $timestamp = '';
 2849:     my $num_tries = 0;
 2850:     if ($$record{'version'}) {
 2851:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2852:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2853:                 $timestamp = $$record{$version.':timestamp'};
 2854:                 if ($timestamp > $last_reset) {
 2855:                     $num_tries ++;
 2856:                 } else {
 2857:                     last;
 2858:                 }
 2859:             }
 2860:         }
 2861:     }
 2862:     return $num_tries;
 2863: }
 2864: 
 2865: # ----------- Determine decrements required in aggregate totals 
 2866: sub decrement_aggs {
 2867:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2868:     my %decrement = (
 2869:                         attempts => 0,
 2870:                         users => 0,
 2871:                         correct => 0
 2872:                     );
 2873:     $decrement{'attempts'} = $aggtries;
 2874:     if ($solvedstatus =~ /^correct/) {
 2875:         $decrement{'correct'} = 1;
 2876:     }
 2877:     if ($aggtries == $totaltries) {
 2878:         $decrement{'users'} = 1;
 2879:     }
 2880:     foreach my $type (keys(%decrement)) {
 2881:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2882:     }
 2883:     return;
 2884: }
 2885: 
 2886: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2887: sub get_last_resets {
 2888:     my ($symb,$courseid,$partids) =@_;
 2889:     my %last_resets;
 2890:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2891:     my $cname = $env{'course.'.$courseid.'.num'};
 2892:     my @keys;
 2893:     foreach my $part (@{$partids}) {
 2894: 	push(@keys,"$symb\0$part\0resettime");
 2895:     }
 2896:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2897: 				     $cdom,$cname);
 2898:     foreach my $part (@{$partids}) {
 2899: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2900:     }
 2901:     return %last_resets;
 2902: }
 2903: 
 2904: # ----------- Handles creating versions for portfolio files as answers
 2905: sub version_portfiles {
 2906:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2907:     my $version_parts = join('|',@$v_flag);
 2908:     my @returned_keys;
 2909:     my $parts = join('|', @$parts_graded);
 2910:     my $portfolio_root = '/userfiles/portfolio';
 2911:     foreach my $key (keys(%$record)) {
 2912:         my $new_portfiles;
 2913:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2914:             my @versioned_portfiles;
 2915:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2916:             foreach my $file (@portfiles) {
 2917:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2918:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2919: 		my ($answer_name,$answer_ver,$answer_ext) =
 2920: 		    &file_name_version_ext($answer_file);
 2921:                 my $getpropath = 1;    
 2922:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2923:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2924:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2925:                 if ($new_answer ne 'problem getting file') {
 2926:                     push(@versioned_portfiles, $directory.$new_answer);
 2927:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2928:                         [$directory.$new_answer],
 2929:                         [$symb,$env{'request.course.id'},'graded']);
 2930:                 }
 2931:             }
 2932:             $$record{$key} = join(',',@versioned_portfiles);
 2933:             push(@returned_keys,$key);
 2934:         }
 2935:     } 
 2936:     return (@returned_keys);   
 2937: }
 2938: 
 2939: sub get_next_version {
 2940:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2941:     my $version;
 2942:     foreach my $row (@$dir_list) {
 2943:         my ($file) = split(/\&/,$row,2);
 2944:         my ($file_name,$file_version,$file_ext) =
 2945: 	    &file_name_version_ext($file);
 2946:         if (($file_name eq $answer_name) && 
 2947: 	    ($file_ext eq $answer_ext)) {
 2948:                 # gets here if filename and extension match, regardless of version
 2949:                 if ($file_version ne '') {
 2950:                 # a versioned file is found  so save it for later
 2951:                 if ($file_version > $version) {
 2952: 		    $version = $file_version;
 2953: 	        }
 2954:             }
 2955:         }
 2956:     } 
 2957:     $version ++;
 2958:     return($version);
 2959: }
 2960: 
 2961: sub version_selected_portfile {
 2962:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2963:     my ($answer_name,$answer_ver,$answer_ext) =
 2964:         &file_name_version_ext($file_name);
 2965:     my $new_answer;
 2966:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2967:     if($env{'form.copy'} eq '-1') {
 2968:         $new_answer = 'problem getting file';
 2969:     } else {
 2970:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2971:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2972:                             $stu_name,$domain,'copy',
 2973: 		        '/portfolio'.$directory.$new_answer);
 2974:     }    
 2975:     return ($new_answer);
 2976: }
 2977: 
 2978: sub file_name_version_ext {
 2979:     my ($file)=@_;
 2980:     my @file_parts = split(/\./, $file);
 2981:     my ($name,$version,$ext);
 2982:     if (@file_parts > 1) {
 2983: 	$ext=pop(@file_parts);
 2984: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2985: 	    $version=pop(@file_parts);
 2986: 	}
 2987: 	$name=join('.',@file_parts);
 2988:     } else {
 2989: 	$name=join('.',@file_parts);
 2990:     }
 2991:     return($name,$version,$ext);
 2992: }
 2993: 
 2994: #--------------------------------------------------------------------------------------
 2995: #
 2996: #-------------------------- Next few routines handles grading by section or whole class
 2997: #
 2998: #--- Javascript to handle grading by section or whole class
 2999: sub viewgrades_js {
 3000:     my ($request) = shift;
 3001: 
 3002:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3003:     $request->print(<<VIEWJAVASCRIPT);
 3004: <script type="text/javascript" language="javascript">
 3005:    function writePoint(partid,weight,point) {
 3006: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3007: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3008: 	if (point == "textval") {
 3009: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3010: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3011: 		alert("$alertmsg"+parseFloat(point));
 3012: 		var resetbox = false;
 3013: 		for (var i=0; i<radioButton.length; i++) {
 3014: 		    if (radioButton[i].checked) {
 3015: 			textbox.value = i;
 3016: 			resetbox = true;
 3017: 		    }
 3018: 		}
 3019: 		if (!resetbox) {
 3020: 		    textbox.value = "";
 3021: 		}
 3022: 		return;
 3023: 	    }
 3024: 	    if (parseFloat(point) > parseFloat(weight)) {
 3025: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3026: 				   ") greater than the weight for the part. Accept?");
 3027: 		if (resp == false) {
 3028: 		    textbox.value = "";
 3029: 		    return;
 3030: 		}
 3031: 	    }
 3032: 	    for (var i=0; i<radioButton.length; i++) {
 3033: 		radioButton[i].checked=false;
 3034: 		if (parseFloat(point) == i) {
 3035: 		    radioButton[i].checked=true;
 3036: 		}
 3037: 	    }
 3038: 
 3039: 	} else {
 3040: 	    textbox.value = parseFloat(point);
 3041: 	}
 3042: 	for (i=0;i<document.classgrade.total.value;i++) {
 3043: 	    var user = document.classgrade["ctr"+i].value;
 3044: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3045: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3046: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3047: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3048: 	    if (saveval != "correct") {
 3049: 		scorename.value = point;
 3050: 		if (selname[0].selected != true) {
 3051: 		    selname[0].selected = true;
 3052: 		}
 3053: 	    }
 3054: 	}
 3055: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3056:     }
 3057: 
 3058:     function writeRadText(partid,weight) {
 3059: 	var selval   = document.classgrade["SELVAL_"+partid];
 3060: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3061:         var override = document.classgrade["FORCE_"+partid].checked;
 3062: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3063: 	if (selval[1].selected || selval[2].selected) {
 3064: 	    for (var i=0; i<radioButton.length; i++) {
 3065: 		radioButton[i].checked=false;
 3066: 
 3067: 	    }
 3068: 	    textbox.value = "";
 3069: 
 3070: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3071: 		var user = document.classgrade["ctr"+i].value;
 3072: 		user = user.replace(new RegExp(':', 'g'),"_");
 3073: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3074: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3075: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3076: 		if ((saveval != "correct") || override) {
 3077: 		    scorename.value = "";
 3078: 		    if (selval[1].selected) {
 3079: 			selname[1].selected = true;
 3080: 		    } else {
 3081: 			selname[2].selected = true;
 3082: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3083: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3084: 		    }
 3085: 		}
 3086: 	    }
 3087: 	} else {
 3088: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3089: 		var user = document.classgrade["ctr"+i].value;
 3090: 		user = user.replace(new RegExp(':', 'g'),"_");
 3091: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3092: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3093: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3094: 		if ((saveval != "correct") || override) {
 3095: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3096: 		    selname[0].selected = true;
 3097: 		}
 3098: 	    }
 3099: 	}	    
 3100:     }
 3101: 
 3102:     function changeSelect(partid,user) {
 3103: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3104: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3105: 	var point  = textbox.value;
 3106: 	var weight = document.classgrade["weight_"+partid].value;
 3107: 
 3108: 	if (isNaN(point) || parseFloat(point) < 0) {
 3109: 	    alert("$alertmsg"+parseFloat(point));
 3110: 	    textbox.value = "";
 3111: 	    return;
 3112: 	}
 3113: 	if (parseFloat(point) > parseFloat(weight)) {
 3114: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3115: 			       ") greater than the weight of the part. Accept?");
 3116: 	    if (resp == false) {
 3117: 		textbox.value = "";
 3118: 		return;
 3119: 	    }
 3120: 	}
 3121: 	selval[0].selected = true;
 3122:     }
 3123: 
 3124:     function changeOneScore(partid,user) {
 3125: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3126: 	if (selval[1].selected || selval[2].selected) {
 3127: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3128: 	    if (selval[2].selected) {
 3129: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3130: 	    }
 3131:         }
 3132:     }
 3133: 
 3134:     function resetEntry(numpart) {
 3135: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3136: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3137: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3138: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3139: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3140: 	    for (var i=0; i<radioButton.length; i++) {
 3141: 		radioButton[i].checked=false;
 3142: 
 3143: 	    }
 3144: 	    textbox.value = "";
 3145: 	    selval[0].selected = true;
 3146: 
 3147: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3148: 		var user = document.classgrade["ctr"+i].value;
 3149: 		user = user.replace(new RegExp(':', 'g'),"_");
 3150: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3151: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3152: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3153: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3154: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3155: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3156: 		if (saveselval == "excused") {
 3157: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3158: 		} else {
 3159: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3160: 		}
 3161: 	    }
 3162: 	}
 3163:     }
 3164: 
 3165: </script>
 3166: VIEWJAVASCRIPT
 3167: }
 3168: 
 3169: #--- show scores for a section or whole class w/ option to change/update a score
 3170: sub viewgrades {
 3171:     my ($request) = shift;
 3172:     &viewgrades_js($request);
 3173: 
 3174:     my ($symb) = &get_symb($request);
 3175:     #need to make sure we have the correct data for later EXT calls, 
 3176:     #thus invalidate the cache
 3177:     &Apache::lonnet::devalidatecourseresdata(
 3178:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3179:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3180:     &Apache::lonnet::clear_EXT_cache_status();
 3181: 
 3182:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3183:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3184: 
 3185:     #view individual student submission form - called using Javascript viewOneStudent
 3186:     $result.=&jscriptNform($symb);
 3187: 
 3188:     #beginning of class grading form
 3189:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3190:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3191: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3192: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3193: 	&build_section_inputs().
 3194: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3195: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3196: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3197: 
 3198:     my $sectionClass;
 3199:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3200:     if ($env{'form.section'} eq 'all') {
 3201: 	$sectionClass=&mt('Class');
 3202:     } elsif ($env{'form.section'} eq 'none') {
 3203: 	$sectionClass=&mt('Students in no Section');
 3204:     } else {
 3205: 	$sectionClass=&mt('Students in Section(s) [_1]');
 3206:     }
 3207:     $result.=
 3208: 	'<h3>'.
 3209: 	&mt("Assign Common Grade to [_1]",$sectionClass,$section_display).'</h3>';
 3210:     $result.= &Apache::loncommon::start_data_table();
 3211:     #radio buttons/text box for assigning points for a section or class.
 3212:     #handles different parts of a problem
 3213:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3214:     my %weight = ();
 3215:     my $ctsparts = 0;
 3216:     my %seen = ();
 3217:     my @part_response_id = &flatten_responseType($responseType);
 3218:     foreach my $part_response_id (@part_response_id) {
 3219:     	my ($partid,$respid) = @{ $part_response_id };
 3220: 	my $part_resp = join('_',@{ $part_response_id });
 3221: 	next if $seen{$partid};
 3222: 	$seen{$partid}++;
 3223: 	my $handgrade=$$handgrade{$part_resp};
 3224: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3225: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3226: 
 3227: 	my $display_part=&get_display_part($partid,$symb);
 3228: 	my $radio.='<table border="0"><tr>';  
 3229: 	my $ctr = 0;
 3230: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3231: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3232: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3233: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3234: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3235: 	    $ctr++;
 3236: 	}
 3237: 	$radio.='</tr></table>';
 3238: 	my $line = '<input type="text" name="TEXTVAL_'.
 3239: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3240: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3241: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3242: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3243: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3244: 		$weight{$partid}.')"> '.
 3245: 	    '<option selected="selected"> </option>'.
 3246: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3247: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3248: 	    '</select></td>'.
 3249:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3250: 	$line.='<input type="hidden" name="partid_'.
 3251: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3252: 	$line.='<input type="hidden" name="weight_'.
 3253: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3254: 
 3255: 	$result.=
 3256: 	    &Apache::loncommon::start_data_table_row()."\n".
 3257: 	    '<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>'.
 3258: 	    &Apache::loncommon::end_data_table_row()."\n";
 3259: 	$ctsparts++;
 3260:     }
 3261:     $result.=&Apache::loncommon::end_data_table()."\n".
 3262: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3263:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3264: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3265: 
 3266:     #table listing all the students in a section/class
 3267:     #header of table
 3268:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in ').$sectionClass,
 3269: 			 $section_display.'</h3>';
 3270:     $result.= &Apache::loncommon::start_data_table().
 3271: 	&Apache::loncommon::start_data_table_header_row().
 3272: 	'<th>'.&mt('No.').'</th>'.
 3273: 	'<th>'.&nameUserString('header')."</th>\n";
 3274:     my (@parts) = sort(&getpartlist($symb));
 3275:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3276:     my @partids = ();
 3277:     foreach my $part (@parts) {
 3278: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3279:         my $narrowtext = &mt('Tries');
 3280: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3281: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3282: 	my ($partid) = &split_part_type($part);
 3283:         push(@partids,$partid);
 3284: 	my $display_part=&get_display_part($partid,$symb);
 3285: 	if ($display =~ /^Partial Credit Factor/) {
 3286: 	    $result.='<th>'.
 3287: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3288: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3289: 	    next;
 3290: 	    
 3291: 	} else {
 3292: 	    if ($display =~ /Problem Status/) {
 3293: 		my $grade_status_mt = &mt('Grade Status');
 3294: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3295: 	    }
 3296: 	    my $part_mt = &mt('Part:');
 3297: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3298: 	}
 3299: 
 3300: 	$result.='<th>'.$display.'</th>'."\n";
 3301:     }
 3302:     $result.=&Apache::loncommon::end_data_table_header_row();
 3303: 
 3304:     my %last_resets = 
 3305: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3306: 
 3307:     #get info for each student
 3308:     #list all the students - with points and grade status
 3309:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3310:     my $ctr = 0;
 3311:     foreach (sort 
 3312: 	     {
 3313: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3314: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3315: 		 }
 3316: 		 return $a cmp $b;
 3317: 	     } (keys(%$fullname))) {
 3318: 	$ctr++;
 3319: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3320: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3321:     }
 3322:     $result.=&Apache::loncommon::end_data_table();
 3323:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3324:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3325: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3326:     if (scalar(%$fullname) eq 0) {
 3327: 	my $colspan=3+scalar(@parts);
 3328: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3329:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3330: 	$result='<span class="LC_warning">'.
 3331: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3332: 	        $section_display, $stu_status).
 3333: 	    '</span>';
 3334:     }
 3335:     $result.=&show_grading_menu_form($symb);
 3336:     return $result;
 3337: }
 3338: 
 3339: #--- call by previous routine to display each student
 3340: sub viewstudentgrade {
 3341:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3342:     my ($uname,$udom) = split(/:/,$student);
 3343:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3344:     my %aggregates = (); 
 3345:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3346: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3347: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3348: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3349: 	'\');" target="_self">'.$fullname.'</a> '.
 3350: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3351:     $student=~s/:/_/; # colon doen't work in javascript for names
 3352:     foreach my $apart (@$parts) {
 3353: 	my ($part,$type) = &split_part_type($apart);
 3354: 	my $score=$record{"resource.$part.$type"};
 3355:         $result.='<td align="center">';
 3356:         my ($aggtries,$totaltries);
 3357:         unless (exists($aggregates{$part})) {
 3358: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3359: 
 3360: 	    $aggtries = $totaltries;
 3361:             if ($$last_resets{$part}) {  
 3362:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3363: 					   $part);
 3364:             }
 3365:             $result.='<input type="hidden" name="'.
 3366:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3367:             $result.='<input type="hidden" name="'.
 3368:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3369:             $aggregates{$part} = 1;
 3370:         }
 3371: 	if ($type eq 'awarded') {
 3372: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3373: 	    $result.='<input type="hidden" name="'.
 3374: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3375: 	    $result.='<input type="text" name="'.
 3376: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3377: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3378: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3379: 	} elsif ($type eq 'solved') {
 3380: 	    my ($status,$foo)=split(/_/,$score,2);
 3381: 	    $status = 'nothing' if ($status eq '');
 3382: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3383: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3384: 	    $result.='&nbsp;<select name="'.
 3385: 		'GD_'.$student.'_'.$part.'_solved" '.
 3386: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3387: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3388: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3389: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3390: 	    $result.="</select>&nbsp;</td>\n";
 3391: 	} else {
 3392: 	    $result.='<input type="hidden" name="'.
 3393: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3394: 		    "\n";
 3395: 	    $result.='<input type="text" name="'.
 3396: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3397: 		'value="'.$score.'" size="4" /></td>'."\n";
 3398: 	}
 3399:     }
 3400:     $result.=&Apache::loncommon::end_data_table_row();
 3401:     return $result;
 3402: }
 3403: 
 3404: #--- change scores for all the students in a section/class
 3405: #    record does not get update if unchanged
 3406: sub editgrades {
 3407:     my ($request) = @_;
 3408: 
 3409:     my $symb=&get_symb($request);
 3410:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3411:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3412:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3413:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3414: 
 3415:     my $result= &Apache::loncommon::start_data_table().
 3416: 	&Apache::loncommon::start_data_table_header_row().
 3417: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3418: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3419:     my %scoreptr = (
 3420: 		    'correct'  =>'correct_by_override',
 3421: 		    'incorrect'=>'incorrect_by_override',
 3422: 		    'excused'  =>'excused',
 3423: 		    'ungraded' =>'ungraded_attempted',
 3424: 		    'nothing'  => '',
 3425: 		    );
 3426:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3427: 
 3428:     my (@partid);
 3429:     my %weight = ();
 3430:     my %columns = ();
 3431:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3432: 
 3433:     my (@parts) = sort(&getpartlist($symb));
 3434:     my $header;
 3435:     while ($ctr < $env{'form.totalparts'}) {
 3436: 	my $partid = $env{'form.partid_'.$ctr};
 3437: 	push(@partid,$partid);
 3438: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3439: 	$ctr++;
 3440:     }
 3441:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3442:     foreach my $partid (@partid) {
 3443: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3444: 	    '<th align="center">'.&mt('New Score').'</th>';
 3445: 	$columns{$partid}=2;
 3446: 	foreach my $stores (@parts) {
 3447: 	    my ($part,$type) = &split_part_type($stores);
 3448: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3449: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3450: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3451: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3452:             my $narrowtext = &mt('Tries');
 3453: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3454: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3455: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3456: 	    $columns{$partid}+=2;
 3457: 	}
 3458:     }
 3459:     foreach my $partid (@partid) {
 3460: 	my $display_part=&get_display_part($partid,$symb);
 3461: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3462: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3463: 	    '</th>';
 3464: 
 3465:     }
 3466:     $result .= &Apache::loncommon::end_data_table_header_row().
 3467: 	&Apache::loncommon::start_data_table_header_row().
 3468: 	$header.
 3469: 	&Apache::loncommon::end_data_table_header_row();
 3470:     my @noupdate;
 3471:     my ($updateCtr,$noupdateCtr) = (1,1);
 3472:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3473: 	my $line;
 3474: 	my $user = $env{'form.ctr'.$i};
 3475: 	my ($uname,$udom)=split(/:/,$user);
 3476: 	my %newrecord;
 3477: 	my $updateflag = 0;
 3478: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3479: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3480: 	if (!&canmodify($usec)) {
 3481: 	    my $numcols=scalar(@partid)*4+2;
 3482: 	    push(@noupdate,
 3483: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3484: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3485: 	    next;
 3486: 	}
 3487:         my %aggregate = ();
 3488:         my $aggregateflag = 0;
 3489: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3490: 	foreach (@partid) {
 3491: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3492: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3493: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3494: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3495: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3496: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3497: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3498: 	    my $score;
 3499: 	    if ($partial eq '') {
 3500: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3501: 	    } elsif ($partial > 0) {
 3502: 		$score = 'correct_by_override';
 3503: 	    } elsif ($partial == 0) {
 3504: 		$score = 'incorrect_by_override';
 3505: 	    }
 3506: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3507: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3508: 
 3509: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3510: 		"$env{'user.name'}:$env{'user.domain'}";
 3511: 	    if ($dropMenu eq 'reset status' &&
 3512: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3513: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3514: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3515: 		$newrecord{'resource.'.$_.'.award'} = '';
 3516: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3517: 		$updateflag = 1;
 3518:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3519:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3520:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3521:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3522:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3523:                     $aggregateflag = 1;
 3524:                 }
 3525: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3526: 		$updateflag = 1;
 3527: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3528: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3529: 		$rec_update++;
 3530: 	    }
 3531: 
 3532: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3533: 		'<td align="center">'.$awarded.
 3534: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3535: 
 3536: 
 3537: 	    my $partid=$_;
 3538: 	    foreach my $stores (@parts) {
 3539: 		my ($part,$type) = &split_part_type($stores);
 3540: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3541: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3542: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3543: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3544: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3545: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3546: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3547: 		    $updateflag=1;
 3548: 		}
 3549: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3550: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3551: 	    }
 3552: 	}
 3553: 	$line.="\n";
 3554: 
 3555: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3556: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3557: 
 3558: 	if ($updateflag) {
 3559: 	    $count++;
 3560: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3561: 				    $udom,$uname);
 3562: 
 3563: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3564: 					      $cnum,$udom,$uname)) {
 3565: 		# need to figure out if should be in queue.
 3566: 		my %record =  
 3567: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3568: 					     $udom,$uname);
 3569: 		my $all_graded = 1;
 3570: 		my $none_graded = 1;
 3571: 		foreach my $part (@parts) {
 3572: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3573: 			$all_graded = 0;
 3574: 		    } else {
 3575: 			$none_graded = 0;
 3576: 		    }
 3577: 		}
 3578: 
 3579: 		if ($all_graded || $none_graded) {
 3580: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3581: 							   $symb,$cdom,$cnum,
 3582: 							   $udom,$uname);
 3583: 		}
 3584: 	    }
 3585: 
 3586: 	    $result.=&Apache::loncommon::start_data_table_row().
 3587: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3588: 		&Apache::loncommon::end_data_table_row();
 3589: 	    $updateCtr++;
 3590: 	} else {
 3591: 	    push(@noupdate,
 3592: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3593: 	    $noupdateCtr++;
 3594: 	}
 3595:         if ($aggregateflag) {
 3596:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3597: 				  $cdom,$cnum);
 3598:         }
 3599:     }
 3600:     if (@noupdate) {
 3601: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3602: 	my $numcols=scalar(@partid)*4+2;
 3603: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3604: 	    '<td align="center" colspan="'.$numcols.'">'.
 3605: 	    &mt('No Changes Occurred For the Students Below').
 3606: 	    '</td>'.
 3607: 	    &Apache::loncommon::end_data_table_row();
 3608: 	foreach my $line (@noupdate) {
 3609: 	    $result.=
 3610: 		&Apache::loncommon::start_data_table_row().
 3611: 		$line.
 3612: 		&Apache::loncommon::end_data_table_row();
 3613: 	}
 3614:     }
 3615:     $result .= &Apache::loncommon::end_data_table().
 3616: 	&show_grading_menu_form($symb);
 3617:     my $msg = '<p><b>'.
 3618: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3619: 	    $rec_update,$count).'</b><br />'.
 3620: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3621: 	'</b></p>';
 3622:     return $title.$msg.$result;
 3623: }
 3624: 
 3625: sub split_part_type {
 3626:     my ($partstr) = @_;
 3627:     my ($temp,@allparts)=split(/_/,$partstr);
 3628:     my $type=pop(@allparts);
 3629:     my $part=join('_',@allparts);
 3630:     return ($part,$type);
 3631: }
 3632: 
 3633: #------------- end of section for handling grading by section/class ---------
 3634: #
 3635: #----------------------------------------------------------------------------
 3636: 
 3637: 
 3638: #----------------------------------------------------------------------------
 3639: #
 3640: #-------------------------- Next few routines handles grading by csv upload
 3641: #
 3642: #--- Javascript to handle csv upload
 3643: sub csvupload_javascript_reverse_associate {
 3644:     my $error1=&mt('You need to specify the username or ID');
 3645:     my $error2=&mt('You need to specify at least one grading field');
 3646:   return(<<ENDPICK);
 3647:   function verify(vf) {
 3648:     var foundsomething=0;
 3649:     var founduname=0;
 3650:     var foundID=0;
 3651:     for (i=0;i<=vf.nfields.value;i++) {
 3652:       tw=eval('vf.f'+i+'.selectedIndex');
 3653:       if (i==0 && tw!=0) { foundID=1; }
 3654:       if (i==1 && tw!=0) { founduname=1; }
 3655:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3656:     }
 3657:     if (founduname==0 && foundID==0) {
 3658: 	alert('$error1');
 3659: 	return;
 3660:     }
 3661:     if (foundsomething==0) {
 3662: 	alert('$error2');
 3663: 	return;
 3664:     }
 3665:     vf.submit();
 3666:   }
 3667:   function flip(vf,tf) {
 3668:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3669:     var i;
 3670:     for (i=0;i<=vf.nfields.value;i++) {
 3671:       //can not pick the same destination field for both name and domain
 3672:       if (((i ==0)||(i ==1)) && 
 3673:           ((tf==0)||(tf==1)) && 
 3674:           (i!=tf) &&
 3675:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3676:         eval('vf.f'+i+'.selectedIndex=0;')
 3677:       }
 3678:     }
 3679:   }
 3680: ENDPICK
 3681: }
 3682: 
 3683: sub csvupload_javascript_forward_associate {
 3684:     my $error1=&mt('You need to specify the username or ID');
 3685:     my $error2=&mt('You need to specify at least one grading field');
 3686:   return(<<ENDPICK);
 3687:   function verify(vf) {
 3688:     var foundsomething=0;
 3689:     var founduname=0;
 3690:     var foundID=0;
 3691:     for (i=0;i<=vf.nfields.value;i++) {
 3692:       tw=eval('vf.f'+i+'.selectedIndex');
 3693:       if (tw==1) { foundID=1; }
 3694:       if (tw==2) { founduname=1; }
 3695:       if (tw>3) { foundsomething=1; }
 3696:     }
 3697:     if (founduname==0 && foundID==0) {
 3698: 	alert('$error1');
 3699: 	return;
 3700:     }
 3701:     if (foundsomething==0) {
 3702: 	alert('$error2');
 3703: 	return;
 3704:     }
 3705:     vf.submit();
 3706:   }
 3707:   function flip(vf,tf) {
 3708:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3709:     var i;
 3710:     //can not pick the same destination field twice
 3711:     for (i=0;i<=vf.nfields.value;i++) {
 3712:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3713:         eval('vf.f'+i+'.selectedIndex=0;')
 3714:       }
 3715:     }
 3716:   }
 3717: ENDPICK
 3718: }
 3719: 
 3720: sub csvuploadmap_header {
 3721:     my ($request,$symb,$datatoken,$distotal)= @_;
 3722:     my $javascript;
 3723:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3724: 	$javascript=&csvupload_javascript_reverse_associate();
 3725:     } else {
 3726: 	$javascript=&csvupload_javascript_forward_associate();
 3727:     }
 3728: 
 3729:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3730:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3731:     my $ignore=&mt('Ignore First Line');
 3732:     $symb = &Apache::lonenc::check_encrypt($symb);
 3733:     $request->print(<<ENDPICK);
 3734: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3735: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3736: $result
 3737: <hr />
 3738: <h3>Identify fields</h3>
 3739: Total number of records found in file: $distotal <hr />
 3740: Enter as many fields as you can. The system will inform you and bring you back
 3741: to this page if the data selected is insufficient to run your class.<hr />
 3742: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3743: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3744: <input type="hidden" name="associate"  value="" />
 3745: <input type="hidden" name="phase"      value="three" />
 3746: <input type="hidden" name="datatoken"  value="$datatoken" />
 3747: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3748: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3749: <input type="hidden" name="upfile_associate" 
 3750:                                        value="$env{'form.upfile_associate'}" />
 3751: <input type="hidden" name="symb"       value="$symb" />
 3752: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3753: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3754: <input type="hidden" name="command"    value="csvuploadoptions" />
 3755: <hr />
 3756: <script type="text/javascript" language="Javascript">
 3757: $javascript
 3758: </script>
 3759: ENDPICK
 3760:     return '';
 3761: 
 3762: }
 3763: 
 3764: sub csvupload_fields {
 3765:     my ($symb) = @_;
 3766:     my (@parts) = &getpartlist($symb);
 3767:     my @fields=(['ID','Student ID'],
 3768: 		['username','Student Username'],
 3769: 		['domain','Student Domain']);
 3770:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3771:     foreach my $part (sort(@parts)) {
 3772: 	my @datum;
 3773: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3774: 	my $name=$part;
 3775: 	if  (!$display) { $display = $name; }
 3776: 	@datum=($name,$display);
 3777: 	if ($name=~/^stores_(.*)_awarded/) {
 3778: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3779: 	}
 3780: 	push(@fields,\@datum);
 3781:     }
 3782:     return (@fields);
 3783: }
 3784: 
 3785: sub csvuploadmap_footer {
 3786:     my ($request,$i,$keyfields) =@_;
 3787:     $request->print(<<ENDPICK);
 3788: </table>
 3789: <input type="hidden" name="nfields" value="$i" />
 3790: <input type="hidden" name="keyfields" value="$keyfields" />
 3791: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3792: </form>
 3793: ENDPICK
 3794: }
 3795: 
 3796: sub checkforfile_js {
 3797:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3798:     my $result =<<CSVFORMJS;
 3799: <script type="text/javascript" language="javascript">
 3800:     function checkUpload(formname) {
 3801: 	if (formname.upfile.value == "") {
 3802: 	    alert("$alertmsg");
 3803: 	    return false;
 3804: 	}
 3805: 	formname.submit();
 3806:     }
 3807:     </script>
 3808: CSVFORMJS
 3809:     return $result;
 3810: }
 3811: 
 3812: sub upcsvScores_form {
 3813:     my ($request) = shift;
 3814:     my ($symb)=&get_symb($request);
 3815:     if (!$symb) {return '';}
 3816:     my $result=&checkforfile_js();
 3817:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3818:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3819:     $result.=$table;
 3820:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3821:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3822:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3823: 	'</b></td></tr>'."\n";
 3824:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3825:     my $upload=&mt("Upload Scores");
 3826:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3827:     my $ignore=&mt('Ignore First Line');
 3828:     $symb = &Apache::lonenc::check_encrypt($symb);
 3829:     $result.=<<ENDUPFORM;
 3830: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3831: <input type="hidden" name="symb" value="$symb" />
 3832: <input type="hidden" name="command" value="csvuploadmap" />
 3833: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3834: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3835: $upfile_select
 3836: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3837: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3838: </form>
 3839: ENDUPFORM
 3840:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3841:                            &mt("How do I create a CSV file from a spreadsheet"))
 3842:     .'</td></tr></table>'."\n";
 3843:     $result.='</td></tr></table><br /><br />'."\n";
 3844:     $result.=&show_grading_menu_form($symb);
 3845:     return $result;
 3846: }
 3847: 
 3848: 
 3849: sub csvuploadmap {
 3850:     my ($request)= @_;
 3851:     my ($symb)=&get_symb($request);
 3852:     if (!$symb) {return '';}
 3853: 
 3854:     my $datatoken;
 3855:     if (!$env{'form.datatoken'}) {
 3856: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3857:     } else {
 3858: 	$datatoken=$env{'form.datatoken'};
 3859: 	&Apache::loncommon::load_tmp_file($request);
 3860:     }
 3861:     my @records=&Apache::loncommon::upfile_record_sep();
 3862:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3863:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3864:     my ($i,$keyfields);
 3865:     if (@records) {
 3866: 	my @fields=&csvupload_fields($symb);
 3867: 
 3868: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3869: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3870: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3871: 							  \@fields);
 3872: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3873: 	    chop($keyfields);
 3874: 	} else {
 3875: 	    unshift(@fields,['none','']);
 3876: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3877: 							    \@fields);
 3878:             foreach my $rec (@records) {
 3879:                 my %temp = &Apache::loncommon::record_sep($rec);
 3880:                 if (%temp) {
 3881:                     $keyfields=join(',',sort(keys(%temp)));
 3882:                     last;
 3883:                 }
 3884:             }
 3885: 	}
 3886:     }
 3887:     &csvuploadmap_footer($request,$i,$keyfields);
 3888:     $request->print(&show_grading_menu_form($symb));
 3889: 
 3890:     return '';
 3891: }
 3892: 
 3893: sub csvuploadoptions {
 3894:     my ($request)= @_;
 3895:     my ($symb)=&get_symb($request);
 3896:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3897:     my $ignore=&mt('Ignore First Line');
 3898:     $request->print(<<ENDPICK);
 3899: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3900: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3901: <input type="hidden" name="command"    value="csvuploadassign" />
 3902: <!--
 3903: <p>
 3904: <label>
 3905:    <input type="checkbox" name="show_full_results" />
 3906:    Show a table of all changes
 3907: </label>
 3908: </p>
 3909: -->
 3910: <p>
 3911: <label>
 3912:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3913:    Overwrite any existing score
 3914: </label>
 3915: </p>
 3916: ENDPICK
 3917:     my %fields=&get_fields();
 3918:     if (!defined($fields{'domain'})) {
 3919: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3920: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3921:     }
 3922:     foreach my $key (sort(keys(%env))) {
 3923: 	if ($key !~ /^form\.(.*)$/) { next; }
 3924: 	my $cleankey=$1;
 3925: 	if ($cleankey eq 'command') { next; }
 3926: 	$request->print('<input type="hidden" name="'.$cleankey.
 3927: 			'"  value="'.$env{$key}.'" />'."\n");
 3928:     }
 3929:     # FIXME do a check for any duplicated user ids...
 3930:     # FIXME do a check for any invalid user ids?...
 3931:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3932: <hr /></form>'."\n");
 3933:     $request->print(&show_grading_menu_form($symb));
 3934:     return '';
 3935: }
 3936: 
 3937: sub get_fields {
 3938:     my %fields;
 3939:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3940:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3941: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3942: 	    if ($env{'form.f'.$i} ne 'none') {
 3943: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3944: 	    }
 3945: 	} else {
 3946: 	    if ($env{'form.f'.$i} ne 'none') {
 3947: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3948: 	    }
 3949: 	}
 3950:     }
 3951:     return %fields;
 3952: }
 3953: 
 3954: sub csvuploadassign {
 3955:     my ($request)= @_;
 3956:     my ($symb)=&get_symb($request);
 3957:     if (!$symb) {return '';}
 3958:     my $error_msg = '';
 3959:     &Apache::loncommon::load_tmp_file($request);
 3960:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3961:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3962:     my %fields=&get_fields();
 3963:     $request->print('<h3>Assigning Grades</h3>');
 3964:     my $courseid=$env{'request.course.id'};
 3965:     my ($classlist) = &getclasslist('all',0);
 3966:     my @notallowed;
 3967:     my @skipped;
 3968:     my $countdone=0;
 3969:     foreach my $grade (@gradedata) {
 3970: 	my %entries=&Apache::loncommon::record_sep($grade);
 3971: 	my $domain;
 3972: 	if ($entries{$fields{'domain'}}) {
 3973: 	    $domain=$entries{$fields{'domain'}};
 3974: 	} else {
 3975: 	    $domain=$env{'form.default_domain'};
 3976: 	}
 3977: 	$domain=~s/\s//g;
 3978: 	my $username=$entries{$fields{'username'}};
 3979: 	$username=~s/\s//g;
 3980: 	if (!$username) {
 3981: 	    my $id=$entries{$fields{'ID'}};
 3982: 	    $id=~s/\s//g;
 3983: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3984: 	    $username=$ids{$id};
 3985: 	}
 3986: 	if (!exists($$classlist{"$username:$domain"})) {
 3987: 	    my $id=$entries{$fields{'ID'}};
 3988: 	    $id=~s/\s//g;
 3989: 	    if ($id) {
 3990: 		push(@skipped,"$id:$domain");
 3991: 	    } else {
 3992: 		push(@skipped,"$username:$domain");
 3993: 	    }
 3994: 	    next;
 3995: 	}
 3996: 	my $usec=$classlist->{"$username:$domain"}[5];
 3997: 	if (!&canmodify($usec)) {
 3998: 	    push(@notallowed,"$username:$domain");
 3999: 	    next;
 4000: 	}
 4001: 	my %points;
 4002: 	my %grades;
 4003: 	foreach my $dest (keys(%fields)) {
 4004: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4005: 		$dest eq 'domain') { next; }
 4006: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4007: 	    if ($dest=~/stores_(.*)_points/) {
 4008: 		my $part=$1;
 4009: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4010: 					      $symb,$domain,$username);
 4011:                 if ($wgt) {
 4012:                     $entries{$fields{$dest}}=~s/\s//g;
 4013:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4014:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4015:                                           : 'correct_by_override';
 4016:                     $grades{"resource.$part.awarded"}=$pcr;
 4017:                     $grades{"resource.$part.solved"}=$award;
 4018:                     $points{$part}=1;
 4019:                 } else {
 4020:                     $error_msg = "<br />" .
 4021:                         &mt("Some point values were assigned"
 4022:                             ." for problems with a weight "
 4023:                             ."of zero. These values were "
 4024:                             ."ignored.");
 4025:                 }
 4026: 	    } else {
 4027: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4028: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4029: 		my $store_key=$dest;
 4030: 		$store_key=~s/^stores/resource/;
 4031: 		$store_key=~s/_/\./g;
 4032: 		$grades{$store_key}=$entries{$fields{$dest}};
 4033: 	    }
 4034: 	}
 4035: 	if (! %grades) { 
 4036:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4037:         } else {
 4038: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4039: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4040: 					   $env{'request.course.id'},
 4041: 					   $domain,$username);
 4042: 	   if ($result eq 'ok') {
 4043: 	      $request->print('.');
 4044: 	   } else {
 4045: 	      $request->print("<p><span class=\"LC_error\">".
 4046:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4047:                                   "$username:$domain",$result)."</span></p>");
 4048: 	   }
 4049: 	   $request->rflush();
 4050: 	   $countdone++;
 4051:         }
 4052:     }
 4053:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4054:     if (@skipped) {
 4055: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4056: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4057:     }
 4058:     if (@notallowed) {
 4059: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4060: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4061:     }
 4062:     $request->print("<br />\n");
 4063:     $request->print(&show_grading_menu_form($symb));
 4064:     return $error_msg;
 4065: }
 4066: #------------- end of section for handling csv file upload ---------
 4067: #
 4068: #-------------------------------------------------------------------
 4069: #
 4070: #-------------- Next few routines handle grading by page/sequence
 4071: #
 4072: #--- Select a page/sequence and a student to grade
 4073: sub pickStudentPage {
 4074:     my ($request) = shift;
 4075: 
 4076:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4077:     $request->print(<<LISTJAVASCRIPT);
 4078: <script type="text/javascript" language="javascript">
 4079: 
 4080: function checkPickOne(formname) {
 4081:     if (radioSelection(formname.student) == null) {
 4082: 	alert("$alertmsg");
 4083: 	return;
 4084:     }
 4085:     ptr = pullDownSelection(formname.selectpage);
 4086:     formname.page.value = formname["page"+ptr].value;
 4087:     formname.title.value = formname["title"+ptr].value;
 4088:     formname.submit();
 4089: }
 4090: 
 4091: </script>
 4092: LISTJAVASCRIPT
 4093:     &commonJSfunctions($request);
 4094:     my ($symb) = &get_symb($request);
 4095:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4096:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4097:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4098: 
 4099:     my $result='<h3><span class="LC_info">&nbsp;'.
 4100: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4101: 
 4102:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4103:     my ($titles,$symbx) = &getSymbMap();
 4104:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4105: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4106: #    my $type=($curpage =~ /\.(page|sequence)/);
 4107:     my $select = '<select name="selectpage">'."\n";
 4108:     my $ctr=0;
 4109:     foreach (@$titles) {
 4110: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4111: 	$select.='<option value="'.$ctr.'" '.
 4112: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4113: 	    '>'.$showtitle.'</option>'."\n";
 4114: 	$ctr++;
 4115:     }
 4116:     $select.= '</select>';
 4117:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4118: 
 4119:     $ctr=0;
 4120:     foreach (@$titles) {
 4121: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4122: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4123: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4124: 	$ctr++;
 4125:     }
 4126:     $result.='<input type="hidden" name="page" />'."\n".
 4127: 	'<input type="hidden" name="title" />'."\n";
 4128: 
 4129:     my $options =
 4130: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4131: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4132:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4133: 
 4134:     $options =
 4135: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4136: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4137: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4138:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4139:     
 4140:     $result.=&build_section_inputs();
 4141:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4142:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4143: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4144: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4145: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4146: 
 4147:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4148: 
 4149:     $result.='&nbsp;<input type="button" '.
 4150: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4151: 
 4152:     $request->print($result);
 4153: 
 4154:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4155: 	&Apache::loncommon::start_data_table().
 4156: 	&Apache::loncommon::start_data_table_header_row().
 4157: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4158: 	'<th>'.&nameUserString('header').'</th>'.
 4159: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4160: 	'<th>'.&nameUserString('header').'</th>'.
 4161: 	&Apache::loncommon::end_data_table_header_row();
 4162:  
 4163:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4164:     my $ptr = 1;
 4165:     foreach my $student (sort 
 4166: 			 {
 4167: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4168: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4169: 			     }
 4170: 			     return $a cmp $b;
 4171: 			 } (keys(%$fullname))) {
 4172: 	my ($uname,$udom) = split(/:/,$student);
 4173: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4174:                                   : '</td>');
 4175: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4176: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4177: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4178: 	$studentTable.=
 4179: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4180:                          : '');
 4181: 	$ptr++;
 4182:     }
 4183:     if ($ptr%2 == 0) {
 4184: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4185: 	    &Apache::loncommon::end_data_table_row();
 4186:     }
 4187:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4188:     $studentTable.='<input type="button" '.
 4189: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4190: 
 4191:     $studentTable.=&show_grading_menu_form($symb);
 4192:     $request->print($studentTable);
 4193: 
 4194:     return '';
 4195: }
 4196: 
 4197: sub getSymbMap {
 4198:     my $navmap = Apache::lonnavmaps::navmap->new();
 4199: 
 4200:     my %symbx = ();
 4201:     my @titles = ();
 4202:     my $minder = 0;
 4203: 
 4204:     # Gather every sequence that has problems.
 4205:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4206: 					       1,0,1);
 4207:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4208: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4209: 	    my $title = $minder.'.'.
 4210: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4211: 	    push(@titles, $title); # minder in case two titles are identical
 4212: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4213: 	    $minder++;
 4214: 	}
 4215:     }
 4216:     return \@titles,\%symbx;
 4217: }
 4218: 
 4219: #
 4220: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4221: sub displayPage {
 4222:     my ($request) = shift;
 4223: 
 4224:     my ($symb) = &get_symb($request);
 4225:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4226:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4227:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4228:     my $pageTitle = $env{'form.page'};
 4229:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4230:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4231:     my $usec=$classlist->{$env{'form.student'}}[5];
 4232: 
 4233:     #need to make sure we have the correct data for later EXT calls, 
 4234:     #thus invalidate the cache
 4235:     &Apache::lonnet::devalidatecourseresdata(
 4236:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4237:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4238:     &Apache::lonnet::clear_EXT_cache_status();
 4239: 
 4240:     if (!&canview($usec)) {
 4241: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4242: 	$request->print(&show_grading_menu_form($symb));
 4243: 	return;
 4244:     }
 4245:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4246:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4247: 	'</h3>'."\n";
 4248:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4249:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4250: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4251:     } else {
 4252: 	delete($env{'form.CODE'});
 4253:     }
 4254:     &sub_page_js($request);
 4255:     $request->print($result);
 4256: 
 4257:     my $navmap = Apache::lonnavmaps::navmap->new();
 4258:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4259:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4260:     if (!$map) {
 4261: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4262: 	$request->print(&show_grading_menu_form($symb));
 4263: 	return; 
 4264:     }
 4265:     my $iterator = $navmap->getIterator($map->map_start(),
 4266: 					$map->map_finish());
 4267: 
 4268:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4269: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4270: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4271: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4272: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4273: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4274: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4275: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4276: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4277: 
 4278:     if (defined($env{'form.CODE'})) {
 4279: 	$studentTable.=
 4280: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4281:     }
 4282:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4283: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4284: 
 4285:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4286: 	&Apache::loncommon::start_data_table().
 4287: 	&Apache::loncommon::start_data_table_header_row().
 4288: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4289: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4290: 	&Apache::loncommon::end_data_table_header_row();
 4291: 
 4292:     &Apache::lonxml::clear_problem_counter();
 4293:     my ($depth,$question,$prob) = (1,1,1);
 4294:     $iterator->next(); # skip the first BEGIN_MAP
 4295:     my $curRes = $iterator->next(); # for "current resource"
 4296:     while ($depth > 0) {
 4297:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4298:         if($curRes == $iterator->END_MAP) { $depth--; }
 4299: 
 4300:         if (ref($curRes) && $curRes->is_problem()) {
 4301: 	    my $parts = $curRes->parts();
 4302:             my $title = $curRes->compTitle();
 4303: 	    my $symbx = $curRes->symb();
 4304: 	    $studentTable.=
 4305: 		&Apache::loncommon::start_data_table_row().
 4306: 		'<td align="center" valign="top" >'.$prob.
 4307: 		(scalar(@{$parts}) == 1 ? '' 
 4308: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4309: 							scalar(@{$parts}))
 4310: 		 ).
 4311: 		 '</td>';
 4312: 	    $studentTable.='<td valign="top">';
 4313: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4314: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4315: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4316: 					     undef,'both',\%form);
 4317: 	    } else {
 4318: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4319: 		$companswer =~ s|<form(.*?)>||g;
 4320: 		$companswer =~ s|</form>||g;
 4321: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4322: #		    $companswer =~ s/$1/ /ms;
 4323: #		    $request->print('match='.$1."<br />\n");
 4324: #		}
 4325: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4326: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4327: 	    }
 4328: 
 4329: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4330: 
 4331: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4332: 		if ($record{'version'} eq '') {
 4333: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4334: 		} else {
 4335: 		    my %responseType = ();
 4336: 		    foreach my $partid (@{$parts}) {
 4337: 			my @responseIds =$curRes->responseIds($partid);
 4338: 			my @responseType =$curRes->responseType($partid);
 4339: 			my %responseIds;
 4340: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4341: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4342: 			}
 4343: 			$responseType{$partid} = \%responseIds;
 4344: 		    }
 4345: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4346: 
 4347: 		}
 4348: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4349: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4350: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4351: 									$env{'request.course.id'},
 4352: 									'','.submission');
 4353:  
 4354: 	    }
 4355: 	    if (&canmodify($usec)) {
 4356: 		foreach my $partid (@{$parts}) {
 4357: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4358: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4359: 		    $question++;
 4360: 		}
 4361: 		$prob++;
 4362: 	    }
 4363: 	    $studentTable.='</td></tr>';
 4364: 
 4365: 	}
 4366:         $curRes = $iterator->next();
 4367:     }
 4368: 
 4369:     $studentTable.='</table>'."\n".
 4370: 	'<input type="button" value="'.&mt('Save').'" '.
 4371: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4372: 	'</form>'."\n";
 4373:     $studentTable.=&show_grading_menu_form($symb);
 4374:     $request->print($studentTable);
 4375: 
 4376:     return '';
 4377: }
 4378: 
 4379: sub displaySubByDates {
 4380:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4381:     my $isCODE=0;
 4382:     my $isTask = ($symb =~/\.task$/);
 4383:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4384:     my $studentTable=&Apache::loncommon::start_data_table().
 4385: 	&Apache::loncommon::start_data_table_header_row().
 4386: 	'<th>'.&mt('Date/Time').'</th>'.
 4387: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4388: 	'<th>'.&mt('Submission').'</th>'.
 4389: 	'<th>'.&mt('Status').'</th>'.
 4390: 	&Apache::loncommon::end_data_table_header_row();
 4391:     my ($version);
 4392:     my %mark;
 4393:     my %orders;
 4394:     $mark{'correct_by_student'} = $checkIcon;
 4395:     if (!exists($$record{'1:timestamp'})) {
 4396: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4397:     }
 4398: 
 4399:     my $interaction;
 4400:     my $no_increment = 1;
 4401:     for ($version=1;$version<=$$record{'version'};$version++) {
 4402: 	my $timestamp = 
 4403: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4404: 	if (exists($$record{$version.':resource.0.version'})) {
 4405: 	    $interaction = $$record{$version.':resource.0.version'};
 4406: 	}
 4407: 
 4408: 	my $where = ($isTask ? "$version:resource.$interaction"
 4409: 		             : "$version:resource");
 4410: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4411: 	    '<td>'.$timestamp.'</td>';
 4412: 	if ($isCODE) {
 4413: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4414: 	}
 4415: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4416: 	my @displaySub = ();
 4417: 	foreach my $partid (@{$parts}) {
 4418: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4419: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4420: 	    
 4421: 
 4422: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4423: 	    my $display_part=&get_display_part($partid,$symb);
 4424: 	    foreach my $matchKey (@matchKey) {
 4425: 		if (exists($$record{$version.':'.$matchKey}) &&
 4426: 		    $$record{$version.':'.$matchKey} ne '') {
 4427: 
 4428: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4429: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4430: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4431: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4432: 			$responseId.')</span>&nbsp;<b>';
 4433: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4434: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4435: 		    } else {
 4436: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4437: 					    $$record{"$where.$partid.tries"});
 4438: 		    }
 4439: 		    my $responseType=($isTask ? 'Task'
 4440:                                               : $responseType->{$partid}->{$responseId});
 4441: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4442: 		    if (!exists($orders{$partid}->{$responseId})) {
 4443: 			$orders{$partid}->{$responseId}=
 4444: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4445:                                        $no_increment);
 4446: 		    }
 4447: 		    $displaySub[0].='</b>&nbsp; '.
 4448: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4449: 		}
 4450: 	    }
 4451: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4452: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4453: 				    $$record{"$where.$partid.checkedin"},
 4454: 				    $$record{"$where.$partid.checkedin.slot"}).
 4455: 					'<br />';
 4456: 	    }
 4457: 	    if (exists $$record{"$where.$partid.award"}) {
 4458: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4459: 		    lc($$record{"$where.$partid.award"}).' '.
 4460: 		    $mark{$$record{"$where.$partid.solved"}}.
 4461: 		    '<br />';
 4462: 	    }
 4463: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4464: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4465: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4466: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4467: 		$displaySub[2].=
 4468: 		    $$record{"$version:resource.$partid.regrader"}.
 4469: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4470: 	    }
 4471: 	}
 4472: 	# needed because old essay regrader has not parts info
 4473: 	if (exists $$record{"$version:resource.regrader"}) {
 4474: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4475: 	}
 4476: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4477: 	if ($displaySub[2]) {
 4478: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4479: 	}
 4480: 	$studentTable.='&nbsp;</td>'.
 4481: 	    &Apache::loncommon::end_data_table_row();
 4482:     }
 4483:     $studentTable.=&Apache::loncommon::end_data_table();
 4484:     return $studentTable;
 4485: }
 4486: 
 4487: sub updateGradeByPage {
 4488:     my ($request) = shift;
 4489: 
 4490:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4491:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4492:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4493:     my $pageTitle = $env{'form.page'};
 4494:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4495:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4496:     my $usec=$classlist->{$env{'form.student'}}[5];
 4497:     if (!&canmodify($usec)) {
 4498: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4499: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4500: 	return;
 4501:     }
 4502:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4503:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4504: 	'</h3>'."\n";
 4505: 
 4506:     $request->print($result);
 4507: 
 4508:     my $navmap = Apache::lonnavmaps::navmap->new();
 4509:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4510:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4511:     if (!$map) {
 4512: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4513: 	my ($symb)=&get_symb($request);
 4514: 	$request->print(&show_grading_menu_form($symb));
 4515: 	return; 
 4516:     }
 4517:     my $iterator = $navmap->getIterator($map->map_start(),
 4518: 					$map->map_finish());
 4519: 
 4520:     my $studentTable=
 4521: 	&Apache::loncommon::start_data_table().
 4522: 	&Apache::loncommon::start_data_table_header_row().
 4523: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4524: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4525: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4526: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4527: 	&Apache::loncommon::end_data_table_header_row();
 4528: 
 4529:     $iterator->next(); # skip the first BEGIN_MAP
 4530:     my $curRes = $iterator->next(); # for "current resource"
 4531:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4532:     while ($depth > 0) {
 4533:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4534:         if($curRes == $iterator->END_MAP) { $depth--; }
 4535: 
 4536:         if (ref($curRes) && $curRes->is_problem()) {
 4537: 	    my $parts = $curRes->parts();
 4538:             my $title = $curRes->compTitle();
 4539: 	    my $symbx = $curRes->symb();
 4540: 	    $studentTable.=
 4541: 		&Apache::loncommon::start_data_table_row().
 4542: 		'<td align="center" valign="top" >'.$prob.
 4543: 		(scalar(@{$parts}) == 1 ? '' 
 4544:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4545: 		.')').'</td>';
 4546: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4547: 
 4548: 	    my %newrecord=();
 4549: 	    my @displayPts=();
 4550:             my %aggregate = ();
 4551:             my $aggregateflag = 0;
 4552: 	    foreach my $partid (@{$parts}) {
 4553: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4554: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4555: 
 4556: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4557: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4558: 		my $partial = $newpts/$wgt;
 4559: 		my $score;
 4560: 		if ($partial > 0) {
 4561: 		    $score = 'correct_by_override';
 4562: 		} elsif ($newpts ne '') { #empty is taken as 0
 4563: 		    $score = 'incorrect_by_override';
 4564: 		}
 4565: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4566: 		if ($dropMenu eq 'excused') {
 4567: 		    $partial = '';
 4568: 		    $score = 'excused';
 4569: 		} elsif ($dropMenu eq 'reset status'
 4570: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4571: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4572: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4573: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4574: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4575: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4576: 		    $changeflag++;
 4577: 		    $newpts = '';
 4578:                     
 4579:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4580:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4581:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4582:                     if ($aggtries > 0) {
 4583:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4584:                         $aggregateflag = 1;
 4585:                     }
 4586: 		}
 4587: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4588: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4589: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4590: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4591: 		    '&nbsp;<br />';
 4592: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4593: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4594: 		    '&nbsp;<br />';
 4595: 		$question++;
 4596: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4597: 
 4598: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4599: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4600: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4601: 		    if (scalar(keys(%newrecord)) > 0);
 4602: 
 4603: 		$changeflag++;
 4604: 	    }
 4605: 	    if (scalar(keys(%newrecord)) > 0) {
 4606: 		my %record = 
 4607: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4608: 					     $udom,$uname);
 4609: 
 4610: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4611: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4612: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4613: 		    $newrecord{'resource.CODE'} = '';
 4614: 		}
 4615: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4616: 					$udom,$uname);
 4617: 		%record = &Apache::lonnet::restore($symbx,
 4618: 						   $env{'request.course.id'},
 4619: 						   $udom,$uname);
 4620: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4621: 					     $cdom,$cnum,$udom,$uname);
 4622: 	    }
 4623: 	    
 4624:             if ($aggregateflag) {
 4625:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4626:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4627:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4628:             }
 4629: 
 4630: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4631: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4632: 		&Apache::loncommon::end_data_table_row();
 4633: 
 4634: 	    $prob++;
 4635: 	}
 4636:         $curRes = $iterator->next();
 4637:     }
 4638: 
 4639:     $studentTable.=&Apache::loncommon::end_data_table();
 4640:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4641:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4642: 		  &mt('The scores were changed for [quant,_1,problem].',
 4643: 		  $changeflag));
 4644:     $request->print($grademsg.$studentTable);
 4645: 
 4646:     return '';
 4647: }
 4648: 
 4649: #-------- end of section for handling grading by page/sequence ---------
 4650: #
 4651: #-------------------------------------------------------------------
 4652: 
 4653: #--------------------Scantron Grading-----------------------------------
 4654: #
 4655: #------ start of section for handling grading by page/sequence ---------
 4656: 
 4657: =pod
 4658: 
 4659: =head1 Bubble sheet grading routines
 4660: 
 4661:   For this documentation:
 4662: 
 4663:    'scanline' refers to the full line of characters
 4664:    from the file that we are parsing that represents one entire sheet
 4665: 
 4666:    'bubble line' refers to the data
 4667:    representing the line of bubbles that are on the physical bubble sheet
 4668: 
 4669: 
 4670: The overall process is that a scanned in bubble sheet data is uploaded
 4671: into a course. When a user wants to grade, they select a
 4672: sequence/folder of resources, a file of bubble sheet info, and pick
 4673: one of the predefined configurations for what each scanline looks
 4674: like.
 4675: 
 4676: Next each scanline is checked for any errors of either 'missing
 4677: bubbles' (it's an error because it may have been mis-scanned
 4678: because too light bubbling), 'double bubble' (each bubble line should
 4679: have no more that one letter picked), invalid or duplicated CODE,
 4680: invalid student ID
 4681: 
 4682: If the CODE option is used that determines the randomization of the
 4683: homework problems, either way the student ID is looked up into a
 4684: username:domain.
 4685: 
 4686: During the validation phase the instructor can choose to skip scanlines. 
 4687: 
 4688: After the validation phase, there are now 3 bubble sheet files
 4689: 
 4690:   scantron_original_filename (unmodified original file)
 4691:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4692:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4693: 
 4694: Also there is a separate hash nohist_scantrondata that contains extra
 4695: correction information that isn't representable in the bubble sheet
 4696: file (see &scantron_getfile() for more information)
 4697: 
 4698: After all scanlines are either valid, marked as valid or skipped, then
 4699: foreach line foreach problem in the picked sequence, an ssi request is
 4700: made that simulates a user submitting their selected letter(s) against
 4701: the homework problem.
 4702: 
 4703: =over 4
 4704: 
 4705: 
 4706: 
 4707: =item defaultFormData
 4708: 
 4709:   Returns html hidden inputs used to hold context/default values.
 4710: 
 4711:  Arguments:
 4712:   $symb - $symb of the current resource 
 4713: 
 4714: =cut
 4715: 
 4716: sub defaultFormData {
 4717:     my ($symb)=@_;
 4718:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4719:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4720:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4721: }
 4722: 
 4723: 
 4724: =pod 
 4725: 
 4726: =item getSequenceDropDown
 4727: 
 4728:    Return html dropdown of possible sequences to grade
 4729:  
 4730:  Arguments:
 4731:    $symb - $symb of the current resource 
 4732: 
 4733: =cut
 4734: 
 4735: sub getSequenceDropDown {
 4736:     my ($symb)=@_;
 4737:     my $result='<select name="selectpage">'."\n";
 4738:     my ($titles,$symbx) = &getSymbMap();
 4739:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4740:     my $ctr=0;
 4741:     foreach (@$titles) {
 4742: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4743: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4744: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4745: 	    '>'.$showtitle.'</option>'."\n";
 4746: 	$ctr++;
 4747:     }
 4748:     $result.= '</select>';
 4749:     return $result;
 4750: }
 4751: 
 4752: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4753:                                    # key is zero-based index - 0, 1, 2 ...
 4754: 
 4755: my %first_bubble_line;             # First bubble line no. for each bubble.
 4756: 
 4757: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4758:                                    # matchresponse or rankresponse, where 
 4759:                                    # an individual response can have multiple 
 4760:                                    # lines
 4761: 
 4762: my %responsetype_per_response;     # responsetype for each response
 4763: 
 4764: # Save and restore the bubble lines array to the form env.
 4765: 
 4766: 
 4767: sub save_bubble_lines {
 4768:     foreach my $line (keys(%bubble_lines_per_response)) {
 4769: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4770: 	$env{"form.scantron.first_bubble_line.$line"} =
 4771: 	    $first_bubble_line{$line};
 4772:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4773:             $subdivided_bubble_lines{$line};
 4774:         $env{"form.scantron.responsetype.$line"} =
 4775:             $responsetype_per_response{$line};
 4776:     }
 4777: }
 4778: 
 4779: 
 4780: sub restore_bubble_lines {
 4781:     my $line = 0;
 4782:     %bubble_lines_per_response = ();
 4783:     while ($env{"form.scantron.bubblelines.$line"}) {
 4784: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4785: 	$bubble_lines_per_response{$line} = $value;
 4786: 	$first_bubble_line{$line}  =
 4787: 	    $env{"form.scantron.first_bubble_line.$line"};
 4788:         $subdivided_bubble_lines{$line} =
 4789:             $env{"form.scantron.sub_bubblelines.$line"};
 4790:         $responsetype_per_response{$line} =
 4791:             $env{"form.scantron.responsetype.$line"};
 4792: 	$line++;
 4793:     }
 4794: }
 4795: 
 4796: #  Given the parsed scanline, get the response for 
 4797: #  'answer' number n:
 4798: 
 4799: sub get_response_bubbles {
 4800:     my ($parsed_line, $response)  = @_;
 4801: 
 4802:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4803:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4804:     
 4805:     my $selected = "";
 4806: 
 4807:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4808: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4809: 	$bubble_line++;
 4810:     }
 4811:     return $selected;
 4812: }
 4813: 
 4814: =pod 
 4815: 
 4816: =item scantron_filenames
 4817: 
 4818:    Returns a list of the scantron files in the current course 
 4819: 
 4820: =cut
 4821: 
 4822: sub scantron_filenames {
 4823:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4824:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4825:     my $getpropath = 1;
 4826:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4827:                                        $getpropath);
 4828:     my @possiblenames;
 4829:     foreach my $filename (sort(@files)) {
 4830: 	($filename)=split(/&/,$filename);
 4831: 	if ($filename!~/^scantron_orig_/) { next ; }
 4832: 	$filename=~s/^scantron_orig_//;
 4833: 	push(@possiblenames,$filename);
 4834:     }
 4835:     return @possiblenames;
 4836: }
 4837: 
 4838: =pod 
 4839: 
 4840: =item scantron_uploads
 4841: 
 4842:    Returns  html drop-down list of scantron files in current course.
 4843: 
 4844:  Arguments:
 4845:    $file2grade - filename to set as selected in the dropdown
 4846: 
 4847: =cut
 4848: 
 4849: sub scantron_uploads {
 4850:     my ($file2grade) = @_;
 4851:     my $result=	'<select name="scantron_selectfile">';
 4852:     $result.="<option></option>";
 4853:     foreach my $filename (sort(&scantron_filenames())) {
 4854: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4855:     }
 4856:     $result.="</select>";
 4857:     return $result;
 4858: }
 4859: 
 4860: =pod 
 4861: 
 4862: =item scantron_scantab
 4863: 
 4864:   Returns html drop down of the scantron formats in the scantronformat.tab
 4865:   file.
 4866: 
 4867: =cut
 4868: 
 4869: sub scantron_scantab {
 4870:     my $result='<select name="scantron_format">'."\n";
 4871:     $result.='<option></option>'."\n";
 4872:     my @lines = &get_scantronformat_file();
 4873:     if (@lines > 0) {
 4874:         foreach my $line (@lines) {
 4875:             next if (($line =~ /^\#/) || ($line eq ''));
 4876: 	    my ($name,$descrip)=split(/:/,$line);
 4877: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4878:         }
 4879:     }
 4880:     $result.='</select>'."\n";
 4881:     return $result;
 4882: }
 4883: 
 4884: =pod
 4885: 
 4886: =item get_scantronformat_file
 4887: 
 4888:   Returns an array containing lines from the scantron format file for
 4889:   the domain of the course.
 4890: 
 4891:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4892:   lines are from this file.
 4893: 
 4894:   Otherwise, if a default.tab has been published in RES space by the 
 4895:   domainconfig user, lines are from this file.
 4896: 
 4897:   Otherwise, fall back to getting lines from the legacy file on the
 4898:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4899: 
 4900: =cut
 4901: 
 4902: sub get_scantronformat_file {
 4903:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4904:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4905:     my $gottab = 0;
 4906:     my @lines;
 4907:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4908:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4909:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4910:             if ($formatfile ne '-1') {
 4911:                 @lines = split("\n",$formatfile,-1);
 4912:                 $gottab = 1;
 4913:             }
 4914:         }
 4915:     }
 4916:     if (!$gottab) {
 4917:         my $confname = $cdom.'-domainconfig';
 4918:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4919:         my $formatfile =  &Apache::lonnet::getfile($default);
 4920:         if ($formatfile ne '-1') {
 4921:             @lines = split("\n",$formatfile,-1);
 4922:             $gottab = 1;
 4923:         }
 4924:     }
 4925:     if (!$gottab) {
 4926:         my @domains = &Apache::lonnet::current_machine_domains();
 4927:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4928:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4929:             @lines = <$fh>;
 4930:             close($fh);
 4931:         } else {
 4932:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4933:             @lines = <$fh>;
 4934:             close($fh);
 4935:         }
 4936:     }
 4937:     return @lines;
 4938: }
 4939: 
 4940: =pod 
 4941: 
 4942: =item scantron_CODElist
 4943: 
 4944:   Returns html drop down of the saved CODE lists from current course,
 4945:   generated from earlier printings.
 4946: 
 4947: =cut
 4948: 
 4949: sub scantron_CODElist {
 4950:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4951:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4952:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4953:     my $namechoice='<option></option>';
 4954:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4955: 	if ($name =~ /^error: 2 /) { next; }
 4956: 	if ($name =~ /^type\0/) { next; }
 4957: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4958:     }
 4959:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4960:     return $namechoice;
 4961: }
 4962: 
 4963: =pod 
 4964: 
 4965: =item scantron_CODEunique
 4966: 
 4967:   Returns the html for "Each CODE to be used once" radio.
 4968: 
 4969: =cut
 4970: 
 4971: sub scantron_CODEunique {
 4972:     my $result='<span class="LC_nobreak">
 4973:                  <label><input type="radio" name="scantron_CODEunique"
 4974:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4975:                 </span>
 4976:                 <span class="LC_nobreak">
 4977:                  <label><input type="radio" name="scantron_CODEunique"
 4978:                         value="no" />'.&mt('No').' </label>
 4979:                 </span>';
 4980:     return $result;
 4981: }
 4982: 
 4983: =pod 
 4984: 
 4985: =item scantron_selectphase
 4986: 
 4987:   Generates the initial screen to start the bubble sheet process.
 4988:   Allows for - starting a grading run.
 4989:              - downloading existing scan data (original, corrected
 4990:                                                 or skipped info)
 4991: 
 4992:              - uploading new scan data
 4993: 
 4994:  Arguments:
 4995:   $r          - The Apache request object
 4996:   $file2grade - name of the file that contain the scanned data to score
 4997: 
 4998: =cut
 4999: 
 5000: sub scantron_selectphase {
 5001:     my ($r,$file2grade) = @_;
 5002:     my ($symb)=&get_symb($r);
 5003:     if (!$symb) {return '';}
 5004:     my $sequence_selector=&getSequenceDropDown($symb);
 5005:     my $default_form_data=&defaultFormData($symb);
 5006:     my $grading_menu_button=&show_grading_menu_form($symb);
 5007:     my $file_selector=&scantron_uploads($file2grade);
 5008:     my $format_selector=&scantron_scantab();
 5009:     my $CODE_selector=&scantron_CODElist();
 5010:     my $CODE_unique=&scantron_CODEunique();
 5011:     my $result;
 5012: 
 5013:     $ssi_error = 0;
 5014: 
 5015:     # Chunk of form to prompt for a file to grade and how:
 5016: 
 5017:     $result.= '
 5018:     <br />
 5019:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5020:     <input type="hidden" name="command" value="scantron_warning" />
 5021:     '.$default_form_data.'
 5022:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5023:        '.&Apache::loncommon::start_data_table_header_row().'
 5024:             <th colspan="2">
 5025:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5026:             </th>
 5027:        '.&Apache::loncommon::end_data_table_header_row().'
 5028:        '.&Apache::loncommon::start_data_table_row().'
 5029:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5030:        '.&Apache::loncommon::end_data_table_row().'
 5031:        '.&Apache::loncommon::start_data_table_row().'
 5032:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5033:        '.&Apache::loncommon::end_data_table_row().'
 5034:        '.&Apache::loncommon::start_data_table_row().'
 5035:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5036:        '.&Apache::loncommon::end_data_table_row().'
 5037:        '.&Apache::loncommon::start_data_table_row().'
 5038:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5039:        '.&Apache::loncommon::end_data_table_row().'
 5040:        '.&Apache::loncommon::start_data_table_row().'
 5041:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5042:        '.&Apache::loncommon::end_data_table_row().'
 5043:        '.&Apache::loncommon::start_data_table_row().'
 5044: 	    <td> '.&mt('Options:').' </td>
 5045:             <td>
 5046: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5047:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5048:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5049: 	    </td>
 5050:        '.&Apache::loncommon::end_data_table_row().'
 5051:        '.&Apache::loncommon::start_data_table_row().'
 5052:             <td colspan="2">
 5053:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5054:             </td>
 5055:        '.&Apache::loncommon::end_data_table_row().'
 5056:     '.&Apache::loncommon::end_data_table().'
 5057:     </form>
 5058: ';
 5059:    
 5060:     $r->print($result);
 5061: 
 5062:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5063:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5064: 
 5065: 	# Chunk of form to prompt for a scantron file upload.
 5066: 
 5067:         $r->print('
 5068:     <br />
 5069:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5070:        '.&Apache::loncommon::start_data_table_header_row().'
 5071:             <th>
 5072:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5073:             </th>
 5074:        '.&Apache::loncommon::end_data_table_header_row().'
 5075:        '.&Apache::loncommon::start_data_table_row().'
 5076:             <td>
 5077: ');
 5078:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5079:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5080:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5081:     $r->print('
 5082:               <script type="text/javascript" language="javascript">
 5083:     function checkUpload(formname) {
 5084: 	if (formname.upfile.value == "") {
 5085: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5086: 	    return false;
 5087: 	}
 5088: 	formname.submit();
 5089:     }
 5090:               </script>
 5091: 
 5092:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5093:                 '.$default_form_data.'
 5094:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5095:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5096:                 <input name="command" value="scantronupload_save" type="hidden" />
 5097:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5098:                 <br />
 5099:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5100:               </form>
 5101: ');
 5102: 
 5103:         $r->print('
 5104:             </td>
 5105:        '.&Apache::loncommon::end_data_table_row().'
 5106:        '.&Apache::loncommon::end_data_table().'
 5107: ');
 5108:     }
 5109: 
 5110:     # Chunk of the form that prompts to view a scoring office file,
 5111:     # corrected file, skipped records in a file.
 5112: 
 5113:     $r->print('
 5114:    <br />
 5115:    <form action="/adm/grades" name="scantron_download">
 5116:      '.$default_form_data.'
 5117:      <input type="hidden" name="command" value="scantron_download" />
 5118:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5119:        '.&Apache::loncommon::start_data_table_header_row().'
 5120:               <th>
 5121:                 &nbsp;'.&mt('Download a scoring office file').'
 5122:               </th>
 5123:        '.&Apache::loncommon::end_data_table_header_row().'
 5124:        '.&Apache::loncommon::start_data_table_row().'
 5125:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5126:                 <br />
 5127:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5128:        '.&Apache::loncommon::end_data_table_row().'
 5129:      '.&Apache::loncommon::end_data_table().'
 5130:    </form>
 5131:    <br />
 5132: ');
 5133: 
 5134:     &Apache::lonpickcode::code_list($r,2);
 5135: 
 5136:     $r->print('<br /><form method="post" name="checkscantron">'.
 5137:              $default_form_data."\n".
 5138:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5139:              &Apache::loncommon::start_data_table_header_row()."\n".
 5140:              '<th colspan="2">
 5141:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5142:              '</th>'."\n".
 5143:               &Apache::loncommon::end_data_table_header_row()."\n".
 5144:               &Apache::loncommon::start_data_table_row()."\n".
 5145:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5146:               '<td> '.$sequence_selector.' </td>'.
 5147:               &Apache::loncommon::end_data_table_row()."\n".
 5148:               &Apache::loncommon::start_data_table_row()."\n".
 5149:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5150:               '<td> '.$file_selector.' </td>'."\n".
 5151:               &Apache::loncommon::end_data_table_row()."\n".
 5152:               &Apache::loncommon::start_data_table_row()."\n".
 5153:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5154:               '<td> '.$format_selector.' </td>'."\n".
 5155:               &Apache::loncommon::end_data_table_row()."\n".
 5156:               &Apache::loncommon::start_data_table_row()."\n".
 5157:               '<td colspan="2">'."\n".
 5158:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5159:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5160:               '</td>'."\n".
 5161:               &Apache::loncommon::end_data_table_row()."\n".
 5162:               &Apache::loncommon::end_data_table()."\n".
 5163:               '</form><br />');
 5164:     $r->print($grading_menu_button);
 5165:     return;
 5166: }
 5167: 
 5168: =pod
 5169: 
 5170: =item get_scantron_config
 5171: 
 5172:    Parse and return the scantron configuration line selected as a
 5173:    hash of configuration file fields.
 5174: 
 5175:  Arguments:
 5176:     which - the name of the configuration to parse from the file.
 5177: 
 5178: 
 5179:  Returns:
 5180:             If the named configuration is not in the file, an empty
 5181:             hash is returned.
 5182:     a hash with the fields
 5183:       name         - internal name for the this configuration setup
 5184:       description  - text to display to operator that describes this config
 5185:       CODElocation - if 0 or the string 'none'
 5186:                           - no CODE exists for this config
 5187:                      if -1 || the string 'letter'
 5188:                           - a CODE exists for this config and is
 5189:                             a string of letters
 5190:                      Unsupported value (but planned for future support)
 5191:                           if a positive integer
 5192:                                - The CODE exists as the first n items from
 5193:                                  the question section of the form
 5194:                           if the string 'number'
 5195:                                - The CODE exists for this config and is
 5196:                                  a string of numbers
 5197:       CODEstart   - (only matter if a CODE exists) column in the line where
 5198:                      the CODE starts
 5199:       CODElength  - length of the CODE
 5200:       IDstart     - column where the student ID number starts
 5201:       IDlength    - length of the student ID info
 5202:       Qstart      - column where the information from the bubbled
 5203:                     'questions' start
 5204:       Qlength     - number of columns comprising a single bubble line from
 5205:                     the sheet. (usually either 1 or 10)
 5206:       Qon         - either a single character representing the character used
 5207:                     to signal a bubble was chosen in the positional setup, or
 5208:                     the string 'letter' if the letter of the chosen bubble is
 5209:                     in the final, or 'number' if a number representing the
 5210:                     chosen bubble is in the file (1->A 0->J)
 5211:       Qoff        - the character used to represent that a bubble was
 5212:                     left blank
 5213:       PaperID     - if the scanning process generates a unique number for each
 5214:                     sheet scanned the column that this ID number starts in
 5215:       PaperIDlength - number of columns that comprise the unique ID number
 5216:                       for the sheet of paper
 5217:       FirstName   - column that the first name starts in
 5218:       FirstNameLength - number of columns that the first name spans
 5219:  
 5220:       LastName    - column that the last name starts in
 5221:       LastNameLength - number of columns that the last name spans
 5222: 
 5223: =cut
 5224: 
 5225: sub get_scantron_config {
 5226:     my ($which) = @_;
 5227:     my @lines = &get_scantronformat_file();
 5228:     my %config;
 5229:     #FIXME probably should move to XML it has already gotten a bit much now
 5230:     foreach my $line (@lines) {
 5231: 	my ($name,$descrip)=split(/:/,$line);
 5232: 	if ($name ne $which ) { next; }
 5233: 	chomp($line);
 5234: 	my @config=split(/:/,$line);
 5235: 	$config{'name'}=$config[0];
 5236: 	$config{'description'}=$config[1];
 5237: 	$config{'CODElocation'}=$config[2];
 5238: 	$config{'CODEstart'}=$config[3];
 5239: 	$config{'CODElength'}=$config[4];
 5240: 	$config{'IDstart'}=$config[5];
 5241: 	$config{'IDlength'}=$config[6];
 5242: 	$config{'Qstart'}=$config[7];
 5243:  	$config{'Qlength'}=$config[8];
 5244: 	$config{'Qoff'}=$config[9];
 5245: 	$config{'Qon'}=$config[10];
 5246: 	$config{'PaperID'}=$config[11];
 5247: 	$config{'PaperIDlength'}=$config[12];
 5248: 	$config{'FirstName'}=$config[13];
 5249: 	$config{'FirstNamelength'}=$config[14];
 5250: 	$config{'LastName'}=$config[15];
 5251: 	$config{'LastNamelength'}=$config[16];
 5252: 	last;
 5253:     }
 5254:     return %config;
 5255: }
 5256: 
 5257: =pod 
 5258: 
 5259: =item username_to_idmap
 5260: 
 5261:     creates a hash keyed by student id with values of the corresponding
 5262:     student username:domain.
 5263: 
 5264:   Arguments:
 5265: 
 5266:     $classlist - reference to the class list hash. This is a hash
 5267:                  keyed by student name:domain  whose elements are references
 5268:                  to arrays containing various chunks of information
 5269:                  about the student. (See loncoursedata for more info).
 5270: 
 5271:   Returns
 5272:     %idmap - the constructed hash
 5273: 
 5274: =cut
 5275: 
 5276: sub username_to_idmap {
 5277:     my ($classlist)= @_;
 5278:     my %idmap;
 5279:     foreach my $student (keys(%$classlist)) {
 5280: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5281: 	    $student;
 5282:     }
 5283:     return %idmap;
 5284: }
 5285: 
 5286: =pod
 5287: 
 5288: =item scantron_fixup_scanline
 5289: 
 5290:    Process a requested correction to a scanline.
 5291: 
 5292:   Arguments:
 5293:     $scantron_config   - hash from &get_scantron_config()
 5294:     $scan_data         - hash of correction information 
 5295:                           (see &scantron_getfile())
 5296:     $line              - existing scanline
 5297:     $whichline         - line number of the passed in scanline
 5298:     $field             - type of change to process 
 5299:                          (either 
 5300:                           'ID'     -> correct the student ID number
 5301:                           'CODE'   -> correct the CODE
 5302:                           'answer' -> fixup the submitted answers)
 5303:     
 5304:    $args               - hash of additional info,
 5305:                           - 'ID' 
 5306:                                'newid' -> studentID to use in replacement
 5307:                                           of existing one
 5308:                           - 'CODE' 
 5309:                                'CODE_ignore_dup' - set to true if duplicates
 5310:                                                    should be ignored.
 5311: 	                       'CODE' - is new code or 'use_unfound'
 5312:                                         if the existing unfound code should
 5313:                                         be used as is
 5314:                           - 'answer'
 5315:                                'response' - new answer or 'none' if blank
 5316:                                'question' - the bubble line to change
 5317:                                'questionnum' - the question identifier,
 5318:                                                may include subquestion. 
 5319: 
 5320:   Returns:
 5321:     $line - the modified scanline
 5322: 
 5323:   Side effects: 
 5324:     $scan_data - may be updated
 5325: 
 5326: =cut
 5327: 
 5328: 
 5329: sub scantron_fixup_scanline {
 5330:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5331:     if ($field eq 'ID') {
 5332: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5333: 	    return ($line,1,'New value too large');
 5334: 	}
 5335: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5336: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5337: 				     $args->{'newid'});
 5338: 	}
 5339: 	substr($line,$$scantron_config{'IDstart'}-1,
 5340: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5341: 	if ($args->{'newid'}=~/^\s*$/) {
 5342: 	    &scan_data($scan_data,"$whichline.user",
 5343: 		       $args->{'username'}.':'.$args->{'domain'});
 5344: 	}
 5345:     } elsif ($field eq 'CODE') {
 5346: 	if ($args->{'CODE_ignore_dup'}) {
 5347: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5348: 	}
 5349: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5350: 	if ($args->{'CODE'} ne 'use_unfound') {
 5351: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5352: 		return ($line,1,'New CODE value too large');
 5353: 	    }
 5354: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5355: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5356: 	    }
 5357: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5358: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5359: 	}
 5360:     } elsif ($field eq 'answer') {
 5361: 	my $length=$scantron_config->{'Qlength'};
 5362: 	my $off=$scantron_config->{'Qoff'};
 5363: 	my $on=$scantron_config->{'Qon'};
 5364: 	my $answer=${off}x$length;
 5365: 	if ($args->{'response'} eq 'none') {
 5366: 	    &scan_data($scan_data,
 5367: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5368: 	} else {
 5369: 	    if ($on eq 'letter') {
 5370: 		my @alphabet=('A'..'Z');
 5371: 		$answer=$alphabet[$args->{'response'}];
 5372: 	    } elsif ($on eq 'number') {
 5373: 		$answer=$args->{'response'}+1;
 5374: 		if ($answer == 10) { $answer = '0'; }
 5375: 	    } else {
 5376: 		substr($answer,$args->{'response'},1)=$on;
 5377: 	    }
 5378: 	    &scan_data($scan_data,
 5379: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5380: 	}
 5381: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5382: 	substr($line,$where-1,$length)=$answer;
 5383:     }
 5384:     return $line;
 5385: }
 5386: 
 5387: =pod
 5388: 
 5389: =item scan_data
 5390: 
 5391:     Edit or look up  an item in the scan_data hash.
 5392: 
 5393:   Arguments:
 5394:     $scan_data  - The hash (see scantron_getfile)
 5395:     $key        - shorthand of the key to edit (actual key is
 5396:                   scantronfilename_key).
 5397:     $data        - New value of the hash entry.
 5398:     $delete      - If true, the entry is removed from the hash.
 5399: 
 5400:   Returns:
 5401:     The new value of the hash table field (undefined if deleted).
 5402: 
 5403: =cut
 5404: 
 5405: 
 5406: sub scan_data {
 5407:     my ($scan_data,$key,$value,$delete)=@_;
 5408:     my $filename=$env{'form.scantron_selectfile'};
 5409:     if (defined($value)) {
 5410: 	$scan_data->{$filename.'_'.$key} = $value;
 5411:     }
 5412:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5413:     return $scan_data->{$filename.'_'.$key};
 5414: }
 5415: 
 5416: # ----- These first few routines are general use routines.----
 5417: 
 5418: # Return the number of occurences of a pattern in a string.
 5419: 
 5420: sub occurence_count {
 5421:     my ($string, $pattern) = @_;
 5422: 
 5423:     my @matches = ($string =~ /$pattern/g);
 5424: 
 5425:     return scalar(@matches);
 5426: }
 5427: 
 5428: 
 5429: # Take a string known to have digits and convert all the
 5430: # digits into letters in the range J,A..I.
 5431: 
 5432: sub digits_to_letters {
 5433:     my ($input) = @_;
 5434: 
 5435:     my @alphabet = ('J', 'A'..'I');
 5436: 
 5437:     my @input    = split(//, $input);
 5438:     my $output ='';
 5439:     for (my $i = 0; $i < scalar(@input); $i++) {
 5440: 	if ($input[$i] =~ /\d/) {
 5441: 	    $output .= $alphabet[$input[$i]];
 5442: 	} else {
 5443: 	    $output .= $input[$i];
 5444: 	}
 5445:     }
 5446:     return $output;
 5447: }
 5448: 
 5449: =pod 
 5450: 
 5451: =item scantron_parse_scanline
 5452: 
 5453:   Decodes a scanline from the selected scantron file
 5454: 
 5455:  Arguments:
 5456:     line             - The text of the scantron file line to process
 5457:     whichline        - Line number
 5458:     scantron_config  - Hash describing the format of the scantron lines.
 5459:     scan_data        - Hash of extra information about the scanline
 5460:                        (see scantron_getfile for more information)
 5461:     just_header      - True if should not process question answers but only
 5462:                        the stuff to the left of the answers.
 5463:  Returns:
 5464:    Hash containing the result of parsing the scanline
 5465: 
 5466:    Keys are all proceeded by the string 'scantron.'
 5467: 
 5468:        CODE    - the CODE in use for this scanline
 5469:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5470:                  by the operator
 5471:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5472:                             CODEs were selected, but the usage has been
 5473:                             forced by the operator
 5474:        ID  - student ID
 5475:        PaperID - if used, the ID number printed on the sheet when the 
 5476:                  paper was scanned
 5477:        FirstName - first name from the sheet
 5478:        LastName  - last name from the sheet
 5479: 
 5480:      if just_header was not true these key may also exist
 5481: 
 5482:        missingerror - a list of bubble ranges that are considered to be answers
 5483:                       to a single question that don't have any bubbles filled in.
 5484:                       Of the form questionnumber:firstbubblenumber:count.
 5485:        doubleerror  - a list of bubble ranges that are considered to be answers
 5486:                       to a single question that have more than one bubble filled in.
 5487:                       Of the form questionnumber::firstbubblenumber:count
 5488:    
 5489:                 In the above, count is the number of bubble responses in the
 5490:                 input line needed to represent the possible answers to the question.
 5491:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5492:                 per line would have count = 2.
 5493: 
 5494:        maxquest     - the number of the last bubble line that was parsed
 5495: 
 5496:        (<number> starts at 1)
 5497:        <number>.answer - zero or more letters representing the selected
 5498:                          letters from the scanline for the bubble line 
 5499:                          <number>.
 5500:                          if blank there was either no bubble or there where
 5501:                          multiple bubbles, (consult the keys missingerror and
 5502:                          doubleerror if this is an error condition)
 5503: 
 5504: =cut
 5505: 
 5506: sub scantron_parse_scanline {
 5507:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5508: 
 5509:     my %record;
 5510:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5511:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5512:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5513:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5514: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5515: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5516: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5517: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5518: 	    $record{'scantron.CODE'}=substr($data,
 5519: 					    $$scantron_config{'CODEstart'}-1,
 5520: 					    $$scantron_config{'CODElength'});
 5521: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5522: 		$record{'scantron.useCODE'}=1;
 5523: 	    }
 5524: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5525: 		$record{'scantron.CODE_ignore_dup'}=1;
 5526: 	    }
 5527: 	} else {
 5528: 	    #FIXME interpret first N questions
 5529: 	}
 5530:     }
 5531:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5532: 				  $$scantron_config{'IDlength'});
 5533:     $record{'scantron.PaperID'}=
 5534: 	substr($data,$$scantron_config{'PaperID'}-1,
 5535: 	       $$scantron_config{'PaperIDlength'});
 5536:     $record{'scantron.FirstName'}=
 5537: 	substr($data,$$scantron_config{'FirstName'}-1,
 5538: 	       $$scantron_config{'FirstNamelength'});
 5539:     $record{'scantron.LastName'}=
 5540: 	substr($data,$$scantron_config{'LastName'}-1,
 5541: 	       $$scantron_config{'LastNamelength'});
 5542:     if ($just_header) { return \%record; }
 5543: 
 5544:     my @alphabet=('A'..'Z');
 5545:     my $questnum=0;
 5546:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5547: 
 5548:     chomp($questions);		# Get rid of any trailing \n.
 5549:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5550:     while (length($questions)) {
 5551: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5552:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5553:                              || 1;
 5554:         $questnum++;
 5555:         my $quest_id = $questnum;
 5556:         my $currentquest = substr($questions,0,$answer_length);
 5557:         $questions       = substr($questions,$answer_length);
 5558:         if (length($currentquest) < $answer_length) { next; }
 5559: 
 5560:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5561:             my $subquestnum = 1;
 5562:             my $subquestions = $currentquest;
 5563:             my @subanswers_needed = 
 5564:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5565:             foreach my $subans (@subanswers_needed) {
 5566:                 my $subans_length =
 5567:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5568:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5569:                 $subquestions   = substr($subquestions,$subans_length);
 5570:                 $quest_id = "$questnum.$subquestnum";
 5571:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5572:                     ($$scantron_config{'Qon'} eq 'number')) {
 5573:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5574:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5575:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5576:                 } else {
 5577:                     $ansnum = &scantron_validator_positional($ansnum,
 5578:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5579:                 }
 5580:                 $subquestnum ++;
 5581:             }
 5582:         } else {
 5583:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5584:                 ($$scantron_config{'Qon'} eq 'number')) {
 5585:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5586:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5587:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5588:             } else {
 5589:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5590:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5591:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5592:             }
 5593:         }
 5594:     }
 5595:     $record{'scantron.maxquest'}=$questnum;
 5596:     return \%record;
 5597: }
 5598: 
 5599: sub scantron_validator_lettnum {
 5600:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5601:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5602: 
 5603:     # Qon 'letter' implies for each slot in currquest we have:
 5604:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5605:     #    about anything else (esp. a value of Qoff) for missing
 5606:     #    bubbles.
 5607:     #
 5608:     # Qon 'number' implies each slot gives a digit that indexes the
 5609:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5610:     #    and * or ? for double bubbles on a single line.
 5611:     #
 5612: 
 5613:     my $matchon;
 5614:     if ($$scantron_config{'Qon'} eq 'letter') {
 5615:         $matchon = '[A-Z]';
 5616:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5617:         $matchon = '\d';
 5618:     }
 5619:     my $occurrences = 0;
 5620:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5621:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5622:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5623:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5624:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5625:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5626:         my @singlelines = split('',$currquest);
 5627:         foreach my $entry (@singlelines) {
 5628:             $occurrences = &occurence_count($entry,$matchon);
 5629:             if ($occurrences > 1) {
 5630:                 last;
 5631:             }
 5632:         } 
 5633:     } else {
 5634:         $occurrences = &occurence_count($currquest,$matchon); 
 5635:     }
 5636:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5637:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5638:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5639:             my $bubble = substr($currquest,$ans,1);
 5640:             if ($bubble =~ /$matchon/ ) {
 5641:                 if ($$scantron_config{'Qon'} eq 'number') {
 5642:                     if ($bubble == 0) {
 5643:                         $bubble = 10; 
 5644:                     }
 5645:                     $record->{"scantron.$ansnum.answer"} = 
 5646:                         $alphabet->[$bubble-1];
 5647:                 } else {
 5648:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5649:                 }
 5650:             } else {
 5651:                 $record->{"scantron.$ansnum.answer"}='';
 5652:             }
 5653:             $ansnum++;
 5654:         }
 5655:     } elsif (!defined($currquest)
 5656:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5657:             || (&occurence_count($currquest,$matchon) == 0)) {
 5658:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5659:             $record->{"scantron.$ansnum.answer"}='';
 5660:             $ansnum++;
 5661:         }
 5662:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5663:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5664:         }
 5665:     } else {
 5666:         if ($$scantron_config{'Qon'} eq 'number') {
 5667:             $currquest = &digits_to_letters($currquest);            
 5668:         }
 5669:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5670:             my $bubble = substr($currquest,$ans,1);
 5671:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5672:             $ansnum++;
 5673:         }
 5674:     }
 5675:     return $ansnum;
 5676: }
 5677: 
 5678: sub scantron_validator_positional {
 5679:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5680:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5681: 
 5682:     # Otherwise there's a positional notation;
 5683:     # each bubble line requires Qlength items, and there are filled in
 5684:     # bubbles for each case where there 'Qon' characters.
 5685:     #
 5686: 
 5687:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5688: 
 5689:     # If the split only gives us one element.. the full length of the
 5690:     # answer string, no bubbles are filled in:
 5691: 
 5692:     if ($answers_needed eq '') {
 5693:         return;
 5694:     }
 5695: 
 5696:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5697:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5698:             $record->{"scantron.$ansnum.answer"}='';
 5699:             $ansnum++;
 5700:         }
 5701:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5702:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5703:         }
 5704:     } elsif (scalar(@array) == 2) {
 5705:         my $location = length($array[0]);
 5706:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5707:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5708:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5709:             if ($ans eq $line_num) {
 5710:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5711:             } else {
 5712:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5713:             }
 5714:             $ansnum++;
 5715:          }
 5716:     } else {
 5717:         #  If there's more than one instance of a bubble character
 5718:         #  That's a double bubble; with positional notation we can
 5719:         #  record all the bubbles filled in as well as the
 5720:         #  fact this response consists of multiple bubbles.
 5721:         #
 5722:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5723:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5724:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5725:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5726:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5727:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5728:             my $doubleerror = 0;
 5729:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5730:                    (!$doubleerror)) {
 5731:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5732:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5733:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5734:                if (length(@currarray) > 2) {
 5735:                    $doubleerror = 1;
 5736:                } 
 5737:             }
 5738:             if ($doubleerror) {
 5739:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5740:             }
 5741:         } else {
 5742:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5743:         }
 5744:         my $item = $ansnum;
 5745:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5746:             $record->{"scantron.$item.answer"} = '';
 5747:             $item ++;
 5748:         }
 5749: 
 5750:         my @ans=@array;
 5751:         my $i=0;
 5752:         my $increment = 0;
 5753:         while ($#ans) {
 5754:             $i+=length($ans[0]) + $increment;
 5755:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5756:             my $bubble = $i%$$scantron_config{'Qlength'};
 5757:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5758:             shift(@ans);
 5759:             $increment = 1;
 5760:         }
 5761:         $ansnum += $answers_needed;
 5762:     }
 5763:     return $ansnum;
 5764: }
 5765: 
 5766: =pod
 5767: 
 5768: =item scantron_add_delay
 5769: 
 5770:    Adds an error message that occurred during the grading phase to a
 5771:    queue of messages to be shown after grading pass is complete
 5772: 
 5773:  Arguments:
 5774:    $delayqueue  - arrary ref of hash ref of error messages
 5775:    $scanline    - the scanline that caused the error
 5776:    $errormesage - the error message
 5777:    $errorcode   - a numeric code for the error
 5778: 
 5779:  Side Effects:
 5780:    updates the $delayqueue to have a new hash ref of the error
 5781: 
 5782: =cut
 5783: 
 5784: sub scantron_add_delay {
 5785:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5786:     push(@$delayqueue,
 5787: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5788: 	  'ecode' => $errorcode }
 5789: 	 );
 5790: }
 5791: 
 5792: =pod
 5793: 
 5794: =item scantron_find_student
 5795: 
 5796:    Finds the username for the current scanline
 5797: 
 5798:   Arguments:
 5799:    $scantron_record - hash result from scantron_parse_scanline
 5800:    $scan_data       - hash of correction information 
 5801:                       (see &scantron_getfile() form more information)
 5802:    $idmap           - hash from &username_to_idmap()
 5803:    $line            - number of current scanline
 5804:  
 5805:   Returns:
 5806:    Either 'username:domain' or undef if unknown
 5807: 
 5808: =cut
 5809: 
 5810: sub scantron_find_student {
 5811:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5812:     my $scanID=$$scantron_record{'scantron.ID'};
 5813:     if ($scanID =~ /^\s*$/) {
 5814:  	return &scan_data($scan_data,"$line.user");
 5815:     }
 5816:     foreach my $id (keys(%$idmap)) {
 5817:  	if (lc($id) eq lc($scanID)) {
 5818:  	    return $$idmap{$id};
 5819:  	}
 5820:     }
 5821:     return undef;
 5822: }
 5823: 
 5824: =pod
 5825: 
 5826: =item scantron_filter
 5827: 
 5828:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5829:    hidden resources was selected
 5830: 
 5831: =cut
 5832: 
 5833: sub scantron_filter {
 5834:     my ($curres)=@_;
 5835: 
 5836:     if (ref($curres) && $curres->is_problem()) {
 5837: 	# if the user has asked to not have either hidden
 5838: 	# or 'randomout' controlled resources to be graded
 5839: 	# don't include them
 5840: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5841: 	    && $curres->randomout) {
 5842: 	    return 0;
 5843: 	}
 5844: 	return 1;
 5845:     }
 5846:     return 0;
 5847: }
 5848: 
 5849: =pod
 5850: 
 5851: =item scantron_process_corrections
 5852: 
 5853:    Gets correction information out of submitted form data and corrects
 5854:    the scanline
 5855: 
 5856: =cut
 5857: 
 5858: sub scantron_process_corrections {
 5859:     my ($r) = @_;
 5860:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5861:     my ($scanlines,$scan_data)=&scantron_getfile();
 5862:     my $classlist=&Apache::loncoursedata::get_classlist();
 5863:     my $which=$env{'form.scantron_line'};
 5864:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5865:     my ($skip,$err,$errmsg);
 5866:     if ($env{'form.scantron_skip_record'}) {
 5867: 	$skip=1;
 5868:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5869: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5870: 	    $env{'form.scantron_domain'};
 5871: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5872: 	($line,$err,$errmsg)=
 5873: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5874: 				     'ID',{'newid'=>$newid,
 5875: 				    'username'=>$env{'form.scantron_username'},
 5876: 				    'domain'=>$env{'form.scantron_domain'}});
 5877:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5878: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5879: 	my $newCODE;
 5880: 	my %args;
 5881: 	if      ($resolution eq 'use_unfound') {
 5882: 	    $newCODE='use_unfound';
 5883: 	} elsif ($resolution eq 'use_found') {
 5884: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5885: 	} elsif ($resolution eq 'use_typed') {
 5886: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5887: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5888: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5889: 	}
 5890: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5891: 	    $args{'CODE_ignore_dup'}=1;
 5892: 	}
 5893: 	$args{'CODE'}=$newCODE;
 5894: 	($line,$err,$errmsg)=
 5895: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5896: 				     'CODE',\%args);
 5897:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5898: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5899: 	    ($line,$err,$errmsg)=
 5900: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5901: 					 $which,'answer',
 5902: 					 { 'question'=>$question,
 5903: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5904:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5905: 	    if ($err) { last; }
 5906: 	}
 5907:     }
 5908:     if ($err) {
 5909: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5910:     } else {
 5911: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5912: 	&scantron_putfile($scanlines,$scan_data);
 5913:     }
 5914: }
 5915: 
 5916: =pod
 5917: 
 5918: =item reset_skipping_status
 5919: 
 5920:    Forgets the current set of remember skipped scanlines (and thus
 5921:    reverts back to considering all lines in the
 5922:    scantron_skipped_<filename> file)
 5923: 
 5924: =cut
 5925: 
 5926: sub reset_skipping_status {
 5927:     my ($scanlines,$scan_data)=&scantron_getfile();
 5928:     &scan_data($scan_data,'remember_skipping',undef,1);
 5929:     &scantron_putfile(undef,$scan_data);
 5930: }
 5931: 
 5932: =pod
 5933: 
 5934: =item start_skipping
 5935: 
 5936:    Marks a scanline to be skipped. 
 5937: 
 5938: =cut
 5939: 
 5940: sub start_skipping {
 5941:     my ($scan_data,$i)=@_;
 5942:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5943:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5944: 	$remembered{$i}=2;
 5945:     } else {
 5946: 	$remembered{$i}=1;
 5947:     }
 5948:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5949: }
 5950: 
 5951: =pod
 5952: 
 5953: =item should_be_skipped
 5954: 
 5955:    Checks whether a scanline should be skipped.
 5956: 
 5957: =cut
 5958: 
 5959: sub should_be_skipped {
 5960:     my ($scanlines,$scan_data,$i)=@_;
 5961:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5962: 	# not redoing old skips
 5963: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5964: 	return 0;
 5965:     }
 5966:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5967: 
 5968:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5969: 	return 0;
 5970:     }
 5971:     return 1;
 5972: }
 5973: 
 5974: =pod
 5975: 
 5976: =item remember_current_skipped
 5977: 
 5978:    Discovers what scanlines are in the scantron_skipped_<filename>
 5979:    file and remembers them into scan_data for later use.
 5980: 
 5981: =cut
 5982: 
 5983: sub remember_current_skipped {
 5984:     my ($scanlines,$scan_data)=&scantron_getfile();
 5985:     my %to_remember;
 5986:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5987: 	if ($scanlines->{'skipped'}[$i]) {
 5988: 	    $to_remember{$i}=1;
 5989: 	}
 5990:     }
 5991: 
 5992:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5993:     &scantron_putfile(undef,$scan_data);
 5994: }
 5995: 
 5996: =pod
 5997: 
 5998: =item check_for_error
 5999: 
 6000:     Checks if there was an error when attempting to remove a specific
 6001:     scantron_.. bubble sheet data file. Prints out an error if
 6002:     something went wrong.
 6003: 
 6004: =cut
 6005: 
 6006: sub check_for_error {
 6007:     my ($r,$result)=@_;
 6008:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6009: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6010:     }
 6011: }
 6012: 
 6013: =pod
 6014: 
 6015: =item scantron_warning_screen
 6016: 
 6017:    Interstitial screen to make sure the operator has selected the
 6018:    correct options before we start the validation phase.
 6019: 
 6020: =cut
 6021: 
 6022: sub scantron_warning_screen {
 6023:     my ($button_text)=@_;
 6024:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6025:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6026:     my $CODElist;
 6027:     if ($scantron_config{'CODElocation'} &&
 6028: 	$scantron_config{'CODEstart'} &&
 6029: 	$scantron_config{'CODElength'}) {
 6030: 	$CODElist=$env{'form.scantron_CODElist'};
 6031: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6032: 	$CODElist=
 6033: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6034: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6035:     }
 6036:     return ('
 6037: <p>
 6038: <span class="LC_warning">
 6039: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6040: </p>
 6041: <table>
 6042: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6043: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6044: '.$CODElist.'
 6045: </table>
 6046: <br />
 6047: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6048: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6049: 
 6050: <br />
 6051: ');
 6052: }
 6053: 
 6054: =pod
 6055: 
 6056: =item scantron_do_warning
 6057: 
 6058:    Check if the operator has picked something for all required
 6059:    fields. Error out if something is missing.
 6060: 
 6061: =cut
 6062: 
 6063: sub scantron_do_warning {
 6064:     my ($r)=@_;
 6065:     my ($symb)=&get_symb($r);
 6066:     if (!$symb) {return '';}
 6067:     my $default_form_data=&defaultFormData($symb);
 6068:     $r->print(&scantron_form_start().$default_form_data);
 6069:     if ( $env{'form.selectpage'} eq '' ||
 6070: 	 $env{'form.scantron_selectfile'} eq '' ||
 6071: 	 $env{'form.scantron_format'} eq '' ) {
 6072: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6073: 	if ( $env{'form.selectpage'} eq '') {
 6074: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6075: 	} 
 6076: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6077: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6078: 	} 
 6079: 	if ( $env{'form.scantron_format'} eq '') {
 6080: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6081: 	} 
 6082:     } else {
 6083: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6084: 	$r->print('
 6085: '.$warning.'
 6086: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6087: <input type="hidden" name="command" value="scantron_validate" />
 6088: ');
 6089:     }
 6090:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6091:     return '';
 6092: }
 6093: 
 6094: =pod
 6095: 
 6096: =item scantron_form_start
 6097: 
 6098:     html hidden input for remembering all selected grading options
 6099: 
 6100: =cut
 6101: 
 6102: sub scantron_form_start {
 6103:     my ($max_bubble)=@_;
 6104:     my $result= <<SCANTRONFORM;
 6105: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6106:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6107:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6108:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6109:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6110:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6111:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6112:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6113:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6114:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6115: SCANTRONFORM
 6116: 
 6117:   my $line = 0;
 6118:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6119:        my $chunk =
 6120: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6121:        $chunk .=
 6122: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6123:        $chunk .= 
 6124:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6125:        $chunk .=
 6126:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6127:        $result .= $chunk;
 6128:        $line++;
 6129:    }
 6130:     return $result;
 6131: }
 6132: 
 6133: =pod
 6134: 
 6135: =item scantron_validate_file
 6136: 
 6137:     Dispatch routine for doing validation of a bubble sheet data file.
 6138: 
 6139:     Also processes any necessary information resets that need to
 6140:     occur before validation begins (ignore previous corrections,
 6141:     restarting the skipped records processing)
 6142: 
 6143: =cut
 6144: 
 6145: sub scantron_validate_file {
 6146:     my ($r) = @_;
 6147:     my ($symb)=&get_symb($r);
 6148:     if (!$symb) {return '';}
 6149:     my $default_form_data=&defaultFormData($symb);
 6150:     
 6151:     # do the detection of only doing skipped records first befroe we delete
 6152:     # them when doing the corrections reset
 6153:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6154: 	&reset_skipping_status();
 6155:     }
 6156:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6157: 	&remember_current_skipped();
 6158: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6159:     }
 6160: 
 6161:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6162: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6163: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6164: 	&check_for_error($r,&scantron_remove_scan_data());
 6165: 	$env{'form.scantron_options_ignore'}='done';
 6166:     }
 6167: 
 6168:     if ($env{'form.scantron_corrections'}) {
 6169: 	&scantron_process_corrections($r);
 6170:     }
 6171:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6172:     #get the student pick code ready
 6173:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6174:     my $max_bubble=&scantron_get_maxbubble();
 6175:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6176:     $r->print($result);
 6177:     
 6178:     my @validate_phases=( 'sequence',
 6179: 			  'ID',
 6180: 			  'CODE',
 6181: 			  'doublebubble',
 6182: 			  'missingbubbles');
 6183:     if (!$env{'form.validatepass'}) {
 6184: 	$env{'form.validatepass'} = 0;
 6185:     }
 6186:     my $currentphase=$env{'form.validatepass'};
 6187: 
 6188: 
 6189:     my $stop=0;
 6190:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6191: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6192: 	$r->rflush();
 6193: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6194: 	{
 6195: 	    no strict 'refs';
 6196: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6197: 	}
 6198:     }
 6199:     if (!$stop) {
 6200: 	my $warning=&scantron_warning_screen('Start Grading');
 6201: 	$r->print(&mt('Validation process complete.').'<br />'.
 6202:                   $warning.
 6203:                   &mt('Perform verification for each student after storage of submissions?').
 6204:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6205:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6206:                   ('&nbsp;'x3).'<label>'.
 6207:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6208:                   '</label></span><br />'.
 6209:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6210:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6211:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6212:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6213:     } else {
 6214: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6215: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6216:     }
 6217:     if ($stop) {
 6218: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6219: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6220: 	    $r->print(' '.&mt('this error').' <br />');
 6221: 
 6222: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6223: 	} else {
 6224:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6225: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6226:             } else {
 6227:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6228:             }
 6229: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6230: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6231: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6232: 	}
 6233:     }
 6234:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6235:     return '';
 6236: }
 6237: 
 6238: 
 6239: =pod
 6240: 
 6241: =item scantron_remove_file
 6242: 
 6243:    Removes the requested bubble sheet data file, makes sure that
 6244:    scantron_original_<filename> is never removed
 6245: 
 6246: 
 6247: =cut
 6248: 
 6249: sub scantron_remove_file {
 6250:     my ($which)=@_;
 6251:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6252:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6253:     my $file='scantron_';
 6254:     if ($which eq 'corrected' || $which eq 'skipped') {
 6255: 	$file.=$which.'_';
 6256:     } else {
 6257: 	return 'refused';
 6258:     }
 6259:     $file.=$env{'form.scantron_selectfile'};
 6260:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6261: }
 6262: 
 6263: 
 6264: =pod
 6265: 
 6266: =item scantron_remove_scan_data
 6267: 
 6268:    Removes all scan_data correction for the requested bubble sheet
 6269:    data file.  (In the case that both the are doing skipped records we need
 6270:    to remember the old skipped lines for the time being so that element
 6271:    persists for a while.)
 6272: 
 6273: =cut
 6274: 
 6275: sub scantron_remove_scan_data {
 6276:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6277:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6278:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6279:     my @todelete;
 6280:     my $filename=$env{'form.scantron_selectfile'};
 6281:     foreach my $key (@keys) {
 6282: 	if ($key=~/^\Q$filename\E_/) {
 6283: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6284: 		$key=~/remember_skipping/) {
 6285: 		next;
 6286: 	    }
 6287: 	    push(@todelete,$key);
 6288: 	}
 6289:     }
 6290:     my $result;
 6291:     if (@todelete) {
 6292: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6293: 				       \@todelete,$cdom,$cname);
 6294:     } else {
 6295: 	$result = 'ok';
 6296:     }
 6297:     return $result;
 6298: }
 6299: 
 6300: 
 6301: =pod
 6302: 
 6303: =item scantron_getfile
 6304: 
 6305:     Fetches the requested bubble sheet data file (all 3 versions), and
 6306:     the scan_data hash
 6307:   
 6308:   Arguments:
 6309:     None
 6310: 
 6311:   Returns:
 6312:     2 hash references
 6313: 
 6314:      - first one has 
 6315:          orig      -
 6316:          corrected -
 6317:          skipped   -  each of which points to an array ref of the specified
 6318:                       file broken up into individual lines
 6319:          count     - number of scanlines
 6320:  
 6321:      - second is the scan_data hash possible keys are
 6322:        ($number refers to scanline numbered $number and thus the key affects
 6323:         only that scanline
 6324:         $bubline refers to the specific bubble line element and the aspects
 6325:         refers to that specific bubble line element)
 6326: 
 6327:        $number.user - username:domain to use
 6328:        $number.CODE_ignore_dup 
 6329:                     - ignore the duplicate CODE error 
 6330:        $number.useCODE
 6331:                     - use the CODE in the scanline as is
 6332:        $number.no_bubble.$bubline
 6333:                     - it is valid that there is no bubbled in bubble
 6334:                       at $number $bubline
 6335:        remember_skipping
 6336:                     - a frozen hash containing keys of $number and values
 6337:                       of either 
 6338:                         1 - we are on a 'do skipped records pass' and plan
 6339:                             on processing this line
 6340:                         2 - we are on a 'do skipped records pass' and this
 6341:                             scanline has been marked to skip yet again
 6342: 
 6343: =cut
 6344: 
 6345: sub scantron_getfile {
 6346:     #FIXME really would prefer a scantron directory
 6347:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6348:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6349:     my $lines;
 6350:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6351: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6352:     my %scanlines;
 6353:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6354:     my $temp=$scanlines{'orig'};
 6355:     $scanlines{'count'}=$#$temp;
 6356: 
 6357:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6358: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6359:     if ($lines eq '-1') {
 6360: 	$scanlines{'corrected'}=[];
 6361:     } else {
 6362: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6363:     }
 6364:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6365: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6366:     if ($lines eq '-1') {
 6367: 	$scanlines{'skipped'}=[];
 6368:     } else {
 6369: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6370:     }
 6371:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6372:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6373:     my %scan_data = @tmp;
 6374:     return (\%scanlines,\%scan_data);
 6375: }
 6376: 
 6377: =pod
 6378: 
 6379: =item lonnet_putfile
 6380: 
 6381:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6382: 
 6383:  Arguments:
 6384:    $contents - data to store
 6385:    $filename - filename to store $contents into
 6386: 
 6387:  Returns:
 6388:    result value from &Apache::lonnet::finishuserfileupload
 6389: 
 6390: =cut
 6391: 
 6392: sub lonnet_putfile {
 6393:     my ($contents,$filename)=@_;
 6394:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6395:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6396:     $env{'form.sillywaytopassafilearound'}=$contents;
 6397:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6398: 
 6399: }
 6400: 
 6401: =pod
 6402: 
 6403: =item scantron_putfile
 6404: 
 6405:     Stores the current version of the bubble sheet data files, and the
 6406:     scan_data hash. (Does not modify the original version only the
 6407:     corrected and skipped versions.
 6408: 
 6409:  Arguments:
 6410:     $scanlines - hash ref that looks like the first return value from
 6411:                  &scantron_getfile()
 6412:     $scan_data - hash ref that looks like the second return value from
 6413:                  &scantron_getfile()
 6414: 
 6415: =cut
 6416: 
 6417: sub scantron_putfile {
 6418:     my ($scanlines,$scan_data) = @_;
 6419:     #FIXME really would prefer a scantron directory
 6420:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6421:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6422:     if ($scanlines) {
 6423: 	my $prefix='scantron_';
 6424: # no need to update orig, shouldn't change
 6425: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6426: #		    $env{'form.scantron_selectfile'});
 6427: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6428: 			$prefix.'corrected_'.
 6429: 			$env{'form.scantron_selectfile'});
 6430: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6431: 			$prefix.'skipped_'.
 6432: 			$env{'form.scantron_selectfile'});
 6433:     }
 6434:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6435: }
 6436: 
 6437: =pod
 6438: 
 6439: =item scantron_get_line
 6440: 
 6441:    Returns the correct version of the scanline
 6442: 
 6443:  Arguments:
 6444:     $scanlines - hash ref that looks like the first return value from
 6445:                  &scantron_getfile()
 6446:     $scan_data - hash ref that looks like the second return value from
 6447:                  &scantron_getfile()
 6448:     $i         - number of the requested line (starts at 0)
 6449: 
 6450:  Returns:
 6451:    A scanline, (either the original or the corrected one if it
 6452:    exists), or undef if the requested scanline should be
 6453:    skipped. (Either because it's an skipped scanline, or it's an
 6454:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6455:    pass.
 6456: 
 6457: =cut
 6458: 
 6459: sub scantron_get_line {
 6460:     my ($scanlines,$scan_data,$i)=@_;
 6461:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6462:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6463:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6464:     return $scanlines->{'orig'}[$i]; 
 6465: }
 6466: 
 6467: =pod
 6468: 
 6469: =item scantron_todo_count
 6470: 
 6471:     Counts the number of scanlines that need processing.
 6472: 
 6473:  Arguments:
 6474:     $scanlines - hash ref that looks like the first return value from
 6475:                  &scantron_getfile()
 6476:     $scan_data - hash ref that looks like the second return value from
 6477:                  &scantron_getfile()
 6478: 
 6479:  Returns:
 6480:     $count - number of scanlines to process
 6481: 
 6482: =cut
 6483: 
 6484: sub get_todo_count {
 6485:     my ($scanlines,$scan_data)=@_;
 6486:     my $count=0;
 6487:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6488: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6489: 	if ($line=~/^[\s\cz]*$/) { next; }
 6490: 	$count++;
 6491:     }
 6492:     return $count;
 6493: }
 6494: 
 6495: =pod
 6496: 
 6497: =item scantron_put_line
 6498: 
 6499:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6500:     data file.
 6501: 
 6502:  Arguments:
 6503:     $scanlines - hash ref that looks like the first return value from
 6504:                  &scantron_getfile()
 6505:     $scan_data - hash ref that looks like the second return value from
 6506:                  &scantron_getfile()
 6507:     $i         - line number to update
 6508:     $newline   - contents of the updated scanline
 6509:     $skip      - if true make the line for skipping and update the
 6510:                  'skipped' file
 6511: 
 6512: =cut
 6513: 
 6514: sub scantron_put_line {
 6515:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6516:     if ($skip) {
 6517: 	$scanlines->{'skipped'}[$i]=$newline;
 6518: 	&start_skipping($scan_data,$i);
 6519: 	return;
 6520:     }
 6521:     $scanlines->{'corrected'}[$i]=$newline;
 6522: }
 6523: 
 6524: =pod
 6525: 
 6526: =item scantron_clear_skip
 6527: 
 6528:    Remove a line from the 'skipped' file
 6529: 
 6530:  Arguments:
 6531:     $scanlines - hash ref that looks like the first return value from
 6532:                  &scantron_getfile()
 6533:     $scan_data - hash ref that looks like the second return value from
 6534:                  &scantron_getfile()
 6535:     $i         - line number to update
 6536: 
 6537: =cut
 6538: 
 6539: sub scantron_clear_skip {
 6540:     my ($scanlines,$scan_data,$i)=@_;
 6541:     if (exists($scanlines->{'skipped'}[$i])) {
 6542: 	undef($scanlines->{'skipped'}[$i]);
 6543: 	return 1;
 6544:     }
 6545:     return 0;
 6546: }
 6547: 
 6548: =pod
 6549: 
 6550: =item scantron_filter_not_exam
 6551: 
 6552:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6553:    filter out resources that are not marked as 'exam' mode
 6554: 
 6555: =cut
 6556: 
 6557: sub scantron_filter_not_exam {
 6558:     my ($curres)=@_;
 6559:     
 6560:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6561: 	# if the user has asked to not have either hidden
 6562: 	# or 'randomout' controlled resources to be graded
 6563: 	# don't include them
 6564: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6565: 	    && $curres->randomout) {
 6566: 	    return 0;
 6567: 	}
 6568: 	return 1;
 6569:     }
 6570:     return 0;
 6571: }
 6572: 
 6573: =pod
 6574: 
 6575: =item scantron_validate_sequence
 6576: 
 6577:     Validates the selected sequence, checking for resource that are
 6578:     not set to exam mode.
 6579: 
 6580: =cut
 6581: 
 6582: sub scantron_validate_sequence {
 6583:     my ($r,$currentphase) = @_;
 6584: 
 6585:     my $navmap=Apache::lonnavmaps::navmap->new();
 6586:     my (undef,undef,$sequence)=
 6587: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6588: 
 6589:     my $map=$navmap->getResourceByUrl($sequence);
 6590: 
 6591:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6592:                                     value="ignore" />');
 6593:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6594: 	my @resources=
 6595: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6596: 	if (@resources) {
 6597: 	    $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>");
 6598: 	    return (1,$currentphase);
 6599: 	}
 6600:     }
 6601: 
 6602:     return (0,$currentphase+1);
 6603: }
 6604: 
 6605: 
 6606: 
 6607: sub scantron_validate_ID {
 6608:     my ($r,$currentphase) = @_;
 6609:     
 6610:     #get student info
 6611:     my $classlist=&Apache::loncoursedata::get_classlist();
 6612:     my %idmap=&username_to_idmap($classlist);
 6613: 
 6614:     #get scantron line setup
 6615:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6616:     my ($scanlines,$scan_data)=&scantron_getfile();
 6617:     
 6618:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6619: 
 6620:     my %found=('ids'=>{},'usernames'=>{});
 6621:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6622: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6623: 	if ($line=~/^[\s\cz]*$/) { next; }
 6624: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6625: 						 $scan_data);
 6626: 	my $id=$$scan_record{'scantron.ID'};
 6627: 	my $found;
 6628: 	foreach my $checkid (keys(%idmap)) {
 6629: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6630: 	}
 6631: 	if ($found) {
 6632: 	    my $username=$idmap{$found};
 6633: 	    if ($found{'ids'}{$found}) {
 6634: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6635: 					 $line,'duplicateID',$found);
 6636: 		return(1,$currentphase);
 6637: 	    } elsif ($found{'usernames'}{$username}) {
 6638: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6639: 					 $line,'duplicateID',$username);
 6640: 		return(1,$currentphase);
 6641: 	    }
 6642: 	    #FIXME store away line we previously saw the ID on to use above
 6643: 	    $found{'ids'}{$found}++;
 6644: 	    $found{'usernames'}{$username}++;
 6645: 	} else {
 6646: 	    if ($id =~ /^\s*$/) {
 6647: 		my $username=&scan_data($scan_data,"$i.user");
 6648: 		if (defined($username) && $found{'usernames'}{$username}) {
 6649: 		    &scantron_get_correction($r,$i,$scan_record,
 6650: 					     \%scantron_config,
 6651: 					     $line,'duplicateID',$username);
 6652: 		    return(1,$currentphase);
 6653: 		} elsif (!defined($username)) {
 6654: 		    &scantron_get_correction($r,$i,$scan_record,
 6655: 					     \%scantron_config,
 6656: 					     $line,'incorrectID');
 6657: 		    return(1,$currentphase);
 6658: 		}
 6659: 		$found{'usernames'}{$username}++;
 6660: 	    } else {
 6661: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6662: 					 $line,'incorrectID');
 6663: 		return(1,$currentphase);
 6664: 	    }
 6665: 	}
 6666:     }
 6667: 
 6668:     return (0,$currentphase+1);
 6669: }
 6670: 
 6671: 
 6672: sub scantron_get_correction {
 6673:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6674: #FIXME in the case of a duplicated ID the previous line, probably need
 6675: #to show both the current line and the previous one and allow skipping
 6676: #the previous one or the current one
 6677: 
 6678:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6679: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6680: 			    " for PaperID <tt>[_1]</tt>",
 6681: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6682:     } else {
 6683: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6684: 			    " in scanline [_1] <pre>[_2]</pre>",
 6685: 			    $i,$line)."</p> \n");
 6686:     }
 6687:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6688: 			  "The name on the paper is [_2],[_3]",
 6689: 			  $$scan_record{'scantron.ID'},
 6690: 			  $$scan_record{'scantron.LastName'},
 6691: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6692: 
 6693:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6694:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6695:                            # Array populated for doublebubble or
 6696:     my @lines_to_correct;  # missingbubble errors to build javascript
 6697:                            # to validate radio button checking   
 6698: 
 6699:     if ($error =~ /ID$/) {
 6700: 	if ($error eq 'incorrectID') {
 6701: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6702: 		      "</p>\n");
 6703: 	} elsif ($error eq 'duplicateID') {
 6704: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6705: 	}
 6706: 	$r->print($message);
 6707: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6708: 	$r->print("\n<ul><li> ");
 6709: 	#FIXME it would be nice if this sent back the user ID and
 6710: 	#could do partial userID matches
 6711: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6712: 				       'scantron_username','scantron_domain'));
 6713: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6714: 	$r->print("\n@".
 6715: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6716: 
 6717: 	$r->print('</li>');
 6718:     } elsif ($error =~ /CODE$/) {
 6719: 	if ($error eq 'incorrectCODE') {
 6720: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6721: 	} elsif ($error eq 'duplicateCODE') {
 6722: 	    $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");
 6723: 	}
 6724: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6725: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6726: 	$r->print($message);
 6727: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6728: 	$r->print("\n<br /> ");
 6729: 	my $i=0;
 6730: 	if ($error eq 'incorrectCODE' 
 6731: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6732: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6733: 	    if ($closest > 0) {
 6734: 		foreach my $testcode (@{$closest}) {
 6735: 		    my $checked='';
 6736: 		    if (!$i) { $checked=' checked="checked" '; }
 6737: 		    $r->print("
 6738:    <label>
 6739:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6740:        ".&mt("Use the similar CODE [_1] instead.",
 6741: 	    "<b><tt>".$testcode."</tt></b>")."
 6742:     </label>
 6743:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6744: 		    $r->print("\n<br />");
 6745: 		    $i++;
 6746: 		}
 6747: 	    }
 6748: 	}
 6749: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6750: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6751: 	    $r->print("
 6752:     <label>
 6753:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6754:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6755: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6756:     </label>");
 6757: 	    $r->print("\n<br />");
 6758: 	}
 6759: 
 6760: 	$r->print(<<ENDSCRIPT);
 6761: <script type="text/javascript">
 6762: function change_radio(field) {
 6763:     var slct=document.scantronupload.scantron_CODE_resolution;
 6764:     var i;
 6765:     for (i=0;i<slct.length;i++) {
 6766:         if (slct[i].value==field) { slct[i].checked=true; }
 6767:     }
 6768: }
 6769: </script>
 6770: ENDSCRIPT
 6771: 	my $href="/adm/pickcode?".
 6772: 	   "form=".&escape("scantronupload").
 6773: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6774: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6775: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6776: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6777: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6778: 	    $r->print("
 6779:     <label>
 6780:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6781:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6782: 	     "<a target='_blank' href='$href'>","</a>")."
 6783:     </label> 
 6784:     ".&mt("Selected CODE is [_1]","<input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />"));
 6785: 	    $r->print("\n<br />");
 6786: 	}
 6787: 	$r->print("
 6788:     <label>
 6789:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6790:        ".&mt("Use [_1] as the CODE.",
 6791: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6792: 	$r->print("\n<br /><br />");
 6793:     } elsif ($error eq 'doublebubble') {
 6794: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6795: 
 6796: 	# The form field scantron_questions is acutally a list of line numbers.
 6797: 	# represented by this form so:
 6798: 
 6799: 	my $line_list = &questions_to_line_list($arg);
 6800: 
 6801: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6802: 		  $line_list.'" />');
 6803: 	$r->print($message);
 6804: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6805: 	foreach my $question (@{$arg}) {
 6806: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6807:                                                    $scan_record, $error);
 6808:             push(@lines_to_correct,@linenums);
 6809: 	}
 6810:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6811:     } elsif ($error eq 'missingbubble') {
 6812: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6813: 	$r->print($message);
 6814: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6815: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6816: 
 6817: 	# The form field scantron_questions is actually a list of line numbers not
 6818: 	# a list of question numbers. Therefore:
 6819: 	#
 6820: 	
 6821: 	my $line_list = &questions_to_line_list($arg);
 6822: 
 6823: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6824: 		  $line_list.'" />');
 6825: 	foreach my $question (@{$arg}) {
 6826: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6827:                                                    $scan_record, $error);
 6828:             push(@lines_to_correct,@linenums);
 6829: 	}
 6830:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6831:     } else {
 6832: 	$r->print("\n<ul>");
 6833:     }
 6834:     $r->print("\n</li></ul>");
 6835: }
 6836: 
 6837: sub verify_bubbles_checked {
 6838:     my (@ansnums) = @_;
 6839:     my $ansnumstr = join('","',@ansnums);
 6840:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6841:     my $output = (<<ENDSCRIPT);
 6842: <script type="text/javascript">
 6843: function verify_bubble_radio(form) {
 6844:     var ansnumArray = new Array ("$ansnumstr");
 6845:     var need_bubble_count = 0;
 6846:     for (var i=0; i<ansnumArray.length; i++) {
 6847:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6848:             var bubble_picked = 0; 
 6849:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6850:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6851:                     bubble_picked = 1;
 6852:                 }
 6853:             }
 6854:             if (bubble_picked == 0) {
 6855:                 need_bubble_count ++;
 6856:             }
 6857:         }
 6858:     }
 6859:     if (need_bubble_count) {
 6860:         alert("$warning");
 6861:         return;
 6862:     }
 6863:     form.submit(); 
 6864: }
 6865: </script>
 6866: ENDSCRIPT
 6867:     return $output;
 6868: }
 6869: 
 6870: =pod
 6871: 
 6872: =item  questions_to_line_list
 6873: 
 6874: Converts a list of questions into a string of comma separated
 6875: line numbers in the answer sheet used by the questions.  This is
 6876: used to fill in the scantron_questions form field.
 6877: 
 6878:   Arguments:
 6879:      questions    - Reference to an array of questions.
 6880: 
 6881: =cut
 6882: 
 6883: 
 6884: sub questions_to_line_list {
 6885:     my ($questions) = @_;
 6886:     my @lines;
 6887: 
 6888:     foreach my $item (@{$questions}) {
 6889:         my $question = $item;
 6890:         my ($first,$count,$last);
 6891:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6892:             $question = $1;
 6893:             my $subquestion = $2;
 6894:             $first = $first_bubble_line{$question-1} + 1;
 6895:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6896:             my $subcount = 1;
 6897:             while ($subcount<$subquestion) {
 6898:                 $first += $subans[$subcount-1];
 6899:                 $subcount ++;
 6900:             }
 6901:             $count = $subans[$subquestion-1];
 6902:         } else {
 6903: 	    $first   = $first_bubble_line{$question-1} + 1;
 6904: 	    $count   = $bubble_lines_per_response{$question-1};
 6905:         }
 6906:         $last = $first+$count-1;
 6907:         push(@lines, ($first..$last));
 6908:     }
 6909:     return join(',', @lines);
 6910: }
 6911: 
 6912: =pod 
 6913: 
 6914: =item prompt_for_corrections
 6915: 
 6916: Prompts for a potentially multiline correction to the
 6917: user's bubbling (factors out common code from scantron_get_correction
 6918: for multi and missing bubble cases).
 6919: 
 6920:  Arguments:
 6921:    $r           - Apache request object.
 6922:    $question    - The question number to prompt for.
 6923:    $scan_config - The scantron file configuration hash.
 6924:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6925:    $error       - Type of error
 6926: 
 6927:  Implicit inputs:
 6928:    %bubble_lines_per_response   - Starting line numbers for each question.
 6929:                                   Numbered from 0 (but question numbers are from
 6930:                                   1.
 6931:    %first_bubble_line           - Starting bubble line for each question.
 6932:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6933:                                   type problems render as separate sub-questions, 
 6934:                                   in exam mode. This hash contains a 
 6935:                                   comma-separated list of the lines per 
 6936:                                   sub-question.
 6937:    %responsetype_per_response   - essayresponse, formularesponse,
 6938:                                   stringresponse, imageresponse, reactionresponse,
 6939:                                   and organicresponse type problem parts can have
 6940:                                   multiple lines per response if the weight
 6941:                                   assigned exceeds 10.  In this case, only
 6942:                                   one bubble per line is permitted, but more 
 6943:                                   than one line might contain bubbles, e.g.
 6944:                                   bubbling of: line 1 - J, line 2 - J, 
 6945:                                   line 3 - B would assign 22 points.  
 6946: 
 6947: =cut
 6948: 
 6949: sub prompt_for_corrections {
 6950:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6951:     my ($current_line,$lines);
 6952:     my @linenums;
 6953:     my $questionnum = $question;
 6954:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6955:         $question = $1;
 6956:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6957:         my $subquestion = $2;
 6958:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6959:         my $subcount = 1;
 6960:         while ($subcount<$subquestion) {
 6961:             $current_line += $subans[$subcount-1];
 6962:             $subcount ++;
 6963:         }
 6964:         $lines = $subans[$subquestion-1];
 6965:     } else {
 6966:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6967:         $lines        = $bubble_lines_per_response{$question-1};
 6968:     }
 6969:     if ($lines > 1) {
 6970:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 6971:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 6972:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 6973:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 6974:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 6975:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 6976:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 6977:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 6978:         } else {
 6979:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 6980:         }
 6981:     }
 6982:     for (my $i =0; $i < $lines; $i++) {
 6983:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 6984: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 6985: 	        		  $questionnum,$error,split('', $selected));
 6986:         push(@linenums,$current_line);
 6987: 	$current_line++;
 6988:     }
 6989:     if ($lines > 1) {
 6990: 	$r->print("<hr /><br />");
 6991:     }
 6992:     return @linenums;
 6993: }
 6994: 
 6995: =pod
 6996: 
 6997: =item scantron_bubble_selector
 6998:   
 6999:    Generates the html radiobuttons to correct a single bubble line
 7000:    possibly showing the existing the selected bubbles if known
 7001: 
 7002:  Arguments:
 7003:     $r           - Apache request object
 7004:     $scan_config - hash from &get_scantron_config()
 7005:     $line        - Number of the line being displayed.
 7006:     $questionnum - Question number (may include subquestion)
 7007:     $error       - Type of error.
 7008:     @selected    - Array of bubbles picked on this line.
 7009: 
 7010: =cut
 7011: 
 7012: sub scantron_bubble_selector {
 7013:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7014:     my $max=$$scan_config{'Qlength'};
 7015: 
 7016:     my $scmode=$$scan_config{'Qon'};
 7017:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7018: 
 7019:     my @alphabet=('A'..'Z');
 7020:     $r->print(&Apache::loncommon::start_data_table().
 7021:               &Apache::loncommon::start_data_table_row());
 7022:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7023:     for (my $i=0;$i<$max+1;$i++) {
 7024: 	$r->print("\n".'<td align="center">');
 7025: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7026: 	else { $r->print('&nbsp;'); }
 7027: 	$r->print('</td>');
 7028:     }
 7029:     $r->print(&Apache::loncommon::end_data_table_row().
 7030:               &Apache::loncommon::start_data_table_row());
 7031:     for (my $i=0;$i<$max;$i++) {
 7032: 	$r->print("\n".
 7033: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7034: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7035:     }
 7036:     my $nobub_checked = ' ';
 7037:     if ($error eq 'missingbubble') {
 7038:         $nobub_checked = ' checked = "checked" ';
 7039:     }
 7040:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7041: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7042:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7043:               $line.'" value="'.$questionnum.'" /></td>');
 7044:     $r->print(&Apache::loncommon::end_data_table_row().
 7045:               &Apache::loncommon::end_data_table());
 7046: }
 7047: 
 7048: =pod
 7049: 
 7050: =item num_matches
 7051: 
 7052:    Counts the number of characters that are the same between the two arguments.
 7053: 
 7054:  Arguments:
 7055:    $orig - CODE from the scanline
 7056:    $code - CODE to match against
 7057: 
 7058:  Returns:
 7059:    $count - integer count of the number of same characters between the
 7060:             two arguments
 7061: 
 7062: =cut
 7063: 
 7064: sub num_matches {
 7065:     my ($orig,$code) = @_;
 7066:     my @code=split(//,$code);
 7067:     my @orig=split(//,$orig);
 7068:     my $same=0;
 7069:     for (my $i=0;$i<scalar(@code);$i++) {
 7070: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7071:     }
 7072:     return $same;
 7073: }
 7074: 
 7075: =pod
 7076: 
 7077: =item scantron_get_closely_matching_CODEs
 7078: 
 7079:    Cycles through all CODEs and finds the set that has the greatest
 7080:    number of same characters as the provided CODE
 7081: 
 7082:  Arguments:
 7083:    $allcodes - hash ref returned by &get_codes()
 7084:    $CODE     - CODE from the current scanline
 7085: 
 7086:  Returns:
 7087:    2 element list
 7088:     - first elements is number of how closely matching the best fit is 
 7089:       (5 means best set has 5 matching characters)
 7090:     - second element is an arrary ref containing the set of valid CODEs
 7091:       that best fit the passed in CODE
 7092: 
 7093: =cut
 7094: 
 7095: sub scantron_get_closely_matching_CODEs {
 7096:     my ($allcodes,$CODE)=@_;
 7097:     my @CODEs;
 7098:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7099: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7100:     }
 7101: 
 7102:     return ($#CODEs,$CODEs[-1]);
 7103: }
 7104: 
 7105: =pod
 7106: 
 7107: =item get_codes
 7108: 
 7109:    Builds a hash which has keys of all of the valid CODEs from the selected
 7110:    set of remembered CODEs.
 7111: 
 7112:  Arguments:
 7113:   $old_name - name of the set of remembered CODEs
 7114:   $cdom     - domain of the course
 7115:   $cnum     - internal course name
 7116: 
 7117:  Returns:
 7118:   %allcodes - keys are the valid CODEs, values are all 1
 7119: 
 7120: =cut
 7121: 
 7122: sub get_codes {
 7123:     my ($old_name, $cdom, $cnum) = @_;
 7124:     if (!$old_name) {
 7125: 	$old_name=$env{'form.scantron_CODElist'};
 7126:     }
 7127:     if (!$cdom) {
 7128: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7129:     }
 7130:     if (!$cnum) {
 7131: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7132:     }
 7133:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7134: 				    $cdom,$cnum);
 7135:     my %allcodes;
 7136:     if ($result{"type\0$old_name"} eq 'number') {
 7137: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7138:     } else {
 7139: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7140:     }
 7141:     return %allcodes;
 7142: }
 7143: 
 7144: =pod
 7145: 
 7146: =item scantron_validate_CODE
 7147: 
 7148:    Validates all scanlines in the selected file to not have any
 7149:    invalid or underspecified CODEs and that none of the codes are
 7150:    duplicated if this was requested.
 7151: 
 7152: =cut
 7153: 
 7154: sub scantron_validate_CODE {
 7155:     my ($r,$currentphase) = @_;
 7156:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7157:     if ($scantron_config{'CODElocation'} &&
 7158: 	$scantron_config{'CODEstart'} &&
 7159: 	$scantron_config{'CODElength'}) {
 7160: 	if (!defined($env{'form.scantron_CODElist'})) {
 7161: 	    &FIXME_blow_up()
 7162: 	}
 7163:     } else {
 7164: 	return (0,$currentphase+1);
 7165:     }
 7166:     
 7167:     my %usedCODEs;
 7168: 
 7169:     my %allcodes=&get_codes();
 7170: 
 7171:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7172: 
 7173:     my ($scanlines,$scan_data)=&scantron_getfile();
 7174:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7175: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7176: 	if ($line=~/^[\s\cz]*$/) { next; }
 7177: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7178: 						 $scan_data);
 7179: 	my $CODE=$$scan_record{'scantron.CODE'};
 7180: 	my $error=0;
 7181: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7182: 	    &scantron_get_correction($r,$i,$scan_record,
 7183: 				     \%scantron_config,
 7184: 				     $line,'incorrectCODE',\%allcodes);
 7185: 	    return(1,$currentphase);
 7186: 	}
 7187: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7188: 	    && !$$scan_record{'scantron.useCODE'}) {
 7189: 	    &scantron_get_correction($r,$i,$scan_record,
 7190: 				     \%scantron_config,
 7191: 				     $line,'incorrectCODE',\%allcodes);
 7192: 	    return(1,$currentphase);
 7193: 	}
 7194: 	if (exists($usedCODEs{$CODE}) 
 7195: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7196: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7197: 	    &scantron_get_correction($r,$i,$scan_record,
 7198: 				     \%scantron_config,
 7199: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7200: 	    return(1,$currentphase);
 7201: 	}
 7202: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7203:     }
 7204:     return (0,$currentphase+1);
 7205: }
 7206: 
 7207: =pod
 7208: 
 7209: =item scantron_validate_doublebubble
 7210: 
 7211:    Validates all scanlines in the selected file to not have any
 7212:    bubble lines with multiple bubbles marked.
 7213: 
 7214: =cut
 7215: 
 7216: sub scantron_validate_doublebubble {
 7217:     my ($r,$currentphase) = @_;
 7218:     #get student info
 7219:     my $classlist=&Apache::loncoursedata::get_classlist();
 7220:     my %idmap=&username_to_idmap($classlist);
 7221: 
 7222:     #get scantron line setup
 7223:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7224:     my ($scanlines,$scan_data)=&scantron_getfile();
 7225:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7226: 
 7227:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7228: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7229: 	if ($line=~/^[\s\cz]*$/) { next; }
 7230: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7231: 						 $scan_data);
 7232: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7233: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7234: 				 'doublebubble',
 7235: 				 $$scan_record{'scantron.doubleerror'});
 7236:     	return (1,$currentphase);
 7237:     }
 7238:     return (0,$currentphase+1);
 7239: }
 7240: 
 7241: 
 7242: sub scantron_get_maxbubble {
 7243:     if (defined($env{'form.scantron_maxbubble'}) &&
 7244: 	$env{'form.scantron_maxbubble'}) {
 7245: 	&restore_bubble_lines();
 7246: 	return $env{'form.scantron_maxbubble'};
 7247:     }
 7248: 
 7249:     my (undef, undef, $sequence) =
 7250: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7251: 
 7252:     my $navmap=Apache::lonnavmaps::navmap->new();
 7253:     my $map=$navmap->getResourceByUrl($sequence);
 7254:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7255: 
 7256:     &Apache::lonxml::clear_problem_counter();
 7257: 
 7258:     my $uname       = $env{'form.student'};
 7259:     my $udom        = $env{'form.userdom'};
 7260:     my $cid         = $env{'request.course.id'};
 7261:     my $total_lines = 0;
 7262:     %bubble_lines_per_response = ();
 7263:     %first_bubble_line         = ();
 7264:     %subdivided_bubble_lines   = ();
 7265:     %responsetype_per_response = ();
 7266: 
 7267:     my $response_number = 0;
 7268:     my $bubble_line     = 0;
 7269:     foreach my $resource (@resources) {
 7270:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7271:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7272: 	    foreach my $part_id (@{$parts}) {
 7273:                 my $lines;
 7274: 
 7275: 	        # TODO - make this a persistent hash not an array.
 7276: 
 7277:                 # optionresponse, matchresponse and rankresponse type items 
 7278:                 # render as separate sub-questions in exam mode.
 7279:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7280:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7281:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7282:                     my ($numbub,$numshown);
 7283:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7284:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7285:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7286:                         }
 7287:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7288:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7289:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7290:                         }
 7291:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7292:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7293:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7294:                         }
 7295:                     }
 7296:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7297:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7298:                     }
 7299:                     my $bubbles_per_line = 10;
 7300:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7301:                     if (($numbub % $bubbles_per_line) != 0) {
 7302:                         $inner_bubble_lines++;
 7303:                     }
 7304:                     for (my $i=0; $i<$numshown; $i++) {
 7305:                         $subdivided_bubble_lines{$response_number} .= 
 7306:                             $inner_bubble_lines.',';
 7307:                     }
 7308:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7309:                     $lines = $numshown * $inner_bubble_lines;
 7310:                 } else {
 7311:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7312:                 } 
 7313: 
 7314:                 $first_bubble_line{$response_number} = $bubble_line;
 7315: 	        $bubble_lines_per_response{$response_number} = $lines;
 7316:                 $responsetype_per_response{$response_number} = 
 7317:                     $analysis->{$part_id.'.type'};
 7318: 	        $response_number++;
 7319: 
 7320: 	        $bubble_line +=  $lines;
 7321: 	        $total_lines +=  $lines;
 7322: 	    }
 7323:         }
 7324:     }
 7325:     &Apache::lonnet::delenv('scantron.');
 7326: 
 7327:     &save_bubble_lines();
 7328:     $env{'form.scantron_maxbubble'} =
 7329: 	$total_lines;
 7330:     return $env{'form.scantron_maxbubble'};
 7331: }
 7332: 
 7333: sub scantron_validate_missingbubbles {
 7334:     my ($r,$currentphase) = @_;
 7335:     #get student info
 7336:     my $classlist=&Apache::loncoursedata::get_classlist();
 7337:     my %idmap=&username_to_idmap($classlist);
 7338: 
 7339:     #get scantron line setup
 7340:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7341:     my ($scanlines,$scan_data)=&scantron_getfile();
 7342:     my $max_bubble=&scantron_get_maxbubble();
 7343:     if (!$max_bubble) { $max_bubble=2**31; }
 7344:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7345: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7346: 	if ($line=~/^[\s\cz]*$/) { next; }
 7347: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7348: 						 $scan_data);
 7349: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7350: 	my @to_correct;
 7351: 	
 7352: 	# Probably here's where the error is...
 7353: 
 7354: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7355:             my $lastbubble;
 7356:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7357:                my $question = $1;
 7358:                my $subquestion = $2;
 7359:                if (!defined($first_bubble_line{$question -1})) { next; }
 7360:                my $first = $first_bubble_line{$question-1};
 7361:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7362:                my $subcount = 1;
 7363:                while ($subcount<$subquestion) {
 7364:                    $first += $subans[$subcount-1];
 7365:                    $subcount ++;
 7366:                }
 7367:                my $count = $subans[$subquestion-1];
 7368:                $lastbubble = $first + $count;
 7369:             } else {
 7370:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7371:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7372:             }
 7373:             if ($lastbubble > $max_bubble) { next; }
 7374: 	    push(@to_correct,$missing);
 7375: 	}
 7376: 	if (@to_correct) {
 7377: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7378: 				     $line,'missingbubble',\@to_correct);
 7379: 	    return (1,$currentphase);
 7380: 	}
 7381: 
 7382:     }
 7383:     return (0,$currentphase+1);
 7384: }
 7385: 
 7386: 
 7387: sub scantron_process_students {
 7388:     my ($r) = @_;
 7389: 
 7390:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7391:     my ($symb)=&get_symb($r);
 7392:     if (!$symb) {
 7393: 	return '';
 7394:     }
 7395:     my $default_form_data=&defaultFormData($symb);
 7396: 
 7397:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7398:     my ($scanlines,$scan_data)=&scantron_getfile();
 7399:     my $classlist=&Apache::loncoursedata::get_classlist();
 7400:     my %idmap=&username_to_idmap($classlist);
 7401:     my $navmap=Apache::lonnavmaps::navmap->new();
 7402:     my $map=$navmap->getResourceByUrl($sequence);
 7403:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7404: #    $r->print("geto ".scalar(@resources)."<br />");
 7405:     my ($uname,$udom);
 7406:     my $result= <<SCANTRONFORM;
 7407: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7408:   <input type="hidden" name="command" value="scantron_configphase" />
 7409:   $default_form_data
 7410: SCANTRONFORM
 7411:     $r->print($result);
 7412: 
 7413:     my @delayqueue;
 7414:     my (%completedstudents,%scandata);
 7415:     
 7416:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7417:     my $count=&get_todo_count($scanlines,$scan_data);
 7418:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7419:  				    'Scantron Progress',$count,
 7420: 				    'inline',undef,'scantronupload');
 7421:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7422: 					  'Processing first student');
 7423:     $r->print('<br />');
 7424:     my $start=&Time::HiRes::time();
 7425:     my $i=-1;
 7426:     my $started;
 7427: 
 7428:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7429: 
 7430:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7431:     # the user and return.
 7432: 
 7433:     if ($ssi_error) {
 7434: 	$r->print("</form>");
 7435: 	&ssi_print_error($r);
 7436: 	$r->print(&show_grading_menu_form($symb));
 7437:         &Apache::lonnet::remove_lock($lock);
 7438: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7439:     }
 7440: 
 7441:     my %lettdig = &letter_to_digits();
 7442:     my $numletts = scalar(keys(%lettdig));
 7443: 
 7444:     while ($i<$scanlines->{'count'}) {
 7445:  	($uname,$udom)=('','');
 7446:  	$i++;
 7447:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7448:  	if ($line=~/^[\s\cz]*$/) { next; }
 7449: 	if ($started) {
 7450: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7451: 						     'last student');
 7452: 	}
 7453: 	$started=1;
 7454:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7455:  						 $scan_data);
 7456:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7457:  					      \%idmap,$i)) {
 7458:   	    &scantron_add_delay(\@delayqueue,$line,
 7459:  				'Unable to find a student that matches',1);
 7460:  	    next;
 7461:   	}
 7462:  	if (exists $completedstudents{$uname}) {
 7463:  	    &scantron_add_delay(\@delayqueue,$line,
 7464:  				'Student '.$uname.' has multiple sheets',2);
 7465:  	    next;
 7466:  	}
 7467:   	($uname,$udom)=split(/:/,$uname);
 7468: 
 7469:         my %partids_by_symb;
 7470:         foreach my $resource (@resources) {
 7471:             my $ressymb = $resource->symb();
 7472:             my ($analysis,$parts) =
 7473:                 &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);            $partids_by_symb{$ressymb} = $parts;
 7474:         }
 7475: 
 7476: 	&Apache::lonxml::clear_problem_counter();
 7477:   	&Apache::lonnet::appenv($scan_record);
 7478: 
 7479: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7480: 	    &scantron_putfile($scanlines,$scan_data);
 7481: 	}
 7482: 	
 7483:         my $scancode;
 7484:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7485:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7486:             $scancode = $scan_record->{'scantron.CODE'};
 7487:         } else {
 7488:             $scancode = '';
 7489:         }
 7490: 
 7491:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7492:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7493:             $ssi_error = 0; # So end of handler error message does not trigger.
 7494:             $r->print("</form>");
 7495:             &ssi_print_error($r);
 7496:             $r->print(&show_grading_menu_form($symb));
 7497:             &Apache::lonnet::remove_lock($lock);
 7498:             return '';      # Why return ''?  Beats me.
 7499:         }
 7500: 
 7501: 	$completedstudents{$uname}={'line'=>$line};
 7502:         if ($env{'form.verifyrecord'}) {
 7503:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7504:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7505:             chomp($studentdata);
 7506:             $studentdata =~ s/\r$//;
 7507:             my $studentrecord = '';
 7508:             my $counter = -1;
 7509:             foreach my $resource (@resources) {
 7510:                 my $ressymb = $resource->symb();
 7511:                 ($counter,my $recording) =
 7512:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7513:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7514:                                              \%scantron_config,\%lettdig,$numletts);
 7515:                 $studentrecord .= $recording;
 7516:             }
 7517:             if ($studentrecord ne $studentdata) {
 7518:                 &Apache::lonxml::clear_problem_counter();
 7519:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7520:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7521:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7522:                     $r->print("</form>");
 7523:                     &ssi_print_error($r);
 7524:                     $r->print(&show_grading_menu_form($symb));
 7525:                     &Apache::lonnet::remove_lock($lock);
 7526:                     delete($completedstudents{$uname});
 7527:                     return '';
 7528:                 }
 7529:                 $counter = -1;
 7530:                 $studentrecord = '';
 7531:                 foreach my $resource (@resources) {
 7532:                     my $ressymb = $resource->symb();
 7533:                     ($counter,my $recording) =
 7534:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7535:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7536:                                                  \%scantron_config,\%lettdig,$numletts);
 7537:                     $studentrecord .= $recording;
 7538:                 }
 7539:                 if ($studentrecord ne $studentdata) {
 7540:                     $r->print('<p><span class="LC_error">');
 7541:                     if ($scancode eq '') {
 7542:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7543:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7544:                     } else {
 7545:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7546:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7547:                     }
 7548:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7549:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7550:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7551:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7552:                               &Apache::loncommon::start_data_table_row().
 7553:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7554:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7555:                               &Apache::loncommon::end_data_table_row().
 7556:                               &Apache::loncommon::start_data_table_row().
 7557:                               '<td>Stored submissions</td>'.
 7558:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7559:                               &Apache::loncommon::end_data_table_row().
 7560:                               &Apache::loncommon::end_data_table().'</p>');
 7561:                 } else {
 7562:                     $r->print('<br /><span class="LC_warning">'.
 7563:                              &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 />'.
 7564:                              &mt("As a consequence, this user's submission history records two tries.").
 7565:                                  '</span><br />');
 7566:                 }
 7567:             }
 7568:         }
 7569:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7570:     } continue {
 7571: 	&Apache::lonxml::clear_problem_counter();
 7572: 	&Apache::lonnet::delenv('scantron.');
 7573:     }
 7574:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7575:     &Apache::lonnet::remove_lock($lock);
 7576: #    my $lasttime = &Time::HiRes::time()-$start;
 7577: #    $r->print("<p>took $lasttime</p>");
 7578: 
 7579:     $r->print("</form>");
 7580:     $r->print(&show_grading_menu_form($symb));
 7581:     return '';
 7582: }
 7583: 
 7584: sub grade_student_bubbles {
 7585:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7586:     if (ref($resources) eq 'ARRAY') {
 7587:         my $count = 0;
 7588:         foreach my $resource (@{$resources}) {
 7589:             my $ressymb = $resource->symb();
 7590:             my %form = ('submitted'      => 'scantron',
 7591:                         'grade_target'   => 'grade',
 7592:                         'grade_username' => $uname,
 7593:                         'grade_domain'   => $udom,
 7594:                         'grade_courseid' => $env{'request.course.id'},
 7595:                         'grade_symb'     => $ressymb,
 7596:                         'CODE'           => $scancode
 7597:                        );
 7598:             if (ref($parts) eq 'HASH') {
 7599:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7600:                     foreach my $part (@{$parts->{$ressymb}}) {
 7601:                         $form{'scantron_questnum_start.'.$part} =
 7602:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7603:                         $count++;
 7604:                     }
 7605:                 }
 7606:             }
 7607:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7608:             return 'ssi_error' if ($ssi_error);
 7609:             last if (&Apache::loncommon::connection_aborted($r));
 7610:         }
 7611:     }
 7612:     return;
 7613: }
 7614: 
 7615: sub scantron_upload_scantron_data {
 7616:     my ($r)=@_;
 7617:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7618:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7619: 							  'domainid',
 7620: 							  'coursename');
 7621:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7622: 						   'domainid');
 7623:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7624:     $r->print('
 7625: <script type="text/javascript" language="javascript">
 7626:     function checkUpload(formname) {
 7627: 	if (formname.upfile.value == "") {
 7628: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 7629: 	    return false;
 7630: 	}
 7631: 	formname.submit();
 7632:     }
 7633: </script>
 7634: 
 7635: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7636: '.$default_form_data.'
 7637: <table>
 7638: <tr><td>'.$select_link.'                             </td></tr>
 7639: <tr><td>'.&mt('Course ID:').'     </td>
 7640:     <td><input name="courseid"   type="text" />      </td></tr>
 7641: <tr><td>'.&mt('Course Name:').'   </td>
 7642:     <td><input name="coursename" type="text" />      </td></tr>
 7643: <tr><td>'.&mt('Domain:').'        </td>
 7644:     <td>'.$domsel.'                                  </td></tr>
 7645: <tr><td>'.&mt('File to upload:').'</td>
 7646:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7647: </table>
 7648: <input name="command" value="scantronupload_save" type="hidden" />
 7649: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7650: </form>
 7651: ');
 7652:     return '';
 7653: }
 7654: 
 7655: 
 7656: sub scantron_upload_scantron_data_save {
 7657:     my($r)=@_;
 7658:     my ($symb)=&get_symb($r,1);
 7659:     my $doanotherupload=
 7660: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7661: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7662: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7663: 	'</form>'."\n";
 7664:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7665: 	!&Apache::lonnet::allowed('usc',
 7666: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7667: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7668: 	if ($symb) {
 7669: 	    $r->print(&show_grading_menu_form($symb));
 7670: 	} else {
 7671: 	    $r->print($doanotherupload);
 7672: 	}
 7673: 	return '';
 7674:     }
 7675:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7676:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7677:     my $fname=$env{'form.upfile.filename'};
 7678:     #FIXME
 7679:     #copied from lonnet::userfileupload()
 7680:     #make that function able to target a specified course
 7681:     # Replace Windows backslashes by forward slashes
 7682:     $fname=~s/\\/\//g;
 7683:     # Get rid of everything but the actual filename
 7684:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7685:     # Replace spaces by underscores
 7686:     $fname=~s/\s+/\_/g;
 7687:     # Replace all other weird characters by nothing
 7688:     $fname=~s/[^\w\.\-]//g;
 7689:     # See if there is anything left
 7690:     unless ($fname) { return 'error: no uploaded file'; }
 7691:     my $uploadedfile=$fname;
 7692:     $fname='scantron_orig_'.$fname;
 7693:     if (length($env{'form.upfile'}) < 2) {
 7694: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7695:     } else {
 7696: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7697: 	if ($result =~ m|^/uploaded/|) {
 7698: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7699: 			  (length($env{'form.upfile'})-1),
 7700: 			  '<span class="LC_filename">'.$result."</span>"));
 7701: 	} else {
 7702: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7703: 			  $result,
 7704: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7705: 
 7706: 	}
 7707:     }
 7708:     if ($symb) {
 7709: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7710:     } else {
 7711: 	$r->print($doanotherupload);
 7712:     }
 7713:     return '';
 7714: }
 7715: 
 7716: sub valid_file {
 7717:     my ($requested_file)=@_;
 7718:     foreach my $filename (sort(&scantron_filenames())) {
 7719: 	if ($requested_file eq $filename) { return 1; }
 7720:     }
 7721:     return 0;
 7722: }
 7723: 
 7724: sub scantron_download_scantron_data {
 7725:     my ($r)=@_;
 7726:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7727:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7728:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7729:     my $file=$env{'form.scantron_selectfile'};
 7730:     if (! &valid_file($file)) {
 7731: 	$r->print('
 7732: 	<p>
 7733: 	    '.&mt('The requested file name was invalid.').'
 7734:         </p>
 7735: ');
 7736: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7737: 	return;
 7738:     }
 7739:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7740:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7741:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7742:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7743:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7744:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7745:     $r->print('
 7746:     <p>
 7747: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7748: 	      '<a href="'.$orig.'">','</a>').'
 7749:     </p>
 7750:     <p>
 7751: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7752: 	      '<a href="'.$corrected.'">','</a>').'
 7753:     </p>
 7754:     <p>
 7755: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7756: 	      '<a href="'.$skipped.'">','</a>').'
 7757:     </p>
 7758: ');
 7759:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7760:     return '';
 7761: }
 7762: 
 7763: sub checkscantron_results {
 7764:     my ($r) = @_;
 7765:     my ($symb)=&get_symb($r);
 7766:     if (!$symb) {return '';}
 7767:     my $grading_menu_button=&show_grading_menu_form($symb);
 7768:     my $cid = $env{'request.course.id'};
 7769:     my %lettdig = &letter_to_digits();
 7770:     my $numletts = scalar(keys(%lettdig));
 7771:     my $cnum = $env{'course.'.$cid.'.num'};
 7772:     my $cdom = $env{'course.'.$cid.'.domain'};
 7773:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7774:     my %record;
 7775:     my %scantron_config =
 7776:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7777:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7778:     my $classlist=&Apache::loncoursedata::get_classlist();
 7779:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7780:     my $navmap=Apache::lonnavmaps::navmap->new();
 7781:     my $map=$navmap->getResourceByUrl($sequence);
 7782:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7783:     my ($uname,$udom);
 7784:     my (%scandata,%lastname,%bylast);
 7785:     $r->print('
 7786: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7787: 
 7788:     my @delayqueue;
 7789:     my %completedstudents;
 7790: 
 7791:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7792:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7793:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7794:                                     'inline',undef,'checkscantron');
 7795:     my ($username,$domain,$started);
 7796: 
 7797:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7798: 
 7799:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7800:                                           'Processing first student');
 7801:     my $start=&Time::HiRes::time();
 7802:     my $i=-1;
 7803: 
 7804:     while ($i<$scanlines->{'count'}) {
 7805:         ($username,$domain,$uname)=('','','');
 7806:         $i++;
 7807:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7808:         if ($line=~/^[\s\cz]*$/) { next; }
 7809:         if ($started) {
 7810:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7811:                                                      'last student');
 7812:         }
 7813:         $started=1;
 7814:         my $scan_record=
 7815:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7816:                                                      $scan_data);
 7817:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7818:                                                               \%idmap,$i)) {
 7819:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7820:                                 'Unable to find a student that matches',1);
 7821:             next;
 7822:         }
 7823:         if (exists $completedstudents{$uname}) {
 7824:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7825:                                 'Student '.$uname.' has multiple sheets',2);
 7826:             next;
 7827:         }
 7828:         my $pid = $scan_record->{'scantron.ID'};
 7829:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7830:         push(@{$bylast{$lastname{$pid}}},$pid);
 7831:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7832:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7833:         chomp($scandata{$pid});
 7834:         $scandata{$pid} =~ s/\r$//;
 7835:         ($username,$domain)=split(/:/,$uname);
 7836:         my $counter = -1;
 7837:         foreach my $resource (@resources) {
 7838:             my $ressymb = $resource->symb();
 7839:             my ($analysis,$parts) =
 7840:                 &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 7841:             ($counter,my $recording) =
 7842:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7843:                                          $scandata{$pid},$parts,
 7844:                                          \%scantron_config,\%lettdig,$numletts);
 7845:             $record{$pid} .= $recording;
 7846:         }
 7847:     }
 7848:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7849:     $r->print('<br />');
 7850:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 7851:     $passed = 0;
 7852:     $failed = 0;
 7853:     $numstudents = 0;
 7854:     foreach my $last (sort(keys(%bylast))) {
 7855:         if (ref($bylast{$last}) eq 'ARRAY') {
 7856:             foreach my $pid (sort(@{$bylast{$last}})) {
 7857:                 my $showscandata = $scandata{$pid};
 7858:                 my $showrecord = $record{$pid};
 7859:                 $showscandata =~ s/\s/&nbsp;/g;
 7860:                 $showrecord =~ s/\s/&nbsp;/g;
 7861:                 if ($scandata{$pid} eq $record{$pid}) {
 7862:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 7863:                     $okstudents .= '<tr class="'.$css_class.'">'.
 7864: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7865: '</tr>'."\n".
 7866: '<tr class="'.$css_class.'">'."\n".
 7867: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 7868:                     $passed ++;
 7869:                 } else {
 7870:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 7871:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7872: '</tr>'."\n".
 7873: '<tr class="'.$css_class.'">'."\n".
 7874: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 7875: '</tr>'."\n";
 7876:                     $failed ++;
 7877:                 }
 7878:                 $numstudents ++;
 7879:             }
 7880:         }
 7881:     }
 7882:     $r->print('<p>'.&mt('Comparison of scantron data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 7883:     $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>');
 7884:     if ($passed) {
 7885:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 7886:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7887:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7888:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7889:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7890:                  $okstudents."\n".
 7891:                  &Apache::loncommon::end_data_table().'<br />');
 7892:     }
 7893:     if ($failed) {
 7894:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 7895:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7896:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7897:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7898:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7899:                  $badstudents."\n".
 7900:                  &Apache::loncommon::end_data_table()).'<br />'.
 7901:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
 7902:     }
 7903:     $r->print('</form><br />'.$grading_menu_button);
 7904:     return;
 7905: }
 7906: 
 7907: sub verify_scantron_grading {
 7908:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 7909:         $scantron_config,$lettdig,$numletts) = @_;
 7910:     my ($record,%expected,%startpos);
 7911:     return ($counter,$record) if (!ref($resource));
 7912:     return ($counter,$record) if (!$resource->is_problem());
 7913:     my $symb = $resource->symb();
 7914:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 7915:     foreach my $part_id (@{$partids}) {
 7916:         $counter ++;
 7917:         $expected{$part_id} = 0;
 7918:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 7919:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 7920:             foreach my $item (@sub_lines) {
 7921:                 $expected{$part_id} += $item;
 7922:             }
 7923:         } else {
 7924:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 7925:         }
 7926:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 7927:     }
 7928:     if ($symb) {
 7929:         my %recorded;
 7930:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 7931:         if ($returnhash{'version'}) {
 7932:             my %lasthash=();
 7933:             my $version;
 7934:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 7935:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 7936:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 7937:                 }
 7938:             }
 7939:             foreach my $key (keys(%lasthash)) {
 7940:                 if ($key =~ /\.scantron$/) {
 7941:                     my $value = &unescape($lasthash{$key});
 7942:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 7943:                     if ($value eq '') {
 7944:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 7945:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 7946:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 7947:                             }
 7948:                         }
 7949:                     } else {
 7950:                         my @tocheck;
 7951:                         my @items = split(//,$value);
 7952:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 7953:                             ($scantron_config->{'Qon'} eq 'number')) {
 7954:                             if (@items < $expected{$part_id}) {
 7955:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 7956:                                 my @singles = split(//,$fragment);
 7957:                                 foreach my $pos (@singles) {
 7958:                                     if ($pos eq ' ') {
 7959:                                         push(@tocheck,$pos);
 7960:                                     } else {
 7961:                                         my $next = shift(@items);
 7962:                                         push(@tocheck,$next);
 7963:                                     }
 7964:                                 }
 7965:                             } else {
 7966:                                 @tocheck = @items;
 7967:                             }
 7968:                             foreach my $letter (@tocheck) {
 7969:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 7970:                                     if ($letter !~ /^[A-J]$/) {
 7971:                                         $letter = $scantron_config->{'Qoff'};
 7972:                                     }
 7973:                                     $recorded{$part_id} .= $letter;
 7974:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 7975:                                     my $digit;
 7976:                                     if ($letter !~ /^[A-J]$/) {
 7977:                                         $digit = $scantron_config->{'Qoff'};
 7978:                                     } else {
 7979:                                         $digit = $lettdig->{$letter};
 7980:                                     }
 7981:                                     $recorded{$part_id} .= $digit;
 7982:                                 }
 7983:                             }
 7984:                         } else {
 7985:                             @tocheck = @items;
 7986:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 7987:                                 my $curr_sub = shift(@tocheck);
 7988:                                 my $digit;
 7989:                                 if ($curr_sub =~ /^[A-J]$/) {
 7990:                                     $digit = $lettdig->{$curr_sub}-1;
 7991:                                 }
 7992:                                 if ($curr_sub eq 'J') {
 7993:                                     $digit += scalar($numletts);
 7994:                                 }
 7995:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 7996:                                     if ($j == $digit) {
 7997:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 7998:                                     } else {
 7999:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8000:                                     }
 8001:                                 }
 8002:                             }
 8003:                         }
 8004:                     }
 8005:                 }
 8006:             }
 8007:         }
 8008:         foreach my $part_id (@{$partids}) {
 8009:             if ($recorded{$part_id} eq '') {
 8010:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8011:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8012:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8013:                     }
 8014:                 }
 8015:             }
 8016:             $record .= $recorded{$part_id};
 8017:         }
 8018:     }
 8019:     return ($counter,$record);
 8020: }
 8021: 
 8022: sub letter_to_digits { 
 8023:     my %lettdig = (
 8024:                     A => 1,
 8025:                     B => 2,
 8026:                     C => 3,
 8027:                     D => 4,
 8028:                     E => 5,
 8029:                     F => 6,
 8030:                     G => 7,
 8031:                     H => 8,
 8032:                     I => 9,
 8033:                     J => 0,
 8034:                   );
 8035:     return %lettdig;
 8036: }
 8037: 
 8038: 
 8039: #-------- end of section for handling grading scantron forms -------
 8040: #
 8041: #-------------------------------------------------------------------
 8042: 
 8043: #-------------------------- Menu interface -------------------------
 8044: #
 8045: #--- Show a Grading Menu button - Calls the next routine ---
 8046: sub show_grading_menu_form {
 8047:     my ($symb)=@_;
 8048:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8049: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8050: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8051: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8052: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8053: 	'</form>'."\n";
 8054:     return $result;
 8055: }
 8056: 
 8057: # -- Retrieve choices for grading form
 8058: sub savedState {
 8059:     my %savedState = ();
 8060:     if ($env{'form.saveState'}) {
 8061: 	foreach (split(/:/,$env{'form.saveState'})) {
 8062: 	    my ($key,$value) = split(/=/,$_,2);
 8063: 	    $savedState{$key} = $value;
 8064: 	}
 8065:     }
 8066:     return \%savedState;
 8067: }
 8068: 
 8069: sub grading_menu {
 8070:     my ($request) = @_;
 8071:     my ($symb)=&get_symb($request);
 8072:     if (!$symb) {return '';}
 8073:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8074:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8075: 
 8076:     $request->print($table);
 8077:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8078:                   'handgrade'=>$hdgrade,
 8079:                   'probTitle'=>$probTitle,
 8080:                   'command'=>'submit_options',
 8081:                   'saveState'=>"",
 8082:                   'gradingMenu'=>1,
 8083:                   'showgrading'=>"yes");
 8084:     
 8085:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8086:     
 8087:     $fields{'command'} = 'csvform';
 8088:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8089:     
 8090:     $fields{'command'} = 'processclicker';
 8091:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8092:     
 8093:     $fields{'command'} = 'scantron_selectphase';
 8094:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8095:     
 8096:     my @menu = ({	categorytitle=>'Course Grading',
 8097:             items =>[
 8098:                         {	linktext => 'Manual Grading/View Submissions',
 8099:                     		url => $url1,
 8100:                     		permission => 'F',
 8101:                     		icon => 'edit-find-replace.png',
 8102:                     		linktitle => 'Start the process of hand grading submissions.'
 8103:                         },
 8104:                 	    {	linktext => 'Upload Scores',
 8105:                     		url => $url2,
 8106:                     		permission => 'F',
 8107:                     		icon => 'uploadscores.png',
 8108:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8109:                 	    },
 8110:                 	    {	linktext => 'Process Clicker',
 8111:                     		url => $url3,
 8112:                     		permission => 'F',
 8113:                     		icon => 'addClickerInfoFile.png',
 8114:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8115:                 	    },
 8116:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
 8117:                     		url => $url4,
 8118:                     		permission => 'F',
 8119:                     		icon => 'stat.png',
 8120:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8121:                 	    }
 8122:                     ]
 8123:             });
 8124: 
 8125:     #$fields{'command'} = 'verify';
 8126:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8127:     #
 8128:     # Create the menu
 8129:     my $Str;
 8130:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8131:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8132:     $Str .= '<input type="hidden" name="command" value="" />'.
 8133:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8134: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8135: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8136: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8137: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8138: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8139: 
 8140:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8141:     #$menudata->{'jscript'}
 8142:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8143:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8144:         ' /> '.
 8145:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8146:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8147: 
 8148:     $Str .="</form>\n";
 8149:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8150:     $request->print(<<GRADINGMENUJS);
 8151: <script type="text/javascript" language="javascript">
 8152:     function checkChoice(formname,val,cmdx) {
 8153: 	if (val <= 2) {
 8154: 	    var cmd = radioSelection(formname.radioChoice);
 8155: 	    var cmdsave = cmd;
 8156: 	} else {
 8157: 	    cmd = cmdx;
 8158: 	    cmdsave = 'submission';
 8159: 	}
 8160: 	formname.command.value = cmd;
 8161: 	if (val < 5) formname.submit();
 8162: 	if (val == 5) {
 8163: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8164: 	        return false;
 8165: 	    } else {
 8166: 	        formname.submit();
 8167: 	    }
 8168: 	}
 8169:     }
 8170: 
 8171:     function checkReceiptNo(formname,nospace) {
 8172: 	var receiptNo = formname.receipt.value;
 8173: 	var checkOpt = false;
 8174: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8175: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8176: 	if (checkOpt) {
 8177: 	    alert("$receiptalert");
 8178: 	    formname.receipt.value = "";
 8179: 	    formname.receipt.focus();
 8180: 	    return false;
 8181: 	}
 8182: 	return true;
 8183:     }
 8184: </script>
 8185: GRADINGMENUJS
 8186:     &commonJSfunctions($request);
 8187:     return $Str;    
 8188: }
 8189: 
 8190: 
 8191: #--- Displays the submissions first page -------
 8192: sub submit_options {
 8193:     my ($request) = @_;
 8194:     my ($symb)=&get_symb($request);
 8195:     if (!$symb) {return '';}
 8196:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8197: 
 8198:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8199:     $request->print(<<GRADINGMENUJS);
 8200: <script type="text/javascript" language="javascript">
 8201:     function checkChoice(formname,val,cmdx) {
 8202: 	if (val <= 2) {
 8203: 	    var cmd = radioSelection(formname.radioChoice);
 8204: 	    var cmdsave = cmd;
 8205: 	} else {
 8206: 	    cmd = cmdx;
 8207: 	    cmdsave = 'submission';
 8208: 	}
 8209: 	formname.command.value = cmd;
 8210: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8211: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8212: 	if (val < 5) formname.submit();
 8213: 	if (val == 5) {
 8214: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8215: 	    formname.submit();
 8216: 	}
 8217: 	if (val < 7) formname.submit();
 8218:     }
 8219: 
 8220:     function checkReceiptNo(formname,nospace) {
 8221: 	var receiptNo = formname.receipt.value;
 8222: 	var checkOpt = false;
 8223: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8224: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8225: 	if (checkOpt) {
 8226: 	    alert("$receiptalert");
 8227: 	    formname.receipt.value = "";
 8228: 	    formname.receipt.focus();
 8229: 	    return false;
 8230: 	}
 8231: 	return true;
 8232:     }
 8233: </script>
 8234: GRADINGMENUJS
 8235:     &commonJSfunctions($request);
 8236:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8237:     my $result;
 8238:     my (undef,$sections) = &getclasslist('all','0');
 8239:     my $savedState = &savedState();
 8240:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8241:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8242:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8243:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8244: 
 8245:     # Preselect sections
 8246:     my $selsec="";
 8247:     if (ref($sections)) {
 8248:         foreach my $section (sort(@$sections)) {
 8249:             $selsec.='<option value="'.$section.'" '.
 8250:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8251:         }
 8252:     }
 8253: 
 8254:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8255: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8256: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8257: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8258: 	'<input type="hidden" name="command"     value="" />'."\n".
 8259: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8260: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8261: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8262: 
 8263:     $result.='
 8264: <h2>
 8265:   '.&mt('Grade Current Resource').'
 8266: </h2>
 8267: <div>
 8268:   '.$table.'
 8269: </div>
 8270: 
 8271: <div class="LC_columnSection">
 8272:   
 8273:     <fieldset>
 8274:       <legend>
 8275:        '.&mt('Sections').'
 8276:       </legend>
 8277:       <select name="section" multiple="multiple" size="5">'."\n";
 8278:     $result.= $selsec;
 8279:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8280:     $result.='
 8281:     </fieldset>
 8282:   
 8283:     <fieldset>
 8284:       <legend>
 8285:         '.&mt('Groups').'
 8286:       </legend>
 8287:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8288:     </fieldset>
 8289:   
 8290:     <fieldset>
 8291:       <legend>
 8292:         '.&mt('Access Status').'
 8293:       </legend>
 8294:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8295:     </fieldset>
 8296:   
 8297:     <fieldset>
 8298:       <legend>
 8299:         '.&mt('Submission Status').'
 8300:       </legend>
 8301:       <select name="submitonly" size="5">
 8302: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8303: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8304: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8305: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8306:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8307:       </select>
 8308:     </fieldset>
 8309:   
 8310: </div>
 8311: 
 8312: <br />
 8313:           <div>
 8314:             <div>
 8315:               <label>
 8316:                 <input type="radio" name="radioChoice" value="submission" '.
 8317:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8318:              &mt('Select individual students to grade and view submissions.').'
 8319: 	      </label> 
 8320:             </div>
 8321:             <div>
 8322: 	      <label>
 8323:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8324:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8325:                     &mt('Grade all selected students in a grading table.').'
 8326:               </label>
 8327:             </div>
 8328:             <div>
 8329: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8330:             </div>
 8331:           </div>
 8332: 
 8333: 
 8334:         <h2>
 8335:          '.&mt('Grade Complete Folder for One Student').'
 8336:         </h2>
 8337:         <div>
 8338:             <div>
 8339:               <label>
 8340:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8341: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8342:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8343:               </label>
 8344:             </div>
 8345:             <div>
 8346: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8347:             </div>
 8348:         </div>
 8349:   </form>';
 8350:     $result .= &show_grading_menu_form($symb);
 8351:     return $result;
 8352: }
 8353: 
 8354: sub reset_perm {
 8355:     undef(%perm);
 8356: }
 8357: 
 8358: sub init_perm {
 8359:     &reset_perm();
 8360:     foreach my $test_perm ('vgr','mgr','opa') {
 8361: 
 8362: 	my $scope = $env{'request.course.id'};
 8363: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8364: 
 8365: 	    $scope .= '/'.$env{'request.course.sec'};
 8366: 	    if ( $perm{$test_perm}=
 8367: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8368: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8369: 	    } else {
 8370: 		delete($perm{$test_perm});
 8371: 	    }
 8372: 	}
 8373:     }
 8374: }
 8375: 
 8376: sub gather_clicker_ids {
 8377:     my %clicker_ids;
 8378: 
 8379:     my $classlist = &Apache::loncoursedata::get_classlist();
 8380: 
 8381:     # Set up a couple variables.
 8382:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8383:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8384:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8385: 
 8386:     foreach my $student (keys(%$classlist)) {
 8387:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8388:         my $username = $classlist->{$student}->[$username_idx];
 8389:         my $domain   = $classlist->{$student}->[$domain_idx];
 8390:         my $clickers =
 8391: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8392:         foreach my $id (split(/\,/,$clickers)) {
 8393:             $id=~s/^[\#0]+//;
 8394:             $id=~s/[\-\:]//g;
 8395:             if (exists($clicker_ids{$id})) {
 8396: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8397:             } else {
 8398: 		$clicker_ids{$id}=$username.':'.$domain;
 8399:             }
 8400:         }
 8401:     }
 8402:     return %clicker_ids;
 8403: }
 8404: 
 8405: sub gather_adv_clicker_ids {
 8406:     my %clicker_ids;
 8407:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8408:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8409:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8410:     foreach my $element (sort(keys(%coursepersonnel))) {
 8411:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8412:             my ($puname,$pudom)=split(/\:/,$person);
 8413:             my $clickers =
 8414: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8415:             foreach my $id (split(/\,/,$clickers)) {
 8416: 		$id=~s/^[\#0]+//;
 8417:                 $id=~s/[\-\:]//g;
 8418: 		if (exists($clicker_ids{$id})) {
 8419: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8420: 		} else {
 8421: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8422: 		}
 8423:             }
 8424:         }
 8425:     }
 8426:     return %clicker_ids;
 8427: }
 8428: 
 8429: sub clicker_grading_parameters {
 8430:     return ('gradingmechanism' => 'scalar',
 8431:             'upfiletype' => 'scalar',
 8432:             'specificid' => 'scalar',
 8433:             'pcorrect' => 'scalar',
 8434:             'pincorrect' => 'scalar');
 8435: }
 8436: 
 8437: sub process_clicker {
 8438:     my ($r)=@_;
 8439:     my ($symb)=&get_symb($r);
 8440:     if (!$symb) {return '';}
 8441:     my $result=&checkforfile_js();
 8442:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8443:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8444:     $result.=$table;
 8445:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8446:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8447:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8448:         '</b></td></tr>'."\n";
 8449:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8450: # Attempt to restore parameters from last session, set defaults if not present
 8451:     my %Saveable_Parameters=&clicker_grading_parameters();
 8452:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8453:                                                  \%Saveable_Parameters);
 8454:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8455:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8456:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8457:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8458: 
 8459:     my %checked;
 8460:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8461:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8462:           $checked{$gradingmechanism}="checked='checked'";
 8463:        }
 8464:     }
 8465: 
 8466:     my $upload=&mt("Upload File");
 8467:     my $type=&mt("Type");
 8468:     my $attendance=&mt("Award points just for participation");
 8469:     my $personnel=&mt("Correctness determined from response by course personnel");
 8470:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8471:     my $given=&mt("Correctness determined from given list of answers").' '.
 8472:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8473:     my $pcorrect=&mt("Percentage points for correct solution");
 8474:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8475:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8476: 						   ('iclicker' => 'i>clicker',
 8477:                                                     'interwrite' => 'interwrite PRS'));
 8478:     $symb = &Apache::lonenc::check_encrypt($symb);
 8479:     $result.=<<ENDUPFORM;
 8480: <script type="text/javascript">
 8481: function sanitycheck() {
 8482: // Accept only integer percentages
 8483:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8484:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8485: // Find out grading choice
 8486:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8487:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8488:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8489:       }
 8490:    }
 8491: // By default, new choice equals user selection
 8492:    newgradingchoice=gradingchoice;
 8493: // Not good to give more points for false answers than correct ones
 8494:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8495:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8496:    }
 8497: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8498:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8499:       document.forms.gradesupload.pcorrect.value=100;
 8500:       document.forms.gradesupload.pincorrect.value=100;
 8501:    }
 8502: // If the values are different, cannot be attendance only
 8503:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8504:        (gradingchoice=='attendance')) {
 8505:        newgradingchoice='personnel';
 8506:    }
 8507: // Change grading choice to new one
 8508:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8509:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8510:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8511:       } else {
 8512:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8513:       }
 8514:    }
 8515: // Remember the old state
 8516:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8517: }
 8518: </script>
 8519: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8520: <input type="hidden" name="symb" value="$symb" />
 8521: <input type="hidden" name="command" value="processclickerfile" />
 8522: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8523: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8524: <input type="file" name="upfile" size="50" />
 8525: <br /><label>$type: $selectform</label>
 8526: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8527: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8528: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8529: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8530: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8531: <br />&nbsp;&nbsp;&nbsp;
 8532: <input type="text" name="givenanswer" size="50" />
 8533: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8534: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8535: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8536: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8537: </form>
 8538: ENDUPFORM
 8539:     $result.='</td></tr></table>'."\n".
 8540:              '</td></tr></table><br /><br />'."\n";
 8541:     $result.=&show_grading_menu_form($symb);
 8542:     return $result;
 8543: }
 8544: 
 8545: sub process_clicker_file {
 8546:     my ($r)=@_;
 8547:     my ($symb)=&get_symb($r);
 8548:     if (!$symb) {return '';}
 8549: 
 8550:     my %Saveable_Parameters=&clicker_grading_parameters();
 8551:     &Apache::loncommon::store_course_settings('grades_clicker',
 8552:                                               \%Saveable_Parameters);
 8553: 
 8554:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8555:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8556: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8557: 	return $result.&show_grading_menu_form($symb);
 8558:     }
 8559:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8560:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8561:         return $result.&show_grading_menu_form($symb);
 8562:     }
 8563:     my $foundgiven=0;
 8564:     if ($env{'form.gradingmechanism'} eq 'given') {
 8565:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8566:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8567:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8568:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8569:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8570:         $foundgiven=$#answers+1;
 8571:     }
 8572:     my %clicker_ids=&gather_clicker_ids();
 8573:     my %correct_ids;
 8574:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8575: 	%correct_ids=&gather_adv_clicker_ids();
 8576:     }
 8577:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8578: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8579: 	   $correct_id=~tr/a-z/A-Z/;
 8580: 	   $correct_id=~s/\s//gs;
 8581: 	   $correct_id=~s/^[\#0]+//;
 8582:            $correct_id=~s/[\-\:]//g;
 8583:            if ($correct_id) {
 8584: 	      $correct_ids{$correct_id}='specified';
 8585:            }
 8586:         }
 8587:     }
 8588:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8589: 	$result.=&mt('Score based on attendance only');
 8590:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8591:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8592:     } else {
 8593: 	my $number=0;
 8594: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8595: 	foreach my $id (sort(keys(%correct_ids))) {
 8596: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8597: 	    if ($correct_ids{$id} eq 'specified') {
 8598: 		$result.=&mt('specified');
 8599: 	    } else {
 8600: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8601: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8602: 	    }
 8603: 	    $number++;
 8604: 	}
 8605:         $result.="</p>\n";
 8606: 	if ($number==0) {
 8607: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8608: 	    return $result.&show_grading_menu_form($symb);
 8609: 	}
 8610:     }
 8611:     if (length($env{'form.upfile'}) < 2) {
 8612:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8613: 		     '<span class="LC_error">',
 8614: 		     '</span>',
 8615: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8616:         return $result.&show_grading_menu_form($symb);
 8617:     }
 8618: 
 8619: # Were able to get all the info needed, now analyze the file
 8620: 
 8621:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8622:     $symb = &Apache::lonenc::check_encrypt($symb);
 8623:     my $heading=&mt('Scanning clicker file');
 8624:     $result.=(<<ENDHEADER);
 8625: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8626: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8627: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8628: <form method="post" action="/adm/grades" name="clickeranalysis">
 8629: <input type="hidden" name="symb" value="$symb" />
 8630: <input type="hidden" name="command" value="assignclickergrades" />
 8631: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8632: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8633: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8634: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8635: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8636: ENDHEADER
 8637:     if ($env{'form.gradingmechanism'} eq 'given') {
 8638:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8639:     } 
 8640:     my %responses;
 8641:     my @questiontitles;
 8642:     my $errormsg='';
 8643:     my $number=0;
 8644:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8645: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8646:     }
 8647:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8648:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8649:     }
 8650:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8651:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8652:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8653:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8654:              '<br />';
 8655:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8656:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8657:        return $result.&show_grading_menu_form($symb);
 8658:     } 
 8659: # Remember Question Titles
 8660: # FIXME: Possibly need delimiter other than ":"
 8661:     for (my $i=0;$i<$number;$i++) {
 8662:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8663:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8664:     }
 8665:     my $correct_count=0;
 8666:     my $student_count=0;
 8667:     my $unknown_count=0;
 8668: # Match answers with usernames
 8669: # FIXME: Possibly need delimiter other than ":"
 8670:     foreach my $id (keys(%responses)) {
 8671:        if ($correct_ids{$id}) {
 8672:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8673:           $correct_count++;
 8674:        } elsif ($clicker_ids{$id}) {
 8675:           if ($clicker_ids{$id}=~/\,/) {
 8676: # More than one user with the same clicker!
 8677:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8678:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8679:                            "<select name='multi".$id."'>";
 8680:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8681:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8682:              }
 8683:              $result.='</select>';
 8684:              $unknown_count++;
 8685:           } else {
 8686: # Good: found one and only one user with the right clicker
 8687:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8688:              $student_count++;
 8689:           }
 8690:        } else {
 8691:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8692:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8693:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8694:                    "\n".&mt("Domain").": ".
 8695:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8696:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8697:           $unknown_count++;
 8698:        }
 8699:     }
 8700:     $result.='<hr />'.
 8701:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8702:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8703:        if ($correct_count==0) {
 8704:           $errormsg.="Found no correct answers answers for grading!";
 8705:        } elsif ($correct_count>1) {
 8706:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8707:        }
 8708:     }
 8709:     if ($number<1) {
 8710:        $errormsg.="Found no questions.";
 8711:     }
 8712:     if ($errormsg) {
 8713:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8714:     } else {
 8715:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8716:     }
 8717:     $result.='</form></td></tr></table>'."\n".
 8718:              '</td></tr></table><br /><br />'."\n";
 8719:     return $result.&show_grading_menu_form($symb);
 8720: }
 8721: 
 8722: sub iclicker_eval {
 8723:     my ($questiontitles,$responses)=@_;
 8724:     my $number=0;
 8725:     my $errormsg='';
 8726:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8727:         my %components=&Apache::loncommon::record_sep($line);
 8728:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8729: 	if ($entries[0] eq 'Question') {
 8730: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8731: 		$$questiontitles[$number]=$entries[$i];
 8732: 		$number++;
 8733: 	    }
 8734: 	}
 8735: 	if ($entries[0]=~/^\#/) {
 8736: 	    my $id=$entries[0];
 8737: 	    my @idresponses;
 8738: 	    $id=~s/^[\#0]+//;
 8739: 	    for (my $i=0;$i<$number;$i++) {
 8740: 		my $idx=3+$i*6;
 8741: 		push(@idresponses,$entries[$idx]);
 8742: 	    }
 8743: 	    $$responses{$id}=join(',',@idresponses);
 8744: 	}
 8745:     }
 8746:     return ($errormsg,$number);
 8747: }
 8748: 
 8749: sub interwrite_eval {
 8750:     my ($questiontitles,$responses)=@_;
 8751:     my $number=0;
 8752:     my $errormsg='';
 8753:     my $skipline=1;
 8754:     my $questionnumber=0;
 8755:     my %idresponses=();
 8756:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8757:         my %components=&Apache::loncommon::record_sep($line);
 8758:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8759:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8760:         if ($entries[1] eq 'Response') { $skipline=1; }
 8761:         next if $skipline;
 8762:         if ($entries[0]!=$questionnumber) {
 8763:            $questionnumber=$entries[0];
 8764:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8765:            $number++;
 8766:         }
 8767:         my $id=$entries[4];
 8768:         $id=~s/^[\#0]+//;
 8769:         $id=~s/^v\d*\://i;
 8770:         $id=~s/[\-\:]//g;
 8771:         $idresponses{$id}[$number]=$entries[6];
 8772:     }
 8773:     foreach my $id (keys(%idresponses)) {
 8774:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8775:        $$responses{$id}=~s/^\s*\,//;
 8776:     }
 8777:     return ($errormsg,$number);
 8778: }
 8779: 
 8780: sub assign_clicker_grades {
 8781:     my ($r)=@_;
 8782:     my ($symb)=&get_symb($r);
 8783:     if (!$symb) {return '';}
 8784: # See which part we are saving to
 8785:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8786: # FIXME: This should probably look for the first handgradeable part
 8787:     my $part=$$partlist[0];
 8788: # Start screen output
 8789:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8790: 
 8791:     my $heading=&mt('Assigning grades based on clicker file');
 8792:     $result.=(<<ENDHEADER);
 8793: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8794: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8795: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8796: ENDHEADER
 8797: # Get correct result
 8798: # FIXME: Possibly need delimiter other than ":"
 8799:     my @correct=();
 8800:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8801:     my $number=$env{'form.number'};
 8802:     if ($gradingmechanism ne 'attendance') {
 8803:        foreach my $key (keys(%env)) {
 8804:           if ($key=~/^form\.correct\:/) {
 8805:              my @input=split(/\,/,$env{$key});
 8806:              for (my $i=0;$i<=$#input;$i++) {
 8807:                  if (($correct[$i]) && ($input[$i]) &&
 8808:                      ($correct[$i] ne $input[$i])) {
 8809:                     $result.='<br /><span class="LC_warning">'.
 8810:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8811:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8812:                  } elsif ($input[$i]) {
 8813:                     $correct[$i]=$input[$i];
 8814:                  }
 8815:              }
 8816:           }
 8817:        }
 8818:        for (my $i=0;$i<$number;$i++) {
 8819:           if (!$correct[$i]) {
 8820:              $result.='<br /><span class="LC_error">'.
 8821:                       &mt('No correct result given for question "[_1]"!',
 8822:                           $env{'form.question:'.$i}).'</span>';
 8823:           }
 8824:        }
 8825:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8826:     }
 8827: # Start grading
 8828:     my $pcorrect=$env{'form.pcorrect'};
 8829:     my $pincorrect=$env{'form.pincorrect'};
 8830:     my $storecount=0;
 8831:     foreach my $key (keys(%env)) {
 8832:        my $user='';
 8833:        if ($key=~/^form\.student\:(.*)$/) {
 8834:           $user=$1;
 8835:        }
 8836:        if ($key=~/^form\.unknown\:(.*)$/) {
 8837:           my $id=$1;
 8838:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8839:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8840:           } elsif ($env{'form.multi'.$id}) {
 8841:              $user=$env{'form.multi'.$id};
 8842:           }
 8843:        }
 8844:        if ($user) { 
 8845:           my @answer=split(/\,/,$env{$key});
 8846:           my $sum=0;
 8847:           my $realnumber=$number;
 8848:           for (my $i=0;$i<$number;$i++) {
 8849:              if ($answer[$i]) {
 8850:                 if ($gradingmechanism eq 'attendance') {
 8851:                    $sum+=$pcorrect;
 8852:                 } elsif ($answer[$i] eq '*') {
 8853:                    $sum+=$pcorrect;
 8854:                 } elsif ($answer[$i] eq '-') {
 8855:                    $realnumber--;
 8856:                 } else {
 8857:                    if ($answer[$i] eq $correct[$i]) {
 8858:                       $sum+=$pcorrect;
 8859:                    } else {
 8860:                       $sum+=$pincorrect;
 8861:                    }
 8862:                 }
 8863:              }
 8864:           }
 8865:           my $ave=$sum/(100*$realnumber);
 8866: # Store
 8867:           my ($username,$domain)=split(/\:/,$user);
 8868:           my %grades=();
 8869:           $grades{"resource.$part.solved"}='correct_by_override';
 8870:           $grades{"resource.$part.awarded"}=$ave;
 8871:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8872:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8873:                                                  $env{'request.course.id'},
 8874:                                                  $domain,$username);
 8875:           if ($returncode ne 'ok') {
 8876:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8877:           } else {
 8878:              $storecount++;
 8879:           }
 8880:        }
 8881:     }
 8882: # We are done
 8883:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 8884:              '</td></tr></table>'."\n".
 8885:              '</td></tr></table><br /><br />'."\n";
 8886:     return $result.&show_grading_menu_form($symb);
 8887: }
 8888: 
 8889: sub handler {
 8890:     my $request=$_[0];
 8891:     &reset_caches();
 8892:     if ($env{'browser.mathml'}) {
 8893: 	&Apache::loncommon::content_type($request,'text/xml');
 8894:     } else {
 8895: 	&Apache::loncommon::content_type($request,'text/html');
 8896:     }
 8897:     $request->send_http_header;
 8898:     return '' if $request->header_only;
 8899:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8900:     my $symb=&get_symb($request,1);
 8901:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8902:     my $command=$commands[0];
 8903: 
 8904:     if ($#commands > 0) {
 8905: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8906:     }
 8907: 
 8908:     $ssi_error = 0;
 8909:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 8910:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 8911:                                           {'bread_crumbs' => $brcrum}));
 8912:     if ($symb eq '' && $command eq '') {
 8913: 	if ($env{'user.adv'}) {
 8914: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8915: 		($env{'form.codethree'})) {
 8916: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8917: 		    $env{'form.codethree'};
 8918: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8919: 		    &Apache::lonnet::checkin($token);
 8920: 		if ($tsymb) {
 8921: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8922: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8923: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 8924: 					  ('grade_username' => $tuname,
 8925: 					   'grade_domain' => $tudom,
 8926: 					   'grade_courseid' => $tcrsid,
 8927: 					   'grade_symb' => $tsymb)));
 8928: 		    } else {
 8929: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8930: 		    }
 8931: 		} else {
 8932: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8933: 		}
 8934: 	    } else {
 8935: 		$request->print(&Apache::lonxml::tokeninputfield());
 8936: 	    }
 8937: 	}
 8938:     } else {
 8939: 	&init_perm();
 8940: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8941: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8942: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8943: 	    &pickStudentPage($request);
 8944: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8945: 	    &displayPage($request);
 8946: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8947: 	    &updateGradeByPage($request);
 8948: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8949: 	    &processGroup($request);
 8950: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8951: 	    $request->print(&grading_menu($request));
 8952: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8953: 	    $request->print(&submit_options($request));
 8954: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8955: 	    $request->print(&viewgrades($request));
 8956: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8957: 	    $request->print(&processHandGrade($request));
 8958: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8959: 	    $request->print(&editgrades($request));
 8960: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8961: 	    $request->print(&verifyreceipt($request));
 8962:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8963:             $request->print(&process_clicker($request));
 8964:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8965:             $request->print(&process_clicker_file($request));
 8966:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8967:             $request->print(&assign_clicker_grades($request));
 8968: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8969: 	    $request->print(&upcsvScores_form($request));
 8970: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8971: 	    $request->print(&csvupload($request));
 8972: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8973: 	    $request->print(&csvuploadmap($request));
 8974: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8975: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8976: 		$request->print(&csvuploadoptions($request));
 8977: 	    } else {
 8978: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8979: 		    $env{'form.upfile_associate'} = 'reverse';
 8980: 		} else {
 8981: 		    $env{'form.upfile_associate'} = 'forward';
 8982: 		}
 8983: 		$request->print(&csvuploadmap($request));
 8984: 	    }
 8985: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8986: 	    $request->print(&csvuploadassign($request));
 8987: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8988: 	    $request->print(&scantron_selectphase($request));
 8989:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8990:  	    $request->print(&scantron_do_warning($request));
 8991: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8992: 	    $request->print(&scantron_validate_file($request));
 8993: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8994: 	    $request->print(&scantron_process_students($request));
 8995:  	} elsif ($command eq 'scantronupload' && 
 8996:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8997: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8998:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8999:  	} elsif ($command eq 'scantronupload_save' &&
 9000:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9001: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9002:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9003:  	} elsif ($command eq 'scantron_download' &&
 9004: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9005:  	    $request->print(&scantron_download_scantron_data($request));
 9006:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9007:             $request->print(&checkscantron_results($request));     
 9008: 	} elsif ($command) {
 9009: 	    $request->print("Access Denied ($command)");
 9010: 	}
 9011:     }
 9012:     if ($ssi_error) {
 9013: 	&ssi_print_error($request);
 9014:     }
 9015:     $request->print(&Apache::loncommon::end_page());
 9016:     &reset_caches();
 9017:     return '';
 9018: }
 9019: 
 9020: 1;
 9021: 
 9022: __END__;
 9023: 
 9024: 
 9025: =head1 NAME
 9026: 
 9027: Apache::grades
 9028: 
 9029: =head1 SYNOPSIS
 9030: 
 9031: Handles the viewing of grades.
 9032: 
 9033: This is part of the LearningOnline Network with CAPA project
 9034: described at http://www.lon-capa.org.
 9035: 
 9036: =head1 OVERVIEW
 9037: 
 9038: Do an ssi with retries:
 9039: While I'd love to factor out this with the vesrion in lonprintout,
 9040: 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
 9041: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9042: 
 9043: At least the logic that drives this has been pulled out into loncommon.
 9044: 
 9045: 
 9046: 
 9047: ssi_with_retries - Does the server side include of a resource.
 9048:                      if the ssi call returns an error we'll retry it up to
 9049:                      the number of times requested by the caller.
 9050:                      If we still have a proble, no text is appended to the
 9051:                      output and we set some global variables.
 9052:                      to indicate to the caller an SSI error occurred.  
 9053:                      All of this is supposed to deal with the issues described
 9054:                      in LonCAPA BZ 5631 see:
 9055:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9056:                      by informing the user that this happened.
 9057: 
 9058: Parameters:
 9059:   resource   - The resource to include.  This is passed directly, without
 9060:                interpretation to lonnet::ssi.
 9061:   form       - The form hash parameters that guide the interpretation of the resource
 9062:                
 9063:   retries    - Number of retries allowed before giving up completely.
 9064: Returns:
 9065:   On success, returns the rendered resource identified by the resource parameter.
 9066: Side Effects:
 9067:   The following global variables can be set:
 9068:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9069:                               It is up to the caller to initialize this to false
 9070:                               if desired.
 9071:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9072:                               of the resource that could not be rendered by the ssi
 9073:                               call.
 9074:    ssi_error_message   - The error string fetched from the ssi response
 9075:                               in the event of an error.
 9076: 
 9077: 
 9078: =head1 HANDLER SUBROUTINE
 9079: 
 9080: ssi_with_retries()
 9081: 
 9082: =head1 SUBROUTINES
 9083: 
 9084: =over
 9085: 
 9086: =item scantron_get_correction() : 
 9087: 
 9088:    Builds the interface screen to interact with the operator to fix a
 9089:    specific error condition in a specific scanline
 9090: 
 9091:  Arguments:
 9092:     $r           - Apache request object
 9093:     $i           - number of the current scanline
 9094:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9095:     $scan_config - hash ref as returned from &get_scantron_config()
 9096:     $line        - full contents of the current scanline
 9097:     $error       - error condition, valid values are
 9098:                    'incorrectCODE', 'duplicateCODE',
 9099:                    'doublebubble', 'missingbubble',
 9100:                    'duplicateID', 'incorrectID'
 9101:     $arg         - extra information needed
 9102:        For errors:
 9103:          - duplicateID   - paper number that this studentID was seen before on
 9104:          - duplicateCODE - array ref of the paper numbers this CODE was
 9105:                            seen on before
 9106:          - incorrectCODE - current incorrect CODE 
 9107:          - doublebubble  - array ref of the bubble lines that have double
 9108:                            bubble errors
 9109:          - missingbubble - array ref of the bubble lines that have missing
 9110:                            bubble errors
 9111: 
 9112: =item  scantron_get_maxbubble() : 
 9113: 
 9114:    Returns the maximum number of bubble lines that are expected to
 9115:    occur. Does this by walking the selected sequence rendering the
 9116:    resource and then checking &Apache::lonxml::get_problem_counter()
 9117:    for what the current value of the problem counter is.
 9118: 
 9119:    Caches the results to $env{'form.scantron_maxbubble'},
 9120:    $env{'form.scantron.bubble_lines.n'}, 
 9121:    $env{'form.scantron.first_bubble_line.n'} and
 9122:    $env{"form.scantron.sub_bubblelines.n"}
 9123:    which are the total number of bubble, lines, the number of bubble
 9124:    lines for response n and number of the first bubble line for response n,
 9125:    and a comma separated list of numbers of bubble lines for sub-questions
 9126:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9127: 
 9128: 
 9129: =item  scantron_validate_missingbubbles() : 
 9130: 
 9131:    Validates all scanlines in the selected file to not have any
 9132:     answers that don't have bubbles that have not been verified
 9133:     to be bubble free.
 9134: 
 9135: =item  scantron_process_students() : 
 9136: 
 9137:    Routine that does the actual grading of the bubble sheet information.
 9138: 
 9139:    The parsed scanline hash is added to %env 
 9140: 
 9141:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9142:    foreach resource , with the form data of
 9143: 
 9144: 	'submitted'     =>'scantron' 
 9145: 	'grade_target'  =>'grade',
 9146: 	'grade_username'=> username of student
 9147: 	'grade_domain'  => domain of student
 9148: 	'grade_courseid'=> of course
 9149: 	'grade_symb'    => symb of resource to grade
 9150: 
 9151:     This triggers a grading pass. The problem grading code takes care
 9152:     of converting the bubbled letter information (now in %env) into a
 9153:     valid submission.
 9154: 
 9155: =item  scantron_upload_scantron_data() :
 9156: 
 9157:     Creates the screen for adding a new bubble sheet data file to a course.
 9158: 
 9159: =item  scantron_upload_scantron_data_save() : 
 9160: 
 9161:    Adds a provided bubble information data file to the course if user
 9162:    has the correct privileges to do so. 
 9163: 
 9164: =item  valid_file() :
 9165: 
 9166:    Validates that the requested bubble data file exists in the course.
 9167: 
 9168: =item  scantron_download_scantron_data() : 
 9169: 
 9170:    Shows a list of the three internal files (original, corrected,
 9171:    skipped) for a specific bubble sheet data file that exists in the
 9172:    course.
 9173: 
 9174: =item  scantron_validate_ID() : 
 9175: 
 9176:    Validates all scanlines in the selected file to not have any
 9177:    invalid or underspecified student IDs
 9178: 
 9179: =back
 9180: 
 9181: =cut

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