File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.558: download - view: text, annotated - select for diffs
Wed Mar 18 12:26:21 2009 UTC (15 years, 2 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
- XHTML: readonly
- Use double quotes for HTML attributes

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.558 2009/03/18 12:26:21 bisitz Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: sub getpartlist {
  100:     my ($symb) = @_;
  101: 
  102:     my $navmap   = Apache::lonnavmaps::navmap->new();
  103:     my $res      = $navmap->getBySymb($symb);
  104:     my $partlist = $res->parts();
  105:     my $url      = $res->src();
  106:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  107: 
  108:     my @stores;
  109:     foreach my $part (@{ $partlist }) {
  110: 	foreach my $key (@metakeys) {
  111: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  112: 	}
  113:     }
  114:     return @stores;
  115: }
  116: 
  117: # --- Get the symbolic name of a problem and the url
  118: sub get_symb {
  119:     my ($request,$silent) = @_;
  120:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  121:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  122:     if ($symb eq '') { 
  123: 	if (!$silent) {
  124: 	    $request->print("Unable to handle ambiguous references:$url:.");
  125: 	    return ();
  126: 	}
  127:     }
  128:     &Apache::lonenc::check_decrypt(\$symb);
  129:     return ($symb);
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: sub response_type {
  147:     my ($symb) = shift;
  148: 
  149:     my $navmap = Apache::lonnavmaps::navmap->new();
  150:     my $res = $navmap->getBySymb($symb);
  151:     my $partlist = $res->parts();
  152:     my %vPart = 
  153: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  154:     my (%response_types,%handgrade);
  155:     foreach my $part (@{ $partlist }) {
  156: 	next if (%vPart && !exists($vPart{$part}));
  157: 
  158: 	my @types = $res->responseType($part);
  159: 	my @ids = $res->responseIds($part);
  160: 	for (my $i=0; $i < scalar(@ids); $i++) {
  161: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  162: 	    $handgrade{$part.'_'.$ids[$i]} = 
  163: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  164: 				     '.handgrade',$symb);
  165: 	}
  166:     }
  167:     return ($partlist,\%handgrade,\%response_types);
  168: }
  169: 
  170: sub flatten_responseType {
  171:     my ($responseType) = @_;
  172:     my @part_response_id =
  173: 	map { 
  174: 	    my $part = $_;
  175: 	    map {
  176: 		[$part,$_]
  177: 		} sort(keys(%{ $responseType->{$part} }));
  178: 	} sort(keys(%$responseType));
  179:     return @part_response_id;
  180: }
  181: 
  182: sub get_display_part {
  183:     my ($partID,$symb)=@_;
  184:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  185:     if (defined($display) and $display ne '') {
  186: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  187:     } else {
  188: 	$display=$partID;
  189:     }
  190:     return $display;
  191: }
  192: 
  193: #--- Show resource title
  194: #--- and parts and response type
  195: sub showResourceInfo {
  196:     my ($symb,$probTitle,$checkboxes) = @_;
  197:     my $col=3;
  198:     if ($checkboxes) { $col=4; }
  199:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  200:     $result .='<table border="0">';
  201:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  202:     my %resptype = ();
  203:     my $hdgrade='no';
  204:     my %partsseen;
  205:     foreach my $partID (sort(keys(%$responseType))) {
  206: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  207: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  208: 	    my $responsetype = $responseType->{$partID}->{$resID};
  209: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  210: 	    $result.='<tr>';
  211: 	    if ($checkboxes) {
  212: 		if (exists($partsseen{$partID})) {
  213: 		    $result.="<td>&nbsp;</td>";
  214: 		} else {
  215: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  216: 		}
  217: 		$partsseen{$partID}=1;
  218: 	    }
  219: 	    my $display_part=&get_display_part($partID,$symb);
  220: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
  221:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  222: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
  223: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  224: 	}
  225:     }
  226:     $result.='</table>'."\n";
  227:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  228: }
  229: 
  230: sub reset_caches {
  231:     &reset_analyze_cache();
  232:     &reset_perm();
  233: }
  234: 
  235: {
  236:     my %analyze_cache;
  237:     my %analyze_cache_formkeys;
  238: 
  239:     sub reset_analyze_cache {
  240: 	undef(%analyze_cache);
  241:         undef(%analyze_cache_formkeys);
  242:     }
  243: 
  244:     sub get_analyze {
  245: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  246: 	my $key = "$symb\0$uname\0$udom";
  247: 	if (exists($analyze_cache{$key})) {
  248:             my $getupdate = 0;
  249:             if (ref($add_to_hash) eq 'HASH') {
  250:                 foreach my $item (keys(%{$add_to_hash})) {
  251:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  252:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  253:                             $getupdate = 1;
  254:                             last;
  255:                         }
  256:                     } else {
  257:                         $getupdate = 1;
  258:                     }
  259:                 }
  260:             }
  261:             if (!$getupdate) {
  262:                 return $analyze_cache{$key};
  263:             }
  264:         }
  265: 
  266: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  267: 	$url=&Apache::lonnet::clutter($url);
  268:         my %form = ('grade_target'      => 'analyze',
  269:                     'grade_domain'      => $udom,
  270:                     'grade_symb'        => $symb,
  271:                     'grade_courseid'    =>  $env{'request.course.id'},
  272:                     'grade_username'    => $uname,
  273:                     'grade_noincrement' => $no_increment);
  274:         if (ref($add_to_hash)) {
  275:             %form = (%form,%{$add_to_hash});
  276:         } 
  277: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  278: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  279: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  280:         if (ref($add_to_hash) eq 'HASH') {
  281:             $analyze_cache_formkeys{$key} = $add_to_hash;
  282:         } else {
  283:             $analyze_cache_formkeys{$key} = {};
  284:         }
  285: 	return $analyze_cache{$key} = \%analyze;
  286:     }
  287: 
  288:     sub get_order {
  289: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  290: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  291: 	return $analyze->{"$partid.$respid.shown"};
  292:     }
  293: 
  294:     sub get_radiobutton_correct_foil {
  295: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  296: 	my $analyze = &get_analyze($symb,$uname,$udom);
  297:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  298:         if (ref($foils) eq 'ARRAY') {
  299: 	    foreach my $foil (@{$foils}) {
  300: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  301: 		    return $foil;
  302: 	        }
  303: 	    }
  304: 	}
  305:     }
  306: 
  307:     sub scantron_partids_tograde {
  308:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  309:         my (%analysis,@parts);
  310:         if (ref($resource)) {
  311:             my $symb = $resource->symb();
  312:             my $add_to_form;
  313:             if ($check_for_randomlist) {
  314:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  315:             }
  316:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  317:             if (ref($analyze) eq 'HASH') {
  318:                 %analysis = %{$analyze};
  319:             }
  320:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  321:                 foreach my $part (@{$analysis{'parts'}}) {
  322:                     my ($id,$respid) = split(/\./,$part);
  323:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  324:                         push(@parts,$part);
  325:                     }
  326:                 }
  327:             }
  328:         }
  329:         return (\%analysis,\@parts);
  330:     }
  331: 
  332: }
  333: 
  334: #--- Clean response type for display
  335: #--- Currently filters option/rank/radiobutton/match/essay/Task
  336: #        response types only.
  337: sub cleanRecord {
  338:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  339: 	$uname,$udom) = @_;
  340:     my $grayFont = '<span class="LC_internal_info">';
  341:     if ($response =~ /^(option|rank)$/) {
  342: 	my %answer=&Apache::lonnet::str2hash($answer);
  343: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  344: 	my ($toprow,$bottomrow);
  345: 	foreach my $foil (@$order) {
  346: 	    if ($grading{$foil} == 1) {
  347: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  348: 	    } else {
  349: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  350: 	    }
  351: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  352: 	}
  353: 	return '<blockquote><table border="1">'.
  354: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  355: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  356: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  357:     } elsif ($response eq 'match') {
  358: 	my %answer=&Apache::lonnet::str2hash($answer);
  359: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  360: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  361: 	my ($toprow,$middlerow,$bottomrow);
  362: 	foreach my $foil (@$order) {
  363: 	    my $item=shift(@items);
  364: 	    if ($grading{$foil} == 1) {
  365: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  366: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  367: 	    } else {
  368: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  369: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  370: 	    }
  371: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  372: 	}
  373: 	return '<blockquote><table border="1">'.
  374: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  375: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  376: 	    $middlerow.'</tr>'.
  377: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  378: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  379:     } elsif ($response eq 'radiobutton') {
  380: 	my %answer=&Apache::lonnet::str2hash($answer);
  381: 	my ($toprow,$bottomrow);
  382: 	my $correct = 
  383: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  384: 	foreach my $foil (@$order) {
  385: 	    if (exists($answer{$foil})) {
  386: 		if ($foil eq $correct) {
  387: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  388: 		} else {
  389: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  390: 		}
  391: 	    } else {
  392: 		$toprow.='<td>'.&mt('false').'</td>';
  393: 	    }
  394: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  395: 	}
  396: 	return '<blockquote><table border="1">'.
  397: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  398: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  399: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  400:     } elsif ($response eq 'essay') {
  401: 	if (! exists ($env{'form.'.$symb})) {
  402: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  403: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  404: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  405: 
  406: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  407: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  408: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  409: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  410: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  411: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  412: 	}
  413: 	$answer =~ s-\n-<br />-g;
  414: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  415:     } elsif ( $response eq 'organic') {
  416: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  417: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  418: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  419: 	return $result;
  420:     } elsif ( $response eq 'Task') {
  421: 	if ( $answer eq 'SUBMITTED') {
  422: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  423: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  424: 	    return $result;
  425: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  426: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  427: 			       keys(%{$record}));
  428: 	    return join('<br />',($version,@matches));
  429: 			       
  430: 			       
  431: 	} else {
  432: 	    my $result =
  433: 		'<p>'
  434: 		.&mt('Overall result: [_1]',
  435: 		     $record->{$version."resource.$respid.$partid.status"})
  436: 		.'</p>';
  437: 	    
  438: 	    $result .= '<ul>';
  439: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  440: 			     keys(%{$record}));
  441: 	    foreach my $grade (sort(@grade)) {
  442: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  443: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  444: 				     $dim, $record->{$grade}).
  445: 			  '</li>';
  446: 	    }
  447: 	    $result.='</ul>';
  448: 	    return $result;
  449: 	}
  450:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  451: 	$answer = 
  452: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  453: 							      $answer);
  454:     }
  455:     return $answer;
  456: }
  457: 
  458: #-- A couple of common js functions
  459: sub commonJSfunctions {
  460:     my $request = shift;
  461:     $request->print(<<COMMONJSFUNCTIONS);
  462: <script type="text/javascript" language="javascript">
  463:     function radioSelection(radioButton) {
  464: 	var selection=null;
  465: 	if (radioButton.length > 1) {
  466: 	    for (var i=0; i<radioButton.length; i++) {
  467: 		if (radioButton[i].checked) {
  468: 		    return radioButton[i].value;
  469: 		}
  470: 	    }
  471: 	} else {
  472: 	    if (radioButton.checked) return radioButton.value;
  473: 	}
  474: 	return selection;
  475:     }
  476: 
  477:     function pullDownSelection(selectOne) {
  478: 	var selection="";
  479: 	if (selectOne.length > 1) {
  480: 	    for (var i=0; i<selectOne.length; i++) {
  481: 		if (selectOne[i].selected) {
  482: 		    return selectOne[i].value;
  483: 		}
  484: 	    }
  485: 	} else {
  486:             // only one value it must be the selected one
  487: 	    return selectOne.value;
  488: 	}
  489:     }
  490: </script>
  491: COMMONJSFUNCTIONS
  492: }
  493: 
  494: #--- Dumps the class list with usernames,list of sections,
  495: #--- section, ids and fullnames for each user.
  496: sub getclasslist {
  497:     my ($getsec,$filterlist,$getgroup) = @_;
  498:     my @getsec;
  499:     my @getgroup;
  500:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  501:     if (!ref($getsec)) {
  502: 	if ($getsec ne '' && $getsec ne 'all') {
  503: 	    @getsec=($getsec);
  504: 	}
  505:     } else {
  506: 	@getsec=@{$getsec};
  507:     }
  508:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  509:     if (!ref($getgroup)) {
  510: 	if ($getgroup ne '' && $getgroup ne 'all') {
  511: 	    @getgroup=($getgroup);
  512: 	}
  513:     } else {
  514: 	@getgroup=@{$getgroup};
  515:     }
  516:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  517: 
  518:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  519:     # Bail out if we were unable to get the classlist
  520:     return if (! defined($classlist));
  521:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  522:     #
  523:     my %sections;
  524:     my %fullnames;
  525:     foreach my $student (keys(%$classlist)) {
  526:         my $end      = 
  527:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  528:         my $start    = 
  529:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  530:         my $id       = 
  531:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  532:         my $section  = 
  533:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  534:         my $fullname = 
  535:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  536:         my $status   = 
  537:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  538:         my $group   = 
  539:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  540: 	# filter students according to status selected
  541: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  542: 	    if (!($stu_status =~ $status)) {
  543: 		delete($classlist->{$student});
  544: 		next;
  545: 	    }
  546: 	}
  547: 	# filter students according to groups selected
  548: 	my @stu_groups = split(/,/,$group);
  549: 	if (@getgroup) {
  550: 	    my $exclude = 1;
  551: 	    foreach my $grp (@getgroup) {
  552: 	        foreach my $stu_group (@stu_groups) {
  553: 	            if ($stu_group eq $grp) {
  554: 	                $exclude = 0;
  555:     	            } 
  556: 	        }
  557:     	        if (($grp eq 'none') && !$group) {
  558:         	        $exclude = 0;
  559:         	}
  560: 	    }
  561: 	    if ($exclude) {
  562: 	        delete($classlist->{$student});
  563: 	    }
  564: 	}
  565: 	$section = ($section ne '' ? $section : 'none');
  566: 	if (&canview($section)) {
  567: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  568: 		$sections{$section}++;
  569: 		if ($classlist->{$student}) {
  570: 		    $fullnames{$student}=$fullname;
  571: 		}
  572: 	    } else {
  573: 		delete($classlist->{$student});
  574: 	    }
  575: 	} else {
  576: 	    delete($classlist->{$student});
  577: 	}
  578:     }
  579:     my %seen = ();
  580:     my @sections = sort(keys(%sections));
  581:     return ($classlist,\@sections,\%fullnames);
  582: }
  583: 
  584: sub canmodify {
  585:     my ($sec)=@_;
  586:     if ($perm{'mgr'}) {
  587: 	if (!defined($perm{'mgr_section'})) {
  588: 	    # can modify whole class
  589: 	    return 1;
  590: 	} else {
  591: 	    if ($sec eq $perm{'mgr_section'}) {
  592: 		#can modify the requested section
  593: 		return 1;
  594: 	    } else {
  595: 		# can't modify the request section
  596: 		return 0;
  597: 	    }
  598: 	}
  599:     }
  600:     #can't modify
  601:     return 0;
  602: }
  603: 
  604: sub canview {
  605:     my ($sec)=@_;
  606:     if ($perm{'vgr'}) {
  607: 	if (!defined($perm{'vgr_section'})) {
  608: 	    # can modify whole class
  609: 	    return 1;
  610: 	} else {
  611: 	    if ($sec eq $perm{'vgr_section'}) {
  612: 		#can modify the requested section
  613: 		return 1;
  614: 	    } else {
  615: 		# can't modify the request section
  616: 		return 0;
  617: 	    }
  618: 	}
  619:     }
  620:     #can't modify
  621:     return 0;
  622: }
  623: 
  624: #--- Retrieve the grade status of a student for all the parts
  625: sub student_gradeStatus {
  626:     my ($symb,$udom,$uname,$partlist) = @_;
  627:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  628:     my %partstatus = ();
  629:     foreach (@$partlist) {
  630: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  631: 	$status              = 'nothing' if ($status eq '');
  632: 	$partstatus{$_}      = $status;
  633: 	my $subkey           = "resource.$_.submitted_by";
  634: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  635:     }
  636:     return %partstatus;
  637: }
  638: 
  639: # hidden form and javascript that calls the form
  640: # Use by verifyscript and viewgrades
  641: # Shows a student's view of problem and submission
  642: sub jscriptNform {
  643:     my ($symb) = @_;
  644:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  645:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  646: 	'    function viewOneStudent(user,domain) {'."\n".
  647: 	'	document.onestudent.student.value = user;'."\n".
  648: 	'	document.onestudent.userdom.value = domain;'."\n".
  649: 	'	document.onestudent.submit();'."\n".
  650: 	'    }'."\n".
  651: 	'</script>'."\n";
  652:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  653: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  654: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  655: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  656: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  657: 	'<input type="hidden" name="command" value="submission" />'."\n".
  658: 	'<input type="hidden" name="student" value="" />'."\n".
  659: 	'<input type="hidden" name="userdom" value="" />'."\n".
  660: 	'</form>'."\n";
  661:     return $jscript;
  662: }
  663: 
  664: 
  665: 
  666: # Given the score (as a number [0-1] and the weight) what is the final
  667: # point value? This function will round to the nearest tenth, third,
  668: # or quarter if one of those is within the tolerance of .00001.
  669: sub compute_points {
  670:     my ($score, $weight) = @_;
  671:     
  672:     my $tolerance = .00001;
  673:     my $points = $score * $weight;
  674: 
  675:     # Check for nearness to 1/x.
  676:     my $check_for_nearness = sub {
  677:         my ($factor) = @_;
  678:         my $num = ($points * $factor) + $tolerance;
  679:         my $floored_num = floor($num);
  680:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  681:             return $floored_num / $factor;
  682:         }
  683:         return $points;
  684:     };
  685: 
  686:     $points = $check_for_nearness->(10);
  687:     $points = $check_for_nearness->(3);
  688:     $points = $check_for_nearness->(4);
  689:     
  690:     return $points;
  691: }
  692: 
  693: #------------------ End of general use routines --------------------
  694: 
  695: #
  696: # Find most similar essay
  697: #
  698: 
  699: sub most_similar {
  700:     my ($uname,$udom,$uessay,$old_essays)=@_;
  701: 
  702: # ignore spaces and punctuation
  703: 
  704:     $uessay=~s/\W+/ /gs;
  705: 
  706: # ignore empty submissions (occuring when only files are sent)
  707: 
  708:     unless ($uessay=~/\w+/) { return ''; }
  709: 
  710: # these will be returned. Do not care if not at least 50 percent similar
  711:     my $limit=0.6;
  712:     my $sname='';
  713:     my $sdom='';
  714:     my $scrsid='';
  715:     my $sessay='';
  716: # go through all essays ...
  717:     foreach my $tkey (keys(%$old_essays)) {
  718: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  719: # ... except the same student
  720:         next if (($tname eq $uname) && ($tdom eq $udom));
  721: 	my $tessay=$old_essays->{$tkey};
  722: 	$tessay=~s/\W+/ /gs;
  723: # String similarity gives up if not even limit
  724: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  725: # Found one
  726: 	if ($tsimilar>$limit) {
  727: 	    $limit=$tsimilar;
  728: 	    $sname=$tname;
  729: 	    $sdom=$tdom;
  730: 	    $scrsid=$tcrsid;
  731: 	    $sessay=$old_essays->{$tkey};
  732: 	}
  733:     }
  734:     if ($limit>0.6) {
  735:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  736:     } else {
  737:        return ('','','','',0);
  738:     }
  739: }
  740: 
  741: #-------------------------------------------------------------------
  742: 
  743: #------------------------------------ Receipt Verification Routines
  744: #
  745: #--- Check whether a receipt number is valid.---
  746: sub verifyreceipt {
  747:     my $request  = shift;
  748: 
  749:     my $courseid = $env{'request.course.id'};
  750:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  751: 	$env{'form.receipt'};
  752:     $receipt     =~ s/[^\-\d]//g;
  753:     my ($symb)   = &get_symb($request);
  754: 
  755:     my $title.=
  756: 	'<h3><span class="LC_info">'.
  757: 	&mt('Verifying  Receipt No. [_1]',$receipt).
  758: 	'</span></h3>'."\n".
  759: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  760: 	'</h4>'."\n";
  761: 
  762:     my ($string,$contents,$matches) = ('','',0);
  763:     my (undef,undef,$fullname) = &getclasslist('all','0');
  764:     
  765:     my $receiptparts=0;
  766:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  767: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  768:     my $parts=['0'];
  769:     if ($receiptparts) { ($parts)=&response_type($symb); }
  770:     
  771:     my $header = 
  772: 	&Apache::loncommon::start_data_table().
  773: 	&Apache::loncommon::start_data_table_header_row().
  774: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  775: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  776: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  777:     if ($receiptparts) {
  778: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  779:     }
  780:     $header.=
  781: 	&Apache::loncommon::end_data_table_header_row();
  782: 
  783:     foreach (sort 
  784: 	     {
  785: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  786: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  787: 		 }
  788: 		 return $a cmp $b;
  789: 	     } (keys(%$fullname))) {
  790: 	my ($uname,$udom)=split(/\:/);
  791: 	foreach my $part (@$parts) {
  792: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  793: 		$contents.=
  794: 		    &Apache::loncommon::start_data_table_row().
  795: 		    '<td>&nbsp;'."\n".
  796: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  797: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  798: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  799: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  800: 		if ($receiptparts) {
  801: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  802: 		}
  803: 		$contents.= 
  804: 		    &Apache::loncommon::end_data_table_row()."\n";
  805: 		
  806: 		$matches++;
  807: 	    }
  808: 	}
  809:     }
  810:     if ($matches == 0) {
  811: 	$string = $title.&mt('No match found for the above receipt.');
  812:     } else {
  813: 	$string = &jscriptNform($symb).$title.
  814: 	    '<p>'.
  815: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  816: 	    '</p>'.
  817: 	    $header.
  818: 	    $contents.
  819: 	    &Apache::loncommon::end_data_table()."\n";
  820:     }
  821:     return $string.&show_grading_menu_form($symb);
  822: }
  823: 
  824: #--- This is called by a number of programs.
  825: #--- Called from the Grading Menu - View/Grade an individual student
  826: #--- Also called directly when one clicks on the subm button 
  827: #    on the problem page.
  828: sub listStudents {
  829:     my ($request) = shift;
  830: 
  831:     my ($symb) = &get_symb($request);
  832:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  833:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  834:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  835:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  836:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  837:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  838:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  839: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  840: 
  841:     my $result='<h3><span class="LC_info">&nbsp;'
  842: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  843: 	.'</span></h3>';
  844: 
  845:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  846: 
  847:     my %lt = ( 'multiple' =>
  848: 	       &mt("Please select a student or group of students before clicking on the Next button."),
  849: 	       'single'   =>
  850: 	       &mt("Please select the student before clicking on the Next button."),
  851: 	       );
  852:     %lt = &Apache::lonlocal::texthash(%lt);
  853:     $request->print(<<LISTJAVASCRIPT);
  854: <script type="text/javascript" language="javascript">
  855:     function checkSelect(checkBox) {
  856: 	var ctr=0;
  857: 	var sense="";
  858: 	if (checkBox.length > 1) {
  859: 	    for (var i=0; i<checkBox.length; i++) {
  860: 		if (checkBox[i].checked) {
  861: 		    ctr++;
  862: 		}
  863: 	    }
  864: 	    sense = '$lt{'multiple'}';
  865: 	} else {
  866: 	    if (checkBox.checked) {
  867: 		ctr = 1;
  868: 	    }
  869: 	    sense = '$lt{'single'}';
  870: 	}
  871: 	if (ctr == 0) {
  872: 	    alert(sense);
  873: 	    return false;
  874: 	}
  875: 	document.gradesub.submit();
  876:     }
  877: 
  878:     function reLoadList(formname) {
  879: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  880: 	formname.command.value = 'submission';
  881: 	formname.submit();
  882:     }
  883: </script>
  884: LISTJAVASCRIPT
  885: 
  886:     &commonJSfunctions($request);
  887:     $request->print($result);
  888: 
  889:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  890:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  891:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  892: 	"\n".$table;
  893: 	
  894:     $gradeTable .= 
  895: 	'&nbsp;<b>'.&mt('View Problem Text').': </b>'.
  896: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  897: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  898: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n";
  899:     $gradeTable .= 
  900: 	'&nbsp;<b>'.&mt('View Answer').': </b>'.
  901: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  902: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  903: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n";
  904: 
  905:     my $submission_options;
  906:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  907: 	$submission_options.=
  908: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  909:     }
  910:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  911:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  912:     $env{'form.Status'} = $saveStatus;
  913:     $submission_options.=
  914: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  915: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  916: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  917: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  918:     $gradeTable .= 
  919: 	'&nbsp;<b>'.&mt('Submissions').': </b>'.$submission_options.'<br />'."\n";
  920: 
  921:     $gradeTable .= 
  922:         '&nbsp;<b>'.&mt('Grading Increments').': </b>'.
  923: 	    '<select name="increment">'.
  924: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  925: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  926: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  927: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  928: 	    '</select>';
  929:     
  930:     $gradeTable .= 
  931:         &build_section_inputs().
  932: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  933: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  934: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  935: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  936: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  937: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  938: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  939: 
  940:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  941: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  942:     } else {
  943: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  944: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  945:     }
  946: 
  947:     $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".
  948: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  949: 
  950: # checkall buttons
  951:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  952:     $gradeTable.='<input type="button" '."\n".
  953: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  954: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  955:     $gradeTable.=&check_buttons();
  956:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  957:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  958:     $gradeTable.= &Apache::loncommon::start_data_table().
  959: 	&Apache::loncommon::start_data_table_header_row();
  960:     my $loop = 0;
  961:     while ($loop < 2) {
  962: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  963: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  964: 	if ($env{'form.showgrading'} eq 'yes' 
  965: 	    && $submitonly ne 'queued'
  966: 	    && $submitonly ne 'all') {
  967: 	    foreach my $part (sort(@$partlist)) {
  968: 		my $display_part=
  969: 		    &get_display_part((split(/_/,$part))[0],$symb);
  970: 		$gradeTable.=
  971: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  972: 	    }
  973: 	} elsif ($submitonly eq 'queued') {
  974: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  975: 	}
  976: 	$loop++;
  977: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  978:     }
  979:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  980: 
  981:     my $ctr = 0;
  982:     foreach my $student (sort 
  983: 			 {
  984: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  985: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  986: 			     }
  987: 			     return $a cmp $b;
  988: 			 }
  989: 			 (keys(%$fullname))) {
  990: 	my ($uname,$udom) = split(/:/,$student);
  991: 
  992: 	my %status = ();
  993: 
  994: 	if ($submitonly eq 'queued') {
  995: 	    my %queue_status = 
  996: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  997: 							$udom,$uname);
  998: 	    next if (!defined($queue_status{'gradingqueue'}));
  999: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1000: 	}
 1001: 
 1002: 	if ($env{'form.showgrading'} eq 'yes' 
 1003: 	    && $submitonly ne 'queued'
 1004: 	    && $submitonly ne 'all') {
 1005: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1006: 	    my $submitted = 0;
 1007: 	    my $graded = 0;
 1008: 	    my $incorrect = 0;
 1009: 	    foreach (keys(%status)) {
 1010: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1011: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1012: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1013: 		
 1014: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1015: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1016: 		    $submitted = 0;
 1017: 		    my ($part)=split(/\./,$partid);
 1018: 		    $gradeTable.='<input type="hidden" name="'.
 1019: 			$student.':'.$part.':submitted_by" value="'.
 1020: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1021: 		}
 1022: 	    }
 1023: 	    
 1024: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1025: 				     $submitonly eq 'incorrect' ||
 1026: 				     $submitonly eq 'graded'));
 1027: 	    next if (!$graded && ($submitonly eq 'graded'));
 1028: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1029: 	}
 1030: 
 1031: 	$ctr++;
 1032: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1033:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1034: 	if ( $perm{'vgr'} eq 'F' ) {
 1035: 	    if ($ctr%2 ==1) {
 1036: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1037: 	    }
 1038: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1039:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1040:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1041: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1042: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1043: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1044: 
 1045: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1046: 		foreach (sort(keys(%status))) {
 1047: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1048: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1049: 		}
 1050: 	    }
 1051: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1052: 	    if ($ctr%2 ==0) {
 1053: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1054: 	    }
 1055: 	}
 1056:     }
 1057:     if ($ctr%2 ==1) {
 1058: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1059: 	    if ($env{'form.showgrading'} eq 'yes' 
 1060: 		&& $submitonly ne 'queued'
 1061: 		&& $submitonly ne 'all') {
 1062: 		foreach (@$partlist) {
 1063: 		    $gradeTable.='<td>&nbsp;</td>';
 1064: 		}
 1065: 	    } elsif ($submitonly eq 'queued') {
 1066: 		$gradeTable.='<td>&nbsp;</td>';
 1067: 	    }
 1068: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1069:     }
 1070: 
 1071:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1072: 	'<input type="button" '.
 1073: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1074: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1075:     if ($ctr == 0) {
 1076: 	my $num_students=(scalar(keys(%$fullname)));
 1077: 	if ($num_students eq 0) {
 1078: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1079: 	} else {
 1080: 	    my $submissions='submissions';
 1081: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1082: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1083: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1084: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1085: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1086: 		    $num_students).
 1087: 		'</span><br />';
 1088: 	}
 1089:     } elsif ($ctr == 1) {
 1090: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1091:     }
 1092:     $gradeTable.=&show_grading_menu_form($symb);
 1093:     $request->print($gradeTable);
 1094:     return '';
 1095: }
 1096: 
 1097: #---- Called from the listStudents routine
 1098: 
 1099: sub check_script {
 1100:     my ($form, $type)=@_;
 1101:     my $chkallscript='<script type="text/javascript">
 1102:     function checkall() {
 1103:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1104:             ele = document.forms.'.$form.'.elements[i];
 1105:             if (ele.name == "'.$type.'") {
 1106:             document.forms.'.$form.'.elements[i].checked=true;
 1107:                                        }
 1108:         }
 1109:     }
 1110: 
 1111:     function checksec() {
 1112:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1113:             ele = document.forms.'.$form.'.elements[i];
 1114:            string = document.forms.'.$form.'.chksec.value;
 1115:            if
 1116:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1117:               document.forms.'.$form.'.elements[i].checked=true;
 1118:             }
 1119:         }
 1120:     }
 1121: 
 1122: 
 1123:     function uncheckall() {
 1124:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1125:             ele = document.forms.'.$form.'.elements[i];
 1126:             if (ele.name == "'.$type.'") {
 1127:             document.forms.'.$form.'.elements[i].checked=false;
 1128:                                        }
 1129:         }
 1130:     }
 1131: 
 1132: </script>'."\n";
 1133:     return $chkallscript;
 1134: }
 1135: 
 1136: sub check_buttons {
 1137:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1138:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1139:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1140:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1141:     return $buttons;
 1142: }
 1143: 
 1144: #     Displays the submissions for one student or a group of students
 1145: sub processGroup {
 1146:     my ($request)  = shift;
 1147:     my $ctr        = 0;
 1148:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1149:     my $total      = scalar(@stuchecked)-1;
 1150: 
 1151:     foreach my $student (@stuchecked) {
 1152: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1153: 	$env{'form.student'}        = $uname;
 1154: 	$env{'form.userdom'}        = $udom;
 1155: 	$env{'form.fullname'}       = $fullname;
 1156: 	&submission($request,$ctr,$total);
 1157: 	$ctr++;
 1158:     }
 1159:     return '';
 1160: }
 1161: 
 1162: #------------------------------------------------------------------------------------
 1163: #
 1164: #-------------------------- Next few routines handles grading by student, essentially
 1165: #                           handles essay response type problem/part
 1166: #
 1167: #--- Javascript to handle the submission page functionality ---
 1168: sub sub_page_js {
 1169:     my $request = shift;
 1170: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1171:     $request->print(<<SUBJAVASCRIPT);
 1172: <script type="text/javascript" language="javascript">
 1173:     function updateRadio(formname,id,weight) {
 1174: 	var gradeBox = formname["GD_BOX"+id];
 1175: 	var radioButton = formname["RADVAL"+id];
 1176: 	var oldpts = formname["oldpts"+id].value;
 1177: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1178: 	gradeBox.value = pts;
 1179: 	var resetbox = false;
 1180: 	if (isNaN(pts) || pts < 0) {
 1181: 	    alert("$alertmsg"+pts);
 1182: 	    for (var i=0; i<radioButton.length; i++) {
 1183: 		if (radioButton[i].checked) {
 1184: 		    gradeBox.value = i;
 1185: 		    resetbox = true;
 1186: 		}
 1187: 	    }
 1188: 	    if (!resetbox) {
 1189: 		formtextbox.value = "";
 1190: 	    }
 1191: 	    return;
 1192: 	}
 1193: 
 1194: 	if (pts > weight) {
 1195: 	    var resp = confirm("You entered a value ("+pts+
 1196: 			       ") greater than the weight for the part. Accept?");
 1197: 	    if (resp == false) {
 1198: 		gradeBox.value = oldpts;
 1199: 		return;
 1200: 	    }
 1201: 	}
 1202: 
 1203: 	for (var i=0; i<radioButton.length; i++) {
 1204: 	    radioButton[i].checked=false;
 1205: 	    if (pts == i && pts != "") {
 1206: 		radioButton[i].checked=true;
 1207: 	    }
 1208: 	}
 1209: 	updateSelect(formname,id);
 1210: 	formname["stores"+id].value = "0";
 1211:     }
 1212: 
 1213:     function writeBox(formname,id,pts) {
 1214: 	var gradeBox = formname["GD_BOX"+id];
 1215: 	if (checkSolved(formname,id) == 'update') {
 1216: 	    gradeBox.value = pts;
 1217: 	} else {
 1218: 	    var oldpts = formname["oldpts"+id].value;
 1219: 	    gradeBox.value = oldpts;
 1220: 	    var radioButton = formname["RADVAL"+id];
 1221: 	    for (var i=0; i<radioButton.length; i++) {
 1222: 		radioButton[i].checked=false;
 1223: 		if (i == oldpts) {
 1224: 		    radioButton[i].checked=true;
 1225: 		}
 1226: 	    }
 1227: 	}
 1228: 	formname["stores"+id].value = "0";
 1229: 	updateSelect(formname,id);
 1230: 	return;
 1231:     }
 1232: 
 1233:     function clearRadBox(formname,id) {
 1234: 	if (checkSolved(formname,id) == 'noupdate') {
 1235: 	    updateSelect(formname,id);
 1236: 	    return;
 1237: 	}
 1238: 	gradeSelect = formname["GD_SEL"+id];
 1239: 	for (var i=0; i<gradeSelect.length; i++) {
 1240: 	    if (gradeSelect[i].selected) {
 1241: 		var selectx=i;
 1242: 	    }
 1243: 	}
 1244: 	var stores = formname["stores"+id];
 1245: 	if (selectx == stores.value) { return };
 1246: 	var gradeBox = formname["GD_BOX"+id];
 1247: 	gradeBox.value = "";
 1248: 	var radioButton = formname["RADVAL"+id];
 1249: 	for (var i=0; i<radioButton.length; i++) {
 1250: 	    radioButton[i].checked=false;
 1251: 	}
 1252: 	stores.value = selectx;
 1253:     }
 1254: 
 1255:     function checkSolved(formname,id) {
 1256: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1257: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1258: 	    if (!reply) {return "noupdate";}
 1259: 	    formname.overRideScore.value = 'yes';
 1260: 	}
 1261: 	return "update";
 1262:     }
 1263: 
 1264:     function updateSelect(formname,id) {
 1265: 	formname["GD_SEL"+id][0].selected = true;
 1266: 	return;
 1267:     }
 1268: 
 1269: //=========== Check that a point is assigned for all the parts  ============
 1270:     function checksubmit(formname,val,total,parttot) {
 1271: 	formname.gradeOpt.value = val;
 1272: 	if (val == "Save & Next") {
 1273: 	    for (i=0;i<=total;i++) {
 1274: 		for (j=0;j<parttot;j++) {
 1275: 		    var partid = formname["partid"+i+"_"+j].value;
 1276: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1277: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1278: 			if (points == "") {
 1279: 			    var name = formname["name"+i].value;
 1280: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1281: 			    var resp = confirm("You did not assign a score for "+studentID+
 1282: 					       ", part "+partid+". Continue?");
 1283: 			    if (resp == false) {
 1284: 				formname["GD_BOX"+i+"_"+partid].focus();
 1285: 				return false;
 1286: 			    }
 1287: 			}
 1288: 		    }
 1289: 		    
 1290: 		}
 1291: 	    }
 1292: 	    
 1293: 	}
 1294: 	if (val == "Grade Student") {
 1295: 	    formname.showgrading.value = "yes";
 1296: 	    if (formname.Status.value == "") {
 1297: 		formname.Status.value = "Active";
 1298: 	    }
 1299: 	    formname.studentNo.value = total;
 1300: 	}
 1301: 	formname.submit();
 1302:     }
 1303: 
 1304: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1305:     function checkSubmitPage(formname,total) {
 1306: 	noscore = new Array(100);
 1307: 	var ptr = 0;
 1308: 	for (i=1;i<total;i++) {
 1309: 	    var partid = formname["q_"+i].value;
 1310: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1311: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1312: 		var status = formname["solved"+i+"_"+partid].value;
 1313: 		if (points == "" && status != "correct_by_student") {
 1314: 		    noscore[ptr] = i;
 1315: 		    ptr++;
 1316: 		}
 1317: 	    }
 1318: 	}
 1319: 	if (ptr != 0) {
 1320: 	    var sense = ptr == 1 ? ": " : "s: ";
 1321: 	    var prolist = "";
 1322: 	    if (ptr == 1) {
 1323: 		prolist = noscore[0];
 1324: 	    } else {
 1325: 		var i = 0;
 1326: 		while (i < ptr-1) {
 1327: 		    prolist += noscore[i]+", ";
 1328: 		    i++;
 1329: 		}
 1330: 		prolist += "and "+noscore[i];
 1331: 	    }
 1332: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1333: 	    if (resp == false) {
 1334: 		return false;
 1335: 	    }
 1336: 	}
 1337: 
 1338: 	formname.submit();
 1339:     }
 1340: </script>
 1341: SUBJAVASCRIPT
 1342: }
 1343: 
 1344: #--- javascript for essay type problem --
 1345: sub sub_page_kw_js {
 1346:     my $request = shift;
 1347:     my $iconpath = $request->dir_config('lonIconsURL');
 1348:     &commonJSfunctions($request);
 1349: 
 1350:     my $inner_js_msg_central=<<INNERJS;
 1351:     <script text="text/javascript">
 1352:     function checkInput() {
 1353:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1354:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1355:       var usrctr = document.msgcenter.usrctr.value;
 1356:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1357:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1358: 
 1359:       var msgchk = "";
 1360:       if (document.msgcenter.subchk.checked) {
 1361:          msgchk = "msgsub,";
 1362:       }
 1363:       var includemsg = 0;
 1364:       for (var i=1; i<=nmsg; i++) {
 1365:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1366:           var frmmsg = document.msgcenter["msg"+i];
 1367:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1368:           var showflg = opener.document.SCORE["shownOnce"+i];
 1369:           showflg.value = "1";
 1370:           var chkbox = document.msgcenter["msgn"+i];
 1371:           if (chkbox.checked) {
 1372:              msgchk += "savemsg"+i+",";
 1373:              includemsg = 1;
 1374:           }
 1375:       }
 1376:       if (document.msgcenter.newmsgchk.checked) {
 1377:          msgchk += "newmsg"+usrctr;
 1378:          includemsg = 1;
 1379:       }
 1380:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1381:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1382:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1383:       includemsg.value = msgchk;
 1384: 
 1385:       self.close()
 1386: 
 1387:     }
 1388:     </script>
 1389: INNERJS
 1390: 
 1391:     my $inner_js_highlight_central=<<INNERJS;
 1392:  <script type="text/javascript">
 1393:     function updateChoice(flag) {
 1394:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1395:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1396:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1397:       opener.document.SCORE.refresh.value = "on";
 1398:       if (opener.document.SCORE.keywords.value!=""){
 1399:          opener.document.SCORE.submit();
 1400:       }
 1401:       self.close()
 1402:     }
 1403: </script>
 1404: INNERJS
 1405: 
 1406:     my $start_page_msg_central = 
 1407:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1408: 				       {'js_ready'  => 1,
 1409: 					'only_body' => 1,
 1410: 					'bgcolor'   =>'#FFFFFF',});
 1411:     my $end_page_msg_central = 
 1412: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1413: 
 1414: 
 1415:     my $start_page_highlight_central = 
 1416:         &Apache::loncommon::start_page('Highlight Central',
 1417: 				       $inner_js_highlight_central,
 1418: 				       {'js_ready'  => 1,
 1419: 					'only_body' => 1,
 1420: 					'bgcolor'   =>'#FFFFFF',});
 1421:     my $end_page_highlight_central = 
 1422: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1423: 
 1424:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1425:     $docopen=~s/^document\.//;
 1426:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1427:     $request->print(<<SUBJAVASCRIPT);
 1428: <script type="text/javascript" language="javascript">
 1429: 
 1430: //===================== Show list of keywords ====================
 1431:   function keywords(formname) {
 1432:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1433:     if (nret==null) return;
 1434:     formname.keywords.value = nret;
 1435: 
 1436:     if (formname.keywords.value != "") {
 1437: 	formname.refresh.value = "on";
 1438: 	formname.submit();
 1439:     }
 1440:     return;
 1441:   }
 1442: 
 1443: //===================== Script to view submitted by ==================
 1444:   function viewSubmitter(submitter) {
 1445:     document.SCORE.refresh.value = "on";
 1446:     document.SCORE.NCT.value = "1";
 1447:     document.SCORE.unamedom0.value = submitter;
 1448:     document.SCORE.submit();
 1449:     return;
 1450:   }
 1451: 
 1452: //===================== Script to add keyword(s) ==================
 1453:   function getSel() {
 1454:     if (document.getSelection) txt = document.getSelection();
 1455:     else if (document.selection) txt = document.selection.createRange().text;
 1456:     else return;
 1457:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1458:     if (cleantxt=="") {
 1459: 	alert("$alertmsg");
 1460: 	return;
 1461:     }
 1462:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1463:     if (nret==null) return;
 1464:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1465:     if (document.SCORE.keywords.value != "") {
 1466: 	document.SCORE.refresh.value = "on";
 1467: 	document.SCORE.submit();
 1468:     }
 1469:     return;
 1470:   }
 1471: 
 1472: //====================== Script for composing message ==============
 1473:    // preload images
 1474:    img1 = new Image();
 1475:    img1.src = "$iconpath/mailbkgrd.gif";
 1476:    img2 = new Image();
 1477:    img2.src = "$iconpath/mailto.gif";
 1478: 
 1479:   function msgCenter(msgform,usrctr,fullname) {
 1480:     var Nmsg  = msgform.savemsgN.value;
 1481:     savedMsgHeader(Nmsg,usrctr,fullname);
 1482:     var subject = msgform.msgsub.value;
 1483:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1484:     re = /msgsub/;
 1485:     var shwsel = "";
 1486:     if (re.test(msgchk)) { shwsel = "checked" }
 1487:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1488:     displaySubject(checkEntities(subject),shwsel);
 1489:     for (var i=1; i<=Nmsg; i++) {
 1490: 	var testmsg = "savemsg"+i+",";
 1491: 	re = new RegExp(testmsg,"g");
 1492: 	shwsel = "";
 1493: 	if (re.test(msgchk)) { shwsel = "checked" }
 1494: 	var message = document.SCORE["savemsg"+i].value;
 1495: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1496: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1497: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1498:     }
 1499:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1500:     shwsel = "";
 1501:     re = /newmsg/;
 1502:     if (re.test(msgchk)) { shwsel = "checked" }
 1503:     newMsg(newmsg,shwsel);
 1504:     msgTail(); 
 1505:     return;
 1506:   }
 1507: 
 1508:   function checkEntities(strx) {
 1509:     if (strx.length == 0) return strx;
 1510:     var orgStr = ["&", "<", ">", '"']; 
 1511:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1512:     var counter = 0;
 1513:     while (counter < 4) {
 1514: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1515: 	counter++;
 1516:     }
 1517:     return strx;
 1518:   }
 1519: 
 1520:   function strReplace(strx, orgStr, newStr) {
 1521:     return strx.split(orgStr).join(newStr);
 1522:   }
 1523: 
 1524:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1525:     var height = 70*Nmsg+250;
 1526:     var scrollbar = "no";
 1527:     if (height > 600) {
 1528: 	height = 600;
 1529: 	scrollbar = "yes";
 1530:     }
 1531:     var xpos = (screen.width-600)/2;
 1532:     xpos = (xpos < 0) ? '0' : xpos;
 1533:     var ypos = (screen.height-height)/2-30;
 1534:     ypos = (ypos < 0) ? '0' : ypos;
 1535: 
 1536:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1537:     pWin.focus();
 1538:     pDoc = pWin.document;
 1539:     pDoc.$docopen;
 1540:     pDoc.write('$start_page_msg_central');
 1541: 
 1542:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1543:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1544:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1545: 
 1546:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1547:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1548:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1549: }
 1550:     function displaySubject(msg,shwsel) {
 1551:     pDoc = pWin.document;
 1552:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1553:     pDoc.write("<td>Subject<\\/td>");
 1554:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1555:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1556: }
 1557: 
 1558:   function displaySavedMsg(ctr,msg,shwsel) {
 1559:     pDoc = pWin.document;
 1560:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1561:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1562:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1563:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1564: }
 1565: 
 1566:   function newMsg(newmsg,shwsel) {
 1567:     pDoc = pWin.document;
 1568:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1569:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1570:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1571:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1572: }
 1573: 
 1574:   function msgTail() {
 1575:     pDoc = pWin.document;
 1576:     pDoc.write("<\\/table>");
 1577:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1578:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1579:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1580:     pDoc.write("<\\/form>");
 1581:     pDoc.write('$end_page_msg_central');
 1582:     pDoc.close();
 1583: }
 1584: 
 1585: //====================== Script for keyword highlight options ==============
 1586:   function kwhighlight() {
 1587:     var kwclr    = document.SCORE.kwclr.value;
 1588:     var kwsize   = document.SCORE.kwsize.value;
 1589:     var kwstyle  = document.SCORE.kwstyle.value;
 1590:     var redsel = "";
 1591:     var grnsel = "";
 1592:     var blusel = "";
 1593:     if (kwclr=="red")   {var redsel="checked"};
 1594:     if (kwclr=="green") {var grnsel="checked"};
 1595:     if (kwclr=="blue")  {var blusel="checked"};
 1596:     var sznsel = "";
 1597:     var sz1sel = "";
 1598:     var sz2sel = "";
 1599:     if (kwsize=="0")  {var sznsel="checked"};
 1600:     if (kwsize=="+1") {var sz1sel="checked"};
 1601:     if (kwsize=="+2") {var sz2sel="checked"};
 1602:     var synsel = "";
 1603:     var syisel = "";
 1604:     var sybsel = "";
 1605:     if (kwstyle=="")    {var synsel="checked"};
 1606:     if (kwstyle=="<i>") {var syisel="checked"};
 1607:     if (kwstyle=="<b>") {var sybsel="checked"};
 1608:     highlightCentral();
 1609:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1610:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1611:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1612:     highlightend();
 1613:     return;
 1614:   }
 1615: 
 1616:   function highlightCentral() {
 1617: //    if (window.hwdWin) window.hwdWin.close();
 1618:     var xpos = (screen.width-400)/2;
 1619:     xpos = (xpos < 0) ? '0' : xpos;
 1620:     var ypos = (screen.height-330)/2-30;
 1621:     ypos = (ypos < 0) ? '0' : ypos;
 1622: 
 1623:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1624:     hwdWin.focus();
 1625:     var hDoc = hwdWin.document;
 1626:     hDoc.$docopen;
 1627:     hDoc.write('$start_page_highlight_central');
 1628:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1629:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1630: 
 1631:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1632:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1633:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1634:   }
 1635: 
 1636:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1637:     var hDoc = hwdWin.document;
 1638:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1639:     hDoc.write("<td align=\\"left\\">");
 1640:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1641:     hDoc.write("<td align=\\"left\\">");
 1642:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1643:     hDoc.write("<td align=\\"left\\">");
 1644:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1645:     hDoc.write("<\\/tr>");
 1646:   }
 1647: 
 1648:   function highlightend() { 
 1649:     var hDoc = hwdWin.document;
 1650:     hDoc.write("<\\/table>");
 1651:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1652:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1653:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1654:     hDoc.write("<\\/form>");
 1655:     hDoc.write('$end_page_highlight_central');
 1656:     hDoc.close();
 1657:   }
 1658: 
 1659: </script>
 1660: SUBJAVASCRIPT
 1661: }
 1662: 
 1663: sub get_increment {
 1664:     my $increment = $env{'form.increment'};
 1665:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1666:         $increment != .1) {
 1667:         $increment = 1;
 1668:     }
 1669:     return $increment;
 1670: }
 1671: 
 1672: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1673: sub gradeBox {
 1674:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1675:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1676: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1677:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1678:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1679:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1680:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1681:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1682: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1683:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1684:     my $display_part= &get_display_part($partid,$symb);
 1685:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1686: 				       [$partid]);
 1687:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1688:     if ($last_resets{$partid}) {
 1689:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1690:     }
 1691:     $result.='<table border="0"><tr>';
 1692:     my $ctr = 0;
 1693:     my $thisweight = 0;
 1694:     my $increment = &get_increment();
 1695: 
 1696:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1697:     while ($thisweight<=$wgt) {
 1698: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1699: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1700: 	    $thisweight.')" value="'.$thisweight.'" '.
 1701: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1702: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1703:         $thisweight += $increment;
 1704: 	$ctr++;
 1705:     }
 1706:     $radio.='</tr></table>';
 1707: 
 1708:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1709: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1710: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1711: 	$wgt.')" /></td>'."\n";
 1712:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1713: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1714: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1715:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1716: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1717:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1718: 	$line.='<option></option>'.
 1719: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1720:     } else {
 1721: 	$line.='<option selected="selected"></option>'.
 1722: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1723:     }
 1724:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1725: 
 1726: 
 1727: 	#&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);
 1728:     $result .= 
 1729: 	    '<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>'.
 1730:     
 1731:     $result.='</tr></table>'."\n";
 1732:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1733: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1734: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1735: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1736:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1737:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1738:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1739:         $aggtries.'" />'."\n";
 1740:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1741:     return $result;
 1742: }
 1743: 
 1744: sub handback_box {
 1745:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1746:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1747:     my (@respids);
 1748:      my @part_response_id = &flatten_responseType($responseType);
 1749:     foreach my $part_response_id (@part_response_id) {
 1750:     	my ($part,$resp) = @{ $part_response_id };
 1751:         if ($part eq $partid) {
 1752:             push(@respids,$resp);
 1753:         }
 1754:     }
 1755:     my $result;
 1756:     foreach my $respid (@respids) {
 1757: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1758: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1759: 	next if (!@$files);
 1760: 	my $file_counter = 1;
 1761: 	foreach my $file (@$files) {
 1762: 	    if ($file =~ /\/portfolio\//) {
 1763:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1764:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1765:     	        $file_disp = "$name.$ext";
 1766:     	        $file = $file_path.$file_disp;
 1767:     	        $result.=&mt('Return commented version of [_1] to student.',
 1768:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1769:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1770:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1771:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1772:     	        $file_counter++;
 1773: 	    }
 1774: 	}
 1775:     }
 1776:     return $result;    
 1777: }
 1778: 
 1779: sub show_problem {
 1780:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1781:     my $rendered;
 1782:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1783:     &Apache::lonxml::remember_problem_counter();
 1784:     if ($mode eq 'both' or $mode eq 'text') {
 1785: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1786: 						       $env{'request.course.id'},
 1787: 						       undef,\%form);
 1788:     }
 1789:     if ($removeform) {
 1790: 	$rendered=~s|<form(.*?)>||g;
 1791: 	$rendered=~s|</form>||g;
 1792: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1793:     }
 1794:     my $companswer;
 1795:     if ($mode eq 'both' or $mode eq 'answer') {
 1796: 	&Apache::lonxml::restore_problem_counter();
 1797: 	$companswer=
 1798: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1799: 						    $env{'request.course.id'},
 1800: 						    %form);
 1801:     }
 1802:     if ($removeform) {
 1803: 	$companswer=~s|<form(.*?)>||g;
 1804: 	$companswer=~s|</form>||g;
 1805: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1806:     }
 1807:     $rendered=
 1808: 	'<div class="LC_grade_show_problem_header">'.
 1809: 	&mt('View of the problem').
 1810: 	'</div><div class="LC_grade_show_problem_problem">'.
 1811: 	$rendered.
 1812: 	'</div>';
 1813:     $companswer=
 1814: 	'<div class="LC_grade_show_problem_header">'.
 1815: 	&mt('Correct answer').
 1816: 	'</div><div class="LC_grade_show_problem_problem">'.
 1817: 	$companswer.
 1818: 	'</div>';
 1819:     my $result;
 1820:     if ($mode eq 'both') {
 1821: 	$result=$rendered.$companswer;
 1822:     } elsif ($mode eq 'text') {
 1823: 	$result=$rendered;
 1824:     } elsif ($mode eq 'answer') {
 1825: 	$result=$companswer;
 1826:     }
 1827:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1828:     return $result;
 1829: }
 1830: 
 1831: sub files_exist {
 1832:     my ($r, $symb) = @_;
 1833:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1834: 
 1835:     foreach my $student (@students) {
 1836:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1837:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1838: 					      $udom,$uname);
 1839:         my ($string,$timestamp)= &get_last_submission(\%record);
 1840:         foreach my $submission (@$string) {
 1841:             my ($partid,$respid) =
 1842: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1843:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1844: 					   \%record);
 1845:             return 1 if (@$files);
 1846:         }
 1847:     }
 1848:     return 0;
 1849: }
 1850: 
 1851: sub download_all_link {
 1852:     my ($r,$symb) = @_;
 1853:     my $all_students = 
 1854: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1855: 
 1856:     my $parts =
 1857: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1858: 
 1859:     my $identifier = &Apache::loncommon::get_cgi_id();
 1860:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1861:                              'cgi.'.$identifier.'.symb' => $symb,
 1862:                              'cgi.'.$identifier.'.parts' => $parts,});
 1863:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1864: 	      &mt('Download All Submitted Documents').'</a>');
 1865:     return
 1866: }
 1867: 
 1868: sub build_section_inputs {
 1869:     my $section_inputs;
 1870:     if ($env{'form.section'} eq '') {
 1871:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1872:     } else {
 1873:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1874:         foreach my $section (@sections) {
 1875:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1876:         }
 1877:     }
 1878:     return $section_inputs;
 1879: }
 1880: 
 1881: # --------------------------- show submissions of a student, option to grade 
 1882: sub submission {
 1883:     my ($request,$counter,$total) = @_;
 1884:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1885:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1886:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1887:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1888:     my $symb = &get_symb($request); 
 1889:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1890: 
 1891:     if (!&canview($usec)) {
 1892: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1893: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1894: 			$env{'request.course.id'}.')</span>');
 1895: 	$request->print(&show_grading_menu_form($symb));
 1896: 	return;
 1897:     }
 1898: 
 1899:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1900:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1901:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1902:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1903:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1904: 	'" src="'.$request->dir_config('lonIconsURL').
 1905: 	'/check.gif" height="16" border="0" />';
 1906: 
 1907:     my %old_essays;
 1908:     # header info
 1909:     if ($counter == 0) {
 1910: 	&sub_page_js($request);
 1911: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1912: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1913: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1914: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1915: 	    &download_all_link($request, $symb);
 1916: 	}
 1917: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1918: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1919: 
 1920: 	# option to display problem, only once else it cause problems 
 1921:         # with the form later since the problem has a form.
 1922: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1923: 	    my $mode;
 1924: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1925: 		$mode='both';
 1926: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1927: 		$mode='text';
 1928: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1929: 		$mode='answer';
 1930: 	    }
 1931: 	    &Apache::lonxml::clear_problem_counter();
 1932: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1933: 	}
 1934: 
 1935: 	# kwclr is the only variable that is guaranteed to be non blank 
 1936:         # if this subroutine has been called once.
 1937: 	my %keyhash = ();
 1938: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1939: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1940: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1941: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1942: 
 1943: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1944: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1945: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1946: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1947: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1948: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1949: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1950: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1951: 	}
 1952: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1953: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1954: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1955: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1956: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1957: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1958: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1959: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1960: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1961: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1962: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1963: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1964: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1965: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1966: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1967: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1968: 			&build_section_inputs().
 1969: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1970: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1971: 			'<input type="hidden" name="NCT"'.
 1972: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1973: 	if ($env{'form.handgrade'} eq 'yes') {
 1974: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1975: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1976: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1977: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1978: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1979: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1980: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1981: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1982: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1983: 	    }
 1984: 	}
 1985: 	
 1986: 	my ($cts,$prnmsg) = (1,'');
 1987: 	while ($cts <= $env{'form.savemsgN'}) {
 1988: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1989: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1990: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1991: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1992: 		'" />'."\n".
 1993: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1994: 	    $cts++;
 1995: 	}
 1996: 	$request->print($prnmsg);
 1997: 
 1998: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1999: #
 2000: # Print out the keyword options line
 2001: #
 2002: 	    $request->print(<<KEYWORDS);
 2003: &nbsp;<b>Keyword Options:</b>&nbsp;
 2004: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2005: <a href="#" onMouseDown="javascript:getSel(); return false"
 2006:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2007: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2008: KEYWORDS
 2009: #
 2010: # Load the other essays for similarity check
 2011: #
 2012:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2013: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2014: 	    $apath=&escape($apath);
 2015: 	    $apath=~s/\W/\_/gs;
 2016: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2017:         }
 2018:     }
 2019: 
 2020: # This is where output for one specific student would start
 2021:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2022:     $request->print("\n\n".
 2023:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2024: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2025: 		    '<div class="LC_grade_show_user_body">'."\n");
 2026: 
 2027:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2028: 	my $mode;
 2029: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2030: 	    $mode='both';
 2031: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2032: 	    $mode='text';
 2033: 	} elsif ($env{'form.vAns'} eq 'all') {
 2034: 	    $mode='answer';
 2035: 	}
 2036: 	&Apache::lonxml::clear_problem_counter();
 2037: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2038:     }
 2039: 
 2040:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2041:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2042: 
 2043:     # Display student info
 2044:     $request->print(($counter == 0 ? '' : '<br />'));
 2045:     my $result='<div class="LC_grade_submissions">';
 2046:     
 2047:     $result.='<div class="LC_grade_submissions_header">';
 2048:     $result.= &mt('Submissions');
 2049:     $result.='<input type="hidden" name="name'.$counter.
 2050: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2051:     if ($env{'form.handgrade'} eq 'no') {
 2052: 	$result.='<span class="LC_grade_check_note">'.
 2053: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2054: 
 2055:     }
 2056: 
 2057: 
 2058: 
 2059:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2060:     my $fullname;
 2061:     my $col_fullnames = [];
 2062:     if ($env{'form.handgrade'} eq 'yes') {
 2063: 	(my $sub_result,$fullname,$col_fullnames)=
 2064: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2065: 				 $counter);
 2066: 	$result.=$sub_result;
 2067:     }
 2068:     $request->print($result."\n");
 2069:     $request->print('</div>'."\n");
 2070:     # print student answer/submission
 2071:     # Options are (1) Handgaded submission only
 2072:     #             (2) Last submission, includes submission that is not handgraded 
 2073:     #                  (for multi-response type part)
 2074:     #             (3) Last submission plus the parts info
 2075:     #             (4) The whole record for this student
 2076:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2077: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2078: 	
 2079: 	my $lastsubonly;
 2080: 
 2081: 	if ($$timestamp eq '') {
 2082: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2083: 	} else {
 2084: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2085: 
 2086: 	    my %seenparts;
 2087: 	    my @part_response_id = &flatten_responseType($responseType);
 2088: 	    foreach my $part (@part_response_id) {
 2089: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2090: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2091: 
 2092: 		my ($partid,$respid) = @{ $part };
 2093: 		my $display_part=&get_display_part($partid,$symb);
 2094: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2095: 		    if (exists($seenparts{$partid})) { next; }
 2096: 		    $seenparts{$partid}=1;
 2097: 		    my $submitby='<b>Part:</b> '.$display_part.
 2098: 			' <b>Collaborative submission by:</b> '.
 2099: 			'<a href="javascript:viewSubmitter(\''.
 2100: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2101: 			'\');" target="_self">'.
 2102: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2103: 		    $request->print($submitby);
 2104: 		    next;
 2105: 		}
 2106: 		my $responsetype = $responseType->{$partid}->{$respid};
 2107: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2108: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2109: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2110: 			' )</span>&nbsp; &nbsp;'.
 2111: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2112: 		    next;
 2113: 		}
 2114: 		foreach my $submission (@$string) {
 2115: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2116: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2117: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2118: 		    # Similarity check
 2119: 		    my $similar='';
 2120: 		    if($env{'form.checkPlag'}){
 2121: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2122: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2123: 			if ($osim) {
 2124: 			    $osim=int($osim*100.0);
 2125: 			    my %old_course_desc = 
 2126: 				&Apache::lonnet::coursedescription($ocrsid,
 2127: 								   {'one_time' => 1});
 2128: 
 2129: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2130: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2131: 				    $osim,
 2132: 				    &Apache::loncommon::plainname($oname,$odom),
 2133: 				    $oname,$odom,
 2134: 				    $old_course_desc{'description'},
 2135: 				    $old_course_desc{'num'},
 2136: 				    $old_course_desc{'domain'}).
 2137: 				'</span></h3><blockquote><i>'.
 2138: 				&keywords_highlight($oessay).
 2139: 				'</i></blockquote><hr />';
 2140: 			}
 2141: 		    }
 2142: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2143: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2144: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2145: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2146: 			my $display_part=&get_display_part($partid,$symb);
 2147: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2148: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2149: 			    ' )</span>&nbsp; &nbsp;';
 2150: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2151: 			if (@$files) {
 2152: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2153: 			    my $file_counter = 0;
 2154: 			    foreach my $file (@$files) {
 2155: 			        $file_counter++;
 2156: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2157: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2158: 			    }
 2159: 			    $lastsubonly.='<br />';
 2160: 			}
 2161: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2162: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2163: 					 $respid,\%record,$order,undef,$uname,$udom);
 2164: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2165: 			$lastsubonly.='</div>';
 2166: 		    }
 2167: 		}
 2168: 	    }
 2169: 	    $lastsubonly.='</div>'."\n";
 2170: 	}
 2171: 	$request->print($lastsubonly);
 2172:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2173: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2174: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2175:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2176: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2177: 								 $env{'request.course.id'},
 2178: 								 $last,'.submission',
 2179: 								 'Apache::grades::keywords_highlight'));
 2180:     }
 2181: 
 2182:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2183: 	.$udom.'" />'."\n");
 2184:     # return if view submission with no grading option
 2185:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2186: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2187: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2188: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2189: 	$toGrade.='</div>'."\n";
 2190: 	if (($env{'form.command'} eq 'submission') || 
 2191: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2192: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2193: 	}
 2194: 	$request->print($toGrade);
 2195: 	return;
 2196:     } else {
 2197: 	$request->print('</div>'."\n");
 2198:     }
 2199: 
 2200:     # essay grading message center
 2201:     if ($env{'form.handgrade'} eq 'yes') {
 2202: 	my $result='<div class="LC_grade_message_center">';
 2203:     
 2204: 	$result.='<div class="LC_grade_message_center_header">'.
 2205: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2206: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2207: 	my $msgfor = $givenn.' '.$lastname;
 2208: 	if (scalar(@$col_fullnames) > 0) {
 2209: 	    my $lastone = pop(@$col_fullnames);
 2210: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2211: 	}
 2212: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2213: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2214: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2215: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2216: 	    ',\''.$msgfor.'\');" target="_self">'.
 2217: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2218: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2219: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2220: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2221: 	    '<br />&nbsp;('.
 2222: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2223: 	$result.='</div></div>';
 2224: 	$request->print($result);
 2225:     }
 2226: 
 2227:     my %seen = ();
 2228:     my @partlist;
 2229:     my @gradePartRespid;
 2230:     my @part_response_id = &flatten_responseType($responseType);
 2231:     $request->print('<div class="LC_grade_assign">'.
 2232: 		    
 2233: 		    '<div class="LC_grade_assign_header">'.
 2234: 		    &mt('Assign Grades').'</div>'.
 2235: 		    '<div class="LC_grade_assign_body">');
 2236:     foreach my $part_response_id (@part_response_id) {
 2237:     	my ($partid,$respid) = @{ $part_response_id };
 2238: 	my $part_resp = join('_',@{ $part_response_id });
 2239: 	next if ($seen{$partid} > 0);
 2240: 	$seen{$partid}++;
 2241: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2242: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2243: 	push(@partlist,$partid);
 2244: 	push(@gradePartRespid,$partid.'.'.$respid);
 2245: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2246:     }
 2247:     $request->print('</div></div>');
 2248: 
 2249:     $request->print('<div class="LC_grade_info_links">');
 2250:     if ($perm{'vgr'}) {
 2251: 	$request->print(
 2252: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2253: 						   $uname,$udom,'check'));
 2254:     }
 2255:     if ($perm{'opa'}) {
 2256: 	$request->print(
 2257: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2258: 					 $uname,$udom,$symb,'check'));
 2259:     }
 2260:     $request->print('</div>');
 2261: 
 2262:     $result='<input type="hidden" name="partlist'.$counter.
 2263: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2264:     $result.='<input type="hidden" name="gradePartRespid'.
 2265: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2266:     my $ctr = 0;
 2267:     while ($ctr < scalar(@partlist)) {
 2268: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2269: 	    $partlist[$ctr].'" />'."\n";
 2270: 	$ctr++;
 2271:     }
 2272:     $request->print($result.''."\n");
 2273: 
 2274: # Done with printing info for one student
 2275: 
 2276:     $request->print('</div>');#LC_grade_show_user_body
 2277:     $request->print('</div>');#LC_grade_show_user
 2278: 
 2279: 
 2280:     # print end of form
 2281:     if ($counter == $total) {
 2282: 	my $endform='<table border="0"><tr><td>'."\n";
 2283: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2284: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2285: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2286: 	my $ntstu ='<select name="NTSTU">'.
 2287: 	    '<option>1</option><option>2</option>'.
 2288: 	    '<option>3</option><option>5</option>'.
 2289: 	    '<option>7</option><option>10</option></select>'."\n";
 2290: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2291: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2292: 	$endform.=&mt('[quant,_1,student]',$ntstu);
 2293: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2294: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2295: 	    '<input type="button" value="'.&mt('Next').'" '.
 2296: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2297: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2298:         $endform.="<input type='hidden' value='".&get_increment().
 2299:             "' name='increment' />";
 2300: 	$endform.='</td></tr></table></form>';
 2301: 	$endform.=&show_grading_menu_form($symb);
 2302: 	$request->print($endform);
 2303:     }
 2304:     return '';
 2305: }
 2306: 
 2307: sub check_collaborators {
 2308:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2309:     my ($result,@col_fullnames);
 2310:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2311:     foreach my $part (keys(%$handgrade)) {
 2312: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2313: 					'.maxcollaborators',
 2314: 					$symb,$udom,$uname);
 2315: 	next if ($ncol <= 0);
 2316: 	$part =~ s/\_/\./g;
 2317: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2318: 	my (@good_collaborators, @bad_collaborators);
 2319: 	foreach my $possible_collaborator
 2320: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2321: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2322: 	    next if ($possible_collaborator eq '');
 2323: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2324: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2325: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2326: 	    # Doing this grep allows 'fuzzy' specification
 2327: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2328: 			       keys(%$classlist));
 2329: 	    if (! scalar(@matches)) {
 2330: 		push(@bad_collaborators, $possible_collaborator);
 2331: 	    } else {
 2332: 		push(@good_collaborators, @matches);
 2333: 	    }
 2334: 	}
 2335: 	if (scalar(@good_collaborators) != 0) {
 2336: 	    $result.='<br />'.&mt('Collaborators: ');
 2337: 	    foreach my $name (@good_collaborators) {
 2338: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2339: 		push(@col_fullnames, $givenn.' '.$lastname);
 2340: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2341: 	    }
 2342: 	    $result.='<br />'."\n";
 2343: 	    my ($part)=split(/\./,$part);
 2344: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2345: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2346: 		"\n";
 2347: 	}
 2348: 	if (scalar(@bad_collaborators) > 0) {
 2349: 	    $result.='<div class="LC_warning">';
 2350: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2351: 	    $result .= '</div>';
 2352: 	}         
 2353: 	if (scalar(@bad_collaborators > $ncol)) {
 2354: 	    $result .= '<div class="LC_warning">';
 2355: 	    $result .= &mt('This student has submitted too many '.
 2356: 		'collaborators.  Maximum is [_1].',$ncol);
 2357: 	    $result .= '</div>';
 2358: 	}
 2359:     }
 2360:     return ($result,$fullname,\@col_fullnames);
 2361: }
 2362: 
 2363: #--- Retrieve the last submission for all the parts
 2364: sub get_last_submission {
 2365:     my ($returnhash)=@_;
 2366:     my (@string,$timestamp);
 2367:     if ($$returnhash{'version'}) {
 2368: 	my %lasthash=();
 2369: 	my ($version);
 2370: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2371: 	    foreach my $key (sort(split(/\:/,
 2372: 					$$returnhash{$version.':keys'}))) {
 2373: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2374: 		$timestamp = 
 2375: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2376: 	    }
 2377: 	}
 2378: 	foreach my $key (keys(%lasthash)) {
 2379: 	    next if ($key !~ /\.submission$/);
 2380: 
 2381: 	    my ($partid,$foo) = split(/submission$/,$key);
 2382: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2383: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2384: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2385: 	}
 2386:     }
 2387:     if (!@string) {
 2388: 	$string[0] =
 2389: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2390:     }
 2391:     return (\@string,\$timestamp);
 2392: }
 2393: 
 2394: #--- High light keywords, with style choosen by user.
 2395: sub keywords_highlight {
 2396:     my $string    = shift;
 2397:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2398:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2399:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2400:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2401:     foreach my $keyword (@keylist) {
 2402: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2403:     }
 2404:     return $string;
 2405: }
 2406: 
 2407: #--- Called from submission routine
 2408: sub processHandGrade {
 2409:     my ($request) = shift;
 2410:     my $symb   = &get_symb($request);
 2411:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2412:     my $button = $env{'form.gradeOpt'};
 2413:     my $ngrade = $env{'form.NCT'};
 2414:     my $ntstu  = $env{'form.NTSTU'};
 2415:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2416:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2417: 
 2418:     if ($button eq 'Save & Next') {
 2419: 	my $ctr = 0;
 2420: 	while ($ctr < $ngrade) {
 2421: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2422: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2423: 	    if ($errorflag eq 'no_score') {
 2424: 		$ctr++;
 2425: 		next;
 2426: 	    }
 2427: 	    if ($errorflag eq 'not_allowed') {
 2428: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2429: 		$ctr++;
 2430: 		next;
 2431: 	    }
 2432: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2433: 	    my ($subject,$message,$msgstatus) = ('','','');
 2434: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2435:             my ($feedurl,$showsymb) =
 2436: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2437: 	    my $messagetail;
 2438: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2439: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2440: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2441: 		$subject.=' ['.$restitle.']';
 2442: 		my (@msgnum) = split(/,/,$includemsg);
 2443: 		foreach (@msgnum) {
 2444: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2445: 		}
 2446: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2447: 		if ($env{'form.withgrades'.$ctr}) {
 2448: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2449: 		    $messagetail = " for <a href=\"".
 2450: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2451: 		}
 2452: 		$msgstatus = 
 2453:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2454: 						     $message.$messagetail,
 2455:                                                      undef,$feedurl,undef,
 2456:                                                      undef,undef,$showsymb,
 2457:                                                      $restitle);
 2458: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2459: 				$msgstatus);
 2460: 	    }
 2461: 	    if ($env{'form.collaborator'.$ctr}) {
 2462: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2463: 		foreach my $collabstr (@collabstrs) {
 2464: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2465: 		    foreach my $collaborator (@collaborators) {
 2466: 			my ($errorflag,$pts,$wgt) = 
 2467: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2468: 					   $env{'form.unamedom'.$ctr},$part);
 2469: 			if ($errorflag eq 'not_allowed') {
 2470: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2471: 			    next;
 2472: 			} elsif ($message ne '') {
 2473: 			    my ($baseurl,$showsymb) = 
 2474: 				&get_feedurl_and_symb($symb,$collaborator,
 2475: 						      $udom);
 2476: 			    if ($env{'form.withgrades'.$ctr}) {
 2477: 				$messagetail = " for <a href=\"".
 2478:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2479: 			    }
 2480: 			    $msgstatus = 
 2481: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2482: 			}
 2483: 		    }
 2484: 		}
 2485: 	    }
 2486: 	    $ctr++;
 2487: 	}
 2488:     }
 2489: 
 2490:     if ($env{'form.handgrade'} eq 'yes') {
 2491: 	# Keywords sorted in alphabatical order
 2492: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2493: 	my %keyhash = ();
 2494: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2495: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2496: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2497: 	$env{'form.keywords'} = join(' ',@keywords);
 2498: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2499: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2500: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2501: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2502: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2503: 
 2504: 	# message center - Order of message gets changed. Blank line is eliminated.
 2505: 	# New messages are saved in env for the next student.
 2506: 	# All messages are saved in nohist_handgrade.db
 2507: 	my ($ctr,$idx) = (1,1);
 2508: 	while ($ctr <= $env{'form.savemsgN'}) {
 2509: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2510: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2511: 		$idx++;
 2512: 	    }
 2513: 	    $ctr++;
 2514: 	}
 2515: 	$ctr = 0;
 2516: 	while ($ctr < $ngrade) {
 2517: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2518: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2519: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2520: 		$idx++;
 2521: 	    }
 2522: 	    $ctr++;
 2523: 	}
 2524: 	$env{'form.savemsgN'} = --$idx;
 2525: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2526: 	my $putresult = &Apache::lonnet::put
 2527: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2528:     }
 2529:     # Called by Save & Refresh from Highlight Attribute Window
 2530:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2531:     if ($env{'form.refresh'} eq 'on') {
 2532: 	my ($ctr,$total) = (0,0);
 2533: 	while ($ctr < $ngrade) {
 2534: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2535: 	    $ctr++;
 2536: 	}
 2537: 	$env{'form.NTSTU'}=$ngrade;
 2538: 	$ctr = 0;
 2539: 	while ($ctr < $total) {
 2540: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2541: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2542: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2543: 	    &submission($request,$ctr,$total-1);
 2544: 	    $ctr++;
 2545: 	}
 2546: 	return '';
 2547:     }
 2548: 
 2549: # Go directly to grade student - from submission or link from chart page
 2550:     if ($button eq 'Grade Student') {
 2551: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2552: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2553: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2554: 	$env{'form.fullname'} = $$fullname{$processUser};
 2555: 	&submission($request,0,0);
 2556: 	return '';
 2557:     }
 2558: 
 2559:     # Get the next/previous one or group of students
 2560:     my $firststu = $env{'form.unamedom0'};
 2561:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2562:     my $ctr = 2;
 2563:     while ($laststu eq '') {
 2564: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2565: 	$ctr++;
 2566: 	$laststu = $firststu if ($ctr > $ngrade);
 2567:     }
 2568: 
 2569:     my (@parsedlist,@nextlist);
 2570:     my ($nextflg) = 0;
 2571:     foreach my $item (sort 
 2572: 	     {
 2573: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2574: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2575: 		 }
 2576: 		 return $a cmp $b;
 2577: 	     } (keys(%$fullname))) {
 2578: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2579: 	    push(@parsedlist,$item);
 2580: 	}
 2581: 	$nextflg = 1 if ($item eq $laststu);
 2582: 	if ($button eq 'Previous') {
 2583: 	    last if ($item eq $firststu);
 2584: 	    push(@parsedlist,$item);
 2585: 	}
 2586:     }
 2587:     $ctr = 0;
 2588:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2589:     my ($partlist) = &response_type($symb);
 2590:     foreach my $student (@parsedlist) {
 2591: 	my $submitonly=$env{'form.submitonly'};
 2592: 	my ($uname,$udom) = split(/:/,$student);
 2593: 	
 2594: 	if ($submitonly eq 'queued') {
 2595: 	    my %queue_status = 
 2596: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2597: 							$udom,$uname);
 2598: 	    next if (!defined($queue_status{'gradingqueue'}));
 2599: 	}
 2600: 
 2601: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2602: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2603: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2604: 	    my $submitted = 0;
 2605: 	    my $ungraded = 0;
 2606: 	    my $incorrect = 0;
 2607: 	    foreach my $item (keys(%status)) {
 2608: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2609: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2610: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2611: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2612: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2613: 		    $submitted = 0;
 2614: 		}
 2615: 	    }
 2616: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2617: 				     $submitonly eq 'incorrect' ||
 2618: 				     $submitonly eq 'graded'));
 2619: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2620: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2621: 	}
 2622: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2623: 	last if ($ctr == $ntstu);
 2624: 	$ctr++;
 2625:     }
 2626: 
 2627:     $ctr = 0;
 2628:     my $total = scalar(@nextlist)-1;
 2629: 
 2630:     foreach (sort(@nextlist)) {
 2631: 	my ($uname,$udom,$submitter) = split(/:/);
 2632: 	$env{'form.student'}  = $uname;
 2633: 	$env{'form.userdom'}  = $udom;
 2634: 	$env{'form.fullname'} = $$fullname{$_};
 2635: 	&submission($request,$ctr,$total);
 2636: 	$ctr++;
 2637:     }
 2638:     if ($total < 0) {
 2639: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2640: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2641: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2642: 	$the_end.=&show_grading_menu_form($symb);
 2643: 	$request->print($the_end);
 2644:     }
 2645:     return '';
 2646: }
 2647: 
 2648: #---- Save the score and award for each student, if changed
 2649: sub saveHandGrade {
 2650:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2651:     my @version_parts;
 2652:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2653: 					   $env{'request.course.id'});
 2654:     if (!&canmodify($usec)) { return('not_allowed'); }
 2655:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2656:     my @parts_graded;
 2657:     my %newrecord  = ();
 2658:     my ($pts,$wgt) = ('','');
 2659:     my %aggregate = ();
 2660:     my $aggregateflag = 0;
 2661:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2662:     foreach my $new_part (@parts) {
 2663: 	#collaborator ($submi may vary for different parts
 2664: 	if ($submitter && $new_part ne $part) { next; }
 2665: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2666: 	if ($dropMenu eq 'excused') {
 2667: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2668: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2669: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2670: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2671: 		}
 2672: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2673: 	    }
 2674: 	} elsif ($dropMenu eq 'reset status'
 2675: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2676: 	    foreach my $key (keys(%record)) {
 2677: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2678: 	    }
 2679: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2680: 		"$env{'user.name'}:$env{'user.domain'}";
 2681:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2682: 
 2683:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2684: 					       [$new_part]);
 2685:             my $aggtries =$totaltries;
 2686:             if ($last_resets{$new_part}) {
 2687:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2688: 					   $new_part);
 2689:             }
 2690: 
 2691:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2692:             if ($aggtries > 0) {
 2693:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2694:                 $aggregateflag = 1;
 2695:             }
 2696: 	} elsif ($dropMenu eq '') {
 2697: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2698: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2699: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2700: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2701: 		next;
 2702: 	    }
 2703: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2704: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2705: 	    my $partial= $pts/$wgt;
 2706: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2707: 		#do not update score for part if not changed.
 2708:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2709: 		next;
 2710: 	    } else {
 2711: 	        push(@parts_graded,$new_part);
 2712: 	    }
 2713: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2714: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2715: 	    }
 2716: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2717: 	    if ($partial == 0) {
 2718: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2719: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2720: 		}
 2721: 	    } else {
 2722: 		if ($record{$reckey} ne 'correct_by_override') {
 2723: 		    $newrecord{$reckey} = 'correct_by_override';
 2724: 		}
 2725: 	    }	    
 2726: 	    if ($submitter && 
 2727: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2728: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2729: 	    }
 2730: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2731: 		"$env{'user.name'}:$env{'user.domain'}";
 2732: 	}
 2733: 	# unless problem has been graded, set flag to version the submitted files
 2734: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2735: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2736: 	        $dropMenu eq 'reset status')
 2737: 	   {
 2738: 	    push(@version_parts,$new_part);
 2739: 	}
 2740:     }
 2741:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2742:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2743: 
 2744:     if (%newrecord) {
 2745:         if (@version_parts) {
 2746:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2747:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2748: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2749: 	    foreach my $new_part (@version_parts) {
 2750: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2751: 				$new_part,\%newrecord);
 2752: 	    }
 2753:         }
 2754: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2755: 				$env{'request.course.id'},$domain,$stuname);
 2756: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2757: 				     $cdom,$cnum,$domain,$stuname);
 2758:     }
 2759:     if ($aggregateflag) {
 2760:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2761: 			      $cdom,$cnum);
 2762:     }
 2763:     return ('',$pts,$wgt);
 2764: }
 2765: 
 2766: sub check_and_remove_from_queue {
 2767:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2768:     my @ungraded_parts;
 2769:     foreach my $part (@{$parts}) {
 2770: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2771: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2772: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2773: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2774: 		) {
 2775: 	    push(@ungraded_parts, $part);
 2776: 	}
 2777:     }
 2778:     if ( !@ungraded_parts ) {
 2779: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2780: 					       $cnum,$domain,$stuname);
 2781:     }
 2782: }
 2783: 
 2784: sub handback_files {
 2785:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2786:     my $portfolio_root = '/userfiles/portfolio';
 2787:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2788: 
 2789:     my @part_response_id = &flatten_responseType($responseType);
 2790:     foreach my $part_response_id (@part_response_id) {
 2791:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2792: 	my $part_resp = join('_',@{ $part_response_id });
 2793:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2794:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2795:                 my $file_counter = 1;
 2796: 		my $file_msg;
 2797:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2798:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2799:                     my ($directory,$answer_file) = 
 2800:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2801:                     my ($answer_name,$answer_ver,$answer_ext) =
 2802: 		        &file_name_version_ext($answer_file);
 2803: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2804:                     my $getpropath = 1;
 2805: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2806: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2807:                     # fix file name
 2808:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2809:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2810:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2811:             	                                $save_file_name);
 2812:                     if ($result !~ m|^/uploaded/|) {
 2813:                         $request->print('<br /><span class="LC_error">'.
 2814:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2815:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2816:                                         '</span>');
 2817:                     } else {
 2818:                         # mark the file as read only
 2819:                         my @files = ($save_file_name);
 2820:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2821:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2822: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2823: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2824: 			}
 2825:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2826: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2827: 
 2828:                     }
 2829:                     $request->print("<br />".$fname." will be the uploaded file name");
 2830:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2831:                     $file_counter++;
 2832:                 }
 2833: 		my $subject = "File Handed Back by Instructor ";
 2834: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2835: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2836: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2837: 		$message .= " and can be found in your portfolio space.";
 2838: 		my ($feedurl,$showsymb) = 
 2839: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2840:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2841: 		my $msgstatus = 
 2842:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2843: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2844:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2845:             }
 2846:         }
 2847:     return;
 2848: }
 2849: 
 2850: sub get_feedurl_and_symb {
 2851:     my ($symb,$uname,$udom) = @_;
 2852:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2853:     $url = &Apache::lonnet::clutter($url);
 2854:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2855: 					$symb,$udom,$uname);
 2856:     if ($encrypturl =~ /^yes$/i) {
 2857: 	&Apache::lonenc::encrypted(\$url,1);
 2858: 	&Apache::lonenc::encrypted(\$symb,1);
 2859:     }
 2860:     return ($url,$symb);
 2861: }
 2862: 
 2863: sub get_submitted_files {
 2864:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2865:     my @files;
 2866:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2867:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2868:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2869:     	    push(@files,$file_url.$file);
 2870:         }
 2871:     }
 2872:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2873:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2874:     }
 2875:     return (\@files);
 2876: }
 2877: 
 2878: # ----------- Provides number of tries since last reset.
 2879: sub get_num_tries {
 2880:     my ($record,$last_reset,$part) = @_;
 2881:     my $timestamp = '';
 2882:     my $num_tries = 0;
 2883:     if ($$record{'version'}) {
 2884:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2885:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2886:                 $timestamp = $$record{$version.':timestamp'};
 2887:                 if ($timestamp > $last_reset) {
 2888:                     $num_tries ++;
 2889:                 } else {
 2890:                     last;
 2891:                 }
 2892:             }
 2893:         }
 2894:     }
 2895:     return $num_tries;
 2896: }
 2897: 
 2898: # ----------- Determine decrements required in aggregate totals 
 2899: sub decrement_aggs {
 2900:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2901:     my %decrement = (
 2902:                         attempts => 0,
 2903:                         users => 0,
 2904:                         correct => 0
 2905:                     );
 2906:     $decrement{'attempts'} = $aggtries;
 2907:     if ($solvedstatus =~ /^correct/) {
 2908:         $decrement{'correct'} = 1;
 2909:     }
 2910:     if ($aggtries == $totaltries) {
 2911:         $decrement{'users'} = 1;
 2912:     }
 2913:     foreach my $type (keys(%decrement)) {
 2914:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2915:     }
 2916:     return;
 2917: }
 2918: 
 2919: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2920: sub get_last_resets {
 2921:     my ($symb,$courseid,$partids) =@_;
 2922:     my %last_resets;
 2923:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2924:     my $cname = $env{'course.'.$courseid.'.num'};
 2925:     my @keys;
 2926:     foreach my $part (@{$partids}) {
 2927: 	push(@keys,"$symb\0$part\0resettime");
 2928:     }
 2929:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2930: 				     $cdom,$cname);
 2931:     foreach my $part (@{$partids}) {
 2932: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2933:     }
 2934:     return %last_resets;
 2935: }
 2936: 
 2937: # ----------- Handles creating versions for portfolio files as answers
 2938: sub version_portfiles {
 2939:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2940:     my $version_parts = join('|',@$v_flag);
 2941:     my @returned_keys;
 2942:     my $parts = join('|', @$parts_graded);
 2943:     my $portfolio_root = '/userfiles/portfolio';
 2944:     foreach my $key (keys(%$record)) {
 2945:         my $new_portfiles;
 2946:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2947:             my @versioned_portfiles;
 2948:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2949:             foreach my $file (@portfiles) {
 2950:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2951:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2952: 		my ($answer_name,$answer_ver,$answer_ext) =
 2953: 		    &file_name_version_ext($answer_file);
 2954:                 my $getpropath = 1;    
 2955:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2956:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2957:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2958:                 if ($new_answer ne 'problem getting file') {
 2959:                     push(@versioned_portfiles, $directory.$new_answer);
 2960:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2961:                         [$directory.$new_answer],
 2962:                         [$symb,$env{'request.course.id'},'graded']);
 2963:                 }
 2964:             }
 2965:             $$record{$key} = join(',',@versioned_portfiles);
 2966:             push(@returned_keys,$key);
 2967:         }
 2968:     } 
 2969:     return (@returned_keys);   
 2970: }
 2971: 
 2972: sub get_next_version {
 2973:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2974:     my $version;
 2975:     foreach my $row (@$dir_list) {
 2976:         my ($file) = split(/\&/,$row,2);
 2977:         my ($file_name,$file_version,$file_ext) =
 2978: 	    &file_name_version_ext($file);
 2979:         if (($file_name eq $answer_name) && 
 2980: 	    ($file_ext eq $answer_ext)) {
 2981:                 # gets here if filename and extension match, regardless of version
 2982:                 if ($file_version ne '') {
 2983:                 # a versioned file is found  so save it for later
 2984:                 if ($file_version > $version) {
 2985: 		    $version = $file_version;
 2986: 	        }
 2987:             }
 2988:         }
 2989:     } 
 2990:     $version ++;
 2991:     return($version);
 2992: }
 2993: 
 2994: sub version_selected_portfile {
 2995:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2996:     my ($answer_name,$answer_ver,$answer_ext) =
 2997:         &file_name_version_ext($file_name);
 2998:     my $new_answer;
 2999:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3000:     if($env{'form.copy'} eq '-1') {
 3001:         $new_answer = 'problem getting file';
 3002:     } else {
 3003:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3004:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3005:                             $stu_name,$domain,'copy',
 3006: 		        '/portfolio'.$directory.$new_answer);
 3007:     }    
 3008:     return ($new_answer);
 3009: }
 3010: 
 3011: sub file_name_version_ext {
 3012:     my ($file)=@_;
 3013:     my @file_parts = split(/\./, $file);
 3014:     my ($name,$version,$ext);
 3015:     if (@file_parts > 1) {
 3016: 	$ext=pop(@file_parts);
 3017: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3018: 	    $version=pop(@file_parts);
 3019: 	}
 3020: 	$name=join('.',@file_parts);
 3021:     } else {
 3022: 	$name=join('.',@file_parts);
 3023:     }
 3024:     return($name,$version,$ext);
 3025: }
 3026: 
 3027: #--------------------------------------------------------------------------------------
 3028: #
 3029: #-------------------------- Next few routines handles grading by section or whole class
 3030: #
 3031: #--- Javascript to handle grading by section or whole class
 3032: sub viewgrades_js {
 3033:     my ($request) = shift;
 3034: 
 3035:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3036:     $request->print(<<VIEWJAVASCRIPT);
 3037: <script type="text/javascript" language="javascript">
 3038:    function writePoint(partid,weight,point) {
 3039: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3040: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3041: 	if (point == "textval") {
 3042: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3043: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3044: 		alert("$alertmsg"+parseFloat(point));
 3045: 		var resetbox = false;
 3046: 		for (var i=0; i<radioButton.length; i++) {
 3047: 		    if (radioButton[i].checked) {
 3048: 			textbox.value = i;
 3049: 			resetbox = true;
 3050: 		    }
 3051: 		}
 3052: 		if (!resetbox) {
 3053: 		    textbox.value = "";
 3054: 		}
 3055: 		return;
 3056: 	    }
 3057: 	    if (parseFloat(point) > parseFloat(weight)) {
 3058: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3059: 				   ") greater than the weight for the part. Accept?");
 3060: 		if (resp == false) {
 3061: 		    textbox.value = "";
 3062: 		    return;
 3063: 		}
 3064: 	    }
 3065: 	    for (var i=0; i<radioButton.length; i++) {
 3066: 		radioButton[i].checked=false;
 3067: 		if (parseFloat(point) == i) {
 3068: 		    radioButton[i].checked=true;
 3069: 		}
 3070: 	    }
 3071: 
 3072: 	} else {
 3073: 	    textbox.value = parseFloat(point);
 3074: 	}
 3075: 	for (i=0;i<document.classgrade.total.value;i++) {
 3076: 	    var user = document.classgrade["ctr"+i].value;
 3077: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3078: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3079: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3080: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3081: 	    if (saveval != "correct") {
 3082: 		scorename.value = point;
 3083: 		if (selname[0].selected != true) {
 3084: 		    selname[0].selected = true;
 3085: 		}
 3086: 	    }
 3087: 	}
 3088: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3089:     }
 3090: 
 3091:     function writeRadText(partid,weight) {
 3092: 	var selval   = document.classgrade["SELVAL_"+partid];
 3093: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3094:         var override = document.classgrade["FORCE_"+partid].checked;
 3095: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3096: 	if (selval[1].selected || selval[2].selected) {
 3097: 	    for (var i=0; i<radioButton.length; i++) {
 3098: 		radioButton[i].checked=false;
 3099: 
 3100: 	    }
 3101: 	    textbox.value = "";
 3102: 
 3103: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3104: 		var user = document.classgrade["ctr"+i].value;
 3105: 		user = user.replace(new RegExp(':', 'g'),"_");
 3106: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3107: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3108: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3109: 		if ((saveval != "correct") || override) {
 3110: 		    scorename.value = "";
 3111: 		    if (selval[1].selected) {
 3112: 			selname[1].selected = true;
 3113: 		    } else {
 3114: 			selname[2].selected = true;
 3115: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3116: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3117: 		    }
 3118: 		}
 3119: 	    }
 3120: 	} else {
 3121: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3122: 		var user = document.classgrade["ctr"+i].value;
 3123: 		user = user.replace(new RegExp(':', 'g'),"_");
 3124: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3125: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3126: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3127: 		if ((saveval != "correct") || override) {
 3128: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3129: 		    selname[0].selected = true;
 3130: 		}
 3131: 	    }
 3132: 	}	    
 3133:     }
 3134: 
 3135:     function changeSelect(partid,user) {
 3136: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3137: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3138: 	var point  = textbox.value;
 3139: 	var weight = document.classgrade["weight_"+partid].value;
 3140: 
 3141: 	if (isNaN(point) || parseFloat(point) < 0) {
 3142: 	    alert("$alertmsg"+parseFloat(point));
 3143: 	    textbox.value = "";
 3144: 	    return;
 3145: 	}
 3146: 	if (parseFloat(point) > parseFloat(weight)) {
 3147: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3148: 			       ") greater than the weight of the part. Accept?");
 3149: 	    if (resp == false) {
 3150: 		textbox.value = "";
 3151: 		return;
 3152: 	    }
 3153: 	}
 3154: 	selval[0].selected = true;
 3155:     }
 3156: 
 3157:     function changeOneScore(partid,user) {
 3158: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3159: 	if (selval[1].selected || selval[2].selected) {
 3160: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3161: 	    if (selval[2].selected) {
 3162: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3163: 	    }
 3164:         }
 3165:     }
 3166: 
 3167:     function resetEntry(numpart) {
 3168: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3169: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3170: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3171: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3172: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3173: 	    for (var i=0; i<radioButton.length; i++) {
 3174: 		radioButton[i].checked=false;
 3175: 
 3176: 	    }
 3177: 	    textbox.value = "";
 3178: 	    selval[0].selected = true;
 3179: 
 3180: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3181: 		var user = document.classgrade["ctr"+i].value;
 3182: 		user = user.replace(new RegExp(':', 'g'),"_");
 3183: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3184: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3185: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3186: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3187: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3188: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3189: 		if (saveselval == "excused") {
 3190: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3191: 		} else {
 3192: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3193: 		}
 3194: 	    }
 3195: 	}
 3196:     }
 3197: 
 3198: </script>
 3199: VIEWJAVASCRIPT
 3200: }
 3201: 
 3202: #--- show scores for a section or whole class w/ option to change/update a score
 3203: sub viewgrades {
 3204:     my ($request) = shift;
 3205:     &viewgrades_js($request);
 3206: 
 3207:     my ($symb) = &get_symb($request);
 3208:     #need to make sure we have the correct data for later EXT calls, 
 3209:     #thus invalidate the cache
 3210:     &Apache::lonnet::devalidatecourseresdata(
 3211:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3212:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3213:     &Apache::lonnet::clear_EXT_cache_status();
 3214: 
 3215:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3216:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3217: 
 3218:     #view individual student submission form - called using Javascript viewOneStudent
 3219:     $result.=&jscriptNform($symb);
 3220: 
 3221:     #beginning of class grading form
 3222:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3223:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3224: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3225: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3226: 	&build_section_inputs().
 3227: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3228: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3229: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3230: 
 3231:     my $sectionClass;
 3232:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3233:     if ($env{'form.section'} eq 'all') {
 3234: 	$sectionClass=&mt('Class');
 3235:     } elsif ($env{'form.section'} eq 'none') {
 3236: 	$sectionClass=&mt('Students in no Section');
 3237:     } else {
 3238: 	$sectionClass=&mt('Students in Section(s) [_1]');
 3239:     }
 3240:     $result.=
 3241: 	'<h3>'.
 3242: 	&mt("Assign Common Grade to [_1]",$sectionClass,$section_display).'</h3>';
 3243:     $result.= &Apache::loncommon::start_data_table();
 3244:     #radio buttons/text box for assigning points for a section or class.
 3245:     #handles different parts of a problem
 3246:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3247:     my %weight = ();
 3248:     my $ctsparts = 0;
 3249:     my %seen = ();
 3250:     my @part_response_id = &flatten_responseType($responseType);
 3251:     foreach my $part_response_id (@part_response_id) {
 3252:     	my ($partid,$respid) = @{ $part_response_id };
 3253: 	my $part_resp = join('_',@{ $part_response_id });
 3254: 	next if $seen{$partid};
 3255: 	$seen{$partid}++;
 3256: 	my $handgrade=$$handgrade{$part_resp};
 3257: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3258: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3259: 
 3260: 	my $display_part=&get_display_part($partid,$symb);
 3261: 	my $radio.='<table border="0"><tr>';  
 3262: 	my $ctr = 0;
 3263: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3264: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3265: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3266: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3267: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3268: 	    $ctr++;
 3269: 	}
 3270: 	$radio.='</tr></table>';
 3271: 	my $line = '<input type="text" name="TEXTVAL_'.
 3272: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3273: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3274: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3275: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3276: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3277: 		$weight{$partid}.')"> '.
 3278: 	    '<option selected="selected"> </option>'.
 3279: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3280: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3281: 	    '</select></td>'.
 3282:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3283: 	$line.='<input type="hidden" name="partid_'.
 3284: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3285: 	$line.='<input type="hidden" name="weight_'.
 3286: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3287: 
 3288: 	$result.=
 3289: 	    &Apache::loncommon::start_data_table_row()."\n".
 3290: 	    '<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>'.
 3291: 	    &Apache::loncommon::end_data_table_row()."\n";
 3292: 	$ctsparts++;
 3293:     }
 3294:     $result.=&Apache::loncommon::end_data_table()."\n".
 3295: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3296:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3297: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3298: 
 3299:     #table listing all the students in a section/class
 3300:     #header of table
 3301:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in ').$sectionClass,
 3302: 			 $section_display.'</h3>';
 3303:     $result.= &Apache::loncommon::start_data_table().
 3304: 	&Apache::loncommon::start_data_table_header_row().
 3305: 	'<th>'.&mt('No.').'</th>'.
 3306: 	'<th>'.&nameUserString('header')."</th>\n";
 3307:     my (@parts) = sort(&getpartlist($symb));
 3308:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3309:     my @partids = ();
 3310:     foreach my $part (@parts) {
 3311: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3312:         my $narrowtext = &mt('Tries');
 3313: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3314: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3315: 	my ($partid) = &split_part_type($part);
 3316:         push(@partids,$partid);
 3317: 	my $display_part=&get_display_part($partid,$symb);
 3318: 	if ($display =~ /^Partial Credit Factor/) {
 3319: 	    $result.='<th>'.
 3320: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3321: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3322: 	    next;
 3323: 	    
 3324: 	} else {
 3325: 	    if ($display =~ /Problem Status/) {
 3326: 		my $grade_status_mt = &mt('Grade Status');
 3327: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3328: 	    }
 3329: 	    my $part_mt = &mt('Part:');
 3330: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3331: 	}
 3332: 
 3333: 	$result.='<th>'.$display.'</th>'."\n";
 3334:     }
 3335:     $result.=&Apache::loncommon::end_data_table_header_row();
 3336: 
 3337:     my %last_resets = 
 3338: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3339: 
 3340:     #get info for each student
 3341:     #list all the students - with points and grade status
 3342:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3343:     my $ctr = 0;
 3344:     foreach (sort 
 3345: 	     {
 3346: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3347: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3348: 		 }
 3349: 		 return $a cmp $b;
 3350: 	     } (keys(%$fullname))) {
 3351: 	$ctr++;
 3352: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3353: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3354:     }
 3355:     $result.=&Apache::loncommon::end_data_table();
 3356:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3357:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3358: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3359:     if (scalar(%$fullname) eq 0) {
 3360: 	my $colspan=3+scalar(@parts);
 3361: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3362:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3363: 	$result='<span class="LC_warning">'.
 3364: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3365: 	        $section_display, $stu_status).
 3366: 	    '</span>';
 3367:     }
 3368:     $result.=&show_grading_menu_form($symb);
 3369:     return $result;
 3370: }
 3371: 
 3372: #--- call by previous routine to display each student
 3373: sub viewstudentgrade {
 3374:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3375:     my ($uname,$udom) = split(/:/,$student);
 3376:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3377:     my %aggregates = (); 
 3378:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3379: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3380: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3381: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3382: 	'\');" target="_self">'.$fullname.'</a> '.
 3383: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3384:     $student=~s/:/_/; # colon doen't work in javascript for names
 3385:     foreach my $apart (@$parts) {
 3386: 	my ($part,$type) = &split_part_type($apart);
 3387: 	my $score=$record{"resource.$part.$type"};
 3388:         $result.='<td align="center">';
 3389:         my ($aggtries,$totaltries);
 3390:         unless (exists($aggregates{$part})) {
 3391: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3392: 
 3393: 	    $aggtries = $totaltries;
 3394:             if ($$last_resets{$part}) {  
 3395:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3396: 					   $part);
 3397:             }
 3398:             $result.='<input type="hidden" name="'.
 3399:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3400:             $result.='<input type="hidden" name="'.
 3401:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3402:             $aggregates{$part} = 1;
 3403:         }
 3404: 	if ($type eq 'awarded') {
 3405: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3406: 	    $result.='<input type="hidden" name="'.
 3407: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3408: 	    $result.='<input type="text" name="'.
 3409: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3410: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3411: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3412: 	} elsif ($type eq 'solved') {
 3413: 	    my ($status,$foo)=split(/_/,$score,2);
 3414: 	    $status = 'nothing' if ($status eq '');
 3415: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3416: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3417: 	    $result.='&nbsp;<select name="'.
 3418: 		'GD_'.$student.'_'.$part.'_solved" '.
 3419: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3420: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3421: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3422: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3423: 	    $result.="</select>&nbsp;</td>\n";
 3424: 	} else {
 3425: 	    $result.='<input type="hidden" name="'.
 3426: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3427: 		    "\n";
 3428: 	    $result.='<input type="text" name="'.
 3429: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3430: 		'value="'.$score.'" size="4" /></td>'."\n";
 3431: 	}
 3432:     }
 3433:     $result.=&Apache::loncommon::end_data_table_row();
 3434:     return $result;
 3435: }
 3436: 
 3437: #--- change scores for all the students in a section/class
 3438: #    record does not get update if unchanged
 3439: sub editgrades {
 3440:     my ($request) = @_;
 3441: 
 3442:     my $symb=&get_symb($request);
 3443:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3444:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3445:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3446:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3447: 
 3448:     my $result= &Apache::loncommon::start_data_table().
 3449: 	&Apache::loncommon::start_data_table_header_row().
 3450: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3451: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3452:     my %scoreptr = (
 3453: 		    'correct'  =>'correct_by_override',
 3454: 		    'incorrect'=>'incorrect_by_override',
 3455: 		    'excused'  =>'excused',
 3456: 		    'ungraded' =>'ungraded_attempted',
 3457: 		    'nothing'  => '',
 3458: 		    );
 3459:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3460: 
 3461:     my (@partid);
 3462:     my %weight = ();
 3463:     my %columns = ();
 3464:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3465: 
 3466:     my (@parts) = sort(&getpartlist($symb));
 3467:     my $header;
 3468:     while ($ctr < $env{'form.totalparts'}) {
 3469: 	my $partid = $env{'form.partid_'.$ctr};
 3470: 	push(@partid,$partid);
 3471: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3472: 	$ctr++;
 3473:     }
 3474:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3475:     foreach my $partid (@partid) {
 3476: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3477: 	    '<th align="center">'.&mt('New Score').'</th>';
 3478: 	$columns{$partid}=2;
 3479: 	foreach my $stores (@parts) {
 3480: 	    my ($part,$type) = &split_part_type($stores);
 3481: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3482: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3483: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3484: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3485:             my $narrowtext = &mt('Tries');
 3486: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3487: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3488: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3489: 	    $columns{$partid}+=2;
 3490: 	}
 3491:     }
 3492:     foreach my $partid (@partid) {
 3493: 	my $display_part=&get_display_part($partid,$symb);
 3494: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3495: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3496: 	    '</th>';
 3497: 
 3498:     }
 3499:     $result .= &Apache::loncommon::end_data_table_header_row().
 3500: 	&Apache::loncommon::start_data_table_header_row().
 3501: 	$header.
 3502: 	&Apache::loncommon::end_data_table_header_row();
 3503:     my @noupdate;
 3504:     my ($updateCtr,$noupdateCtr) = (1,1);
 3505:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3506: 	my $line;
 3507: 	my $user = $env{'form.ctr'.$i};
 3508: 	my ($uname,$udom)=split(/:/,$user);
 3509: 	my %newrecord;
 3510: 	my $updateflag = 0;
 3511: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3512: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3513: 	if (!&canmodify($usec)) {
 3514: 	    my $numcols=scalar(@partid)*4+2;
 3515: 	    push(@noupdate,
 3516: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3517: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3518: 	    next;
 3519: 	}
 3520:         my %aggregate = ();
 3521:         my $aggregateflag = 0;
 3522: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3523: 	foreach (@partid) {
 3524: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3525: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3526: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3527: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3528: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3529: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3530: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3531: 	    my $score;
 3532: 	    if ($partial eq '') {
 3533: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3534: 	    } elsif ($partial > 0) {
 3535: 		$score = 'correct_by_override';
 3536: 	    } elsif ($partial == 0) {
 3537: 		$score = 'incorrect_by_override';
 3538: 	    }
 3539: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3540: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3541: 
 3542: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3543: 		"$env{'user.name'}:$env{'user.domain'}";
 3544: 	    if ($dropMenu eq 'reset status' &&
 3545: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3546: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3547: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3548: 		$newrecord{'resource.'.$_.'.award'} = '';
 3549: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3550: 		$updateflag = 1;
 3551:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3552:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3553:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3554:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3555:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3556:                     $aggregateflag = 1;
 3557:                 }
 3558: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3559: 		$updateflag = 1;
 3560: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3561: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3562: 		$rec_update++;
 3563: 	    }
 3564: 
 3565: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3566: 		'<td align="center">'.$awarded.
 3567: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3568: 
 3569: 
 3570: 	    my $partid=$_;
 3571: 	    foreach my $stores (@parts) {
 3572: 		my ($part,$type) = &split_part_type($stores);
 3573: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3574: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3575: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3576: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3577: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3578: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3579: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3580: 		    $updateflag=1;
 3581: 		}
 3582: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3583: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3584: 	    }
 3585: 	}
 3586: 	$line.="\n";
 3587: 
 3588: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3589: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3590: 
 3591: 	if ($updateflag) {
 3592: 	    $count++;
 3593: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3594: 				    $udom,$uname);
 3595: 
 3596: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3597: 					      $cnum,$udom,$uname)) {
 3598: 		# need to figure out if should be in queue.
 3599: 		my %record =  
 3600: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3601: 					     $udom,$uname);
 3602: 		my $all_graded = 1;
 3603: 		my $none_graded = 1;
 3604: 		foreach my $part (@parts) {
 3605: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3606: 			$all_graded = 0;
 3607: 		    } else {
 3608: 			$none_graded = 0;
 3609: 		    }
 3610: 		}
 3611: 
 3612: 		if ($all_graded || $none_graded) {
 3613: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3614: 							   $symb,$cdom,$cnum,
 3615: 							   $udom,$uname);
 3616: 		}
 3617: 	    }
 3618: 
 3619: 	    $result.=&Apache::loncommon::start_data_table_row().
 3620: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3621: 		&Apache::loncommon::end_data_table_row();
 3622: 	    $updateCtr++;
 3623: 	} else {
 3624: 	    push(@noupdate,
 3625: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3626: 	    $noupdateCtr++;
 3627: 	}
 3628:         if ($aggregateflag) {
 3629:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3630: 				  $cdom,$cnum);
 3631:         }
 3632:     }
 3633:     if (@noupdate) {
 3634: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3635: 	my $numcols=scalar(@partid)*4+2;
 3636: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3637: 	    '<td align="center" colspan="'.$numcols.'">'.
 3638: 	    &mt('No Changes Occurred For the Students Below').
 3639: 	    '</td>'.
 3640: 	    &Apache::loncommon::end_data_table_row();
 3641: 	foreach my $line (@noupdate) {
 3642: 	    $result.=
 3643: 		&Apache::loncommon::start_data_table_row().
 3644: 		$line.
 3645: 		&Apache::loncommon::end_data_table_row();
 3646: 	}
 3647:     }
 3648:     $result .= &Apache::loncommon::end_data_table().
 3649: 	&show_grading_menu_form($symb);
 3650:     my $msg = '<p><b>'.
 3651: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3652: 	    $rec_update,$count).'</b><br />'.
 3653: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3654: 	'</b></p>';
 3655:     return $title.$msg.$result;
 3656: }
 3657: 
 3658: sub split_part_type {
 3659:     my ($partstr) = @_;
 3660:     my ($temp,@allparts)=split(/_/,$partstr);
 3661:     my $type=pop(@allparts);
 3662:     my $part=join('_',@allparts);
 3663:     return ($part,$type);
 3664: }
 3665: 
 3666: #------------- end of section for handling grading by section/class ---------
 3667: #
 3668: #----------------------------------------------------------------------------
 3669: 
 3670: 
 3671: #----------------------------------------------------------------------------
 3672: #
 3673: #-------------------------- Next few routines handles grading by csv upload
 3674: #
 3675: #--- Javascript to handle csv upload
 3676: sub csvupload_javascript_reverse_associate {
 3677:     my $error1=&mt('You need to specify the username or ID');
 3678:     my $error2=&mt('You need to specify at least one grading field');
 3679:   return(<<ENDPICK);
 3680:   function verify(vf) {
 3681:     var foundsomething=0;
 3682:     var founduname=0;
 3683:     var foundID=0;
 3684:     for (i=0;i<=vf.nfields.value;i++) {
 3685:       tw=eval('vf.f'+i+'.selectedIndex');
 3686:       if (i==0 && tw!=0) { foundID=1; }
 3687:       if (i==1 && tw!=0) { founduname=1; }
 3688:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3689:     }
 3690:     if (founduname==0 && foundID==0) {
 3691: 	alert('$error1');
 3692: 	return;
 3693:     }
 3694:     if (foundsomething==0) {
 3695: 	alert('$error2');
 3696: 	return;
 3697:     }
 3698:     vf.submit();
 3699:   }
 3700:   function flip(vf,tf) {
 3701:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3702:     var i;
 3703:     for (i=0;i<=vf.nfields.value;i++) {
 3704:       //can not pick the same destination field for both name and domain
 3705:       if (((i ==0)||(i ==1)) && 
 3706:           ((tf==0)||(tf==1)) && 
 3707:           (i!=tf) &&
 3708:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3709:         eval('vf.f'+i+'.selectedIndex=0;')
 3710:       }
 3711:     }
 3712:   }
 3713: ENDPICK
 3714: }
 3715: 
 3716: sub csvupload_javascript_forward_associate {
 3717:     my $error1=&mt('You need to specify the username or ID');
 3718:     my $error2=&mt('You need to specify at least one grading field');
 3719:   return(<<ENDPICK);
 3720:   function verify(vf) {
 3721:     var foundsomething=0;
 3722:     var founduname=0;
 3723:     var foundID=0;
 3724:     for (i=0;i<=vf.nfields.value;i++) {
 3725:       tw=eval('vf.f'+i+'.selectedIndex');
 3726:       if (tw==1) { foundID=1; }
 3727:       if (tw==2) { founduname=1; }
 3728:       if (tw>3) { foundsomething=1; }
 3729:     }
 3730:     if (founduname==0 && foundID==0) {
 3731: 	alert('$error1');
 3732: 	return;
 3733:     }
 3734:     if (foundsomething==0) {
 3735: 	alert('$error2');
 3736: 	return;
 3737:     }
 3738:     vf.submit();
 3739:   }
 3740:   function flip(vf,tf) {
 3741:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3742:     var i;
 3743:     //can not pick the same destination field twice
 3744:     for (i=0;i<=vf.nfields.value;i++) {
 3745:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3746:         eval('vf.f'+i+'.selectedIndex=0;')
 3747:       }
 3748:     }
 3749:   }
 3750: ENDPICK
 3751: }
 3752: 
 3753: sub csvuploadmap_header {
 3754:     my ($request,$symb,$datatoken,$distotal)= @_;
 3755:     my $javascript;
 3756:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3757: 	$javascript=&csvupload_javascript_reverse_associate();
 3758:     } else {
 3759: 	$javascript=&csvupload_javascript_forward_associate();
 3760:     }
 3761: 
 3762:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3763:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3764:     my $ignore=&mt('Ignore First Line');
 3765:     $symb = &Apache::lonenc::check_encrypt($symb);
 3766:     $request->print(<<ENDPICK);
 3767: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3768: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3769: $result
 3770: <hr />
 3771: <h3>Identify fields</h3>
 3772: Total number of records found in file: $distotal <hr />
 3773: Enter as many fields as you can. The system will inform you and bring you back
 3774: to this page if the data selected is insufficient to run your class.<hr />
 3775: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3776: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3777: <input type="hidden" name="associate"  value="" />
 3778: <input type="hidden" name="phase"      value="three" />
 3779: <input type="hidden" name="datatoken"  value="$datatoken" />
 3780: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3781: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3782: <input type="hidden" name="upfile_associate" 
 3783:                                        value="$env{'form.upfile_associate'}" />
 3784: <input type="hidden" name="symb"       value="$symb" />
 3785: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3786: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3787: <input type="hidden" name="command"    value="csvuploadoptions" />
 3788: <hr />
 3789: <script type="text/javascript" language="Javascript">
 3790: $javascript
 3791: </script>
 3792: ENDPICK
 3793:     return '';
 3794: 
 3795: }
 3796: 
 3797: sub csvupload_fields {
 3798:     my ($symb) = @_;
 3799:     my (@parts) = &getpartlist($symb);
 3800:     my @fields=(['ID','Student/Employee ID'],
 3801: 		['username','Student Username'],
 3802: 		['domain','Student Domain']);
 3803:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3804:     foreach my $part (sort(@parts)) {
 3805: 	my @datum;
 3806: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3807: 	my $name=$part;
 3808: 	if  (!$display) { $display = $name; }
 3809: 	@datum=($name,$display);
 3810: 	if ($name=~/^stores_(.*)_awarded/) {
 3811: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3812: 	}
 3813: 	push(@fields,\@datum);
 3814:     }
 3815:     return (@fields);
 3816: }
 3817: 
 3818: sub csvuploadmap_footer {
 3819:     my ($request,$i,$keyfields) =@_;
 3820:     $request->print(<<ENDPICK);
 3821: </table>
 3822: <input type="hidden" name="nfields" value="$i" />
 3823: <input type="hidden" name="keyfields" value="$keyfields" />
 3824: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3825: </form>
 3826: ENDPICK
 3827: }
 3828: 
 3829: sub checkforfile_js {
 3830:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3831:     my $result =<<CSVFORMJS;
 3832: <script type="text/javascript" language="javascript">
 3833:     function checkUpload(formname) {
 3834: 	if (formname.upfile.value == "") {
 3835: 	    alert("$alertmsg");
 3836: 	    return false;
 3837: 	}
 3838: 	formname.submit();
 3839:     }
 3840:     </script>
 3841: CSVFORMJS
 3842:     return $result;
 3843: }
 3844: 
 3845: sub upcsvScores_form {
 3846:     my ($request) = shift;
 3847:     my ($symb)=&get_symb($request);
 3848:     if (!$symb) {return '';}
 3849:     my $result=&checkforfile_js();
 3850:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3851:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3852:     $result.=$table;
 3853:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3854:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3855:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3856: 	'</b></td></tr>'."\n";
 3857:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3858:     my $upload=&mt("Upload Scores");
 3859:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3860:     my $ignore=&mt('Ignore First Line');
 3861:     $symb = &Apache::lonenc::check_encrypt($symb);
 3862:     $result.=<<ENDUPFORM;
 3863: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3864: <input type="hidden" name="symb" value="$symb" />
 3865: <input type="hidden" name="command" value="csvuploadmap" />
 3866: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3867: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3868: $upfile_select
 3869: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3870: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3871: </form>
 3872: ENDUPFORM
 3873:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3874:                            &mt("How do I create a CSV file from a spreadsheet"))
 3875:     .'</td></tr></table>'."\n";
 3876:     $result.='</td></tr></table><br /><br />'."\n";
 3877:     $result.=&show_grading_menu_form($symb);
 3878:     return $result;
 3879: }
 3880: 
 3881: 
 3882: sub csvuploadmap {
 3883:     my ($request)= @_;
 3884:     my ($symb)=&get_symb($request);
 3885:     if (!$symb) {return '';}
 3886: 
 3887:     my $datatoken;
 3888:     if (!$env{'form.datatoken'}) {
 3889: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3890:     } else {
 3891: 	$datatoken=$env{'form.datatoken'};
 3892: 	&Apache::loncommon::load_tmp_file($request);
 3893:     }
 3894:     my @records=&Apache::loncommon::upfile_record_sep();
 3895:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3896:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3897:     my ($i,$keyfields);
 3898:     if (@records) {
 3899: 	my @fields=&csvupload_fields($symb);
 3900: 
 3901: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3902: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3903: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3904: 							  \@fields);
 3905: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3906: 	    chop($keyfields);
 3907: 	} else {
 3908: 	    unshift(@fields,['none','']);
 3909: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3910: 							    \@fields);
 3911:             foreach my $rec (@records) {
 3912:                 my %temp = &Apache::loncommon::record_sep($rec);
 3913:                 if (%temp) {
 3914:                     $keyfields=join(',',sort(keys(%temp)));
 3915:                     last;
 3916:                 }
 3917:             }
 3918: 	}
 3919:     }
 3920:     &csvuploadmap_footer($request,$i,$keyfields);
 3921:     $request->print(&show_grading_menu_form($symb));
 3922: 
 3923:     return '';
 3924: }
 3925: 
 3926: sub csvuploadoptions {
 3927:     my ($request)= @_;
 3928:     my ($symb)=&get_symb($request);
 3929:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3930:     my $ignore=&mt('Ignore First Line');
 3931:     $request->print(<<ENDPICK);
 3932: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3933: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3934: <input type="hidden" name="command"    value="csvuploadassign" />
 3935: <!--
 3936: <p>
 3937: <label>
 3938:    <input type="checkbox" name="show_full_results" />
 3939:    Show a table of all changes
 3940: </label>
 3941: </p>
 3942: -->
 3943: <p>
 3944: <label>
 3945:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3946:    Overwrite any existing score
 3947: </label>
 3948: </p>
 3949: ENDPICK
 3950:     my %fields=&get_fields();
 3951:     if (!defined($fields{'domain'})) {
 3952: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3953: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3954:     }
 3955:     foreach my $key (sort(keys(%env))) {
 3956: 	if ($key !~ /^form\.(.*)$/) { next; }
 3957: 	my $cleankey=$1;
 3958: 	if ($cleankey eq 'command') { next; }
 3959: 	$request->print('<input type="hidden" name="'.$cleankey.
 3960: 			'"  value="'.$env{$key}.'" />'."\n");
 3961:     }
 3962:     # FIXME do a check for any duplicated user ids...
 3963:     # FIXME do a check for any invalid user ids?...
 3964:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3965: <hr /></form>'."\n");
 3966:     $request->print(&show_grading_menu_form($symb));
 3967:     return '';
 3968: }
 3969: 
 3970: sub get_fields {
 3971:     my %fields;
 3972:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3973:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3974: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3975: 	    if ($env{'form.f'.$i} ne 'none') {
 3976: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3977: 	    }
 3978: 	} else {
 3979: 	    if ($env{'form.f'.$i} ne 'none') {
 3980: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3981: 	    }
 3982: 	}
 3983:     }
 3984:     return %fields;
 3985: }
 3986: 
 3987: sub csvuploadassign {
 3988:     my ($request)= @_;
 3989:     my ($symb)=&get_symb($request);
 3990:     if (!$symb) {return '';}
 3991:     my $error_msg = '';
 3992:     &Apache::loncommon::load_tmp_file($request);
 3993:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3994:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3995:     my %fields=&get_fields();
 3996:     $request->print('<h3>Assigning Grades</h3>');
 3997:     my $courseid=$env{'request.course.id'};
 3998:     my ($classlist) = &getclasslist('all',0);
 3999:     my @notallowed;
 4000:     my @skipped;
 4001:     my $countdone=0;
 4002:     foreach my $grade (@gradedata) {
 4003: 	my %entries=&Apache::loncommon::record_sep($grade);
 4004: 	my $domain;
 4005: 	if ($entries{$fields{'domain'}}) {
 4006: 	    $domain=$entries{$fields{'domain'}};
 4007: 	} else {
 4008: 	    $domain=$env{'form.default_domain'};
 4009: 	}
 4010: 	$domain=~s/\s//g;
 4011: 	my $username=$entries{$fields{'username'}};
 4012: 	$username=~s/\s//g;
 4013: 	if (!$username) {
 4014: 	    my $id=$entries{$fields{'ID'}};
 4015: 	    $id=~s/\s//g;
 4016: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4017: 	    $username=$ids{$id};
 4018: 	}
 4019: 	if (!exists($$classlist{"$username:$domain"})) {
 4020: 	    my $id=$entries{$fields{'ID'}};
 4021: 	    $id=~s/\s//g;
 4022: 	    if ($id) {
 4023: 		push(@skipped,"$id:$domain");
 4024: 	    } else {
 4025: 		push(@skipped,"$username:$domain");
 4026: 	    }
 4027: 	    next;
 4028: 	}
 4029: 	my $usec=$classlist->{"$username:$domain"}[5];
 4030: 	if (!&canmodify($usec)) {
 4031: 	    push(@notallowed,"$username:$domain");
 4032: 	    next;
 4033: 	}
 4034: 	my %points;
 4035: 	my %grades;
 4036: 	foreach my $dest (keys(%fields)) {
 4037: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4038: 		$dest eq 'domain') { next; }
 4039: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4040: 	    if ($dest=~/stores_(.*)_points/) {
 4041: 		my $part=$1;
 4042: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4043: 					      $symb,$domain,$username);
 4044:                 if ($wgt) {
 4045:                     $entries{$fields{$dest}}=~s/\s//g;
 4046:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4047:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4048:                                           : 'correct_by_override';
 4049:                     $grades{"resource.$part.awarded"}=$pcr;
 4050:                     $grades{"resource.$part.solved"}=$award;
 4051:                     $points{$part}=1;
 4052:                 } else {
 4053:                     $error_msg = "<br />" .
 4054:                         &mt("Some point values were assigned"
 4055:                             ." for problems with a weight "
 4056:                             ."of zero. These values were "
 4057:                             ."ignored.");
 4058:                 }
 4059: 	    } else {
 4060: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4061: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4062: 		my $store_key=$dest;
 4063: 		$store_key=~s/^stores/resource/;
 4064: 		$store_key=~s/_/\./g;
 4065: 		$grades{$store_key}=$entries{$fields{$dest}};
 4066: 	    }
 4067: 	}
 4068: 	if (! %grades) { 
 4069:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4070:         } else {
 4071: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4072: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4073: 					   $env{'request.course.id'},
 4074: 					   $domain,$username);
 4075: 	   if ($result eq 'ok') {
 4076: 	      $request->print('.');
 4077: 	   } else {
 4078: 	      $request->print("<p><span class=\"LC_error\">".
 4079:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4080:                                   "$username:$domain",$result)."</span></p>");
 4081: 	   }
 4082: 	   $request->rflush();
 4083: 	   $countdone++;
 4084:         }
 4085:     }
 4086:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4087:     if (@skipped) {
 4088: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4089: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4090:     }
 4091:     if (@notallowed) {
 4092: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4093: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4094:     }
 4095:     $request->print("<br />\n");
 4096:     $request->print(&show_grading_menu_form($symb));
 4097:     return $error_msg;
 4098: }
 4099: #------------- end of section for handling csv file upload ---------
 4100: #
 4101: #-------------------------------------------------------------------
 4102: #
 4103: #-------------- Next few routines handle grading by page/sequence
 4104: #
 4105: #--- Select a page/sequence and a student to grade
 4106: sub pickStudentPage {
 4107:     my ($request) = shift;
 4108: 
 4109:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4110:     $request->print(<<LISTJAVASCRIPT);
 4111: <script type="text/javascript" language="javascript">
 4112: 
 4113: function checkPickOne(formname) {
 4114:     if (radioSelection(formname.student) == null) {
 4115: 	alert("$alertmsg");
 4116: 	return;
 4117:     }
 4118:     ptr = pullDownSelection(formname.selectpage);
 4119:     formname.page.value = formname["page"+ptr].value;
 4120:     formname.title.value = formname["title"+ptr].value;
 4121:     formname.submit();
 4122: }
 4123: 
 4124: </script>
 4125: LISTJAVASCRIPT
 4126:     &commonJSfunctions($request);
 4127:     my ($symb) = &get_symb($request);
 4128:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4129:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4130:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4131: 
 4132:     my $result='<h3><span class="LC_info">&nbsp;'.
 4133: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4134: 
 4135:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4136:     my ($titles,$symbx) = &getSymbMap();
 4137:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4138: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4139: #    my $type=($curpage =~ /\.(page|sequence)/);
 4140:     my $select = '<select name="selectpage">'."\n";
 4141:     my $ctr=0;
 4142:     foreach (@$titles) {
 4143: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4144: 	$select.='<option value="'.$ctr.'" '.
 4145: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4146: 	    '>'.$showtitle.'</option>'."\n";
 4147: 	$ctr++;
 4148:     }
 4149:     $select.= '</select>';
 4150:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4151: 
 4152:     $ctr=0;
 4153:     foreach (@$titles) {
 4154: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4155: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4156: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4157: 	$ctr++;
 4158:     }
 4159:     $result.='<input type="hidden" name="page" />'."\n".
 4160: 	'<input type="hidden" name="title" />'."\n";
 4161: 
 4162:     my $options =
 4163: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4164: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4165:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4166: 
 4167:     $options =
 4168: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4169: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4170: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4171:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4172:     
 4173:     $result.=&build_section_inputs();
 4174:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4175:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4176: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4177: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4178: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4179: 
 4180:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4181: 
 4182:     $result.='&nbsp;<input type="button" '.
 4183: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4184: 
 4185:     $request->print($result);
 4186: 
 4187:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4188: 	&Apache::loncommon::start_data_table().
 4189: 	&Apache::loncommon::start_data_table_header_row().
 4190: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4191: 	'<th>'.&nameUserString('header').'</th>'.
 4192: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4193: 	'<th>'.&nameUserString('header').'</th>'.
 4194: 	&Apache::loncommon::end_data_table_header_row();
 4195:  
 4196:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4197:     my $ptr = 1;
 4198:     foreach my $student (sort 
 4199: 			 {
 4200: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4201: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4202: 			     }
 4203: 			     return $a cmp $b;
 4204: 			 } (keys(%$fullname))) {
 4205: 	my ($uname,$udom) = split(/:/,$student);
 4206: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4207:                                   : '</td>');
 4208: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4209: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4210: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4211: 	$studentTable.=
 4212: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4213:                          : '');
 4214: 	$ptr++;
 4215:     }
 4216:     if ($ptr%2 == 0) {
 4217: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4218: 	    &Apache::loncommon::end_data_table_row();
 4219:     }
 4220:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4221:     $studentTable.='<input type="button" '.
 4222: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4223: 
 4224:     $studentTable.=&show_grading_menu_form($symb);
 4225:     $request->print($studentTable);
 4226: 
 4227:     return '';
 4228: }
 4229: 
 4230: sub getSymbMap {
 4231:     my $navmap = Apache::lonnavmaps::navmap->new();
 4232: 
 4233:     my %symbx = ();
 4234:     my @titles = ();
 4235:     my $minder = 0;
 4236: 
 4237:     # Gather every sequence that has problems.
 4238:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4239: 					       1,0,1);
 4240:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4241: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4242: 	    my $title = $minder.'.'.
 4243: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4244: 	    push(@titles, $title); # minder in case two titles are identical
 4245: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4246: 	    $minder++;
 4247: 	}
 4248:     }
 4249:     return \@titles,\%symbx;
 4250: }
 4251: 
 4252: #
 4253: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4254: sub displayPage {
 4255:     my ($request) = shift;
 4256: 
 4257:     my ($symb) = &get_symb($request);
 4258:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4259:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4260:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4261:     my $pageTitle = $env{'form.page'};
 4262:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4263:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4264:     my $usec=$classlist->{$env{'form.student'}}[5];
 4265: 
 4266:     #need to make sure we have the correct data for later EXT calls, 
 4267:     #thus invalidate the cache
 4268:     &Apache::lonnet::devalidatecourseresdata(
 4269:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4270:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4271:     &Apache::lonnet::clear_EXT_cache_status();
 4272: 
 4273:     if (!&canview($usec)) {
 4274: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4275: 	$request->print(&show_grading_menu_form($symb));
 4276: 	return;
 4277:     }
 4278:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4279:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4280: 	'</h3>'."\n";
 4281:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4282:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4283: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4284:     } else {
 4285: 	delete($env{'form.CODE'});
 4286:     }
 4287:     &sub_page_js($request);
 4288:     $request->print($result);
 4289: 
 4290:     my $navmap = Apache::lonnavmaps::navmap->new();
 4291:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4292:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4293:     if (!$map) {
 4294: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4295: 	$request->print(&show_grading_menu_form($symb));
 4296: 	return; 
 4297:     }
 4298:     my $iterator = $navmap->getIterator($map->map_start(),
 4299: 					$map->map_finish());
 4300: 
 4301:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4302: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4303: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4304: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4305: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4306: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4307: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4308: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4309: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4310: 
 4311:     if (defined($env{'form.CODE'})) {
 4312: 	$studentTable.=
 4313: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4314:     }
 4315:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4316: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4317: 
 4318:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4319: 	&Apache::loncommon::start_data_table().
 4320: 	&Apache::loncommon::start_data_table_header_row().
 4321: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4322: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4323: 	&Apache::loncommon::end_data_table_header_row();
 4324: 
 4325:     &Apache::lonxml::clear_problem_counter();
 4326:     my ($depth,$question,$prob) = (1,1,1);
 4327:     $iterator->next(); # skip the first BEGIN_MAP
 4328:     my $curRes = $iterator->next(); # for "current resource"
 4329:     while ($depth > 0) {
 4330:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4331:         if($curRes == $iterator->END_MAP) { $depth--; }
 4332: 
 4333:         if (ref($curRes) && $curRes->is_problem()) {
 4334: 	    my $parts = $curRes->parts();
 4335:             my $title = $curRes->compTitle();
 4336: 	    my $symbx = $curRes->symb();
 4337: 	    $studentTable.=
 4338: 		&Apache::loncommon::start_data_table_row().
 4339: 		'<td align="center" valign="top" >'.$prob.
 4340: 		(scalar(@{$parts}) == 1 ? '' 
 4341: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4342: 							scalar(@{$parts}))
 4343: 		 ).
 4344: 		 '</td>';
 4345: 	    $studentTable.='<td valign="top">';
 4346: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4347: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4348: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4349: 					     undef,'both',\%form);
 4350: 	    } else {
 4351: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4352: 		$companswer =~ s|<form(.*?)>||g;
 4353: 		$companswer =~ s|</form>||g;
 4354: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4355: #		    $companswer =~ s/$1/ /ms;
 4356: #		    $request->print('match='.$1."<br />\n");
 4357: #		}
 4358: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4359: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4360: 	    }
 4361: 
 4362: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4363: 
 4364: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4365: 		if ($record{'version'} eq '') {
 4366: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4367: 		} else {
 4368: 		    my %responseType = ();
 4369: 		    foreach my $partid (@{$parts}) {
 4370: 			my @responseIds =$curRes->responseIds($partid);
 4371: 			my @responseType =$curRes->responseType($partid);
 4372: 			my %responseIds;
 4373: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4374: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4375: 			}
 4376: 			$responseType{$partid} = \%responseIds;
 4377: 		    }
 4378: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4379: 
 4380: 		}
 4381: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4382: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4383: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4384: 									$env{'request.course.id'},
 4385: 									'','.submission');
 4386:  
 4387: 	    }
 4388: 	    if (&canmodify($usec)) {
 4389: 		foreach my $partid (@{$parts}) {
 4390: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4391: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4392: 		    $question++;
 4393: 		}
 4394: 		$prob++;
 4395: 	    }
 4396: 	    $studentTable.='</td></tr>';
 4397: 
 4398: 	}
 4399:         $curRes = $iterator->next();
 4400:     }
 4401: 
 4402:     $studentTable.='</table>'."\n".
 4403: 	'<input type="button" value="'.&mt('Save').'" '.
 4404: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4405: 	'</form>'."\n";
 4406:     $studentTable.=&show_grading_menu_form($symb);
 4407:     $request->print($studentTable);
 4408: 
 4409:     return '';
 4410: }
 4411: 
 4412: sub displaySubByDates {
 4413:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4414:     my $isCODE=0;
 4415:     my $isTask = ($symb =~/\.task$/);
 4416:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4417:     my $studentTable=&Apache::loncommon::start_data_table().
 4418: 	&Apache::loncommon::start_data_table_header_row().
 4419: 	'<th>'.&mt('Date/Time').'</th>'.
 4420: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4421: 	'<th>'.&mt('Submission').'</th>'.
 4422: 	'<th>'.&mt('Status').'</th>'.
 4423: 	&Apache::loncommon::end_data_table_header_row();
 4424:     my ($version);
 4425:     my %mark;
 4426:     my %orders;
 4427:     $mark{'correct_by_student'} = $checkIcon;
 4428:     if (!exists($$record{'1:timestamp'})) {
 4429: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4430:     }
 4431: 
 4432:     my $interaction;
 4433:     my $no_increment = 1;
 4434:     for ($version=1;$version<=$$record{'version'};$version++) {
 4435: 	my $timestamp = 
 4436: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4437: 	if (exists($$record{$version.':resource.0.version'})) {
 4438: 	    $interaction = $$record{$version.':resource.0.version'};
 4439: 	}
 4440: 
 4441: 	my $where = ($isTask ? "$version:resource.$interaction"
 4442: 		             : "$version:resource");
 4443: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4444: 	    '<td>'.$timestamp.'</td>';
 4445: 	if ($isCODE) {
 4446: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4447: 	}
 4448: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4449: 	my @displaySub = ();
 4450: 	foreach my $partid (@{$parts}) {
 4451: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4452: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4453: 	    
 4454: 
 4455: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4456: 	    my $display_part=&get_display_part($partid,$symb);
 4457: 	    foreach my $matchKey (@matchKey) {
 4458: 		if (exists($$record{$version.':'.$matchKey}) &&
 4459: 		    $$record{$version.':'.$matchKey} ne '') {
 4460: 
 4461: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4462: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4463: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4464: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4465: 			$responseId.')</span>&nbsp;<b>';
 4466: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4467: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4468: 		    } else {
 4469: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4470: 					    $$record{"$where.$partid.tries"});
 4471: 		    }
 4472: 		    my $responseType=($isTask ? 'Task'
 4473:                                               : $responseType->{$partid}->{$responseId});
 4474: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4475: 		    if (!exists($orders{$partid}->{$responseId})) {
 4476: 			$orders{$partid}->{$responseId}=
 4477: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4478:                                        $no_increment);
 4479: 		    }
 4480: 		    $displaySub[0].='</b>&nbsp; '.
 4481: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4482: 		}
 4483: 	    }
 4484: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4485: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4486: 				    $$record{"$where.$partid.checkedin"},
 4487: 				    $$record{"$where.$partid.checkedin.slot"}).
 4488: 					'<br />';
 4489: 	    }
 4490: 	    if (exists $$record{"$where.$partid.award"}) {
 4491: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4492: 		    lc($$record{"$where.$partid.award"}).' '.
 4493: 		    $mark{$$record{"$where.$partid.solved"}}.
 4494: 		    '<br />';
 4495: 	    }
 4496: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4497: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4498: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4499: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4500: 		$displaySub[2].=
 4501: 		    $$record{"$version:resource.$partid.regrader"}.
 4502: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4503: 	    }
 4504: 	}
 4505: 	# needed because old essay regrader has not parts info
 4506: 	if (exists $$record{"$version:resource.regrader"}) {
 4507: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4508: 	}
 4509: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4510: 	if ($displaySub[2]) {
 4511: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4512: 	}
 4513: 	$studentTable.='&nbsp;</td>'.
 4514: 	    &Apache::loncommon::end_data_table_row();
 4515:     }
 4516:     $studentTable.=&Apache::loncommon::end_data_table();
 4517:     return $studentTable;
 4518: }
 4519: 
 4520: sub updateGradeByPage {
 4521:     my ($request) = shift;
 4522: 
 4523:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4524:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4525:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4526:     my $pageTitle = $env{'form.page'};
 4527:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4528:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4529:     my $usec=$classlist->{$env{'form.student'}}[5];
 4530:     if (!&canmodify($usec)) {
 4531: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4532: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4533: 	return;
 4534:     }
 4535:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4536:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4537: 	'</h3>'."\n";
 4538: 
 4539:     $request->print($result);
 4540: 
 4541:     my $navmap = Apache::lonnavmaps::navmap->new();
 4542:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4543:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4544:     if (!$map) {
 4545: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4546: 	my ($symb)=&get_symb($request);
 4547: 	$request->print(&show_grading_menu_form($symb));
 4548: 	return; 
 4549:     }
 4550:     my $iterator = $navmap->getIterator($map->map_start(),
 4551: 					$map->map_finish());
 4552: 
 4553:     my $studentTable=
 4554: 	&Apache::loncommon::start_data_table().
 4555: 	&Apache::loncommon::start_data_table_header_row().
 4556: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4557: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4558: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4559: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4560: 	&Apache::loncommon::end_data_table_header_row();
 4561: 
 4562:     $iterator->next(); # skip the first BEGIN_MAP
 4563:     my $curRes = $iterator->next(); # for "current resource"
 4564:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4565:     while ($depth > 0) {
 4566:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4567:         if($curRes == $iterator->END_MAP) { $depth--; }
 4568: 
 4569:         if (ref($curRes) && $curRes->is_problem()) {
 4570: 	    my $parts = $curRes->parts();
 4571:             my $title = $curRes->compTitle();
 4572: 	    my $symbx = $curRes->symb();
 4573: 	    $studentTable.=
 4574: 		&Apache::loncommon::start_data_table_row().
 4575: 		'<td align="center" valign="top" >'.$prob.
 4576: 		(scalar(@{$parts}) == 1 ? '' 
 4577:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4578: 		.')').'</td>';
 4579: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4580: 
 4581: 	    my %newrecord=();
 4582: 	    my @displayPts=();
 4583:             my %aggregate = ();
 4584:             my $aggregateflag = 0;
 4585: 	    foreach my $partid (@{$parts}) {
 4586: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4587: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4588: 
 4589: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4590: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4591: 		my $partial = $newpts/$wgt;
 4592: 		my $score;
 4593: 		if ($partial > 0) {
 4594: 		    $score = 'correct_by_override';
 4595: 		} elsif ($newpts ne '') { #empty is taken as 0
 4596: 		    $score = 'incorrect_by_override';
 4597: 		}
 4598: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4599: 		if ($dropMenu eq 'excused') {
 4600: 		    $partial = '';
 4601: 		    $score = 'excused';
 4602: 		} elsif ($dropMenu eq 'reset status'
 4603: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4604: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4605: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4606: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4607: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4608: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4609: 		    $changeflag++;
 4610: 		    $newpts = '';
 4611:                     
 4612:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4613:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4614:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4615:                     if ($aggtries > 0) {
 4616:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4617:                         $aggregateflag = 1;
 4618:                     }
 4619: 		}
 4620: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4621: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4622: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4623: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4624: 		    '&nbsp;<br />';
 4625: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4626: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4627: 		    '&nbsp;<br />';
 4628: 		$question++;
 4629: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4630: 
 4631: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4632: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4633: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4634: 		    if (scalar(keys(%newrecord)) > 0);
 4635: 
 4636: 		$changeflag++;
 4637: 	    }
 4638: 	    if (scalar(keys(%newrecord)) > 0) {
 4639: 		my %record = 
 4640: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4641: 					     $udom,$uname);
 4642: 
 4643: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4644: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4645: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4646: 		    $newrecord{'resource.CODE'} = '';
 4647: 		}
 4648: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4649: 					$udom,$uname);
 4650: 		%record = &Apache::lonnet::restore($symbx,
 4651: 						   $env{'request.course.id'},
 4652: 						   $udom,$uname);
 4653: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4654: 					     $cdom,$cnum,$udom,$uname);
 4655: 	    }
 4656: 	    
 4657:             if ($aggregateflag) {
 4658:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4659:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4660:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4661:             }
 4662: 
 4663: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4664: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4665: 		&Apache::loncommon::end_data_table_row();
 4666: 
 4667: 	    $prob++;
 4668: 	}
 4669:         $curRes = $iterator->next();
 4670:     }
 4671: 
 4672:     $studentTable.=&Apache::loncommon::end_data_table();
 4673:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4674:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4675: 		  &mt('The scores were changed for [quant,_1,problem].',
 4676: 		  $changeflag));
 4677:     $request->print($grademsg.$studentTable);
 4678: 
 4679:     return '';
 4680: }
 4681: 
 4682: #-------- end of section for handling grading by page/sequence ---------
 4683: #
 4684: #-------------------------------------------------------------------
 4685: 
 4686: #--------------------Scantron Grading-----------------------------------
 4687: #
 4688: #------ start of section for handling grading by page/sequence ---------
 4689: 
 4690: =pod
 4691: 
 4692: =head1 Bubble sheet grading routines
 4693: 
 4694:   For this documentation:
 4695: 
 4696:    'scanline' refers to the full line of characters
 4697:    from the file that we are parsing that represents one entire sheet
 4698: 
 4699:    'bubble line' refers to the data
 4700:    representing the line of bubbles that are on the physical bubble sheet
 4701: 
 4702: 
 4703: The overall process is that a scanned in bubble sheet data is uploaded
 4704: into a course. When a user wants to grade, they select a
 4705: sequence/folder of resources, a file of bubble sheet info, and pick
 4706: one of the predefined configurations for what each scanline looks
 4707: like.
 4708: 
 4709: Next each scanline is checked for any errors of either 'missing
 4710: bubbles' (it's an error because it may have been mis-scanned
 4711: because too light bubbling), 'double bubble' (each bubble line should
 4712: have no more that one letter picked), invalid or duplicated CODE,
 4713: invalid student/employee ID
 4714: 
 4715: If the CODE option is used that determines the randomization of the
 4716: homework problems, either way the student/employee ID is looked up into a
 4717: username:domain.
 4718: 
 4719: During the validation phase the instructor can choose to skip scanlines. 
 4720: 
 4721: After the validation phase, there are now 3 bubble sheet files
 4722: 
 4723:   scantron_original_filename (unmodified original file)
 4724:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4725:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4726: 
 4727: Also there is a separate hash nohist_scantrondata that contains extra
 4728: correction information that isn't representable in the bubble sheet
 4729: file (see &scantron_getfile() for more information)
 4730: 
 4731: After all scanlines are either valid, marked as valid or skipped, then
 4732: foreach line foreach problem in the picked sequence, an ssi request is
 4733: made that simulates a user submitting their selected letter(s) against
 4734: the homework problem.
 4735: 
 4736: =over 4
 4737: 
 4738: 
 4739: 
 4740: =item defaultFormData
 4741: 
 4742:   Returns html hidden inputs used to hold context/default values.
 4743: 
 4744:  Arguments:
 4745:   $symb - $symb of the current resource 
 4746: 
 4747: =cut
 4748: 
 4749: sub defaultFormData {
 4750:     my ($symb)=@_;
 4751:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4752:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4753:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4754: }
 4755: 
 4756: 
 4757: =pod 
 4758: 
 4759: =item getSequenceDropDown
 4760: 
 4761:    Return html dropdown of possible sequences to grade
 4762:  
 4763:  Arguments:
 4764:    $symb - $symb of the current resource 
 4765: 
 4766: =cut
 4767: 
 4768: sub getSequenceDropDown {
 4769:     my ($symb)=@_;
 4770:     my $result='<select name="selectpage">'."\n";
 4771:     my ($titles,$symbx) = &getSymbMap();
 4772:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4773:     my $ctr=0;
 4774:     foreach (@$titles) {
 4775: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4776: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4777: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4778: 	    '>'.$showtitle.'</option>'."\n";
 4779: 	$ctr++;
 4780:     }
 4781:     $result.= '</select>';
 4782:     return $result;
 4783: }
 4784: 
 4785: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4786:                                    # key is zero-based index - 0, 1, 2 ...
 4787: 
 4788: my %first_bubble_line;             # First bubble line no. for each bubble.
 4789: 
 4790: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4791:                                    # matchresponse or rankresponse, where 
 4792:                                    # an individual response can have multiple 
 4793:                                    # lines
 4794: 
 4795: my %responsetype_per_response;     # responsetype for each response
 4796: 
 4797: # Save and restore the bubble lines array to the form env.
 4798: 
 4799: 
 4800: sub save_bubble_lines {
 4801:     foreach my $line (keys(%bubble_lines_per_response)) {
 4802: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4803: 	$env{"form.scantron.first_bubble_line.$line"} =
 4804: 	    $first_bubble_line{$line};
 4805:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4806:             $subdivided_bubble_lines{$line};
 4807:         $env{"form.scantron.responsetype.$line"} =
 4808:             $responsetype_per_response{$line};
 4809:     }
 4810: }
 4811: 
 4812: 
 4813: sub restore_bubble_lines {
 4814:     my $line = 0;
 4815:     %bubble_lines_per_response = ();
 4816:     while ($env{"form.scantron.bubblelines.$line"}) {
 4817: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4818: 	$bubble_lines_per_response{$line} = $value;
 4819: 	$first_bubble_line{$line}  =
 4820: 	    $env{"form.scantron.first_bubble_line.$line"};
 4821:         $subdivided_bubble_lines{$line} =
 4822:             $env{"form.scantron.sub_bubblelines.$line"};
 4823:         $responsetype_per_response{$line} =
 4824:             $env{"form.scantron.responsetype.$line"};
 4825: 	$line++;
 4826:     }
 4827: }
 4828: 
 4829: #  Given the parsed scanline, get the response for 
 4830: #  'answer' number n:
 4831: 
 4832: sub get_response_bubbles {
 4833:     my ($parsed_line, $response)  = @_;
 4834: 
 4835:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4836:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4837:     
 4838:     my $selected = "";
 4839: 
 4840:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4841: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4842: 	$bubble_line++;
 4843:     }
 4844:     return $selected;
 4845: }
 4846: 
 4847: =pod 
 4848: 
 4849: =item scantron_filenames
 4850: 
 4851:    Returns a list of the scantron files in the current course 
 4852: 
 4853: =cut
 4854: 
 4855: sub scantron_filenames {
 4856:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4857:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4858:     my $getpropath = 1;
 4859:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4860:                                        $getpropath);
 4861:     my @possiblenames;
 4862:     foreach my $filename (sort(@files)) {
 4863: 	($filename)=split(/&/,$filename);
 4864: 	if ($filename!~/^scantron_orig_/) { next ; }
 4865: 	$filename=~s/^scantron_orig_//;
 4866: 	push(@possiblenames,$filename);
 4867:     }
 4868:     return @possiblenames;
 4869: }
 4870: 
 4871: =pod 
 4872: 
 4873: =item scantron_uploads
 4874: 
 4875:    Returns  html drop-down list of scantron files in current course.
 4876: 
 4877:  Arguments:
 4878:    $file2grade - filename to set as selected in the dropdown
 4879: 
 4880: =cut
 4881: 
 4882: sub scantron_uploads {
 4883:     my ($file2grade) = @_;
 4884:     my $result=	'<select name="scantron_selectfile">';
 4885:     $result.="<option></option>";
 4886:     foreach my $filename (sort(&scantron_filenames())) {
 4887: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4888:     }
 4889:     $result.="</select>";
 4890:     return $result;
 4891: }
 4892: 
 4893: =pod 
 4894: 
 4895: =item scantron_scantab
 4896: 
 4897:   Returns html drop down of the scantron formats in the scantronformat.tab
 4898:   file.
 4899: 
 4900: =cut
 4901: 
 4902: sub scantron_scantab {
 4903:     my $result='<select name="scantron_format">'."\n";
 4904:     $result.='<option></option>'."\n";
 4905:     my @lines = &get_scantronformat_file();
 4906:     if (@lines > 0) {
 4907:         foreach my $line (@lines) {
 4908:             next if (($line =~ /^\#/) || ($line eq ''));
 4909: 	    my ($name,$descrip)=split(/:/,$line);
 4910: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4911:         }
 4912:     }
 4913:     $result.='</select>'."\n";
 4914:     return $result;
 4915: }
 4916: 
 4917: =pod
 4918: 
 4919: =item get_scantronformat_file
 4920: 
 4921:   Returns an array containing lines from the scantron format file for
 4922:   the domain of the course.
 4923: 
 4924:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4925:   lines are from this file.
 4926: 
 4927:   Otherwise, if a default.tab has been published in RES space by the 
 4928:   domainconfig user, lines are from this file.
 4929: 
 4930:   Otherwise, fall back to getting lines from the legacy file on the
 4931:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4932: 
 4933: =cut
 4934: 
 4935: sub get_scantronformat_file {
 4936:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4937:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4938:     my $gottab = 0;
 4939:     my @lines;
 4940:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4941:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4942:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4943:             if ($formatfile ne '-1') {
 4944:                 @lines = split("\n",$formatfile,-1);
 4945:                 $gottab = 1;
 4946:             }
 4947:         }
 4948:     }
 4949:     if (!$gottab) {
 4950:         my $confname = $cdom.'-domainconfig';
 4951:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4952:         my $formatfile =  &Apache::lonnet::getfile($default);
 4953:         if ($formatfile ne '-1') {
 4954:             @lines = split("\n",$formatfile,-1);
 4955:             $gottab = 1;
 4956:         }
 4957:     }
 4958:     if (!$gottab) {
 4959:         my @domains = &Apache::lonnet::current_machine_domains();
 4960:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4961:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4962:             @lines = <$fh>;
 4963:             close($fh);
 4964:         } else {
 4965:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4966:             @lines = <$fh>;
 4967:             close($fh);
 4968:         }
 4969:     }
 4970:     return @lines;
 4971: }
 4972: 
 4973: =pod 
 4974: 
 4975: =item scantron_CODElist
 4976: 
 4977:   Returns html drop down of the saved CODE lists from current course,
 4978:   generated from earlier printings.
 4979: 
 4980: =cut
 4981: 
 4982: sub scantron_CODElist {
 4983:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4984:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4985:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4986:     my $namechoice='<option></option>';
 4987:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4988: 	if ($name =~ /^error: 2 /) { next; }
 4989: 	if ($name =~ /^type\0/) { next; }
 4990: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4991:     }
 4992:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4993:     return $namechoice;
 4994: }
 4995: 
 4996: =pod 
 4997: 
 4998: =item scantron_CODEunique
 4999: 
 5000:   Returns the html for "Each CODE to be used once" radio.
 5001: 
 5002: =cut
 5003: 
 5004: sub scantron_CODEunique {
 5005:     my $result='<span class="LC_nobreak">
 5006:                  <label><input type="radio" name="scantron_CODEunique"
 5007:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5008:                 </span>
 5009:                 <span class="LC_nobreak">
 5010:                  <label><input type="radio" name="scantron_CODEunique"
 5011:                         value="no" />'.&mt('No').' </label>
 5012:                 </span>';
 5013:     return $result;
 5014: }
 5015: 
 5016: =pod 
 5017: 
 5018: =item scantron_selectphase
 5019: 
 5020:   Generates the initial screen to start the bubble sheet process.
 5021:   Allows for - starting a grading run.
 5022:              - downloading existing scan data (original, corrected
 5023:                                                 or skipped info)
 5024: 
 5025:              - uploading new scan data
 5026: 
 5027:  Arguments:
 5028:   $r          - The Apache request object
 5029:   $file2grade - name of the file that contain the scanned data to score
 5030: 
 5031: =cut
 5032: 
 5033: sub scantron_selectphase {
 5034:     my ($r,$file2grade) = @_;
 5035:     my ($symb)=&get_symb($r);
 5036:     if (!$symb) {return '';}
 5037:     my $sequence_selector=&getSequenceDropDown($symb);
 5038:     my $default_form_data=&defaultFormData($symb);
 5039:     my $grading_menu_button=&show_grading_menu_form($symb);
 5040:     my $file_selector=&scantron_uploads($file2grade);
 5041:     my $format_selector=&scantron_scantab();
 5042:     my $CODE_selector=&scantron_CODElist();
 5043:     my $CODE_unique=&scantron_CODEunique();
 5044:     my $result;
 5045: 
 5046:     $ssi_error = 0;
 5047: 
 5048:     # Chunk of form to prompt for a file to grade and how:
 5049: 
 5050:     $result.= '
 5051:     <br />
 5052:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5053:     <input type="hidden" name="command" value="scantron_warning" />
 5054:     '.$default_form_data.'
 5055:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5056:        '.&Apache::loncommon::start_data_table_header_row().'
 5057:             <th colspan="2">
 5058:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5059:             </th>
 5060:        '.&Apache::loncommon::end_data_table_header_row().'
 5061:        '.&Apache::loncommon::start_data_table_row().'
 5062:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5063:        '.&Apache::loncommon::end_data_table_row().'
 5064:        '.&Apache::loncommon::start_data_table_row().'
 5065:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5066:        '.&Apache::loncommon::end_data_table_row().'
 5067:        '.&Apache::loncommon::start_data_table_row().'
 5068:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5069:        '.&Apache::loncommon::end_data_table_row().'
 5070:        '.&Apache::loncommon::start_data_table_row().'
 5071:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5072:        '.&Apache::loncommon::end_data_table_row().'
 5073:        '.&Apache::loncommon::start_data_table_row().'
 5074:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5075:        '.&Apache::loncommon::end_data_table_row().'
 5076:        '.&Apache::loncommon::start_data_table_row().'
 5077: 	    <td> '.&mt('Options:').' </td>
 5078:             <td>
 5079: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5080:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5081:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5082: 	    </td>
 5083:        '.&Apache::loncommon::end_data_table_row().'
 5084:        '.&Apache::loncommon::start_data_table_row().'
 5085:             <td colspan="2">
 5086:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5087:             </td>
 5088:        '.&Apache::loncommon::end_data_table_row().'
 5089:     '.&Apache::loncommon::end_data_table().'
 5090:     </form>
 5091: ';
 5092:    
 5093:     $r->print($result);
 5094: 
 5095:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5096:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5097: 
 5098: 	# Chunk of form to prompt for a scantron file upload.
 5099: 
 5100:         $r->print('
 5101:     <br />
 5102:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5103:        '.&Apache::loncommon::start_data_table_header_row().'
 5104:             <th>
 5105:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5106:             </th>
 5107:        '.&Apache::loncommon::end_data_table_header_row().'
 5108:        '.&Apache::loncommon::start_data_table_row().'
 5109:             <td>
 5110: ');
 5111:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5112:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5113:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5114:     $r->print('
 5115:               <script type="text/javascript" language="javascript">
 5116:     function checkUpload(formname) {
 5117: 	if (formname.upfile.value == "") {
 5118: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5119: 	    return false;
 5120: 	}
 5121: 	formname.submit();
 5122:     }
 5123:               </script>
 5124: 
 5125:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5126:                 '.$default_form_data.'
 5127:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5128:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5129:                 <input name="command" value="scantronupload_save" type="hidden" />
 5130:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5131:                 <br />
 5132:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5133:               </form>
 5134: ');
 5135: 
 5136:         $r->print('
 5137:             </td>
 5138:        '.&Apache::loncommon::end_data_table_row().'
 5139:        '.&Apache::loncommon::end_data_table().'
 5140: ');
 5141:     }
 5142: 
 5143:     # Chunk of the form that prompts to view a scoring office file,
 5144:     # corrected file, skipped records in a file.
 5145: 
 5146:     $r->print('
 5147:    <br />
 5148:    <form action="/adm/grades" name="scantron_download">
 5149:      '.$default_form_data.'
 5150:      <input type="hidden" name="command" value="scantron_download" />
 5151:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5152:        '.&Apache::loncommon::start_data_table_header_row().'
 5153:               <th>
 5154:                 &nbsp;'.&mt('Download a scoring office file').'
 5155:               </th>
 5156:        '.&Apache::loncommon::end_data_table_header_row().'
 5157:        '.&Apache::loncommon::start_data_table_row().'
 5158:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5159:                 <br />
 5160:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5161:        '.&Apache::loncommon::end_data_table_row().'
 5162:      '.&Apache::loncommon::end_data_table().'
 5163:    </form>
 5164:    <br />
 5165: ');
 5166: 
 5167:     &Apache::lonpickcode::code_list($r,2);
 5168: 
 5169:     $r->print('<br /><form method="post" name="checkscantron">'.
 5170:              $default_form_data."\n".
 5171:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5172:              &Apache::loncommon::start_data_table_header_row()."\n".
 5173:              '<th colspan="2">
 5174:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5175:              '</th>'."\n".
 5176:               &Apache::loncommon::end_data_table_header_row()."\n".
 5177:               &Apache::loncommon::start_data_table_row()."\n".
 5178:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5179:               '<td> '.$sequence_selector.' </td>'.
 5180:               &Apache::loncommon::end_data_table_row()."\n".
 5181:               &Apache::loncommon::start_data_table_row()."\n".
 5182:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5183:               '<td> '.$file_selector.' </td>'."\n".
 5184:               &Apache::loncommon::end_data_table_row()."\n".
 5185:               &Apache::loncommon::start_data_table_row()."\n".
 5186:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5187:               '<td> '.$format_selector.' </td>'."\n".
 5188:               &Apache::loncommon::end_data_table_row()."\n".
 5189:               &Apache::loncommon::start_data_table_row()."\n".
 5190:               '<td> '.&mt('Options').' </td>'."\n".
 5191:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5192:               &Apache::loncommon::end_data_table_row()."\n".
 5193:               &Apache::loncommon::start_data_table_row()."\n".
 5194:               '<td colspan="2">'."\n".
 5195:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5196:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5197:               '</td>'."\n".
 5198:               &Apache::loncommon::end_data_table_row()."\n".
 5199:               &Apache::loncommon::end_data_table()."\n".
 5200:               '</form><br />');
 5201:     $r->print($grading_menu_button);
 5202:     return;
 5203: }
 5204: 
 5205: =pod
 5206: 
 5207: =item get_scantron_config
 5208: 
 5209:    Parse and return the scantron configuration line selected as a
 5210:    hash of configuration file fields.
 5211: 
 5212:  Arguments:
 5213:     which - the name of the configuration to parse from the file.
 5214: 
 5215: 
 5216:  Returns:
 5217:             If the named configuration is not in the file, an empty
 5218:             hash is returned.
 5219:     a hash with the fields
 5220:       name         - internal name for the this configuration setup
 5221:       description  - text to display to operator that describes this config
 5222:       CODElocation - if 0 or the string 'none'
 5223:                           - no CODE exists for this config
 5224:                      if -1 || the string 'letter'
 5225:                           - a CODE exists for this config and is
 5226:                             a string of letters
 5227:                      Unsupported value (but planned for future support)
 5228:                           if a positive integer
 5229:                                - The CODE exists as the first n items from
 5230:                                  the question section of the form
 5231:                           if the string 'number'
 5232:                                - The CODE exists for this config and is
 5233:                                  a string of numbers
 5234:       CODEstart   - (only matter if a CODE exists) column in the line where
 5235:                      the CODE starts
 5236:       CODElength  - length of the CODE
 5237:       IDstart     - column where the student/employee ID number starts
 5238:       IDlength    - length of the student/employee ID info
 5239:       Qstart      - column where the information from the bubbled
 5240:                     'questions' start
 5241:       Qlength     - number of columns comprising a single bubble line from
 5242:                     the sheet. (usually either 1 or 10)
 5243:       Qon         - either a single character representing the character used
 5244:                     to signal a bubble was chosen in the positional setup, or
 5245:                     the string 'letter' if the letter of the chosen bubble is
 5246:                     in the final, or 'number' if a number representing the
 5247:                     chosen bubble is in the file (1->A 0->J)
 5248:       Qoff        - the character used to represent that a bubble was
 5249:                     left blank
 5250:       PaperID     - if the scanning process generates a unique number for each
 5251:                     sheet scanned the column that this ID number starts in
 5252:       PaperIDlength - number of columns that comprise the unique ID number
 5253:                       for the sheet of paper
 5254:       FirstName   - column that the first name starts in
 5255:       FirstNameLength - number of columns that the first name spans
 5256:  
 5257:       LastName    - column that the last name starts in
 5258:       LastNameLength - number of columns that the last name spans
 5259: 
 5260: =cut
 5261: 
 5262: sub get_scantron_config {
 5263:     my ($which) = @_;
 5264:     my @lines = &get_scantronformat_file();
 5265:     my %config;
 5266:     #FIXME probably should move to XML it has already gotten a bit much now
 5267:     foreach my $line (@lines) {
 5268: 	my ($name,$descrip)=split(/:/,$line);
 5269: 	if ($name ne $which ) { next; }
 5270: 	chomp($line);
 5271: 	my @config=split(/:/,$line);
 5272: 	$config{'name'}=$config[0];
 5273: 	$config{'description'}=$config[1];
 5274: 	$config{'CODElocation'}=$config[2];
 5275: 	$config{'CODEstart'}=$config[3];
 5276: 	$config{'CODElength'}=$config[4];
 5277: 	$config{'IDstart'}=$config[5];
 5278: 	$config{'IDlength'}=$config[6];
 5279: 	$config{'Qstart'}=$config[7];
 5280:  	$config{'Qlength'}=$config[8];
 5281: 	$config{'Qoff'}=$config[9];
 5282: 	$config{'Qon'}=$config[10];
 5283: 	$config{'PaperID'}=$config[11];
 5284: 	$config{'PaperIDlength'}=$config[12];
 5285: 	$config{'FirstName'}=$config[13];
 5286: 	$config{'FirstNamelength'}=$config[14];
 5287: 	$config{'LastName'}=$config[15];
 5288: 	$config{'LastNamelength'}=$config[16];
 5289: 	last;
 5290:     }
 5291:     return %config;
 5292: }
 5293: 
 5294: =pod 
 5295: 
 5296: =item username_to_idmap
 5297: 
 5298:     creates a hash keyed by student/employee ID with values of the corresponding
 5299:     student username:domain.
 5300: 
 5301:   Arguments:
 5302: 
 5303:     $classlist - reference to the class list hash. This is a hash
 5304:                  keyed by student name:domain  whose elements are references
 5305:                  to arrays containing various chunks of information
 5306:                  about the student. (See loncoursedata for more info).
 5307: 
 5308:   Returns
 5309:     %idmap - the constructed hash
 5310: 
 5311: =cut
 5312: 
 5313: sub username_to_idmap {
 5314:     my ($classlist)= @_;
 5315:     my %idmap;
 5316:     foreach my $student (keys(%$classlist)) {
 5317: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5318: 	    $student;
 5319:     }
 5320:     return %idmap;
 5321: }
 5322: 
 5323: =pod
 5324: 
 5325: =item scantron_fixup_scanline
 5326: 
 5327:    Process a requested correction to a scanline.
 5328: 
 5329:   Arguments:
 5330:     $scantron_config   - hash from &get_scantron_config()
 5331:     $scan_data         - hash of correction information 
 5332:                           (see &scantron_getfile())
 5333:     $line              - existing scanline
 5334:     $whichline         - line number of the passed in scanline
 5335:     $field             - type of change to process 
 5336:                          (either 
 5337:                           'ID'     -> correct the student/employee ID number
 5338:                           'CODE'   -> correct the CODE
 5339:                           'answer' -> fixup the submitted answers)
 5340:     
 5341:    $args               - hash of additional info,
 5342:                           - 'ID' 
 5343:                                'newid' -> studentID to use in replacement
 5344:                                           of existing one
 5345:                           - 'CODE' 
 5346:                                'CODE_ignore_dup' - set to true if duplicates
 5347:                                                    should be ignored.
 5348: 	                       'CODE' - is new code or 'use_unfound'
 5349:                                         if the existing unfound code should
 5350:                                         be used as is
 5351:                           - 'answer'
 5352:                                'response' - new answer or 'none' if blank
 5353:                                'question' - the bubble line to change
 5354:                                'questionnum' - the question identifier,
 5355:                                                may include subquestion. 
 5356: 
 5357:   Returns:
 5358:     $line - the modified scanline
 5359: 
 5360:   Side effects: 
 5361:     $scan_data - may be updated
 5362: 
 5363: =cut
 5364: 
 5365: 
 5366: sub scantron_fixup_scanline {
 5367:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5368:     if ($field eq 'ID') {
 5369: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5370: 	    return ($line,1,'New value too large');
 5371: 	}
 5372: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5373: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5374: 				     $args->{'newid'});
 5375: 	}
 5376: 	substr($line,$$scantron_config{'IDstart'}-1,
 5377: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5378: 	if ($args->{'newid'}=~/^\s*$/) {
 5379: 	    &scan_data($scan_data,"$whichline.user",
 5380: 		       $args->{'username'}.':'.$args->{'domain'});
 5381: 	}
 5382:     } elsif ($field eq 'CODE') {
 5383: 	if ($args->{'CODE_ignore_dup'}) {
 5384: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5385: 	}
 5386: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5387: 	if ($args->{'CODE'} ne 'use_unfound') {
 5388: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5389: 		return ($line,1,'New CODE value too large');
 5390: 	    }
 5391: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5392: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5393: 	    }
 5394: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5395: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5396: 	}
 5397:     } elsif ($field eq 'answer') {
 5398: 	my $length=$scantron_config->{'Qlength'};
 5399: 	my $off=$scantron_config->{'Qoff'};
 5400: 	my $on=$scantron_config->{'Qon'};
 5401: 	my $answer=${off}x$length;
 5402: 	if ($args->{'response'} eq 'none') {
 5403: 	    &scan_data($scan_data,
 5404: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5405: 	} else {
 5406: 	    if ($on eq 'letter') {
 5407: 		my @alphabet=('A'..'Z');
 5408: 		$answer=$alphabet[$args->{'response'}];
 5409: 	    } elsif ($on eq 'number') {
 5410: 		$answer=$args->{'response'}+1;
 5411: 		if ($answer == 10) { $answer = '0'; }
 5412: 	    } else {
 5413: 		substr($answer,$args->{'response'},1)=$on;
 5414: 	    }
 5415: 	    &scan_data($scan_data,
 5416: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5417: 	}
 5418: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5419: 	substr($line,$where-1,$length)=$answer;
 5420:     }
 5421:     return $line;
 5422: }
 5423: 
 5424: =pod
 5425: 
 5426: =item scan_data
 5427: 
 5428:     Edit or look up  an item in the scan_data hash.
 5429: 
 5430:   Arguments:
 5431:     $scan_data  - The hash (see scantron_getfile)
 5432:     $key        - shorthand of the key to edit (actual key is
 5433:                   scantronfilename_key).
 5434:     $data        - New value of the hash entry.
 5435:     $delete      - If true, the entry is removed from the hash.
 5436: 
 5437:   Returns:
 5438:     The new value of the hash table field (undefined if deleted).
 5439: 
 5440: =cut
 5441: 
 5442: 
 5443: sub scan_data {
 5444:     my ($scan_data,$key,$value,$delete)=@_;
 5445:     my $filename=$env{'form.scantron_selectfile'};
 5446:     if (defined($value)) {
 5447: 	$scan_data->{$filename.'_'.$key} = $value;
 5448:     }
 5449:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5450:     return $scan_data->{$filename.'_'.$key};
 5451: }
 5452: 
 5453: # ----- These first few routines are general use routines.----
 5454: 
 5455: # Return the number of occurences of a pattern in a string.
 5456: 
 5457: sub occurence_count {
 5458:     my ($string, $pattern) = @_;
 5459: 
 5460:     my @matches = ($string =~ /$pattern/g);
 5461: 
 5462:     return scalar(@matches);
 5463: }
 5464: 
 5465: 
 5466: # Take a string known to have digits and convert all the
 5467: # digits into letters in the range J,A..I.
 5468: 
 5469: sub digits_to_letters {
 5470:     my ($input) = @_;
 5471: 
 5472:     my @alphabet = ('J', 'A'..'I');
 5473: 
 5474:     my @input    = split(//, $input);
 5475:     my $output ='';
 5476:     for (my $i = 0; $i < scalar(@input); $i++) {
 5477: 	if ($input[$i] =~ /\d/) {
 5478: 	    $output .= $alphabet[$input[$i]];
 5479: 	} else {
 5480: 	    $output .= $input[$i];
 5481: 	}
 5482:     }
 5483:     return $output;
 5484: }
 5485: 
 5486: =pod 
 5487: 
 5488: =item scantron_parse_scanline
 5489: 
 5490:   Decodes a scanline from the selected scantron file
 5491: 
 5492:  Arguments:
 5493:     line             - The text of the scantron file line to process
 5494:     whichline        - Line number
 5495:     scantron_config  - Hash describing the format of the scantron lines.
 5496:     scan_data        - Hash of extra information about the scanline
 5497:                        (see scantron_getfile for more information)
 5498:     just_header      - True if should not process question answers but only
 5499:                        the stuff to the left of the answers.
 5500:  Returns:
 5501:    Hash containing the result of parsing the scanline
 5502: 
 5503:    Keys are all proceeded by the string 'scantron.'
 5504: 
 5505:        CODE    - the CODE in use for this scanline
 5506:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5507:                  by the operator
 5508:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5509:                             CODEs were selected, but the usage has been
 5510:                             forced by the operator
 5511:        ID  - student/employee ID
 5512:        PaperID - if used, the ID number printed on the sheet when the 
 5513:                  paper was scanned
 5514:        FirstName - first name from the sheet
 5515:        LastName  - last name from the sheet
 5516: 
 5517:      if just_header was not true these key may also exist
 5518: 
 5519:        missingerror - a list of bubble ranges that are considered to be answers
 5520:                       to a single question that don't have any bubbles filled in.
 5521:                       Of the form questionnumber:firstbubblenumber:count.
 5522:        doubleerror  - a list of bubble ranges that are considered to be answers
 5523:                       to a single question that have more than one bubble filled in.
 5524:                       Of the form questionnumber::firstbubblenumber:count
 5525:    
 5526:                 In the above, count is the number of bubble responses in the
 5527:                 input line needed to represent the possible answers to the question.
 5528:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5529:                 per line would have count = 2.
 5530: 
 5531:        maxquest     - the number of the last bubble line that was parsed
 5532: 
 5533:        (<number> starts at 1)
 5534:        <number>.answer - zero or more letters representing the selected
 5535:                          letters from the scanline for the bubble line 
 5536:                          <number>.
 5537:                          if blank there was either no bubble or there where
 5538:                          multiple bubbles, (consult the keys missingerror and
 5539:                          doubleerror if this is an error condition)
 5540: 
 5541: =cut
 5542: 
 5543: sub scantron_parse_scanline {
 5544:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5545: 
 5546:     my %record;
 5547:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5548:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5549:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5550:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5551: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5552: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5553: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5554: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5555: 	    $record{'scantron.CODE'}=substr($data,
 5556: 					    $$scantron_config{'CODEstart'}-1,
 5557: 					    $$scantron_config{'CODElength'});
 5558: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5559: 		$record{'scantron.useCODE'}=1;
 5560: 	    }
 5561: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5562: 		$record{'scantron.CODE_ignore_dup'}=1;
 5563: 	    }
 5564: 	} else {
 5565: 	    #FIXME interpret first N questions
 5566: 	}
 5567:     }
 5568:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5569: 				  $$scantron_config{'IDlength'});
 5570:     $record{'scantron.PaperID'}=
 5571: 	substr($data,$$scantron_config{'PaperID'}-1,
 5572: 	       $$scantron_config{'PaperIDlength'});
 5573:     $record{'scantron.FirstName'}=
 5574: 	substr($data,$$scantron_config{'FirstName'}-1,
 5575: 	       $$scantron_config{'FirstNamelength'});
 5576:     $record{'scantron.LastName'}=
 5577: 	substr($data,$$scantron_config{'LastName'}-1,
 5578: 	       $$scantron_config{'LastNamelength'});
 5579:     if ($just_header) { return \%record; }
 5580: 
 5581:     my @alphabet=('A'..'Z');
 5582:     my $questnum=0;
 5583:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5584: 
 5585:     chomp($questions);		# Get rid of any trailing \n.
 5586:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5587:     while (length($questions)) {
 5588: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5589:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5590:                              || 1;
 5591:         $questnum++;
 5592:         my $quest_id = $questnum;
 5593:         my $currentquest = substr($questions,0,$answer_length);
 5594:         $questions       = substr($questions,$answer_length);
 5595:         if (length($currentquest) < $answer_length) { next; }
 5596: 
 5597:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5598:             my $subquestnum = 1;
 5599:             my $subquestions = $currentquest;
 5600:             my @subanswers_needed = 
 5601:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5602:             foreach my $subans (@subanswers_needed) {
 5603:                 my $subans_length =
 5604:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5605:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5606:                 $subquestions   = substr($subquestions,$subans_length);
 5607:                 $quest_id = "$questnum.$subquestnum";
 5608:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5609:                     ($$scantron_config{'Qon'} eq 'number')) {
 5610:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5611:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5612:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5613:                 } else {
 5614:                     $ansnum = &scantron_validator_positional($ansnum,
 5615:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5616:                 }
 5617:                 $subquestnum ++;
 5618:             }
 5619:         } else {
 5620:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5621:                 ($$scantron_config{'Qon'} eq 'number')) {
 5622:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5623:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5624:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5625:             } else {
 5626:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5627:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5628:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5629:             }
 5630:         }
 5631:     }
 5632:     $record{'scantron.maxquest'}=$questnum;
 5633:     return \%record;
 5634: }
 5635: 
 5636: sub scantron_validator_lettnum {
 5637:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5638:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5639: 
 5640:     # Qon 'letter' implies for each slot in currquest we have:
 5641:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5642:     #    about anything else (esp. a value of Qoff) for missing
 5643:     #    bubbles.
 5644:     #
 5645:     # Qon 'number' implies each slot gives a digit that indexes the
 5646:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5647:     #    and * or ? for double bubbles on a single line.
 5648:     #
 5649: 
 5650:     my $matchon;
 5651:     if ($$scantron_config{'Qon'} eq 'letter') {
 5652:         $matchon = '[A-Z]';
 5653:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5654:         $matchon = '\d';
 5655:     }
 5656:     my $occurrences = 0;
 5657:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5658:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5659:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5660:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5661:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5662:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5663:         my @singlelines = split('',$currquest);
 5664:         foreach my $entry (@singlelines) {
 5665:             $occurrences = &occurence_count($entry,$matchon);
 5666:             if ($occurrences > 1) {
 5667:                 last;
 5668:             }
 5669:         } 
 5670:     } else {
 5671:         $occurrences = &occurence_count($currquest,$matchon); 
 5672:     }
 5673:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5674:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5675:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5676:             my $bubble = substr($currquest,$ans,1);
 5677:             if ($bubble =~ /$matchon/ ) {
 5678:                 if ($$scantron_config{'Qon'} eq 'number') {
 5679:                     if ($bubble == 0) {
 5680:                         $bubble = 10; 
 5681:                     }
 5682:                     $record->{"scantron.$ansnum.answer"} = 
 5683:                         $alphabet->[$bubble-1];
 5684:                 } else {
 5685:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5686:                 }
 5687:             } else {
 5688:                 $record->{"scantron.$ansnum.answer"}='';
 5689:             }
 5690:             $ansnum++;
 5691:         }
 5692:     } elsif (!defined($currquest)
 5693:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5694:             || (&occurence_count($currquest,$matchon) == 0)) {
 5695:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5696:             $record->{"scantron.$ansnum.answer"}='';
 5697:             $ansnum++;
 5698:         }
 5699:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5700:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5701:         }
 5702:     } else {
 5703:         if ($$scantron_config{'Qon'} eq 'number') {
 5704:             $currquest = &digits_to_letters($currquest);            
 5705:         }
 5706:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5707:             my $bubble = substr($currquest,$ans,1);
 5708:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5709:             $ansnum++;
 5710:         }
 5711:     }
 5712:     return $ansnum;
 5713: }
 5714: 
 5715: sub scantron_validator_positional {
 5716:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5717:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5718: 
 5719:     # Otherwise there's a positional notation;
 5720:     # each bubble line requires Qlength items, and there are filled in
 5721:     # bubbles for each case where there 'Qon' characters.
 5722:     #
 5723: 
 5724:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5725: 
 5726:     # If the split only gives us one element.. the full length of the
 5727:     # answer string, no bubbles are filled in:
 5728: 
 5729:     if ($answers_needed eq '') {
 5730:         return;
 5731:     }
 5732: 
 5733:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5734:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5735:             $record->{"scantron.$ansnum.answer"}='';
 5736:             $ansnum++;
 5737:         }
 5738:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5739:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5740:         }
 5741:     } elsif (scalar(@array) == 2) {
 5742:         my $location = length($array[0]);
 5743:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5744:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5745:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5746:             if ($ans eq $line_num) {
 5747:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5748:             } else {
 5749:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5750:             }
 5751:             $ansnum++;
 5752:          }
 5753:     } else {
 5754:         #  If there's more than one instance of a bubble character
 5755:         #  That's a double bubble; with positional notation we can
 5756:         #  record all the bubbles filled in as well as the
 5757:         #  fact this response consists of multiple bubbles.
 5758:         #
 5759:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5760:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5761:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5762:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5763:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5764:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5765:             my $doubleerror = 0;
 5766:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5767:                    (!$doubleerror)) {
 5768:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5769:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5770:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5771:                if (length(@currarray) > 2) {
 5772:                    $doubleerror = 1;
 5773:                } 
 5774:             }
 5775:             if ($doubleerror) {
 5776:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5777:             }
 5778:         } else {
 5779:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5780:         }
 5781:         my $item = $ansnum;
 5782:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5783:             $record->{"scantron.$item.answer"} = '';
 5784:             $item ++;
 5785:         }
 5786: 
 5787:         my @ans=@array;
 5788:         my $i=0;
 5789:         my $increment = 0;
 5790:         while ($#ans) {
 5791:             $i+=length($ans[0]) + $increment;
 5792:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5793:             my $bubble = $i%$$scantron_config{'Qlength'};
 5794:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5795:             shift(@ans);
 5796:             $increment = 1;
 5797:         }
 5798:         $ansnum += $answers_needed;
 5799:     }
 5800:     return $ansnum;
 5801: }
 5802: 
 5803: =pod
 5804: 
 5805: =item scantron_add_delay
 5806: 
 5807:    Adds an error message that occurred during the grading phase to a
 5808:    queue of messages to be shown after grading pass is complete
 5809: 
 5810:  Arguments:
 5811:    $delayqueue  - arrary ref of hash ref of error messages
 5812:    $scanline    - the scanline that caused the error
 5813:    $errormesage - the error message
 5814:    $errorcode   - a numeric code for the error
 5815: 
 5816:  Side Effects:
 5817:    updates the $delayqueue to have a new hash ref of the error
 5818: 
 5819: =cut
 5820: 
 5821: sub scantron_add_delay {
 5822:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5823:     push(@$delayqueue,
 5824: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5825: 	  'ecode' => $errorcode }
 5826: 	 );
 5827: }
 5828: 
 5829: =pod
 5830: 
 5831: =item scantron_find_student
 5832: 
 5833:    Finds the username for the current scanline
 5834: 
 5835:   Arguments:
 5836:    $scantron_record - hash result from scantron_parse_scanline
 5837:    $scan_data       - hash of correction information 
 5838:                       (see &scantron_getfile() form more information)
 5839:    $idmap           - hash from &username_to_idmap()
 5840:    $line            - number of current scanline
 5841:  
 5842:   Returns:
 5843:    Either 'username:domain' or undef if unknown
 5844: 
 5845: =cut
 5846: 
 5847: sub scantron_find_student {
 5848:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5849:     my $scanID=$$scantron_record{'scantron.ID'};
 5850:     if ($scanID =~ /^\s*$/) {
 5851:  	return &scan_data($scan_data,"$line.user");
 5852:     }
 5853:     foreach my $id (keys(%$idmap)) {
 5854:  	if (lc($id) eq lc($scanID)) {
 5855:  	    return $$idmap{$id};
 5856:  	}
 5857:     }
 5858:     return undef;
 5859: }
 5860: 
 5861: =pod
 5862: 
 5863: =item scantron_filter
 5864: 
 5865:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5866:    hidden resources was selected
 5867: 
 5868: =cut
 5869: 
 5870: sub scantron_filter {
 5871:     my ($curres)=@_;
 5872: 
 5873:     if (ref($curres) && $curres->is_problem()) {
 5874: 	# if the user has asked to not have either hidden
 5875: 	# or 'randomout' controlled resources to be graded
 5876: 	# don't include them
 5877: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5878: 	    && $curres->randomout) {
 5879: 	    return 0;
 5880: 	}
 5881: 	return 1;
 5882:     }
 5883:     return 0;
 5884: }
 5885: 
 5886: =pod
 5887: 
 5888: =item scantron_process_corrections
 5889: 
 5890:    Gets correction information out of submitted form data and corrects
 5891:    the scanline
 5892: 
 5893: =cut
 5894: 
 5895: sub scantron_process_corrections {
 5896:     my ($r) = @_;
 5897:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5898:     my ($scanlines,$scan_data)=&scantron_getfile();
 5899:     my $classlist=&Apache::loncoursedata::get_classlist();
 5900:     my $which=$env{'form.scantron_line'};
 5901:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5902:     my ($skip,$err,$errmsg);
 5903:     if ($env{'form.scantron_skip_record'}) {
 5904: 	$skip=1;
 5905:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5906: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5907: 	    $env{'form.scantron_domain'};
 5908: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5909: 	($line,$err,$errmsg)=
 5910: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5911: 				     'ID',{'newid'=>$newid,
 5912: 				    'username'=>$env{'form.scantron_username'},
 5913: 				    'domain'=>$env{'form.scantron_domain'}});
 5914:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5915: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5916: 	my $newCODE;
 5917: 	my %args;
 5918: 	if      ($resolution eq 'use_unfound') {
 5919: 	    $newCODE='use_unfound';
 5920: 	} elsif ($resolution eq 'use_found') {
 5921: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5922: 	} elsif ($resolution eq 'use_typed') {
 5923: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5924: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5925: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5926: 	}
 5927: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5928: 	    $args{'CODE_ignore_dup'}=1;
 5929: 	}
 5930: 	$args{'CODE'}=$newCODE;
 5931: 	($line,$err,$errmsg)=
 5932: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5933: 				     'CODE',\%args);
 5934:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5935: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5936: 	    ($line,$err,$errmsg)=
 5937: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5938: 					 $which,'answer',
 5939: 					 { 'question'=>$question,
 5940: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5941:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5942: 	    if ($err) { last; }
 5943: 	}
 5944:     }
 5945:     if ($err) {
 5946: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5947:     } else {
 5948: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5949: 	&scantron_putfile($scanlines,$scan_data);
 5950:     }
 5951: }
 5952: 
 5953: =pod
 5954: 
 5955: =item reset_skipping_status
 5956: 
 5957:    Forgets the current set of remember skipped scanlines (and thus
 5958:    reverts back to considering all lines in the
 5959:    scantron_skipped_<filename> file)
 5960: 
 5961: =cut
 5962: 
 5963: sub reset_skipping_status {
 5964:     my ($scanlines,$scan_data)=&scantron_getfile();
 5965:     &scan_data($scan_data,'remember_skipping',undef,1);
 5966:     &scantron_putfile(undef,$scan_data);
 5967: }
 5968: 
 5969: =pod
 5970: 
 5971: =item start_skipping
 5972: 
 5973:    Marks a scanline to be skipped. 
 5974: 
 5975: =cut
 5976: 
 5977: sub start_skipping {
 5978:     my ($scan_data,$i)=@_;
 5979:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5980:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5981: 	$remembered{$i}=2;
 5982:     } else {
 5983: 	$remembered{$i}=1;
 5984:     }
 5985:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5986: }
 5987: 
 5988: =pod
 5989: 
 5990: =item should_be_skipped
 5991: 
 5992:    Checks whether a scanline should be skipped.
 5993: 
 5994: =cut
 5995: 
 5996: sub should_be_skipped {
 5997:     my ($scanlines,$scan_data,$i)=@_;
 5998:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5999: 	# not redoing old skips
 6000: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6001: 	return 0;
 6002:     }
 6003:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6004: 
 6005:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6006: 	return 0;
 6007:     }
 6008:     return 1;
 6009: }
 6010: 
 6011: =pod
 6012: 
 6013: =item remember_current_skipped
 6014: 
 6015:    Discovers what scanlines are in the scantron_skipped_<filename>
 6016:    file and remembers them into scan_data for later use.
 6017: 
 6018: =cut
 6019: 
 6020: sub remember_current_skipped {
 6021:     my ($scanlines,$scan_data)=&scantron_getfile();
 6022:     my %to_remember;
 6023:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6024: 	if ($scanlines->{'skipped'}[$i]) {
 6025: 	    $to_remember{$i}=1;
 6026: 	}
 6027:     }
 6028: 
 6029:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6030:     &scantron_putfile(undef,$scan_data);
 6031: }
 6032: 
 6033: =pod
 6034: 
 6035: =item check_for_error
 6036: 
 6037:     Checks if there was an error when attempting to remove a specific
 6038:     scantron_.. bubble sheet data file. Prints out an error if
 6039:     something went wrong.
 6040: 
 6041: =cut
 6042: 
 6043: sub check_for_error {
 6044:     my ($r,$result)=@_;
 6045:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6046: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6047:     }
 6048: }
 6049: 
 6050: =pod
 6051: 
 6052: =item scantron_warning_screen
 6053: 
 6054:    Interstitial screen to make sure the operator has selected the
 6055:    correct options before we start the validation phase.
 6056: 
 6057: =cut
 6058: 
 6059: sub scantron_warning_screen {
 6060:     my ($button_text)=@_;
 6061:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6062:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6063:     my $CODElist;
 6064:     if ($scantron_config{'CODElocation'} &&
 6065: 	$scantron_config{'CODEstart'} &&
 6066: 	$scantron_config{'CODElength'}) {
 6067: 	$CODElist=$env{'form.scantron_CODElist'};
 6068: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6069: 	$CODElist=
 6070: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6071: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6072:     }
 6073:     return ('
 6074: <p>
 6075: <span class="LC_warning">
 6076: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6077: </p>
 6078: <table>
 6079: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6080: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6081: '.$CODElist.'
 6082: </table>
 6083: <br />
 6084: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6085: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6086: 
 6087: <br />
 6088: ');
 6089: }
 6090: 
 6091: =pod
 6092: 
 6093: =item scantron_do_warning
 6094: 
 6095:    Check if the operator has picked something for all required
 6096:    fields. Error out if something is missing.
 6097: 
 6098: =cut
 6099: 
 6100: sub scantron_do_warning {
 6101:     my ($r)=@_;
 6102:     my ($symb)=&get_symb($r);
 6103:     if (!$symb) {return '';}
 6104:     my $default_form_data=&defaultFormData($symb);
 6105:     $r->print(&scantron_form_start().$default_form_data);
 6106:     if ( $env{'form.selectpage'} eq '' ||
 6107: 	 $env{'form.scantron_selectfile'} eq '' ||
 6108: 	 $env{'form.scantron_format'} eq '' ) {
 6109: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6110: 	if ( $env{'form.selectpage'} eq '') {
 6111: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6112: 	} 
 6113: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6114: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6115: 	} 
 6116: 	if ( $env{'form.scantron_format'} eq '') {
 6117: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6118: 	} 
 6119:     } else {
 6120: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6121: 	$r->print('
 6122: '.$warning.'
 6123: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6124: <input type="hidden" name="command" value="scantron_validate" />
 6125: ');
 6126:     }
 6127:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6128:     return '';
 6129: }
 6130: 
 6131: =pod
 6132: 
 6133: =item scantron_form_start
 6134: 
 6135:     html hidden input for remembering all selected grading options
 6136: 
 6137: =cut
 6138: 
 6139: sub scantron_form_start {
 6140:     my ($max_bubble)=@_;
 6141:     my $result= <<SCANTRONFORM;
 6142: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6143:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6144:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6145:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6146:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6147:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6148:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6149:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6150:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6151:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6152: SCANTRONFORM
 6153: 
 6154:   my $line = 0;
 6155:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6156:        my $chunk =
 6157: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6158:        $chunk .=
 6159: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6160:        $chunk .= 
 6161:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6162:        $chunk .=
 6163:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6164:        $result .= $chunk;
 6165:        $line++;
 6166:    }
 6167:     return $result;
 6168: }
 6169: 
 6170: =pod
 6171: 
 6172: =item scantron_validate_file
 6173: 
 6174:     Dispatch routine for doing validation of a bubble sheet data file.
 6175: 
 6176:     Also processes any necessary information resets that need to
 6177:     occur before validation begins (ignore previous corrections,
 6178:     restarting the skipped records processing)
 6179: 
 6180: =cut
 6181: 
 6182: sub scantron_validate_file {
 6183:     my ($r) = @_;
 6184:     my ($symb)=&get_symb($r);
 6185:     if (!$symb) {return '';}
 6186:     my $default_form_data=&defaultFormData($symb);
 6187:     
 6188:     # do the detection of only doing skipped records first befroe we delete
 6189:     # them when doing the corrections reset
 6190:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6191: 	&reset_skipping_status();
 6192:     }
 6193:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6194: 	&remember_current_skipped();
 6195: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6196:     }
 6197: 
 6198:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6199: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6200: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6201: 	&check_for_error($r,&scantron_remove_scan_data());
 6202: 	$env{'form.scantron_options_ignore'}='done';
 6203:     }
 6204: 
 6205:     if ($env{'form.scantron_corrections'}) {
 6206: 	&scantron_process_corrections($r);
 6207:     }
 6208:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6209:     #get the student pick code ready
 6210:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6211:     my $max_bubble=&scantron_get_maxbubble();
 6212:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6213:     $r->print($result);
 6214:     
 6215:     my @validate_phases=( 'sequence',
 6216: 			  'ID',
 6217: 			  'CODE',
 6218: 			  'doublebubble',
 6219: 			  'missingbubbles');
 6220:     if (!$env{'form.validatepass'}) {
 6221: 	$env{'form.validatepass'} = 0;
 6222:     }
 6223:     my $currentphase=$env{'form.validatepass'};
 6224: 
 6225: 
 6226:     my $stop=0;
 6227:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6228: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6229: 	$r->rflush();
 6230: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6231: 	{
 6232: 	    no strict 'refs';
 6233: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6234: 	}
 6235:     }
 6236:     if (!$stop) {
 6237: 	my $warning=&scantron_warning_screen('Start Grading');
 6238: 	$r->print(&mt('Validation process complete.').'<br />'.
 6239:                   $warning.
 6240:                   &mt('Perform verification for each student after storage of submissions?').
 6241:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6242:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6243:                   ('&nbsp;'x3).'<label>'.
 6244:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6245:                   '</label></span><br />'.
 6246:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6247:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6248:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6249:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6250:     } else {
 6251: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6252: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6253:     }
 6254:     if ($stop) {
 6255: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6256: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6257: 	    $r->print(' '.&mt('this error').' <br />');
 6258: 
 6259: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6260: 	} else {
 6261:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6262: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6263:             } else {
 6264:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6265:             }
 6266: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6267: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6268: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6269: 	}
 6270:     }
 6271:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6272:     return '';
 6273: }
 6274: 
 6275: 
 6276: =pod
 6277: 
 6278: =item scantron_remove_file
 6279: 
 6280:    Removes the requested bubble sheet data file, makes sure that
 6281:    scantron_original_<filename> is never removed
 6282: 
 6283: 
 6284: =cut
 6285: 
 6286: sub scantron_remove_file {
 6287:     my ($which)=@_;
 6288:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6289:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6290:     my $file='scantron_';
 6291:     if ($which eq 'corrected' || $which eq 'skipped') {
 6292: 	$file.=$which.'_';
 6293:     } else {
 6294: 	return 'refused';
 6295:     }
 6296:     $file.=$env{'form.scantron_selectfile'};
 6297:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6298: }
 6299: 
 6300: 
 6301: =pod
 6302: 
 6303: =item scantron_remove_scan_data
 6304: 
 6305:    Removes all scan_data correction for the requested bubble sheet
 6306:    data file.  (In the case that both the are doing skipped records we need
 6307:    to remember the old skipped lines for the time being so that element
 6308:    persists for a while.)
 6309: 
 6310: =cut
 6311: 
 6312: sub scantron_remove_scan_data {
 6313:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6314:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6315:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6316:     my @todelete;
 6317:     my $filename=$env{'form.scantron_selectfile'};
 6318:     foreach my $key (@keys) {
 6319: 	if ($key=~/^\Q$filename\E_/) {
 6320: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6321: 		$key=~/remember_skipping/) {
 6322: 		next;
 6323: 	    }
 6324: 	    push(@todelete,$key);
 6325: 	}
 6326:     }
 6327:     my $result;
 6328:     if (@todelete) {
 6329: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6330: 				       \@todelete,$cdom,$cname);
 6331:     } else {
 6332: 	$result = 'ok';
 6333:     }
 6334:     return $result;
 6335: }
 6336: 
 6337: 
 6338: =pod
 6339: 
 6340: =item scantron_getfile
 6341: 
 6342:     Fetches the requested bubble sheet data file (all 3 versions), and
 6343:     the scan_data hash
 6344:   
 6345:   Arguments:
 6346:     None
 6347: 
 6348:   Returns:
 6349:     2 hash references
 6350: 
 6351:      - first one has 
 6352:          orig      -
 6353:          corrected -
 6354:          skipped   -  each of which points to an array ref of the specified
 6355:                       file broken up into individual lines
 6356:          count     - number of scanlines
 6357:  
 6358:      - second is the scan_data hash possible keys are
 6359:        ($number refers to scanline numbered $number and thus the key affects
 6360:         only that scanline
 6361:         $bubline refers to the specific bubble line element and the aspects
 6362:         refers to that specific bubble line element)
 6363: 
 6364:        $number.user - username:domain to use
 6365:        $number.CODE_ignore_dup 
 6366:                     - ignore the duplicate CODE error 
 6367:        $number.useCODE
 6368:                     - use the CODE in the scanline as is
 6369:        $number.no_bubble.$bubline
 6370:                     - it is valid that there is no bubbled in bubble
 6371:                       at $number $bubline
 6372:        remember_skipping
 6373:                     - a frozen hash containing keys of $number and values
 6374:                       of either 
 6375:                         1 - we are on a 'do skipped records pass' and plan
 6376:                             on processing this line
 6377:                         2 - we are on a 'do skipped records pass' and this
 6378:                             scanline has been marked to skip yet again
 6379: 
 6380: =cut
 6381: 
 6382: sub scantron_getfile {
 6383:     #FIXME really would prefer a scantron directory
 6384:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6385:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6386:     my $lines;
 6387:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6388: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6389:     my %scanlines;
 6390:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6391:     my $temp=$scanlines{'orig'};
 6392:     $scanlines{'count'}=$#$temp;
 6393: 
 6394:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6395: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6396:     if ($lines eq '-1') {
 6397: 	$scanlines{'corrected'}=[];
 6398:     } else {
 6399: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6400:     }
 6401:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6402: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6403:     if ($lines eq '-1') {
 6404: 	$scanlines{'skipped'}=[];
 6405:     } else {
 6406: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6407:     }
 6408:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6409:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6410:     my %scan_data = @tmp;
 6411:     return (\%scanlines,\%scan_data);
 6412: }
 6413: 
 6414: =pod
 6415: 
 6416: =item lonnet_putfile
 6417: 
 6418:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6419: 
 6420:  Arguments:
 6421:    $contents - data to store
 6422:    $filename - filename to store $contents into
 6423: 
 6424:  Returns:
 6425:    result value from &Apache::lonnet::finishuserfileupload
 6426: 
 6427: =cut
 6428: 
 6429: sub lonnet_putfile {
 6430:     my ($contents,$filename)=@_;
 6431:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6432:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6433:     $env{'form.sillywaytopassafilearound'}=$contents;
 6434:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6435: 
 6436: }
 6437: 
 6438: =pod
 6439: 
 6440: =item scantron_putfile
 6441: 
 6442:     Stores the current version of the bubble sheet data files, and the
 6443:     scan_data hash. (Does not modify the original version only the
 6444:     corrected and skipped versions.
 6445: 
 6446:  Arguments:
 6447:     $scanlines - hash ref that looks like the first return value from
 6448:                  &scantron_getfile()
 6449:     $scan_data - hash ref that looks like the second return value from
 6450:                  &scantron_getfile()
 6451: 
 6452: =cut
 6453: 
 6454: sub scantron_putfile {
 6455:     my ($scanlines,$scan_data) = @_;
 6456:     #FIXME really would prefer a scantron directory
 6457:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6459:     if ($scanlines) {
 6460: 	my $prefix='scantron_';
 6461: # no need to update orig, shouldn't change
 6462: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6463: #		    $env{'form.scantron_selectfile'});
 6464: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6465: 			$prefix.'corrected_'.
 6466: 			$env{'form.scantron_selectfile'});
 6467: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6468: 			$prefix.'skipped_'.
 6469: 			$env{'form.scantron_selectfile'});
 6470:     }
 6471:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6472: }
 6473: 
 6474: =pod
 6475: 
 6476: =item scantron_get_line
 6477: 
 6478:    Returns the correct version of the scanline
 6479: 
 6480:  Arguments:
 6481:     $scanlines - hash ref that looks like the first return value from
 6482:                  &scantron_getfile()
 6483:     $scan_data - hash ref that looks like the second return value from
 6484:                  &scantron_getfile()
 6485:     $i         - number of the requested line (starts at 0)
 6486: 
 6487:  Returns:
 6488:    A scanline, (either the original or the corrected one if it
 6489:    exists), or undef if the requested scanline should be
 6490:    skipped. (Either because it's an skipped scanline, or it's an
 6491:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6492:    pass.
 6493: 
 6494: =cut
 6495: 
 6496: sub scantron_get_line {
 6497:     my ($scanlines,$scan_data,$i)=@_;
 6498:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6499:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6500:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6501:     return $scanlines->{'orig'}[$i]; 
 6502: }
 6503: 
 6504: =pod
 6505: 
 6506: =item scantron_todo_count
 6507: 
 6508:     Counts the number of scanlines that need processing.
 6509: 
 6510:  Arguments:
 6511:     $scanlines - hash ref that looks like the first return value from
 6512:                  &scantron_getfile()
 6513:     $scan_data - hash ref that looks like the second return value from
 6514:                  &scantron_getfile()
 6515: 
 6516:  Returns:
 6517:     $count - number of scanlines to process
 6518: 
 6519: =cut
 6520: 
 6521: sub get_todo_count {
 6522:     my ($scanlines,$scan_data)=@_;
 6523:     my $count=0;
 6524:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6525: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6526: 	if ($line=~/^[\s\cz]*$/) { next; }
 6527: 	$count++;
 6528:     }
 6529:     return $count;
 6530: }
 6531: 
 6532: =pod
 6533: 
 6534: =item scantron_put_line
 6535: 
 6536:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6537:     data file.
 6538: 
 6539:  Arguments:
 6540:     $scanlines - hash ref that looks like the first return value from
 6541:                  &scantron_getfile()
 6542:     $scan_data - hash ref that looks like the second return value from
 6543:                  &scantron_getfile()
 6544:     $i         - line number to update
 6545:     $newline   - contents of the updated scanline
 6546:     $skip      - if true make the line for skipping and update the
 6547:                  'skipped' file
 6548: 
 6549: =cut
 6550: 
 6551: sub scantron_put_line {
 6552:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6553:     if ($skip) {
 6554: 	$scanlines->{'skipped'}[$i]=$newline;
 6555: 	&start_skipping($scan_data,$i);
 6556: 	return;
 6557:     }
 6558:     $scanlines->{'corrected'}[$i]=$newline;
 6559: }
 6560: 
 6561: =pod
 6562: 
 6563: =item scantron_clear_skip
 6564: 
 6565:    Remove a line from the 'skipped' file
 6566: 
 6567:  Arguments:
 6568:     $scanlines - hash ref that looks like the first return value from
 6569:                  &scantron_getfile()
 6570:     $scan_data - hash ref that looks like the second return value from
 6571:                  &scantron_getfile()
 6572:     $i         - line number to update
 6573: 
 6574: =cut
 6575: 
 6576: sub scantron_clear_skip {
 6577:     my ($scanlines,$scan_data,$i)=@_;
 6578:     if (exists($scanlines->{'skipped'}[$i])) {
 6579: 	undef($scanlines->{'skipped'}[$i]);
 6580: 	return 1;
 6581:     }
 6582:     return 0;
 6583: }
 6584: 
 6585: =pod
 6586: 
 6587: =item scantron_filter_not_exam
 6588: 
 6589:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6590:    filter out resources that are not marked as 'exam' mode
 6591: 
 6592: =cut
 6593: 
 6594: sub scantron_filter_not_exam {
 6595:     my ($curres)=@_;
 6596:     
 6597:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6598: 	# if the user has asked to not have either hidden
 6599: 	# or 'randomout' controlled resources to be graded
 6600: 	# don't include them
 6601: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6602: 	    && $curres->randomout) {
 6603: 	    return 0;
 6604: 	}
 6605: 	return 1;
 6606:     }
 6607:     return 0;
 6608: }
 6609: 
 6610: =pod
 6611: 
 6612: =item scantron_validate_sequence
 6613: 
 6614:     Validates the selected sequence, checking for resource that are
 6615:     not set to exam mode.
 6616: 
 6617: =cut
 6618: 
 6619: sub scantron_validate_sequence {
 6620:     my ($r,$currentphase) = @_;
 6621: 
 6622:     my $navmap=Apache::lonnavmaps::navmap->new();
 6623:     my (undef,undef,$sequence)=
 6624: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6625: 
 6626:     my $map=$navmap->getResourceByUrl($sequence);
 6627: 
 6628:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6629:                                     value="ignore" />');
 6630:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6631: 	my @resources=
 6632: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6633: 	if (@resources) {
 6634: 	    $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>");
 6635: 	    return (1,$currentphase);
 6636: 	}
 6637:     }
 6638: 
 6639:     return (0,$currentphase+1);
 6640: }
 6641: 
 6642: 
 6643: 
 6644: sub scantron_validate_ID {
 6645:     my ($r,$currentphase) = @_;
 6646:     
 6647:     #get student info
 6648:     my $classlist=&Apache::loncoursedata::get_classlist();
 6649:     my %idmap=&username_to_idmap($classlist);
 6650: 
 6651:     #get scantron line setup
 6652:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6653:     my ($scanlines,$scan_data)=&scantron_getfile();
 6654:     
 6655:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6656: 
 6657:     my %found=('ids'=>{},'usernames'=>{});
 6658:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6659: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6660: 	if ($line=~/^[\s\cz]*$/) { next; }
 6661: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6662: 						 $scan_data);
 6663: 	my $id=$$scan_record{'scantron.ID'};
 6664: 	my $found;
 6665: 	foreach my $checkid (keys(%idmap)) {
 6666: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6667: 	}
 6668: 	if ($found) {
 6669: 	    my $username=$idmap{$found};
 6670: 	    if ($found{'ids'}{$found}) {
 6671: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6672: 					 $line,'duplicateID',$found);
 6673: 		return(1,$currentphase);
 6674: 	    } elsif ($found{'usernames'}{$username}) {
 6675: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6676: 					 $line,'duplicateID',$username);
 6677: 		return(1,$currentphase);
 6678: 	    }
 6679: 	    #FIXME store away line we previously saw the ID on to use above
 6680: 	    $found{'ids'}{$found}++;
 6681: 	    $found{'usernames'}{$username}++;
 6682: 	} else {
 6683: 	    if ($id =~ /^\s*$/) {
 6684: 		my $username=&scan_data($scan_data,"$i.user");
 6685: 		if (defined($username) && $found{'usernames'}{$username}) {
 6686: 		    &scantron_get_correction($r,$i,$scan_record,
 6687: 					     \%scantron_config,
 6688: 					     $line,'duplicateID',$username);
 6689: 		    return(1,$currentphase);
 6690: 		} elsif (!defined($username)) {
 6691: 		    &scantron_get_correction($r,$i,$scan_record,
 6692: 					     \%scantron_config,
 6693: 					     $line,'incorrectID');
 6694: 		    return(1,$currentphase);
 6695: 		}
 6696: 		$found{'usernames'}{$username}++;
 6697: 	    } else {
 6698: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6699: 					 $line,'incorrectID');
 6700: 		return(1,$currentphase);
 6701: 	    }
 6702: 	}
 6703:     }
 6704: 
 6705:     return (0,$currentphase+1);
 6706: }
 6707: 
 6708: 
 6709: sub scantron_get_correction {
 6710:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6711: #FIXME in the case of a duplicated ID the previous line, probably need
 6712: #to show both the current line and the previous one and allow skipping
 6713: #the previous one or the current one
 6714: 
 6715:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6716: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6717: 			    " for PaperID <tt>[_1]</tt>",
 6718: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6719:     } else {
 6720: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6721: 			    " in scanline [_1] <pre>[_2]</pre>",
 6722: 			    $i,$line)."</p> \n");
 6723:     }
 6724:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6725: 			  "The name on the paper is [_2],[_3]",
 6726: 			  $$scan_record{'scantron.ID'},
 6727: 			  $$scan_record{'scantron.LastName'},
 6728: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6729: 
 6730:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6731:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6732:                            # Array populated for doublebubble or
 6733:     my @lines_to_correct;  # missingbubble errors to build javascript
 6734:                            # to validate radio button checking   
 6735: 
 6736:     if ($error =~ /ID$/) {
 6737: 	if ($error eq 'incorrectID') {
 6738: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6739: 		      "</p>\n");
 6740: 	} elsif ($error eq 'duplicateID') {
 6741: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6742: 	}
 6743: 	$r->print($message);
 6744: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6745: 	$r->print("\n<ul><li> ");
 6746: 	#FIXME it would be nice if this sent back the user ID and
 6747: 	#could do partial userID matches
 6748: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6749: 				       'scantron_username','scantron_domain'));
 6750: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6751: 	$r->print("\n@".
 6752: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6753: 
 6754: 	$r->print('</li>');
 6755:     } elsif ($error =~ /CODE$/) {
 6756: 	if ($error eq 'incorrectCODE') {
 6757: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6758: 	} elsif ($error eq 'duplicateCODE') {
 6759: 	    $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");
 6760: 	}
 6761: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6762: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6763: 	$r->print($message);
 6764: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6765: 	$r->print("\n<br /> ");
 6766: 	my $i=0;
 6767: 	if ($error eq 'incorrectCODE' 
 6768: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6769: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6770: 	    if ($closest > 0) {
 6771: 		foreach my $testcode (@{$closest}) {
 6772: 		    my $checked='';
 6773: 		    if (!$i) { $checked=' checked="checked" '; }
 6774: 		    $r->print("
 6775:    <label>
 6776:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6777:        ".&mt("Use the similar CODE [_1] instead.",
 6778: 	    "<b><tt>".$testcode."</tt></b>")."
 6779:     </label>
 6780:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6781: 		    $r->print("\n<br />");
 6782: 		    $i++;
 6783: 		}
 6784: 	    }
 6785: 	}
 6786: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6787: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6788: 	    $r->print("
 6789:     <label>
 6790:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6791:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6792: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6793:     </label>");
 6794: 	    $r->print("\n<br />");
 6795: 	}
 6796: 
 6797: 	$r->print(<<ENDSCRIPT);
 6798: <script type="text/javascript">
 6799: function change_radio(field) {
 6800:     var slct=document.scantronupload.scantron_CODE_resolution;
 6801:     var i;
 6802:     for (i=0;i<slct.length;i++) {
 6803:         if (slct[i].value==field) { slct[i].checked=true; }
 6804:     }
 6805: }
 6806: </script>
 6807: ENDSCRIPT
 6808: 	my $href="/adm/pickcode?".
 6809: 	   "form=".&escape("scantronupload").
 6810: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6811: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6812: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6813: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6814: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6815: 	    $r->print("
 6816:     <label>
 6817:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6818:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6819: 	     "<a target='_blank' href='$href'>","</a>")."
 6820:     </label> 
 6821:     ".&mt("Selected CODE is [_1]",'<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
 6822: 	    $r->print("\n<br />");
 6823: 	}
 6824: 	$r->print("
 6825:     <label>
 6826:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6827:        ".&mt("Use [_1] as the CODE.",
 6828: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6829: 	$r->print("\n<br /><br />");
 6830:     } elsif ($error eq 'doublebubble') {
 6831: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6832: 
 6833: 	# The form field scantron_questions is acutally a list of line numbers.
 6834: 	# represented by this form so:
 6835: 
 6836: 	my $line_list = &questions_to_line_list($arg);
 6837: 
 6838: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6839: 		  $line_list.'" />');
 6840: 	$r->print($message);
 6841: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6842: 	foreach my $question (@{$arg}) {
 6843: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6844:                                                    $scan_record, $error);
 6845:             push(@lines_to_correct,@linenums);
 6846: 	}
 6847:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6848:     } elsif ($error eq 'missingbubble') {
 6849: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6850: 	$r->print($message);
 6851: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6852: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6853: 
 6854: 	# The form field scantron_questions is actually a list of line numbers not
 6855: 	# a list of question numbers. Therefore:
 6856: 	#
 6857: 	
 6858: 	my $line_list = &questions_to_line_list($arg);
 6859: 
 6860: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6861: 		  $line_list.'" />');
 6862: 	foreach my $question (@{$arg}) {
 6863: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6864:                                                    $scan_record, $error);
 6865:             push(@lines_to_correct,@linenums);
 6866: 	}
 6867:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6868:     } else {
 6869: 	$r->print("\n<ul>");
 6870:     }
 6871:     $r->print("\n</li></ul>");
 6872: }
 6873: 
 6874: sub verify_bubbles_checked {
 6875:     my (@ansnums) = @_;
 6876:     my $ansnumstr = join('","',@ansnums);
 6877:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6878:     my $output = (<<ENDSCRIPT);
 6879: <script type="text/javascript">
 6880: function verify_bubble_radio(form) {
 6881:     var ansnumArray = new Array ("$ansnumstr");
 6882:     var need_bubble_count = 0;
 6883:     for (var i=0; i<ansnumArray.length; i++) {
 6884:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6885:             var bubble_picked = 0; 
 6886:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6887:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6888:                     bubble_picked = 1;
 6889:                 }
 6890:             }
 6891:             if (bubble_picked == 0) {
 6892:                 need_bubble_count ++;
 6893:             }
 6894:         }
 6895:     }
 6896:     if (need_bubble_count) {
 6897:         alert("$warning");
 6898:         return;
 6899:     }
 6900:     form.submit(); 
 6901: }
 6902: </script>
 6903: ENDSCRIPT
 6904:     return $output;
 6905: }
 6906: 
 6907: =pod
 6908: 
 6909: =item  questions_to_line_list
 6910: 
 6911: Converts a list of questions into a string of comma separated
 6912: line numbers in the answer sheet used by the questions.  This is
 6913: used to fill in the scantron_questions form field.
 6914: 
 6915:   Arguments:
 6916:      questions    - Reference to an array of questions.
 6917: 
 6918: =cut
 6919: 
 6920: 
 6921: sub questions_to_line_list {
 6922:     my ($questions) = @_;
 6923:     my @lines;
 6924: 
 6925:     foreach my $item (@{$questions}) {
 6926:         my $question = $item;
 6927:         my ($first,$count,$last);
 6928:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6929:             $question = $1;
 6930:             my $subquestion = $2;
 6931:             $first = $first_bubble_line{$question-1} + 1;
 6932:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6933:             my $subcount = 1;
 6934:             while ($subcount<$subquestion) {
 6935:                 $first += $subans[$subcount-1];
 6936:                 $subcount ++;
 6937:             }
 6938:             $count = $subans[$subquestion-1];
 6939:         } else {
 6940: 	    $first   = $first_bubble_line{$question-1} + 1;
 6941: 	    $count   = $bubble_lines_per_response{$question-1};
 6942:         }
 6943:         $last = $first+$count-1;
 6944:         push(@lines, ($first..$last));
 6945:     }
 6946:     return join(',', @lines);
 6947: }
 6948: 
 6949: =pod 
 6950: 
 6951: =item prompt_for_corrections
 6952: 
 6953: Prompts for a potentially multiline correction to the
 6954: user's bubbling (factors out common code from scantron_get_correction
 6955: for multi and missing bubble cases).
 6956: 
 6957:  Arguments:
 6958:    $r           - Apache request object.
 6959:    $question    - The question number to prompt for.
 6960:    $scan_config - The scantron file configuration hash.
 6961:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6962:    $error       - Type of error
 6963: 
 6964:  Implicit inputs:
 6965:    %bubble_lines_per_response   - Starting line numbers for each question.
 6966:                                   Numbered from 0 (but question numbers are from
 6967:                                   1.
 6968:    %first_bubble_line           - Starting bubble line for each question.
 6969:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6970:                                   type problems render as separate sub-questions, 
 6971:                                   in exam mode. This hash contains a 
 6972:                                   comma-separated list of the lines per 
 6973:                                   sub-question.
 6974:    %responsetype_per_response   - essayresponse, formularesponse,
 6975:                                   stringresponse, imageresponse, reactionresponse,
 6976:                                   and organicresponse type problem parts can have
 6977:                                   multiple lines per response if the weight
 6978:                                   assigned exceeds 10.  In this case, only
 6979:                                   one bubble per line is permitted, but more 
 6980:                                   than one line might contain bubbles, e.g.
 6981:                                   bubbling of: line 1 - J, line 2 - J, 
 6982:                                   line 3 - B would assign 22 points.  
 6983: 
 6984: =cut
 6985: 
 6986: sub prompt_for_corrections {
 6987:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6988:     my ($current_line,$lines);
 6989:     my @linenums;
 6990:     my $questionnum = $question;
 6991:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6992:         $question = $1;
 6993:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6994:         my $subquestion = $2;
 6995:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6996:         my $subcount = 1;
 6997:         while ($subcount<$subquestion) {
 6998:             $current_line += $subans[$subcount-1];
 6999:             $subcount ++;
 7000:         }
 7001:         $lines = $subans[$subquestion-1];
 7002:     } else {
 7003:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7004:         $lines        = $bubble_lines_per_response{$question-1};
 7005:     }
 7006:     if ($lines > 1) {
 7007:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7008:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7009:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7010:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7011:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7012:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7013:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7014:             $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 />');
 7015:         } else {
 7016:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7017:         }
 7018:     }
 7019:     for (my $i =0; $i < $lines; $i++) {
 7020:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7021: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7022: 	        		  $questionnum,$error,split('', $selected));
 7023:         push(@linenums,$current_line);
 7024: 	$current_line++;
 7025:     }
 7026:     if ($lines > 1) {
 7027: 	$r->print("<hr /><br />");
 7028:     }
 7029:     return @linenums;
 7030: }
 7031: 
 7032: =pod
 7033: 
 7034: =item scantron_bubble_selector
 7035:   
 7036:    Generates the html radiobuttons to correct a single bubble line
 7037:    possibly showing the existing the selected bubbles if known
 7038: 
 7039:  Arguments:
 7040:     $r           - Apache request object
 7041:     $scan_config - hash from &get_scantron_config()
 7042:     $line        - Number of the line being displayed.
 7043:     $questionnum - Question number (may include subquestion)
 7044:     $error       - Type of error.
 7045:     @selected    - Array of bubbles picked on this line.
 7046: 
 7047: =cut
 7048: 
 7049: sub scantron_bubble_selector {
 7050:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7051:     my $max=$$scan_config{'Qlength'};
 7052: 
 7053:     my $scmode=$$scan_config{'Qon'};
 7054:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7055: 
 7056:     my @alphabet=('A'..'Z');
 7057:     $r->print(&Apache::loncommon::start_data_table().
 7058:               &Apache::loncommon::start_data_table_row());
 7059:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7060:     for (my $i=0;$i<$max+1;$i++) {
 7061: 	$r->print("\n".'<td align="center">');
 7062: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7063: 	else { $r->print('&nbsp;'); }
 7064: 	$r->print('</td>');
 7065:     }
 7066:     $r->print(&Apache::loncommon::end_data_table_row().
 7067:               &Apache::loncommon::start_data_table_row());
 7068:     for (my $i=0;$i<$max;$i++) {
 7069: 	$r->print("\n".
 7070: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7071: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7072:     }
 7073:     my $nobub_checked = ' ';
 7074:     if ($error eq 'missingbubble') {
 7075:         $nobub_checked = ' checked = "checked" ';
 7076:     }
 7077:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7078: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7079:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7080:               $line.'" value="'.$questionnum.'" /></td>');
 7081:     $r->print(&Apache::loncommon::end_data_table_row().
 7082:               &Apache::loncommon::end_data_table());
 7083: }
 7084: 
 7085: =pod
 7086: 
 7087: =item num_matches
 7088: 
 7089:    Counts the number of characters that are the same between the two arguments.
 7090: 
 7091:  Arguments:
 7092:    $orig - CODE from the scanline
 7093:    $code - CODE to match against
 7094: 
 7095:  Returns:
 7096:    $count - integer count of the number of same characters between the
 7097:             two arguments
 7098: 
 7099: =cut
 7100: 
 7101: sub num_matches {
 7102:     my ($orig,$code) = @_;
 7103:     my @code=split(//,$code);
 7104:     my @orig=split(//,$orig);
 7105:     my $same=0;
 7106:     for (my $i=0;$i<scalar(@code);$i++) {
 7107: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7108:     }
 7109:     return $same;
 7110: }
 7111: 
 7112: =pod
 7113: 
 7114: =item scantron_get_closely_matching_CODEs
 7115: 
 7116:    Cycles through all CODEs and finds the set that has the greatest
 7117:    number of same characters as the provided CODE
 7118: 
 7119:  Arguments:
 7120:    $allcodes - hash ref returned by &get_codes()
 7121:    $CODE     - CODE from the current scanline
 7122: 
 7123:  Returns:
 7124:    2 element list
 7125:     - first elements is number of how closely matching the best fit is 
 7126:       (5 means best set has 5 matching characters)
 7127:     - second element is an arrary ref containing the set of valid CODEs
 7128:       that best fit the passed in CODE
 7129: 
 7130: =cut
 7131: 
 7132: sub scantron_get_closely_matching_CODEs {
 7133:     my ($allcodes,$CODE)=@_;
 7134:     my @CODEs;
 7135:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7136: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7137:     }
 7138: 
 7139:     return ($#CODEs,$CODEs[-1]);
 7140: }
 7141: 
 7142: =pod
 7143: 
 7144: =item get_codes
 7145: 
 7146:    Builds a hash which has keys of all of the valid CODEs from the selected
 7147:    set of remembered CODEs.
 7148: 
 7149:  Arguments:
 7150:   $old_name - name of the set of remembered CODEs
 7151:   $cdom     - domain of the course
 7152:   $cnum     - internal course name
 7153: 
 7154:  Returns:
 7155:   %allcodes - keys are the valid CODEs, values are all 1
 7156: 
 7157: =cut
 7158: 
 7159: sub get_codes {
 7160:     my ($old_name, $cdom, $cnum) = @_;
 7161:     if (!$old_name) {
 7162: 	$old_name=$env{'form.scantron_CODElist'};
 7163:     }
 7164:     if (!$cdom) {
 7165: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7166:     }
 7167:     if (!$cnum) {
 7168: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7169:     }
 7170:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7171: 				    $cdom,$cnum);
 7172:     my %allcodes;
 7173:     if ($result{"type\0$old_name"} eq 'number') {
 7174: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7175:     } else {
 7176: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7177:     }
 7178:     return %allcodes;
 7179: }
 7180: 
 7181: =pod
 7182: 
 7183: =item scantron_validate_CODE
 7184: 
 7185:    Validates all scanlines in the selected file to not have any
 7186:    invalid or underspecified CODEs and that none of the codes are
 7187:    duplicated if this was requested.
 7188: 
 7189: =cut
 7190: 
 7191: sub scantron_validate_CODE {
 7192:     my ($r,$currentphase) = @_;
 7193:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7194:     if ($scantron_config{'CODElocation'} &&
 7195: 	$scantron_config{'CODEstart'} &&
 7196: 	$scantron_config{'CODElength'}) {
 7197: 	if (!defined($env{'form.scantron_CODElist'})) {
 7198: 	    &FIXME_blow_up()
 7199: 	}
 7200:     } else {
 7201: 	return (0,$currentphase+1);
 7202:     }
 7203:     
 7204:     my %usedCODEs;
 7205: 
 7206:     my %allcodes=&get_codes();
 7207: 
 7208:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7209: 
 7210:     my ($scanlines,$scan_data)=&scantron_getfile();
 7211:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7212: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7213: 	if ($line=~/^[\s\cz]*$/) { next; }
 7214: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7215: 						 $scan_data);
 7216: 	my $CODE=$$scan_record{'scantron.CODE'};
 7217: 	my $error=0;
 7218: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7219: 	    &scantron_get_correction($r,$i,$scan_record,
 7220: 				     \%scantron_config,
 7221: 				     $line,'incorrectCODE',\%allcodes);
 7222: 	    return(1,$currentphase);
 7223: 	}
 7224: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7225: 	    && !$$scan_record{'scantron.useCODE'}) {
 7226: 	    &scantron_get_correction($r,$i,$scan_record,
 7227: 				     \%scantron_config,
 7228: 				     $line,'incorrectCODE',\%allcodes);
 7229: 	    return(1,$currentphase);
 7230: 	}
 7231: 	if (exists($usedCODEs{$CODE}) 
 7232: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7233: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7234: 	    &scantron_get_correction($r,$i,$scan_record,
 7235: 				     \%scantron_config,
 7236: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7237: 	    return(1,$currentphase);
 7238: 	}
 7239: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7240:     }
 7241:     return (0,$currentphase+1);
 7242: }
 7243: 
 7244: =pod
 7245: 
 7246: =item scantron_validate_doublebubble
 7247: 
 7248:    Validates all scanlines in the selected file to not have any
 7249:    bubble lines with multiple bubbles marked.
 7250: 
 7251: =cut
 7252: 
 7253: sub scantron_validate_doublebubble {
 7254:     my ($r,$currentphase) = @_;
 7255:     #get student info
 7256:     my $classlist=&Apache::loncoursedata::get_classlist();
 7257:     my %idmap=&username_to_idmap($classlist);
 7258: 
 7259:     #get scantron line setup
 7260:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7261:     my ($scanlines,$scan_data)=&scantron_getfile();
 7262:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7263: 
 7264:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7265: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7266: 	if ($line=~/^[\s\cz]*$/) { next; }
 7267: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7268: 						 $scan_data);
 7269: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7270: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7271: 				 'doublebubble',
 7272: 				 $$scan_record{'scantron.doubleerror'});
 7273:     	return (1,$currentphase);
 7274:     }
 7275:     return (0,$currentphase+1);
 7276: }
 7277: 
 7278: 
 7279: sub scantron_get_maxbubble {
 7280:     if (defined($env{'form.scantron_maxbubble'}) &&
 7281: 	$env{'form.scantron_maxbubble'}) {
 7282: 	&restore_bubble_lines();
 7283: 	return $env{'form.scantron_maxbubble'};
 7284:     }
 7285: 
 7286:     my (undef, undef, $sequence) =
 7287: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7288: 
 7289:     my $navmap=Apache::lonnavmaps::navmap->new();
 7290:     my $map=$navmap->getResourceByUrl($sequence);
 7291:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7292: 
 7293:     &Apache::lonxml::clear_problem_counter();
 7294: 
 7295:     my $uname       = $env{'user.name'};
 7296:     my $udom        = $env{'user.domain'};
 7297:     my $cid         = $env{'request.course.id'};
 7298:     my $total_lines = 0;
 7299:     %bubble_lines_per_response = ();
 7300:     %first_bubble_line         = ();
 7301:     %subdivided_bubble_lines   = ();
 7302:     %responsetype_per_response = ();
 7303: 
 7304:     my $response_number = 0;
 7305:     my $bubble_line     = 0;
 7306:     foreach my $resource (@resources) {
 7307:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7308:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7309: 	    foreach my $part_id (@{$parts}) {
 7310:                 my $lines;
 7311: 
 7312: 	        # TODO - make this a persistent hash not an array.
 7313: 
 7314:                 # optionresponse, matchresponse and rankresponse type items 
 7315:                 # render as separate sub-questions in exam mode.
 7316:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7317:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7318:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7319:                     my ($numbub,$numshown);
 7320:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7321:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7322:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7323:                         }
 7324:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7325:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7326:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7327:                         }
 7328:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7329:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7330:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7331:                         }
 7332:                     }
 7333:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7334:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7335:                     }
 7336:                     my $bubbles_per_line = 10;
 7337:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7338:                     if (($numbub % $bubbles_per_line) != 0) {
 7339:                         $inner_bubble_lines++;
 7340:                     }
 7341:                     for (my $i=0; $i<$numshown; $i++) {
 7342:                         $subdivided_bubble_lines{$response_number} .= 
 7343:                             $inner_bubble_lines.',';
 7344:                     }
 7345:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7346:                     $lines = $numshown * $inner_bubble_lines;
 7347:                 } else {
 7348:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7349:                 } 
 7350: 
 7351:                 $first_bubble_line{$response_number} = $bubble_line;
 7352: 	        $bubble_lines_per_response{$response_number} = $lines;
 7353:                 $responsetype_per_response{$response_number} = 
 7354:                     $analysis->{$part_id.'.type'};
 7355: 	        $response_number++;
 7356: 
 7357: 	        $bubble_line +=  $lines;
 7358: 	        $total_lines +=  $lines;
 7359: 	    }
 7360:         }
 7361:     }
 7362:     &Apache::lonnet::delenv('scantron.');
 7363: 
 7364:     &save_bubble_lines();
 7365:     $env{'form.scantron_maxbubble'} =
 7366: 	$total_lines;
 7367:     return $env{'form.scantron_maxbubble'};
 7368: }
 7369: 
 7370: sub scantron_validate_missingbubbles {
 7371:     my ($r,$currentphase) = @_;
 7372:     #get student info
 7373:     my $classlist=&Apache::loncoursedata::get_classlist();
 7374:     my %idmap=&username_to_idmap($classlist);
 7375: 
 7376:     #get scantron line setup
 7377:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7378:     my ($scanlines,$scan_data)=&scantron_getfile();
 7379:     my $max_bubble=&scantron_get_maxbubble();
 7380:     if (!$max_bubble) { $max_bubble=2**31; }
 7381:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7382: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7383: 	if ($line=~/^[\s\cz]*$/) { next; }
 7384: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7385: 						 $scan_data);
 7386: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7387: 	my @to_correct;
 7388: 	
 7389: 	# Probably here's where the error is...
 7390: 
 7391: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7392:             my $lastbubble;
 7393:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7394:                my $question = $1;
 7395:                my $subquestion = $2;
 7396:                if (!defined($first_bubble_line{$question -1})) { next; }
 7397:                my $first = $first_bubble_line{$question-1};
 7398:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7399:                my $subcount = 1;
 7400:                while ($subcount<$subquestion) {
 7401:                    $first += $subans[$subcount-1];
 7402:                    $subcount ++;
 7403:                }
 7404:                my $count = $subans[$subquestion-1];
 7405:                $lastbubble = $first + $count;
 7406:             } else {
 7407:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7408:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7409:             }
 7410:             if ($lastbubble > $max_bubble) { next; }
 7411: 	    push(@to_correct,$missing);
 7412: 	}
 7413: 	if (@to_correct) {
 7414: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7415: 				     $line,'missingbubble',\@to_correct);
 7416: 	    return (1,$currentphase);
 7417: 	}
 7418: 
 7419:     }
 7420:     return (0,$currentphase+1);
 7421: }
 7422: 
 7423: 
 7424: sub scantron_process_students {
 7425:     my ($r) = @_;
 7426: 
 7427:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7428:     my ($symb)=&get_symb($r);
 7429:     if (!$symb) {
 7430: 	return '';
 7431:     }
 7432:     my $default_form_data=&defaultFormData($symb);
 7433: 
 7434:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7435:     my ($scanlines,$scan_data)=&scantron_getfile();
 7436:     my $classlist=&Apache::loncoursedata::get_classlist();
 7437:     my %idmap=&username_to_idmap($classlist);
 7438:     my $navmap=Apache::lonnavmaps::navmap->new();
 7439:     my $map=$navmap->getResourceByUrl($sequence);
 7440:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7441:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7442:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7443:                             \%grader_randomlists_by_symb);
 7444:     foreach my $resource (@resources) {
 7445:         my $ressymb = $resource->symb();
 7446:         my ($analysis,$parts) =
 7447:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7448:                                       $env{'user.name'},$env{'user.domain'},1);
 7449:         $grader_partids_by_symb{$ressymb} = $parts;
 7450:         if (ref($analysis) eq 'HASH') {
 7451:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7452:                 $grader_randomlists_by_symb{$ressymb} = 
 7453:                     $analysis->{'parts_withrandomlist'};
 7454:             }
 7455:         }
 7456:     }
 7457: 
 7458:     my ($uname,$udom);
 7459:     my $result= <<SCANTRONFORM;
 7460: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7461:   <input type="hidden" name="command" value="scantron_configphase" />
 7462:   $default_form_data
 7463: SCANTRONFORM
 7464:     $r->print($result);
 7465: 
 7466:     my @delayqueue;
 7467:     my (%completedstudents,%scandata);
 7468:     
 7469:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7470:     my $count=&get_todo_count($scanlines,$scan_data);
 7471:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7472:  				    'Scantron Progress',$count,
 7473: 				    'inline',undef,'scantronupload');
 7474:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7475: 					  'Processing first student');
 7476:     $r->print('<br />');
 7477:     my $start=&Time::HiRes::time();
 7478:     my $i=-1;
 7479:     my $started;
 7480: 
 7481:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7482: 
 7483:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7484:     # the user and return.
 7485: 
 7486:     if ($ssi_error) {
 7487: 	$r->print("</form>");
 7488: 	&ssi_print_error($r);
 7489: 	$r->print(&show_grading_menu_form($symb));
 7490:         &Apache::lonnet::remove_lock($lock);
 7491: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7492:     }
 7493: 
 7494:     my %lettdig = &letter_to_digits();
 7495:     my $numletts = scalar(keys(%lettdig));
 7496: 
 7497:     while ($i<$scanlines->{'count'}) {
 7498:  	($uname,$udom)=('','');
 7499:  	$i++;
 7500:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7501:  	if ($line=~/^[\s\cz]*$/) { next; }
 7502: 	if ($started) {
 7503: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7504: 						     'last student');
 7505: 	}
 7506: 	$started=1;
 7507:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7508:  						 $scan_data);
 7509:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7510:  					      \%idmap,$i)) {
 7511:   	    &scantron_add_delay(\@delayqueue,$line,
 7512:  				'Unable to find a student that matches',1);
 7513:  	    next;
 7514:   	}
 7515:  	if (exists $completedstudents{$uname}) {
 7516:  	    &scantron_add_delay(\@delayqueue,$line,
 7517:  				'Student '.$uname.' has multiple sheets',2);
 7518:  	    next;
 7519:  	}
 7520:   	($uname,$udom)=split(/:/,$uname);
 7521: 
 7522:         my %partids_by_symb;
 7523:         foreach my $resource (@resources) {
 7524:             my $ressymb = $resource->symb();
 7525:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7526:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7527:                 my ($analysis,$parts) =
 7528:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7529:                 $partids_by_symb{$ressymb} = $parts;
 7530:             } else {
 7531:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7532:             }
 7533:         }
 7534: 
 7535: 	&Apache::lonxml::clear_problem_counter();
 7536:   	&Apache::lonnet::appenv($scan_record);
 7537: 
 7538: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7539: 	    &scantron_putfile($scanlines,$scan_data);
 7540: 	}
 7541: 	
 7542:         my $scancode;
 7543:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7544:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7545:             $scancode = $scan_record->{'scantron.CODE'};
 7546:         } else {
 7547:             $scancode = '';
 7548:         }
 7549: 
 7550:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7551:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7552:             $ssi_error = 0; # So end of handler error message does not trigger.
 7553:             $r->print("</form>");
 7554:             &ssi_print_error($r);
 7555:             $r->print(&show_grading_menu_form($symb));
 7556:             &Apache::lonnet::remove_lock($lock);
 7557:             return '';      # Why return ''?  Beats me.
 7558:         }
 7559: 
 7560: 	$completedstudents{$uname}={'line'=>$line};
 7561:         if ($env{'form.verifyrecord'}) {
 7562:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7563:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7564:             chomp($studentdata);
 7565:             $studentdata =~ s/\r$//;
 7566:             my $studentrecord = '';
 7567:             my $counter = -1;
 7568:             foreach my $resource (@resources) {
 7569:                 my $ressymb = $resource->symb();
 7570:                 ($counter,my $recording) =
 7571:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7572:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7573:                                              \%scantron_config,\%lettdig,$numletts);
 7574:                 $studentrecord .= $recording;
 7575:             }
 7576:             if ($studentrecord ne $studentdata) {
 7577:                 &Apache::lonxml::clear_problem_counter();
 7578:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7579:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7580:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7581:                     $r->print("</form>");
 7582:                     &ssi_print_error($r);
 7583:                     $r->print(&show_grading_menu_form($symb));
 7584:                     &Apache::lonnet::remove_lock($lock);
 7585:                     delete($completedstudents{$uname});
 7586:                     return '';
 7587:                 }
 7588:                 $counter = -1;
 7589:                 $studentrecord = '';
 7590:                 foreach my $resource (@resources) {
 7591:                     my $ressymb = $resource->symb();
 7592:                     ($counter,my $recording) =
 7593:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7594:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7595:                                                  \%scantron_config,\%lettdig,$numletts);
 7596:                     $studentrecord .= $recording;
 7597:                 }
 7598:                 if ($studentrecord ne $studentdata) {
 7599:                     $r->print('<p><span class="LC_error">');
 7600:                     if ($scancode eq '') {
 7601:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7602:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7603:                     } else {
 7604:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7605:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7606:                     }
 7607:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7608:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7609:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7610:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7611:                               &Apache::loncommon::start_data_table_row().
 7612:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7613:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7614:                               &Apache::loncommon::end_data_table_row().
 7615:                               &Apache::loncommon::start_data_table_row().
 7616:                               '<td>Stored submissions</td>'.
 7617:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7618:                               &Apache::loncommon::end_data_table_row().
 7619:                               &Apache::loncommon::end_data_table().'</p>');
 7620:                 } else {
 7621:                     $r->print('<br /><span class="LC_warning">'.
 7622:                              &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 />'.
 7623:                              &mt("As a consequence, this user's submission history records two tries.").
 7624:                                  '</span><br />');
 7625:                 }
 7626:             }
 7627:         }
 7628:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7629:     } continue {
 7630: 	&Apache::lonxml::clear_problem_counter();
 7631: 	&Apache::lonnet::delenv('scantron.');
 7632:     }
 7633:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7634:     &Apache::lonnet::remove_lock($lock);
 7635: #    my $lasttime = &Time::HiRes::time()-$start;
 7636: #    $r->print("<p>took $lasttime</p>");
 7637: 
 7638:     $r->print("</form>");
 7639:     $r->print(&show_grading_menu_form($symb));
 7640:     return '';
 7641: }
 7642: 
 7643: sub graders_resources_pass {
 7644:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7645:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7646:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7647:         foreach my $resource (@{$resources}) {
 7648:             my $ressymb = $resource->symb();
 7649:             my ($analysis,$parts) =
 7650:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7651:                                           $env{'user.name'},$env{'user.domain'},1);
 7652:             $grader_partids_by_symb->{$ressymb} = $parts;
 7653:             if (ref($analysis) eq 'HASH') {
 7654:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7655:                     $grader_randomlists_by_symb->{$ressymb} =
 7656:                         $analysis->{'parts_withrandomlist'};
 7657:                 }
 7658:             }
 7659:         }
 7660:     }
 7661:     return;
 7662: }
 7663: 
 7664: sub grade_student_bubbles {
 7665:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7666:     if (ref($resources) eq 'ARRAY') {
 7667:         my $count = 0;
 7668:         foreach my $resource (@{$resources}) {
 7669:             my $ressymb = $resource->symb();
 7670:             my %form = ('submitted'      => 'scantron',
 7671:                         'grade_target'   => 'grade',
 7672:                         'grade_username' => $uname,
 7673:                         'grade_domain'   => $udom,
 7674:                         'grade_courseid' => $env{'request.course.id'},
 7675:                         'grade_symb'     => $ressymb,
 7676:                         'CODE'           => $scancode
 7677:                        );
 7678:             if (ref($parts) eq 'HASH') {
 7679:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7680:                     foreach my $part (@{$parts->{$ressymb}}) {
 7681:                         $form{'scantron_questnum_start.'.$part} =
 7682:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7683:                         $count++;
 7684:                     }
 7685:                 }
 7686:             }
 7687:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7688:             return 'ssi_error' if ($ssi_error);
 7689:             last if (&Apache::loncommon::connection_aborted($r));
 7690:         }
 7691:     }
 7692:     return;
 7693: }
 7694: 
 7695: sub scantron_upload_scantron_data {
 7696:     my ($r)=@_;
 7697:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7698:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7699: 							  'domainid',
 7700: 							  'coursename');
 7701:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7702: 						   'domainid');
 7703:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7704:     $r->print('
 7705: <script type="text/javascript" language="javascript">
 7706:     function checkUpload(formname) {
 7707: 	if (formname.upfile.value == "") {
 7708: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 7709: 	    return false;
 7710: 	}
 7711: 	formname.submit();
 7712:     }
 7713: </script>
 7714: 
 7715: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7716: '.$default_form_data.'
 7717: <table>
 7718: <tr><td>'.$select_link.'                             </td></tr>
 7719: <tr><td>'.&mt('Course ID:').'     </td>
 7720:     <td><input name="courseid"   type="text" />      </td></tr>
 7721: <tr><td>'.&mt('Course Name:').'   </td>
 7722:     <td><input name="coursename" type="text" />      </td></tr>
 7723: <tr><td>'.&mt('Domain:').'        </td>
 7724:     <td>'.$domsel.'                                  </td></tr>
 7725: <tr><td>'.&mt('File to upload:').'</td>
 7726:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7727: </table>
 7728: <input name="command" value="scantronupload_save" type="hidden" />
 7729: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7730: </form>
 7731: ');
 7732:     return '';
 7733: }
 7734: 
 7735: 
 7736: sub scantron_upload_scantron_data_save {
 7737:     my($r)=@_;
 7738:     my ($symb)=&get_symb($r,1);
 7739:     my $doanotherupload=
 7740: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7741: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7742: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7743: 	'</form>'."\n";
 7744:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7745: 	!&Apache::lonnet::allowed('usc',
 7746: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7747: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7748: 	if ($symb) {
 7749: 	    $r->print(&show_grading_menu_form($symb));
 7750: 	} else {
 7751: 	    $r->print($doanotherupload);
 7752: 	}
 7753: 	return '';
 7754:     }
 7755:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7756:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7757:     my $fname=$env{'form.upfile.filename'};
 7758:     #FIXME
 7759:     #copied from lonnet::userfileupload()
 7760:     #make that function able to target a specified course
 7761:     # Replace Windows backslashes by forward slashes
 7762:     $fname=~s/\\/\//g;
 7763:     # Get rid of everything but the actual filename
 7764:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7765:     # Replace spaces by underscores
 7766:     $fname=~s/\s+/\_/g;
 7767:     # Replace all other weird characters by nothing
 7768:     $fname=~s/[^\w\.\-]//g;
 7769:     # See if there is anything left
 7770:     unless ($fname) { return 'error: no uploaded file'; }
 7771:     my $uploadedfile=$fname;
 7772:     $fname='scantron_orig_'.$fname;
 7773:     if (length($env{'form.upfile'}) < 2) {
 7774: 	$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>"));
 7775:     } else {
 7776: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7777: 	if ($result =~ m|^/uploaded/|) {
 7778: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7779: 			  (length($env{'form.upfile'})-1),
 7780: 			  '<span class="LC_filename">'.$result."</span>"));
 7781: 	} else {
 7782: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7783: 			  $result,
 7784: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7785: 
 7786: 	}
 7787:     }
 7788:     if ($symb) {
 7789: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7790:     } else {
 7791: 	$r->print($doanotherupload);
 7792:     }
 7793:     return '';
 7794: }
 7795: 
 7796: sub valid_file {
 7797:     my ($requested_file)=@_;
 7798:     foreach my $filename (sort(&scantron_filenames())) {
 7799: 	if ($requested_file eq $filename) { return 1; }
 7800:     }
 7801:     return 0;
 7802: }
 7803: 
 7804: sub scantron_download_scantron_data {
 7805:     my ($r)=@_;
 7806:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7807:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7808:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7809:     my $file=$env{'form.scantron_selectfile'};
 7810:     if (! &valid_file($file)) {
 7811: 	$r->print('
 7812: 	<p>
 7813: 	    '.&mt('The requested file name was invalid.').'
 7814:         </p>
 7815: ');
 7816: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7817: 	return;
 7818:     }
 7819:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7820:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7821:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7822:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7823:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7824:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7825:     $r->print('
 7826:     <p>
 7827: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7828: 	      '<a href="'.$orig.'">','</a>').'
 7829:     </p>
 7830:     <p>
 7831: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7832: 	      '<a href="'.$corrected.'">','</a>').'
 7833:     </p>
 7834:     <p>
 7835: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7836: 	      '<a href="'.$skipped.'">','</a>').'
 7837:     </p>
 7838: ');
 7839:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7840:     return '';
 7841: }
 7842: 
 7843: sub checkscantron_results {
 7844:     my ($r) = @_;
 7845:     my ($symb)=&get_symb($r);
 7846:     if (!$symb) {return '';}
 7847:     my $grading_menu_button=&show_grading_menu_form($symb);
 7848:     my $cid = $env{'request.course.id'};
 7849:     my %lettdig = &letter_to_digits();
 7850:     my $numletts = scalar(keys(%lettdig));
 7851:     my $cnum = $env{'course.'.$cid.'.num'};
 7852:     my $cdom = $env{'course.'.$cid.'.domain'};
 7853:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7854:     my %record;
 7855:     my %scantron_config =
 7856:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7857:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7858:     my $classlist=&Apache::loncoursedata::get_classlist();
 7859:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7860:     my $navmap=Apache::lonnavmaps::navmap->new();
 7861:     my $map=$navmap->getResourceByUrl($sequence);
 7862:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7863:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7864:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 7865: 
 7866:     my ($uname,$udom);
 7867:     my (%scandata,%lastname,%bylast);
 7868:     $r->print('
 7869: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7870: 
 7871:     my @delayqueue;
 7872:     my %completedstudents;
 7873: 
 7874:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7875:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7876:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7877:                                     'inline',undef,'checkscantron');
 7878:     my ($username,$domain,$started);
 7879: 
 7880:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7881: 
 7882:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7883:                                           'Processing first student');
 7884:     my $start=&Time::HiRes::time();
 7885:     my $i=-1;
 7886: 
 7887:     while ($i<$scanlines->{'count'}) {
 7888:         ($username,$domain,$uname)=('','','');
 7889:         $i++;
 7890:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7891:         if ($line=~/^[\s\cz]*$/) { next; }
 7892:         if ($started) {
 7893:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7894:                                                      'last student');
 7895:         }
 7896:         $started=1;
 7897:         my $scan_record=
 7898:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7899:                                                      $scan_data);
 7900:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7901:                                                               \%idmap,$i)) {
 7902:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7903:                                 'Unable to find a student that matches',1);
 7904:             next;
 7905:         }
 7906:         if (exists $completedstudents{$uname}) {
 7907:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7908:                                 'Student '.$uname.' has multiple sheets',2);
 7909:             next;
 7910:         }
 7911:         my $pid = $scan_record->{'scantron.ID'};
 7912:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7913:         push(@{$bylast{$lastname{$pid}}},$pid);
 7914:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7915:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7916:         chomp($scandata{$pid});
 7917:         $scandata{$pid} =~ s/\r$//;
 7918:         ($username,$domain)=split(/:/,$uname);
 7919:         my $counter = -1;
 7920:         foreach my $resource (@resources) {
 7921:             my $parts;
 7922:             my $ressymb = $resource->symb();
 7923:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7924:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7925:                 (my $analysis,$parts) =
 7926:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 7927:             } else {
 7928:                 $parts = $grader_partids_by_symb{$ressymb};
 7929:             }
 7930:             ($counter,my $recording) =
 7931:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7932:                                          $scandata{$pid},$parts,
 7933:                                          \%scantron_config,\%lettdig,$numletts);
 7934:             $record{$pid} .= $recording;
 7935:         }
 7936:     }
 7937:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7938:     $r->print('<br />');
 7939:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 7940:     $passed = 0;
 7941:     $failed = 0;
 7942:     $numstudents = 0;
 7943:     foreach my $last (sort(keys(%bylast))) {
 7944:         if (ref($bylast{$last}) eq 'ARRAY') {
 7945:             foreach my $pid (sort(@{$bylast{$last}})) {
 7946:                 my $showscandata = $scandata{$pid};
 7947:                 my $showrecord = $record{$pid};
 7948:                 $showscandata =~ s/\s/&nbsp;/g;
 7949:                 $showrecord =~ s/\s/&nbsp;/g;
 7950:                 if ($scandata{$pid} eq $record{$pid}) {
 7951:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 7952:                     $okstudents .= '<tr class="'.$css_class.'">'.
 7953: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7954: '</tr>'."\n".
 7955: '<tr class="'.$css_class.'">'."\n".
 7956: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 7957:                     $passed ++;
 7958:                 } else {
 7959:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 7960:                     $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".
 7961: '</tr>'."\n".
 7962: '<tr class="'.$css_class.'">'."\n".
 7963: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 7964: '</tr>'."\n";
 7965:                     $failed ++;
 7966:                 }
 7967:                 $numstudents ++;
 7968:             }
 7969:         }
 7970:     }
 7971:     $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>');
 7972:     $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>');
 7973:     if ($passed) {
 7974:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 7975:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7976:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7977:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7978:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7979:                  $okstudents."\n".
 7980:                  &Apache::loncommon::end_data_table().'<br />');
 7981:     }
 7982:     if ($failed) {
 7983:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 7984:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7985:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7986:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7987:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7988:                  $badstudents."\n".
 7989:                  &Apache::loncommon::end_data_table()).'<br />'.
 7990:                  &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.');  
 7991:     }
 7992:     $r->print('</form><br />'.$grading_menu_button);
 7993:     return;
 7994: }
 7995: 
 7996: sub verify_scantron_grading {
 7997:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 7998:         $scantron_config,$lettdig,$numletts) = @_;
 7999:     my ($record,%expected,%startpos);
 8000:     return ($counter,$record) if (!ref($resource));
 8001:     return ($counter,$record) if (!$resource->is_problem());
 8002:     my $symb = $resource->symb();
 8003:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8004:     foreach my $part_id (@{$partids}) {
 8005:         $counter ++;
 8006:         $expected{$part_id} = 0;
 8007:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8008:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8009:             foreach my $item (@sub_lines) {
 8010:                 $expected{$part_id} += $item;
 8011:             }
 8012:         } else {
 8013:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8014:         }
 8015:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8016:     }
 8017:     if ($symb) {
 8018:         my %recorded;
 8019:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8020:         if ($returnhash{'version'}) {
 8021:             my %lasthash=();
 8022:             my $version;
 8023:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8024:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8025:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8026:                 }
 8027:             }
 8028:             foreach my $key (keys(%lasthash)) {
 8029:                 if ($key =~ /\.scantron$/) {
 8030:                     my $value = &unescape($lasthash{$key});
 8031:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8032:                     if ($value eq '') {
 8033:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8034:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8035:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8036:                             }
 8037:                         }
 8038:                     } else {
 8039:                         my @tocheck;
 8040:                         my @items = split(//,$value);
 8041:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8042:                             ($scantron_config->{'Qon'} eq 'number')) {
 8043:                             if (@items < $expected{$part_id}) {
 8044:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8045:                                 my @singles = split(//,$fragment);
 8046:                                 foreach my $pos (@singles) {
 8047:                                     if ($pos eq ' ') {
 8048:                                         push(@tocheck,$pos);
 8049:                                     } else {
 8050:                                         my $next = shift(@items);
 8051:                                         push(@tocheck,$next);
 8052:                                     }
 8053:                                 }
 8054:                             } else {
 8055:                                 @tocheck = @items;
 8056:                             }
 8057:                             foreach my $letter (@tocheck) {
 8058:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8059:                                     if ($letter !~ /^[A-J]$/) {
 8060:                                         $letter = $scantron_config->{'Qoff'};
 8061:                                     }
 8062:                                     $recorded{$part_id} .= $letter;
 8063:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8064:                                     my $digit;
 8065:                                     if ($letter !~ /^[A-J]$/) {
 8066:                                         $digit = $scantron_config->{'Qoff'};
 8067:                                     } else {
 8068:                                         $digit = $lettdig->{$letter};
 8069:                                     }
 8070:                                     $recorded{$part_id} .= $digit;
 8071:                                 }
 8072:                             }
 8073:                         } else {
 8074:                             @tocheck = @items;
 8075:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8076:                                 my $curr_sub = shift(@tocheck);
 8077:                                 my $digit;
 8078:                                 if ($curr_sub =~ /^[A-J]$/) {
 8079:                                     $digit = $lettdig->{$curr_sub}-1;
 8080:                                 }
 8081:                                 if ($curr_sub eq 'J') {
 8082:                                     $digit += scalar($numletts);
 8083:                                 }
 8084:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8085:                                     if ($j == $digit) {
 8086:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8087:                                     } else {
 8088:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8089:                                     }
 8090:                                 }
 8091:                             }
 8092:                         }
 8093:                     }
 8094:                 }
 8095:             }
 8096:         }
 8097:         foreach my $part_id (@{$partids}) {
 8098:             if ($recorded{$part_id} eq '') {
 8099:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8100:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8101:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8102:                     }
 8103:                 }
 8104:             }
 8105:             $record .= $recorded{$part_id};
 8106:         }
 8107:     }
 8108:     return ($counter,$record);
 8109: }
 8110: 
 8111: sub letter_to_digits { 
 8112:     my %lettdig = (
 8113:                     A => 1,
 8114:                     B => 2,
 8115:                     C => 3,
 8116:                     D => 4,
 8117:                     E => 5,
 8118:                     F => 6,
 8119:                     G => 7,
 8120:                     H => 8,
 8121:                     I => 9,
 8122:                     J => 0,
 8123:                   );
 8124:     return %lettdig;
 8125: }
 8126: 
 8127: 
 8128: #-------- end of section for handling grading scantron forms -------
 8129: #
 8130: #-------------------------------------------------------------------
 8131: 
 8132: #-------------------------- Menu interface -------------------------
 8133: #
 8134: #--- Show a Grading Menu button - Calls the next routine ---
 8135: sub show_grading_menu_form {
 8136:     my ($symb)=@_;
 8137:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8138: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8139: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8140: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8141: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8142: 	'</form>'."\n";
 8143:     return $result;
 8144: }
 8145: 
 8146: # -- Retrieve choices for grading form
 8147: sub savedState {
 8148:     my %savedState = ();
 8149:     if ($env{'form.saveState'}) {
 8150: 	foreach (split(/:/,$env{'form.saveState'})) {
 8151: 	    my ($key,$value) = split(/=/,$_,2);
 8152: 	    $savedState{$key} = $value;
 8153: 	}
 8154:     }
 8155:     return \%savedState;
 8156: }
 8157: 
 8158: sub grading_menu {
 8159:     my ($request) = @_;
 8160:     my ($symb)=&get_symb($request);
 8161:     if (!$symb) {return '';}
 8162:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8163:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8164: 
 8165:     $request->print($table);
 8166:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8167:                   'handgrade'=>$hdgrade,
 8168:                   'probTitle'=>$probTitle,
 8169:                   'command'=>'submit_options',
 8170:                   'saveState'=>"",
 8171:                   'gradingMenu'=>1,
 8172:                   'showgrading'=>"yes");
 8173:     
 8174:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8175:     
 8176:     $fields{'command'} = 'csvform';
 8177:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8178:     
 8179:     $fields{'command'} = 'processclicker';
 8180:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8181:     
 8182:     $fields{'command'} = 'scantron_selectphase';
 8183:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8184:     
 8185:     my @menu = ({	categorytitle=>'Course Grading',
 8186:             items =>[
 8187:                         {	linktext => 'Manual Grading/View Submissions',
 8188:                     		url => $url1,
 8189:                     		permission => 'F',
 8190:                     		icon => 'edit-find-replace.png',
 8191:                     		linktitle => 'Start the process of hand grading submissions.'
 8192:                         },
 8193:                 	    {	linktext => 'Upload Scores',
 8194:                     		url => $url2,
 8195:                     		permission => 'F',
 8196:                     		icon => 'uploadscores.png',
 8197:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8198:                 	    },
 8199:                 	    {	linktext => 'Process Clicker',
 8200:                     		url => $url3,
 8201:                     		permission => 'F',
 8202:                     		icon => 'addClickerInfoFile.png',
 8203:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8204:                 	    },
 8205:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
 8206:                     		url => $url4,
 8207:                     		permission => 'F',
 8208:                     		icon => 'stat.png',
 8209:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8210:                 	    }
 8211:                     ]
 8212:             });
 8213: 
 8214:     #$fields{'command'} = 'verify';
 8215:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8216:     #
 8217:     # Create the menu
 8218:     my $Str;
 8219:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8220:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8221:     $Str .= '<input type="hidden" name="command" value="" />'.
 8222:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8223: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8224: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8225: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8226: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8227: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8228: 
 8229:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8230:     #$menudata->{'jscript'}
 8231:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8232:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8233:         ' /> '.
 8234:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8235:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8236: 
 8237:     $Str .="</form>\n";
 8238:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8239:     $request->print(<<GRADINGMENUJS);
 8240: <script type="text/javascript" language="javascript">
 8241:     function checkChoice(formname,val,cmdx) {
 8242: 	if (val <= 2) {
 8243: 	    var cmd = radioSelection(formname.radioChoice);
 8244: 	    var cmdsave = cmd;
 8245: 	} else {
 8246: 	    cmd = cmdx;
 8247: 	    cmdsave = 'submission';
 8248: 	}
 8249: 	formname.command.value = cmd;
 8250: 	if (val < 5) formname.submit();
 8251: 	if (val == 5) {
 8252: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8253: 	        return false;
 8254: 	    } else {
 8255: 	        formname.submit();
 8256: 	    }
 8257: 	}
 8258:     }
 8259: 
 8260:     function checkReceiptNo(formname,nospace) {
 8261: 	var receiptNo = formname.receipt.value;
 8262: 	var checkOpt = false;
 8263: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8264: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8265: 	if (checkOpt) {
 8266: 	    alert("$receiptalert");
 8267: 	    formname.receipt.value = "";
 8268: 	    formname.receipt.focus();
 8269: 	    return false;
 8270: 	}
 8271: 	return true;
 8272:     }
 8273: </script>
 8274: GRADINGMENUJS
 8275:     &commonJSfunctions($request);
 8276:     return $Str;    
 8277: }
 8278: 
 8279: 
 8280: #--- Displays the submissions first page -------
 8281: sub submit_options {
 8282:     my ($request) = @_;
 8283:     my ($symb)=&get_symb($request);
 8284:     if (!$symb) {return '';}
 8285:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8286: 
 8287:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8288:     $request->print(<<GRADINGMENUJS);
 8289: <script type="text/javascript" language="javascript">
 8290:     function checkChoice(formname,val,cmdx) {
 8291: 	if (val <= 2) {
 8292: 	    var cmd = radioSelection(formname.radioChoice);
 8293: 	    var cmdsave = cmd;
 8294: 	} else {
 8295: 	    cmd = cmdx;
 8296: 	    cmdsave = 'submission';
 8297: 	}
 8298: 	formname.command.value = cmd;
 8299: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8300: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8301: 	if (val < 5) formname.submit();
 8302: 	if (val == 5) {
 8303: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8304: 	    formname.submit();
 8305: 	}
 8306: 	if (val < 7) formname.submit();
 8307:     }
 8308: 
 8309:     function checkReceiptNo(formname,nospace) {
 8310: 	var receiptNo = formname.receipt.value;
 8311: 	var checkOpt = false;
 8312: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8313: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8314: 	if (checkOpt) {
 8315: 	    alert("$receiptalert");
 8316: 	    formname.receipt.value = "";
 8317: 	    formname.receipt.focus();
 8318: 	    return false;
 8319: 	}
 8320: 	return true;
 8321:     }
 8322: </script>
 8323: GRADINGMENUJS
 8324:     &commonJSfunctions($request);
 8325:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8326:     my $result;
 8327:     my (undef,$sections) = &getclasslist('all','0');
 8328:     my $savedState = &savedState();
 8329:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8330:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8331:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8332:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8333: 
 8334:     # Preselect sections
 8335:     my $selsec="";
 8336:     if (ref($sections)) {
 8337:         foreach my $section (sort(@$sections)) {
 8338:             $selsec.='<option value="'.$section.'" '.
 8339:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8340:         }
 8341:     }
 8342: 
 8343:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8344: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8345: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8346: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8347: 	'<input type="hidden" name="command"     value="" />'."\n".
 8348: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8349: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8350: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8351: 
 8352:     $result.='
 8353: <h2>
 8354:   '.&mt('Grade Current Resource').'
 8355: </h2>
 8356: <div>
 8357:   '.$table.'
 8358: </div>
 8359: 
 8360: <div class="LC_columnSection">
 8361:   
 8362:     <fieldset>
 8363:       <legend>
 8364:        '.&mt('Sections').'
 8365:       </legend>
 8366:       <select name="section" multiple="multiple" size="5">'."\n";
 8367:     $result.= $selsec;
 8368:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8369:     $result.='
 8370:     </fieldset>
 8371:   
 8372:     <fieldset>
 8373:       <legend>
 8374:         '.&mt('Groups').'
 8375:       </legend>
 8376:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8377:     </fieldset>
 8378:   
 8379:     <fieldset>
 8380:       <legend>
 8381:         '.&mt('Access Status').'
 8382:       </legend>
 8383:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8384:     </fieldset>
 8385:   
 8386:     <fieldset>
 8387:       <legend>
 8388:         '.&mt('Submission Status').'
 8389:       </legend>
 8390:       <select name="submitonly" size="5">
 8391: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8392: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8393: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8394: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8395:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8396:       </select>
 8397:     </fieldset>
 8398:   
 8399: </div>
 8400: 
 8401: <br />
 8402:           <div>
 8403:             <div>
 8404:               <label>
 8405:                 <input type="radio" name="radioChoice" value="submission" '.
 8406:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8407:              &mt('Select individual students to grade and view submissions.').'
 8408: 	      </label> 
 8409:             </div>
 8410:             <div>
 8411: 	      <label>
 8412:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8413:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8414:                     &mt('Grade all selected students in a grading table.').'
 8415:               </label>
 8416:             </div>
 8417:             <div>
 8418: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8419:             </div>
 8420:           </div>
 8421: 
 8422: 
 8423:         <h2>
 8424:          '.&mt('Grade Complete Folder for One Student').'
 8425:         </h2>
 8426:         <div>
 8427:             <div>
 8428:               <label>
 8429:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8430: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8431:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8432:               </label>
 8433:             </div>
 8434:             <div>
 8435: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8436:             </div>
 8437:         </div>
 8438:   </form>';
 8439:     $result .= &show_grading_menu_form($symb);
 8440:     return $result;
 8441: }
 8442: 
 8443: sub reset_perm {
 8444:     undef(%perm);
 8445: }
 8446: 
 8447: sub init_perm {
 8448:     &reset_perm();
 8449:     foreach my $test_perm ('vgr','mgr','opa') {
 8450: 
 8451: 	my $scope = $env{'request.course.id'};
 8452: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8453: 
 8454: 	    $scope .= '/'.$env{'request.course.sec'};
 8455: 	    if ( $perm{$test_perm}=
 8456: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8457: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8458: 	    } else {
 8459: 		delete($perm{$test_perm});
 8460: 	    }
 8461: 	}
 8462:     }
 8463: }
 8464: 
 8465: sub gather_clicker_ids {
 8466:     my %clicker_ids;
 8467: 
 8468:     my $classlist = &Apache::loncoursedata::get_classlist();
 8469: 
 8470:     # Set up a couple variables.
 8471:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8472:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8473:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8474: 
 8475:     foreach my $student (keys(%$classlist)) {
 8476:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8477:         my $username = $classlist->{$student}->[$username_idx];
 8478:         my $domain   = $classlist->{$student}->[$domain_idx];
 8479:         my $clickers =
 8480: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8481:         foreach my $id (split(/\,/,$clickers)) {
 8482:             $id=~s/^[\#0]+//;
 8483:             $id=~s/[\-\:]//g;
 8484:             if (exists($clicker_ids{$id})) {
 8485: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8486:             } else {
 8487: 		$clicker_ids{$id}=$username.':'.$domain;
 8488:             }
 8489:         }
 8490:     }
 8491:     return %clicker_ids;
 8492: }
 8493: 
 8494: sub gather_adv_clicker_ids {
 8495:     my %clicker_ids;
 8496:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8497:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8498:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8499:     foreach my $element (sort(keys(%coursepersonnel))) {
 8500:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8501:             my ($puname,$pudom)=split(/\:/,$person);
 8502:             my $clickers =
 8503: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8504:             foreach my $id (split(/\,/,$clickers)) {
 8505: 		$id=~s/^[\#0]+//;
 8506:                 $id=~s/[\-\:]//g;
 8507: 		if (exists($clicker_ids{$id})) {
 8508: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8509: 		} else {
 8510: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8511: 		}
 8512:             }
 8513:         }
 8514:     }
 8515:     return %clicker_ids;
 8516: }
 8517: 
 8518: sub clicker_grading_parameters {
 8519:     return ('gradingmechanism' => 'scalar',
 8520:             'upfiletype' => 'scalar',
 8521:             'specificid' => 'scalar',
 8522:             'pcorrect' => 'scalar',
 8523:             'pincorrect' => 'scalar');
 8524: }
 8525: 
 8526: sub process_clicker {
 8527:     my ($r)=@_;
 8528:     my ($symb)=&get_symb($r);
 8529:     if (!$symb) {return '';}
 8530:     my $result=&checkforfile_js();
 8531:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8532:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8533:     $result.=$table;
 8534:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8535:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8536:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8537:         '</b></td></tr>'."\n";
 8538:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8539: # Attempt to restore parameters from last session, set defaults if not present
 8540:     my %Saveable_Parameters=&clicker_grading_parameters();
 8541:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8542:                                                  \%Saveable_Parameters);
 8543:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8544:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8545:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8546:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8547: 
 8548:     my %checked;
 8549:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8550:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8551:           $checked{$gradingmechanism}="checked='checked'";
 8552:        }
 8553:     }
 8554: 
 8555:     my $upload=&mt("Upload File");
 8556:     my $type=&mt("Type");
 8557:     my $attendance=&mt("Award points just for participation");
 8558:     my $personnel=&mt("Correctness determined from response by course personnel");
 8559:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8560:     my $given=&mt("Correctness determined from given list of answers").' '.
 8561:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8562:     my $pcorrect=&mt("Percentage points for correct solution");
 8563:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8564:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8565: 						   ('iclicker' => 'i>clicker',
 8566:                                                     'interwrite' => 'interwrite PRS'));
 8567:     $symb = &Apache::lonenc::check_encrypt($symb);
 8568:     $result.=<<ENDUPFORM;
 8569: <script type="text/javascript">
 8570: function sanitycheck() {
 8571: // Accept only integer percentages
 8572:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8573:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8574: // Find out grading choice
 8575:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8576:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8577:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8578:       }
 8579:    }
 8580: // By default, new choice equals user selection
 8581:    newgradingchoice=gradingchoice;
 8582: // Not good to give more points for false answers than correct ones
 8583:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8584:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8585:    }
 8586: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8587:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8588:       document.forms.gradesupload.pcorrect.value=100;
 8589:       document.forms.gradesupload.pincorrect.value=100;
 8590:    }
 8591: // If the values are different, cannot be attendance only
 8592:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8593:        (gradingchoice=='attendance')) {
 8594:        newgradingchoice='personnel';
 8595:    }
 8596: // Change grading choice to new one
 8597:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8598:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8599:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8600:       } else {
 8601:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8602:       }
 8603:    }
 8604: // Remember the old state
 8605:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8606: }
 8607: </script>
 8608: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8609: <input type="hidden" name="symb" value="$symb" />
 8610: <input type="hidden" name="command" value="processclickerfile" />
 8611: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8612: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8613: <input type="file" name="upfile" size="50" />
 8614: <br /><label>$type: $selectform</label>
 8615: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8616: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8617: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8618: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8619: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8620: <br />&nbsp;&nbsp;&nbsp;
 8621: <input type="text" name="givenanswer" size="50" />
 8622: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8623: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8624: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8625: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8626: </form>
 8627: ENDUPFORM
 8628:     $result.='</td></tr></table>'."\n".
 8629:              '</td></tr></table><br /><br />'."\n";
 8630:     $result.=&show_grading_menu_form($symb);
 8631:     return $result;
 8632: }
 8633: 
 8634: sub process_clicker_file {
 8635:     my ($r)=@_;
 8636:     my ($symb)=&get_symb($r);
 8637:     if (!$symb) {return '';}
 8638: 
 8639:     my %Saveable_Parameters=&clicker_grading_parameters();
 8640:     &Apache::loncommon::store_course_settings('grades_clicker',
 8641:                                               \%Saveable_Parameters);
 8642: 
 8643:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8644:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8645: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8646: 	return $result.&show_grading_menu_form($symb);
 8647:     }
 8648:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8649:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8650:         return $result.&show_grading_menu_form($symb);
 8651:     }
 8652:     my $foundgiven=0;
 8653:     if ($env{'form.gradingmechanism'} eq 'given') {
 8654:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8655:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8656:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8657:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8658:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8659:         $foundgiven=$#answers+1;
 8660:     }
 8661:     my %clicker_ids=&gather_clicker_ids();
 8662:     my %correct_ids;
 8663:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8664: 	%correct_ids=&gather_adv_clicker_ids();
 8665:     }
 8666:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8667: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8668: 	   $correct_id=~tr/a-z/A-Z/;
 8669: 	   $correct_id=~s/\s//gs;
 8670: 	   $correct_id=~s/^[\#0]+//;
 8671:            $correct_id=~s/[\-\:]//g;
 8672:            if ($correct_id) {
 8673: 	      $correct_ids{$correct_id}='specified';
 8674:            }
 8675:         }
 8676:     }
 8677:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8678: 	$result.=&mt('Score based on attendance only');
 8679:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8680:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8681:     } else {
 8682: 	my $number=0;
 8683: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8684: 	foreach my $id (sort(keys(%correct_ids))) {
 8685: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8686: 	    if ($correct_ids{$id} eq 'specified') {
 8687: 		$result.=&mt('specified');
 8688: 	    } else {
 8689: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8690: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8691: 	    }
 8692: 	    $number++;
 8693: 	}
 8694:         $result.="</p>\n";
 8695: 	if ($number==0) {
 8696: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8697: 	    return $result.&show_grading_menu_form($symb);
 8698: 	}
 8699:     }
 8700:     if (length($env{'form.upfile'}) < 2) {
 8701:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8702: 		     '<span class="LC_error">',
 8703: 		     '</span>',
 8704: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8705:         return $result.&show_grading_menu_form($symb);
 8706:     }
 8707: 
 8708: # Were able to get all the info needed, now analyze the file
 8709: 
 8710:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8711:     $symb = &Apache::lonenc::check_encrypt($symb);
 8712:     my $heading=&mt('Scanning clicker file');
 8713:     $result.=(<<ENDHEADER);
 8714: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8715: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8716: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8717: <form method="post" action="/adm/grades" name="clickeranalysis">
 8718: <input type="hidden" name="symb" value="$symb" />
 8719: <input type="hidden" name="command" value="assignclickergrades" />
 8720: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8721: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8722: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8723: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8724: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8725: ENDHEADER
 8726:     if ($env{'form.gradingmechanism'} eq 'given') {
 8727:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8728:     } 
 8729:     my %responses;
 8730:     my @questiontitles;
 8731:     my $errormsg='';
 8732:     my $number=0;
 8733:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8734: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8735:     }
 8736:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8737:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8738:     }
 8739:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8740:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8741:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8742:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8743:              '<br />';
 8744:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8745:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8746:        return $result.&show_grading_menu_form($symb);
 8747:     } 
 8748: # Remember Question Titles
 8749: # FIXME: Possibly need delimiter other than ":"
 8750:     for (my $i=0;$i<$number;$i++) {
 8751:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8752:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8753:     }
 8754:     my $correct_count=0;
 8755:     my $student_count=0;
 8756:     my $unknown_count=0;
 8757: # Match answers with usernames
 8758: # FIXME: Possibly need delimiter other than ":"
 8759:     foreach my $id (keys(%responses)) {
 8760:        if ($correct_ids{$id}) {
 8761:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8762:           $correct_count++;
 8763:        } elsif ($clicker_ids{$id}) {
 8764:           if ($clicker_ids{$id}=~/\,/) {
 8765: # More than one user with the same clicker!
 8766:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8767:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8768:                            "<select name='multi".$id."'>";
 8769:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8770:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8771:              }
 8772:              $result.='</select>';
 8773:              $unknown_count++;
 8774:           } else {
 8775: # Good: found one and only one user with the right clicker
 8776:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8777:              $student_count++;
 8778:           }
 8779:        } else {
 8780:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8781:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8782:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8783:                    "\n".&mt("Domain").": ".
 8784:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8785:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8786:           $unknown_count++;
 8787:        }
 8788:     }
 8789:     $result.='<hr />'.
 8790:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8791:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8792:        if ($correct_count==0) {
 8793:           $errormsg.="Found no correct answers answers for grading!";
 8794:        } elsif ($correct_count>1) {
 8795:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8796:        }
 8797:     }
 8798:     if ($number<1) {
 8799:        $errormsg.="Found no questions.";
 8800:     }
 8801:     if ($errormsg) {
 8802:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8803:     } else {
 8804:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8805:     }
 8806:     $result.='</form></td></tr></table>'."\n".
 8807:              '</td></tr></table><br /><br />'."\n";
 8808:     return $result.&show_grading_menu_form($symb);
 8809: }
 8810: 
 8811: sub iclicker_eval {
 8812:     my ($questiontitles,$responses)=@_;
 8813:     my $number=0;
 8814:     my $errormsg='';
 8815:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8816:         my %components=&Apache::loncommon::record_sep($line);
 8817:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8818: 	if ($entries[0] eq 'Question') {
 8819: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8820: 		$$questiontitles[$number]=$entries[$i];
 8821: 		$number++;
 8822: 	    }
 8823: 	}
 8824: 	if ($entries[0]=~/^\#/) {
 8825: 	    my $id=$entries[0];
 8826: 	    my @idresponses;
 8827: 	    $id=~s/^[\#0]+//;
 8828: 	    for (my $i=0;$i<$number;$i++) {
 8829: 		my $idx=3+$i*6;
 8830: 		push(@idresponses,$entries[$idx]);
 8831: 	    }
 8832: 	    $$responses{$id}=join(',',@idresponses);
 8833: 	}
 8834:     }
 8835:     return ($errormsg,$number);
 8836: }
 8837: 
 8838: sub interwrite_eval {
 8839:     my ($questiontitles,$responses)=@_;
 8840:     my $number=0;
 8841:     my $errormsg='';
 8842:     my $skipline=1;
 8843:     my $questionnumber=0;
 8844:     my %idresponses=();
 8845:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8846:         my %components=&Apache::loncommon::record_sep($line);
 8847:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8848:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8849:         if ($entries[1] eq 'Response') { $skipline=1; }
 8850:         next if $skipline;
 8851:         if ($entries[0]!=$questionnumber) {
 8852:            $questionnumber=$entries[0];
 8853:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8854:            $number++;
 8855:         }
 8856:         my $id=$entries[4];
 8857:         $id=~s/^[\#0]+//;
 8858:         $id=~s/^v\d*\://i;
 8859:         $id=~s/[\-\:]//g;
 8860:         $idresponses{$id}[$number]=$entries[6];
 8861:     }
 8862:     foreach my $id (keys(%idresponses)) {
 8863:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8864:        $$responses{$id}=~s/^\s*\,//;
 8865:     }
 8866:     return ($errormsg,$number);
 8867: }
 8868: 
 8869: sub assign_clicker_grades {
 8870:     my ($r)=@_;
 8871:     my ($symb)=&get_symb($r);
 8872:     if (!$symb) {return '';}
 8873: # See which part we are saving to
 8874:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8875: # FIXME: This should probably look for the first handgradeable part
 8876:     my $part=$$partlist[0];
 8877: # Start screen output
 8878:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8879: 
 8880:     my $heading=&mt('Assigning grades based on clicker file');
 8881:     $result.=(<<ENDHEADER);
 8882: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8883: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8884: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8885: ENDHEADER
 8886: # Get correct result
 8887: # FIXME: Possibly need delimiter other than ":"
 8888:     my @correct=();
 8889:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8890:     my $number=$env{'form.number'};
 8891:     if ($gradingmechanism ne 'attendance') {
 8892:        foreach my $key (keys(%env)) {
 8893:           if ($key=~/^form\.correct\:/) {
 8894:              my @input=split(/\,/,$env{$key});
 8895:              for (my $i=0;$i<=$#input;$i++) {
 8896:                  if (($correct[$i]) && ($input[$i]) &&
 8897:                      ($correct[$i] ne $input[$i])) {
 8898:                     $result.='<br /><span class="LC_warning">'.
 8899:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8900:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8901:                  } elsif ($input[$i]) {
 8902:                     $correct[$i]=$input[$i];
 8903:                  }
 8904:              }
 8905:           }
 8906:        }
 8907:        for (my $i=0;$i<$number;$i++) {
 8908:           if (!$correct[$i]) {
 8909:              $result.='<br /><span class="LC_error">'.
 8910:                       &mt('No correct result given for question "[_1]"!',
 8911:                           $env{'form.question:'.$i}).'</span>';
 8912:           }
 8913:        }
 8914:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8915:     }
 8916: # Start grading
 8917:     my $pcorrect=$env{'form.pcorrect'};
 8918:     my $pincorrect=$env{'form.pincorrect'};
 8919:     my $storecount=0;
 8920:     foreach my $key (keys(%env)) {
 8921:        my $user='';
 8922:        if ($key=~/^form\.student\:(.*)$/) {
 8923:           $user=$1;
 8924:        }
 8925:        if ($key=~/^form\.unknown\:(.*)$/) {
 8926:           my $id=$1;
 8927:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8928:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8929:           } elsif ($env{'form.multi'.$id}) {
 8930:              $user=$env{'form.multi'.$id};
 8931:           }
 8932:        }
 8933:        if ($user) { 
 8934:           my @answer=split(/\,/,$env{$key});
 8935:           my $sum=0;
 8936:           my $realnumber=$number;
 8937:           for (my $i=0;$i<$number;$i++) {
 8938:              if ($answer[$i]) {
 8939:                 if ($gradingmechanism eq 'attendance') {
 8940:                    $sum+=$pcorrect;
 8941:                 } elsif ($answer[$i] eq '*') {
 8942:                    $sum+=$pcorrect;
 8943:                 } elsif ($answer[$i] eq '-') {
 8944:                    $realnumber--;
 8945:                 } else {
 8946:                    if ($answer[$i] eq $correct[$i]) {
 8947:                       $sum+=$pcorrect;
 8948:                    } else {
 8949:                       $sum+=$pincorrect;
 8950:                    }
 8951:                 }
 8952:              }
 8953:           }
 8954:           my $ave=$sum/(100*$realnumber);
 8955: # Store
 8956:           my ($username,$domain)=split(/\:/,$user);
 8957:           my %grades=();
 8958:           $grades{"resource.$part.solved"}='correct_by_override';
 8959:           $grades{"resource.$part.awarded"}=$ave;
 8960:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8961:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8962:                                                  $env{'request.course.id'},
 8963:                                                  $domain,$username);
 8964:           if ($returncode ne 'ok') {
 8965:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8966:           } else {
 8967:              $storecount++;
 8968:           }
 8969:        }
 8970:     }
 8971: # We are done
 8972:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 8973:              '</td></tr></table>'."\n".
 8974:              '</td></tr></table><br /><br />'."\n";
 8975:     return $result.&show_grading_menu_form($symb);
 8976: }
 8977: 
 8978: sub handler {
 8979:     my $request=$_[0];
 8980:     &reset_caches();
 8981:     if ($env{'browser.mathml'}) {
 8982: 	&Apache::loncommon::content_type($request,'text/xml');
 8983:     } else {
 8984: 	&Apache::loncommon::content_type($request,'text/html');
 8985:     }
 8986:     $request->send_http_header;
 8987:     return '' if $request->header_only;
 8988:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8989:     my $symb=&get_symb($request,1);
 8990:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8991:     my $command=$commands[0];
 8992: 
 8993:     if ($#commands > 0) {
 8994: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8995:     }
 8996: 
 8997:     $ssi_error = 0;
 8998:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 8999:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9000:                                           {'bread_crumbs' => $brcrum}));
 9001:     if ($symb eq '' && $command eq '') {
 9002: 	if ($env{'user.adv'}) {
 9003: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9004: 		($env{'form.codethree'})) {
 9005: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9006: 		    $env{'form.codethree'};
 9007: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9008: 		    &Apache::lonnet::checkin($token);
 9009: 		if ($tsymb) {
 9010: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9011: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9012: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9013: 					  ('grade_username' => $tuname,
 9014: 					   'grade_domain' => $tudom,
 9015: 					   'grade_courseid' => $tcrsid,
 9016: 					   'grade_symb' => $tsymb)));
 9017: 		    } else {
 9018: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9019: 		    }
 9020: 		} else {
 9021: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9022: 		}
 9023: 	    } else {
 9024: 		$request->print(&Apache::lonxml::tokeninputfield());
 9025: 	    }
 9026: 	}
 9027:     } else {
 9028: 	&init_perm();
 9029: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9030: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9031: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9032: 	    &pickStudentPage($request);
 9033: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9034: 	    &displayPage($request);
 9035: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9036: 	    &updateGradeByPage($request);
 9037: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9038: 	    &processGroup($request);
 9039: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9040: 	    $request->print(&grading_menu($request));
 9041: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9042: 	    $request->print(&submit_options($request));
 9043: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9044: 	    $request->print(&viewgrades($request));
 9045: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9046: 	    $request->print(&processHandGrade($request));
 9047: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9048: 	    $request->print(&editgrades($request));
 9049: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9050: 	    $request->print(&verifyreceipt($request));
 9051:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9052:             $request->print(&process_clicker($request));
 9053:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9054:             $request->print(&process_clicker_file($request));
 9055:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9056:             $request->print(&assign_clicker_grades($request));
 9057: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9058: 	    $request->print(&upcsvScores_form($request));
 9059: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9060: 	    $request->print(&csvupload($request));
 9061: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9062: 	    $request->print(&csvuploadmap($request));
 9063: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9064: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9065: 		$request->print(&csvuploadoptions($request));
 9066: 	    } else {
 9067: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9068: 		    $env{'form.upfile_associate'} = 'reverse';
 9069: 		} else {
 9070: 		    $env{'form.upfile_associate'} = 'forward';
 9071: 		}
 9072: 		$request->print(&csvuploadmap($request));
 9073: 	    }
 9074: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9075: 	    $request->print(&csvuploadassign($request));
 9076: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9077: 	    $request->print(&scantron_selectphase($request));
 9078:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9079:  	    $request->print(&scantron_do_warning($request));
 9080: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9081: 	    $request->print(&scantron_validate_file($request));
 9082: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9083: 	    $request->print(&scantron_process_students($request));
 9084:  	} elsif ($command eq 'scantronupload' && 
 9085:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9086: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9087:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9088:  	} elsif ($command eq 'scantronupload_save' &&
 9089:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9090: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9091:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9092:  	} elsif ($command eq 'scantron_download' &&
 9093: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9094:  	    $request->print(&scantron_download_scantron_data($request));
 9095:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9096:             $request->print(&checkscantron_results($request));     
 9097: 	} elsif ($command) {
 9098: 	    $request->print("Access Denied ($command)");
 9099: 	}
 9100:     }
 9101:     if ($ssi_error) {
 9102: 	&ssi_print_error($request);
 9103:     }
 9104:     $request->print(&Apache::loncommon::end_page());
 9105:     &reset_caches();
 9106:     return '';
 9107: }
 9108: 
 9109: 1;
 9110: 
 9111: __END__;
 9112: 
 9113: 
 9114: =head1 NAME
 9115: 
 9116: Apache::grades
 9117: 
 9118: =head1 SYNOPSIS
 9119: 
 9120: Handles the viewing of grades.
 9121: 
 9122: This is part of the LearningOnline Network with CAPA project
 9123: described at http://www.lon-capa.org.
 9124: 
 9125: =head1 OVERVIEW
 9126: 
 9127: Do an ssi with retries:
 9128: While I'd love to factor out this with the vesrion in lonprintout,
 9129: 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
 9130: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9131: 
 9132: At least the logic that drives this has been pulled out into loncommon.
 9133: 
 9134: 
 9135: 
 9136: ssi_with_retries - Does the server side include of a resource.
 9137:                      if the ssi call returns an error we'll retry it up to
 9138:                      the number of times requested by the caller.
 9139:                      If we still have a proble, no text is appended to the
 9140:                      output and we set some global variables.
 9141:                      to indicate to the caller an SSI error occurred.  
 9142:                      All of this is supposed to deal with the issues described
 9143:                      in LonCAPA BZ 5631 see:
 9144:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9145:                      by informing the user that this happened.
 9146: 
 9147: Parameters:
 9148:   resource   - The resource to include.  This is passed directly, without
 9149:                interpretation to lonnet::ssi.
 9150:   form       - The form hash parameters that guide the interpretation of the resource
 9151:                
 9152:   retries    - Number of retries allowed before giving up completely.
 9153: Returns:
 9154:   On success, returns the rendered resource identified by the resource parameter.
 9155: Side Effects:
 9156:   The following global variables can be set:
 9157:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9158:                               It is up to the caller to initialize this to false
 9159:                               if desired.
 9160:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9161:                               of the resource that could not be rendered by the ssi
 9162:                               call.
 9163:    ssi_error_message   - The error string fetched from the ssi response
 9164:                               in the event of an error.
 9165: 
 9166: 
 9167: =head1 HANDLER SUBROUTINE
 9168: 
 9169: ssi_with_retries()
 9170: 
 9171: =head1 SUBROUTINES
 9172: 
 9173: =over
 9174: 
 9175: =item scantron_get_correction() : 
 9176: 
 9177:    Builds the interface screen to interact with the operator to fix a
 9178:    specific error condition in a specific scanline
 9179: 
 9180:  Arguments:
 9181:     $r           - Apache request object
 9182:     $i           - number of the current scanline
 9183:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9184:     $scan_config - hash ref as returned from &get_scantron_config()
 9185:     $line        - full contents of the current scanline
 9186:     $error       - error condition, valid values are
 9187:                    'incorrectCODE', 'duplicateCODE',
 9188:                    'doublebubble', 'missingbubble',
 9189:                    'duplicateID', 'incorrectID'
 9190:     $arg         - extra information needed
 9191:        For errors:
 9192:          - duplicateID   - paper number that this studentID was seen before on
 9193:          - duplicateCODE - array ref of the paper numbers this CODE was
 9194:                            seen on before
 9195:          - incorrectCODE - current incorrect CODE 
 9196:          - doublebubble  - array ref of the bubble lines that have double
 9197:                            bubble errors
 9198:          - missingbubble - array ref of the bubble lines that have missing
 9199:                            bubble errors
 9200: 
 9201: =item  scantron_get_maxbubble() : 
 9202: 
 9203:    Returns the maximum number of bubble lines that are expected to
 9204:    occur. Does this by walking the selected sequence rendering the
 9205:    resource and then checking &Apache::lonxml::get_problem_counter()
 9206:    for what the current value of the problem counter is.
 9207: 
 9208:    Caches the results to $env{'form.scantron_maxbubble'},
 9209:    $env{'form.scantron.bubble_lines.n'}, 
 9210:    $env{'form.scantron.first_bubble_line.n'} and
 9211:    $env{"form.scantron.sub_bubblelines.n"}
 9212:    which are the total number of bubble, lines, the number of bubble
 9213:    lines for response n and number of the first bubble line for response n,
 9214:    and a comma separated list of numbers of bubble lines for sub-questions
 9215:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9216: 
 9217: 
 9218: =item  scantron_validate_missingbubbles() : 
 9219: 
 9220:    Validates all scanlines in the selected file to not have any
 9221:     answers that don't have bubbles that have not been verified
 9222:     to be bubble free.
 9223: 
 9224: =item  scantron_process_students() : 
 9225: 
 9226:    Routine that does the actual grading of the bubble sheet information.
 9227: 
 9228:    The parsed scanline hash is added to %env 
 9229: 
 9230:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9231:    foreach resource , with the form data of
 9232: 
 9233: 	'submitted'     =>'scantron' 
 9234: 	'grade_target'  =>'grade',
 9235: 	'grade_username'=> username of student
 9236: 	'grade_domain'  => domain of student
 9237: 	'grade_courseid'=> of course
 9238: 	'grade_symb'    => symb of resource to grade
 9239: 
 9240:     This triggers a grading pass. The problem grading code takes care
 9241:     of converting the bubbled letter information (now in %env) into a
 9242:     valid submission.
 9243: 
 9244: =item  scantron_upload_scantron_data() :
 9245: 
 9246:     Creates the screen for adding a new bubble sheet data file to a course.
 9247: 
 9248: =item  scantron_upload_scantron_data_save() : 
 9249: 
 9250:    Adds a provided bubble information data file to the course if user
 9251:    has the correct privileges to do so. 
 9252: 
 9253: =item  valid_file() :
 9254: 
 9255:    Validates that the requested bubble data file exists in the course.
 9256: 
 9257: =item  scantron_download_scantron_data() : 
 9258: 
 9259:    Shows a list of the three internal files (original, corrected,
 9260:    skipped) for a specific bubble sheet data file that exists in the
 9261:    course.
 9262: 
 9263: =item  scantron_validate_ID() : 
 9264: 
 9265:    Validates all scanlines in the selected file to not have any
 9266:    invalid or underspecified student/employee IDs
 9267: 
 9268: =back
 9269: 
 9270: =cut

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