File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.671: download - view: text, annotated - select for diffs
Tue Jan 3 00:28:17 2012 UTC (12 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse, BZ4492-feature_Support_horizontal_radioresponse, BZ4492-Support_horizontal_radioresponse
- Bug 6450. Course personnel with vgr priv can view student's prior
  versions of a Bridge Task (BT).
  - bridgetask.pm
    - generation of Show Slot list and Show Grading Status buttons moved
      to new routine: &add_slotlist_button().
    - "Show Slot list", "Show Grading Status", "Show a previously done version"
      "Get a submission to grade", "Change reservation" buttons not shown
      when course personnel display student's version of a BT.
    - ensure tags have unique ids (replace duplicate LC_task_feedback with
      LC_task_answer.

  - grades.pm
    - Header: "View of the problem" replaced with "View of the problem for
              <student name>
    - Header: "Correct answer" replaced with "Correct answer for "
              <student name>
    - New routine: &show_previous_task_version() to show student's previous
      version of a BT.
    - New routine: &choose_task_version_form() provides a web form to select
      display of a student's version of a BT (in same window or in pop-up).
    - New routine: &previous_display_javascript() javascript to launch pop-up
      etc. for other version.
    - &startpage() has four additional args: $stuvcurrent,$stuvdisp,$nomenu,$js
      student's current BT version, version being displayed, no page menu (for
      pop-up), and javascript to launch previous version pop-up.a

  - lonhtmlcommon.pm
    - &resource_info_box() has two additional args: $stuvcurrent,$stuvdisp
      student's current BT version, and version being displayed.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.671 2012/01/03 00:28:17 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: 
   58: #  These variables are used to recover from ssi errors
   59: 
   60: my $ssi_retries = 5;
   61: my $ssi_error;
   62: my $ssi_error_resource;
   63: my $ssi_error_message;
   64: 
   65: 
   66: sub ssi_with_retries {
   67:     my ($resource, $retries, %form) = @_;
   68:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   69:     if ($response->is_error) {
   70: 	$ssi_error          = 1;
   71: 	$ssi_error_resource = $resource;
   72: 	$ssi_error_message  = $response->code . " " . $response->message;
   73:     }
   74: 
   75:     return $content;
   76: 
   77: }
   78: #
   79: #  Prodcuces an ssi retry failure error message to the user:
   80: #
   81: 
   82: sub ssi_print_error {
   83:     my ($r) = @_;
   84:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   85:     $r->print('
   86: <br />
   87: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   88: <p>
   89: '.&mt('Unable to retrieve a resource from a server:').'<br />
   90: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   91: '.&mt('Error:').' '.$ssi_error_message.'
   92: </p>
   93: <p>'.
   94: &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 />'.
   95: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   96: '</p>');
   97:     return;
   98: }
   99: 
  100: #
  101: # --- Retrieve the parts from the metadata file.---
  102: # Returns an array of everything that the resources stores away
  103: #
  104: 
  105: sub getpartlist {
  106:     my ($symb,$errorref) = @_;
  107: 
  108:     my $navmap   = Apache::lonnavmaps::navmap->new();
  109:     unless (ref($navmap)) {
  110:         if (ref($errorref)) { 
  111:             $$errorref = 'navmap';
  112:             return;
  113:         }
  114:     }
  115:     my $res      = $navmap->getBySymb($symb);
  116:     my $partlist = $res->parts();
  117:     my $url      = $res->src();
  118:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  119: 
  120:     my @stores;
  121:     foreach my $part (@{ $partlist }) {
  122: 	foreach my $key (@metakeys) {
  123: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  124: 	}
  125:     }
  126:     return @stores;
  127: }
  128: 
  129: #--- Format fullname, username:domain if different for display
  130: #--- Use anywhere where the student names are listed
  131: sub nameUserString {
  132:     my ($type,$fullname,$uname,$udom) = @_;
  133:     if ($type eq 'header') {
  134: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  135:     } else {
  136: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  137: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  138:     }
  139: }
  140: 
  141: #--- Get the partlist and the response type for a given problem. ---
  142: #--- Indicate if a response type is coded handgraded or not. ---
  143: #--- Sets response_error pointer to "1" if navmaps object broken ---
  144: sub response_type {
  145:     my ($symb,$response_error) = @_;
  146: 
  147:     my $navmap = Apache::lonnavmaps::navmap->new();
  148:     unless (ref($navmap)) {
  149:         if (ref($response_error)) {
  150:             $$response_error = 1;
  151:         }
  152:         return;
  153:     }
  154:     my $res = $navmap->getBySymb($symb);
  155:     unless (ref($res)) {
  156:         $$response_error = 1;
  157:         return;
  158:     }
  159:     my $partlist = $res->parts();
  160:     my %vPart = 
  161: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  162:     my (%response_types,%handgrade);
  163:     foreach my $part (@{ $partlist }) {
  164: 	next if (%vPart && !exists($vPart{$part}));
  165: 
  166: 	my @types = $res->responseType($part);
  167: 	my @ids = $res->responseIds($part);
  168: 	for (my $i=0; $i < scalar(@ids); $i++) {
  169: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  170: 	    $handgrade{$part.'_'.$ids[$i]} = 
  171: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  172: 				     '.handgrade',$symb);
  173: 	}
  174:     }
  175:     return ($partlist,\%handgrade,\%response_types);
  176: }
  177: 
  178: sub flatten_responseType {
  179:     my ($responseType) = @_;
  180:     my @part_response_id =
  181: 	map { 
  182: 	    my $part = $_;
  183: 	    map {
  184: 		[$part,$_]
  185: 		} sort(keys(%{ $responseType->{$part} }));
  186: 	} sort(keys(%$responseType));
  187:     return @part_response_id;
  188: }
  189: 
  190: sub get_display_part {
  191:     my ($partID,$symb)=@_;
  192:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  193:     if (defined($display) and $display ne '') {
  194:         $display.= ' (<span class="LC_internal_info">'
  195:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  196:     } else {
  197: 	$display=$partID;
  198:     }
  199:     return $display;
  200: }
  201: 
  202: sub reset_caches {
  203:     &reset_analyze_cache();
  204:     &reset_perm();
  205: }
  206: 
  207: {
  208:     my %analyze_cache;
  209:     my %analyze_cache_formkeys;
  210: 
  211:     sub reset_analyze_cache {
  212: 	undef(%analyze_cache);
  213:         undef(%analyze_cache_formkeys);
  214:     }
  215: 
  216:     sub get_analyze {
  217: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  218: 	my $key = "$symb\0$uname\0$udom";
  219:         if ($type eq 'randomizetry') {
  220:             if ($trial ne '') {
  221:                 $key .= "\0".$trial;
  222:             }
  223:         }
  224: 	if (exists($analyze_cache{$key})) {
  225:             my $getupdate = 0;
  226:             if (ref($add_to_hash) eq 'HASH') {
  227:                 foreach my $item (keys(%{$add_to_hash})) {
  228:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  229:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  230:                             $getupdate = 1;
  231:                             last;
  232:                         }
  233:                     } else {
  234:                         $getupdate = 1;
  235:                     }
  236:                 }
  237:             }
  238:             if (!$getupdate) {
  239:                 return $analyze_cache{$key};
  240:             }
  241:         }
  242: 
  243: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  244: 	$url=&Apache::lonnet::clutter($url);
  245:         my %form = ('grade_target'      => 'analyze',
  246:                     'grade_domain'      => $udom,
  247:                     'grade_symb'        => $symb,
  248:                     'grade_courseid'    =>  $env{'request.course.id'},
  249:                     'grade_username'    => $uname,
  250:                     'grade_noincrement' => $no_increment);
  251:         if ($bubbles_per_row ne '') {
  252:             $form{'bubbles_per_row'} = $bubbles_per_row;
  253:         }
  254:         if ($type eq 'randomizetry') {
  255:             $form{'grade_questiontype'} = $type;
  256:             if ($rndseed ne '') {
  257:                 $form{'grade_rndseed'} = $rndseed;
  258:             }
  259:         }
  260:         if (ref($add_to_hash)) {
  261:             %form = (%form,%{$add_to_hash});
  262:         }
  263: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  264: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  265: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  266:         if (ref($add_to_hash) eq 'HASH') {
  267:             $analyze_cache_formkeys{$key} = $add_to_hash;
  268:         } else {
  269:             $analyze_cache_formkeys{$key} = {};
  270:         }
  271: 	return $analyze_cache{$key} = \%analyze;
  272:     }
  273: 
  274:     sub get_order {
  275: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  276: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  277: 	return $analyze->{"$partid.$respid.shown"};
  278:     }
  279: 
  280:     sub get_radiobutton_correct_foil {
  281: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  282: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  283:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  284:         if (ref($foils) eq 'ARRAY') {
  285: 	    foreach my $foil (@{$foils}) {
  286: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  287: 		    return $foil;
  288: 	        }
  289: 	    }
  290: 	}
  291:     }
  292: 
  293:     sub scantron_partids_tograde {
  294:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
  295:         my (%analysis,@parts);
  296:         if (ref($resource)) {
  297:             my $symb = $resource->symb();
  298:             my $add_to_form;
  299:             if ($check_for_randomlist) {
  300:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  301:             }
  302:             my $analyze = 
  303:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  304:                              undef,undef,undef,$bubbles_per_row);
  305:             if (ref($analyze) eq 'HASH') {
  306:                 %analysis = %{$analyze};
  307:             }
  308:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  309:                 foreach my $part (@{$analysis{'parts'}}) {
  310:                     my ($id,$respid) = split(/\./,$part);
  311:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  312:                         push(@parts,$part);
  313:                     }
  314:                 }
  315:             }
  316:         }
  317:         return (\%analysis,\@parts);
  318:     }
  319: 
  320: }
  321: 
  322: #--- Clean response type for display
  323: #--- Currently filters option/rank/radiobutton/match/essay/Task
  324: #        response types only.
  325: sub cleanRecord {
  326:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  327: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  328:     my $grayFont = '<span class="LC_internal_info">';
  329:     if ($response =~ /^(option|rank)$/) {
  330: 	my %answer=&Apache::lonnet::str2hash($answer);
  331: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  332: 	my ($toprow,$bottomrow);
  333: 	foreach my $foil (@$order) {
  334: 	    if ($grading{$foil} == 1) {
  335: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  336: 	    } else {
  337: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  338: 	    }
  339: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  340: 	}
  341: 	return '<blockquote><table border="1">'.
  342: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  343: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  344: 	    $bottomrow.'</tr></table></blockquote>';
  345:     } elsif ($response eq 'match') {
  346: 	my %answer=&Apache::lonnet::str2hash($answer);
  347: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  348: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  349: 	my ($toprow,$middlerow,$bottomrow);
  350: 	foreach my $foil (@$order) {
  351: 	    my $item=shift(@items);
  352: 	    if ($grading{$foil} == 1) {
  353: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  354: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  355: 	    } else {
  356: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  357: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  358: 	    }
  359: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  360: 	}
  361: 	return '<blockquote><table border="1">'.
  362: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  363: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  364: 	    $middlerow.'</tr>'.
  365: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  366: 	    $bottomrow.'</tr></table></blockquote>';
  367:     } elsif ($response eq 'radiobutton') {
  368: 	my %answer=&Apache::lonnet::str2hash($answer);
  369: 	my ($toprow,$bottomrow);
  370: 	my $correct = 
  371: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  372: 	foreach my $foil (@$order) {
  373: 	    if (exists($answer{$foil})) {
  374: 		if ($foil eq $correct) {
  375: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  376: 		} else {
  377: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  378: 		}
  379: 	    } else {
  380: 		$toprow.='<td>'.&mt('false').'</td>';
  381: 	    }
  382: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  383: 	}
  384: 	return '<blockquote><table border="1">'.
  385: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  386: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  387: 	    $bottomrow.'</tr></table></blockquote>';
  388:     } elsif ($response eq 'essay') {
  389: 	if (! exists ($env{'form.'.$symb})) {
  390: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  391: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  392: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  393: 
  394: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  395: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  396: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  397: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  398: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  399: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  400: 	}
  401: 	$answer =~ s-\n-<br />-g;
  402: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  403:     } elsif ( $response eq 'organic') {
  404: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  405: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  406: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  407: 	return $result;
  408:     } elsif ( $response eq 'Task') {
  409: 	if ( $answer eq 'SUBMITTED') {
  410: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  411: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  412: 	    return $result;
  413: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  414: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  415: 			       keys(%{$record}));
  416: 	    return join('<br />',($version,@matches));
  417: 			       
  418: 			       
  419: 	} else {
  420: 	    my $result =
  421: 		'<p>'
  422: 		.&mt('Overall result: [_1]',
  423: 		     $record->{$version."resource.$respid.$partid.status"})
  424: 		.'</p>';
  425: 	    
  426: 	    $result .= '<ul>';
  427: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  428: 			     keys(%{$record}));
  429: 	    foreach my $grade (sort(@grade)) {
  430: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  431: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  432: 				     $dim, $record->{$grade}).
  433: 			  '</li>';
  434: 	    }
  435: 	    $result.='</ul>';
  436: 	    return $result;
  437: 	}
  438:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  439: 	$answer = 
  440: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  441: 							      $answer);
  442:     }
  443:     return $answer;
  444: }
  445: 
  446: #-- A couple of common js functions
  447: sub commonJSfunctions {
  448:     my $request = shift;
  449:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  450:     function radioSelection(radioButton) {
  451: 	var selection=null;
  452: 	if (radioButton.length > 1) {
  453: 	    for (var i=0; i<radioButton.length; i++) {
  454: 		if (radioButton[i].checked) {
  455: 		    return radioButton[i].value;
  456: 		}
  457: 	    }
  458: 	} else {
  459: 	    if (radioButton.checked) return radioButton.value;
  460: 	}
  461: 	return selection;
  462:     }
  463: 
  464:     function pullDownSelection(selectOne) {
  465: 	var selection="";
  466: 	if (selectOne.length > 1) {
  467: 	    for (var i=0; i<selectOne.length; i++) {
  468: 		if (selectOne[i].selected) {
  469: 		    return selectOne[i].value;
  470: 		}
  471: 	    }
  472: 	} else {
  473:             // only one value it must be the selected one
  474: 	    return selectOne.value;
  475: 	}
  476:     }
  477: COMMONJSFUNCTIONS
  478: }
  479: 
  480: #--- Dumps the class list with usernames,list of sections,
  481: #--- section, ids and fullnames for each user.
  482: sub getclasslist {
  483:     my ($getsec,$filterlist,$getgroup) = @_;
  484:     my @getsec;
  485:     my @getgroup;
  486:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  487:     if (!ref($getsec)) {
  488: 	if ($getsec ne '' && $getsec ne 'all') {
  489: 	    @getsec=($getsec);
  490: 	}
  491:     } else {
  492: 	@getsec=@{$getsec};
  493:     }
  494:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  495:     if (!ref($getgroup)) {
  496: 	if ($getgroup ne '' && $getgroup ne 'all') {
  497: 	    @getgroup=($getgroup);
  498: 	}
  499:     } else {
  500: 	@getgroup=@{$getgroup};
  501:     }
  502:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  503: 
  504:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  505:     # Bail out if we were unable to get the classlist
  506:     return if (! defined($classlist));
  507:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  508:     #
  509:     my %sections;
  510:     my %fullnames;
  511:     foreach my $student (keys(%$classlist)) {
  512:         my $end      = 
  513:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  514:         my $start    = 
  515:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  516:         my $id       = 
  517:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  518:         my $section  = 
  519:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  520:         my $fullname = 
  521:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  522:         my $status   = 
  523:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  524:         my $group   = 
  525:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  526: 	# filter students according to status selected
  527: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  528: 	    if (!($stu_status =~ $status)) {
  529: 		delete($classlist->{$student});
  530: 		next;
  531: 	    }
  532: 	}
  533: 	# filter students according to groups selected
  534: 	my @stu_groups = split(/,/,$group);
  535: 	if (@getgroup) {
  536: 	    my $exclude = 1;
  537: 	    foreach my $grp (@getgroup) {
  538: 	        foreach my $stu_group (@stu_groups) {
  539: 	            if ($stu_group eq $grp) {
  540: 	                $exclude = 0;
  541:     	            } 
  542: 	        }
  543:     	        if (($grp eq 'none') && !$group) {
  544:         	        $exclude = 0;
  545:         	}
  546: 	    }
  547: 	    if ($exclude) {
  548: 	        delete($classlist->{$student});
  549: 	    }
  550: 	}
  551: 	$section = ($section ne '' ? $section : 'none');
  552: 	if (&canview($section)) {
  553: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  554: 		$sections{$section}++;
  555: 		if ($classlist->{$student}) {
  556: 		    $fullnames{$student}=$fullname;
  557: 		}
  558: 	    } else {
  559: 		delete($classlist->{$student});
  560: 	    }
  561: 	} else {
  562: 	    delete($classlist->{$student});
  563: 	}
  564:     }
  565:     my %seen = ();
  566:     my @sections = sort(keys(%sections));
  567:     return ($classlist,\@sections,\%fullnames);
  568: }
  569: 
  570: sub canmodify {
  571:     my ($sec)=@_;
  572:     if ($perm{'mgr'}) {
  573: 	if (!defined($perm{'mgr_section'})) {
  574: 	    # can modify whole class
  575: 	    return 1;
  576: 	} else {
  577: 	    if ($sec eq $perm{'mgr_section'}) {
  578: 		#can modify the requested section
  579: 		return 1;
  580: 	    } else {
  581: 		# can't modify the request section
  582: 		return 0;
  583: 	    }
  584: 	}
  585:     }
  586:     #can't modify
  587:     return 0;
  588: }
  589: 
  590: sub canview {
  591:     my ($sec)=@_;
  592:     if ($perm{'vgr'}) {
  593: 	if (!defined($perm{'vgr_section'})) {
  594: 	    # can modify whole class
  595: 	    return 1;
  596: 	} else {
  597: 	    if ($sec eq $perm{'vgr_section'}) {
  598: 		#can modify the requested section
  599: 		return 1;
  600: 	    } else {
  601: 		# can't modify the request section
  602: 		return 0;
  603: 	    }
  604: 	}
  605:     }
  606:     #can't modify
  607:     return 0;
  608: }
  609: 
  610: #--- Retrieve the grade status of a student for all the parts
  611: sub student_gradeStatus {
  612:     my ($symb,$udom,$uname,$partlist) = @_;
  613:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  614:     my %partstatus = ();
  615:     foreach (@$partlist) {
  616: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  617: 	$status              = 'nothing' if ($status eq '');
  618: 	$partstatus{$_}      = $status;
  619: 	my $subkey           = "resource.$_.submitted_by";
  620: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  621:     }
  622:     return %partstatus;
  623: }
  624: 
  625: # hidden form and javascript that calls the form
  626: # Use by verifyscript and viewgrades
  627: # Shows a student's view of problem and submission
  628: sub jscriptNform {
  629:     my ($symb) = @_;
  630:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  631:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  632: 	'    function viewOneStudent(user,domain) {'."\n".
  633: 	'	document.onestudent.student.value = user;'."\n".
  634: 	'	document.onestudent.userdom.value = domain;'."\n".
  635: 	'	document.onestudent.submit();'."\n".
  636: 	'    }'."\n".
  637: 	"\n");
  638:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  639: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  640: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  641: 	'<input type="hidden" name="command" value="submission" />'."\n".
  642: 	'<input type="hidden" name="student" value="" />'."\n".
  643: 	'<input type="hidden" name="userdom" value="" />'."\n".
  644: 	'</form>'."\n";
  645:     return $jscript;
  646: }
  647: 
  648: 
  649: 
  650: # Given the score (as a number [0-1] and the weight) what is the final
  651: # point value? This function will round to the nearest tenth, third,
  652: # or quarter if one of those is within the tolerance of .00001.
  653: sub compute_points {
  654:     my ($score, $weight) = @_;
  655:     
  656:     my $tolerance = .00001;
  657:     my $points = $score * $weight;
  658: 
  659:     # Check for nearness to 1/x.
  660:     my $check_for_nearness = sub {
  661:         my ($factor) = @_;
  662:         my $num = ($points * $factor) + $tolerance;
  663:         my $floored_num = floor($num);
  664:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  665:             return $floored_num / $factor;
  666:         }
  667:         return $points;
  668:     };
  669: 
  670:     $points = $check_for_nearness->(10);
  671:     $points = $check_for_nearness->(3);
  672:     $points = $check_for_nearness->(4);
  673:     
  674:     return $points;
  675: }
  676: 
  677: #------------------ End of general use routines --------------------
  678: 
  679: #
  680: # Find most similar essay
  681: #
  682: 
  683: sub most_similar {
  684:     my ($uname,$udom,$uessay,$old_essays)=@_;
  685: 
  686: # ignore spaces and punctuation
  687: 
  688:     $uessay=~s/\W+/ /gs;
  689: 
  690: # ignore empty submissions (occuring when only files are sent)
  691: 
  692:     unless ($uessay=~/\w+/s) { return ''; }
  693: 
  694: # these will be returned. Do not care if not at least 50 percent similar
  695:     my $limit=0.6;
  696:     my $sname='';
  697:     my $sdom='';
  698:     my $scrsid='';
  699:     my $sessay='';
  700: # go through all essays ...
  701:     foreach my $tkey (keys(%$old_essays)) {
  702: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  703: # ... except the same student
  704:         next if (($tname eq $uname) && ($tdom eq $udom));
  705: 	my $tessay=$old_essays->{$tkey};
  706: 	$tessay=~s/\W+/ /gs;
  707: # String similarity gives up if not even limit
  708: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  709: # Found one
  710: 	if ($tsimilar>$limit) {
  711: 	    $limit=$tsimilar;
  712: 	    $sname=$tname;
  713: 	    $sdom=$tdom;
  714: 	    $scrsid=$tcrsid;
  715: 	    $sessay=$old_essays->{$tkey};
  716: 	}
  717:     }
  718:     if ($limit>0.6) {
  719:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  720:     } else {
  721:        return ('','','','',0);
  722:     }
  723: }
  724: 
  725: #-------------------------------------------------------------------
  726: 
  727: #------------------------------------ Receipt Verification Routines
  728: #
  729: 
  730: sub initialverifyreceipt {
  731:    my ($request,$symb) = @_;
  732:    &commonJSfunctions($request);
  733:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  734:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  735:         '-<input type="text" name="receipt" size="4" />'.
  736:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  737:         '<input type="hidden" name="command" value="verify" />'.
  738:         "</form>\n";
  739: }
  740: 
  741: #--- Check whether a receipt number is valid.---
  742: sub verifyreceipt {
  743:     my ($request,$symb)  = @_;
  744: 
  745:     my $courseid = $env{'request.course.id'};
  746:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  747: 	$env{'form.receipt'};
  748:     $receipt     =~ s/[^\-\d]//g;
  749: 
  750:     my $title.=
  751: 	'<h3><span class="LC_info">'.
  752: 	&mt('Verifying Receipt Number [_1]',$receipt).
  753: 	'</span></h3>'."\n";
  754: 
  755:     my ($string,$contents,$matches) = ('','',0);
  756:     my (undef,undef,$fullname) = &getclasslist('all','0');
  757:     
  758:     my $receiptparts=0;
  759:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  760: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  761:     my $parts=['0'];
  762:     if ($receiptparts) {
  763:         my $res_error; 
  764:         ($parts)=&response_type($symb,\$res_error);
  765:         if ($res_error) {
  766:             return &navmap_errormsg();
  767:         } 
  768:     }
  769:     
  770:     my $header = 
  771: 	&Apache::loncommon::start_data_table().
  772: 	&Apache::loncommon::start_data_table_header_row().
  773: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  774: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  775: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  776:     if ($receiptparts) {
  777: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  778:     }
  779:     $header.=
  780: 	&Apache::loncommon::end_data_table_header_row();
  781: 
  782:     foreach (sort 
  783: 	     {
  784: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  785: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  786: 		 }
  787: 		 return $a cmp $b;
  788: 	     } (keys(%$fullname))) {
  789: 	my ($uname,$udom)=split(/\:/);
  790: 	foreach my $part (@$parts) {
  791: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  792: 		$contents.=
  793: 		    &Apache::loncommon::start_data_table_row().
  794: 		    '<td>&nbsp;'."\n".
  795: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  796: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  797: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  798: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  799: 		if ($receiptparts) {
  800: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  801: 		}
  802: 		$contents.= 
  803: 		    &Apache::loncommon::end_data_table_row()."\n";
  804: 		
  805: 		$matches++;
  806: 	    }
  807: 	}
  808:     }
  809:     if ($matches == 0) {
  810:         $string = $title
  811:                  .'<p class="LC_warning">'
  812:                  .&mt('No match found for the above receipt number.')
  813:                  .'</p>';
  814:     } else {
  815: 	$string = &jscriptNform($symb).$title.
  816: 	    '<p>'.
  817: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  818: 	    '</p>'.
  819: 	    $header.
  820: 	    $contents.
  821: 	    &Apache::loncommon::end_data_table()."\n";
  822:     }
  823:     return $string;
  824: }
  825: 
  826: #--- This is called by a number of programs.
  827: #--- Called from the Grading Menu - View/Grade an individual student
  828: #--- Also called directly when one clicks on the subm button 
  829: #    on the problem page.
  830: sub listStudents {
  831:     my ($request,$symb,$submitonly) = @_;
  832: 
  833:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  834:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  835:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  836:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  837:     unless ($submitonly) {
  838:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  839:     }
  840: 
  841:     my $result='';
  842:     my $res_error;
  843:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  844: 
  845:     my %lt = &Apache::lonlocal::texthash (
  846: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  847: 		'single'   => 'Please select the student before clicking on the Next button.',
  848: 	     );
  849:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  850:     function checkSelect(checkBox) {
  851: 	var ctr=0;
  852: 	var sense="";
  853: 	if (checkBox.length > 1) {
  854: 	    for (var i=0; i<checkBox.length; i++) {
  855: 		if (checkBox[i].checked) {
  856: 		    ctr++;
  857: 		}
  858: 	    }
  859: 	    sense = '$lt{'multiple'}';
  860: 	} else {
  861: 	    if (checkBox.checked) {
  862: 		ctr = 1;
  863: 	    }
  864: 	    sense = '$lt{'single'}';
  865: 	}
  866: 	if (ctr == 0) {
  867: 	    alert(sense);
  868: 	    return false;
  869: 	}
  870: 	document.gradesub.submit();
  871:     }
  872: 
  873:     function reLoadList(formname) {
  874: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  875: 	formname.command.value = 'submission';
  876: 	formname.submit();
  877:     }
  878: LISTJAVASCRIPT
  879: 
  880:     &commonJSfunctions($request);
  881:     $request->print($result);
  882: 
  883:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  884: 	"\n";
  885: 	
  886:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  887:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  888:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  889:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  890:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  891:                   .&Apache::lonhtmlcommon::row_closure();
  892:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  893:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  894:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  895:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  896:                   .&Apache::lonhtmlcommon::row_closure();
  897: 
  898:     my $submission_options;
  899:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  900:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  901:     $env{'form.Status'} = $saveStatus;
  902:     $submission_options.=
  903:         '<span class="LC_nobreak">'.
  904:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
  905:         &mt('last submission only').' </label></span>'."\n".
  906:         '<span class="LC_nobreak">'.
  907:         '<label><input type="radio" name="lastSub" value="last" /> '.
  908:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  909:         '<span class="LC_nobreak">'.
  910:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
  911:         &mt('by dates and submissions').'</label></span>'."\n".
  912:         '<span class="LC_nobreak">'.
  913:         '<label><input type="radio" name="lastSub" value="all" /> '.
  914:         &mt('all details').'</label></span>';
  915:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  916:                   .$submission_options
  917:                   .&Apache::lonhtmlcommon::row_closure();
  918: 
  919:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  920:                   .'<select name="increment">'
  921:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  922:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  923:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  924:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  925:                   .'</select>'
  926:                   .&Apache::lonhtmlcommon::row_closure();
  927: 
  928:     $gradeTable .= 
  929:         &build_section_inputs().
  930: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  931: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  932: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  933: 
  934:     if (exists($env{'form.Status'})) {
  935: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  936:     } else {
  937:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  938:                       .&Apache::lonhtmlcommon::StatusOptions(
  939:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  940:                       .&Apache::lonhtmlcommon::row_closure();
  941:     }
  942: 
  943:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  944:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  945:                   .&Apache::lonhtmlcommon::row_closure(1)
  946:                   .&Apache::lonhtmlcommon::end_pick_box();
  947: 
  948:     $gradeTable .= '<p>'
  949:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
  950:                   .'<input type="hidden" name="command" value="processGroup" />'
  951:                   .'</p>';
  952: 
  953: # checkall buttons
  954:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  955:     $gradeTable.='<input type="button" '."\n".
  956:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  957:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  958:     $gradeTable.=&check_buttons();
  959:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  960:     $gradeTable.= &Apache::loncommon::start_data_table().
  961: 	&Apache::loncommon::start_data_table_header_row();
  962:     my $loop = 0;
  963:     while ($loop < 2) {
  964: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  965: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  966: 	if (($submitonly ne 'queued') && ($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 (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1003: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1004: 	    my $submitted = 0;
 1005: 	    my $graded = 0;
 1006: 	    my $incorrect = 0;
 1007: 	    foreach (keys(%status)) {
 1008: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1009: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1010: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1011: 		
 1012: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1013: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1014: 		    $submitted = 0;
 1015: 		    my ($part)=split(/\./,$partid);
 1016: 		    $gradeTable.='<input type="hidden" name="'.
 1017: 			$student.':'.$part.':submitted_by" value="'.
 1018: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1019: 		}
 1020: 	    }
 1021: 	    
 1022: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1023: 				     $submitonly eq 'incorrect' ||
 1024: 				     $submitonly eq 'graded'));
 1025: 	    next if (!$graded && ($submitonly eq 'graded'));
 1026: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1027: 	}
 1028: 
 1029: 	$ctr++;
 1030: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1031:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1032: 	if ( $perm{'vgr'} eq 'F' ) {
 1033: 	    if ($ctr%2 ==1) {
 1034: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1035: 	    }
 1036: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1037:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1038:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1039: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1040: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1041: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1042: 
 1043: 	    if ($submitonly ne 'all') {
 1044: 		foreach (sort(keys(%status))) {
 1045: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1046: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1047: 		}
 1048: 	    }
 1049: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1050: 	    if ($ctr%2 ==0) {
 1051: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1052: 	    }
 1053: 	}
 1054:     }
 1055:     if ($ctr%2 ==1) {
 1056: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1057: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1058: 		foreach (@$partlist) {
 1059: 		    $gradeTable.='<td>&nbsp;</td>';
 1060: 		}
 1061: 	    } elsif ($submitonly eq 'queued') {
 1062: 		$gradeTable.='<td>&nbsp;</td>';
 1063: 	    }
 1064: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1065:     }
 1066: 
 1067:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1068:         '<input type="button" '.
 1069:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1070:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1071:     if ($ctr == 0) {
 1072: 	my $num_students=(scalar(keys(%$fullname)));
 1073: 	if ($num_students eq 0) {
 1074: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1075: 	} else {
 1076: 	    my $submissions='submissions';
 1077: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1078: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1079: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1080: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1081: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1082: 		    $num_students).
 1083: 		'</span><br />';
 1084: 	}
 1085:     } elsif ($ctr == 1) {
 1086: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1087:     }
 1088:     $request->print($gradeTable);
 1089:     return '';
 1090: }
 1091: 
 1092: #---- Called from the listStudents routine
 1093: 
 1094: sub check_script {
 1095:     my ($form, $type)=@_;
 1096:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1097:     function checkall() {
 1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1099:             ele = document.forms.'.$form.'.elements[i];
 1100:             if (ele.name == "'.$type.'") {
 1101:             document.forms.'.$form.'.elements[i].checked=true;
 1102:                                        }
 1103:         }
 1104:     }
 1105: 
 1106:     function checksec() {
 1107:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1108:             ele = document.forms.'.$form.'.elements[i];
 1109:            string = document.forms.'.$form.'.chksec.value;
 1110:            if
 1111:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1112:               document.forms.'.$form.'.elements[i].checked=true;
 1113:             }
 1114:         }
 1115:     }
 1116: 
 1117: 
 1118:     function uncheckall() {
 1119:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1120:             ele = document.forms.'.$form.'.elements[i];
 1121:             if (ele.name == "'.$type.'") {
 1122:             document.forms.'.$form.'.elements[i].checked=false;
 1123:                                        }
 1124:         }
 1125:     }
 1126: 
 1127: '."\n");
 1128:     return $chkallscript;
 1129: }
 1130: 
 1131: sub check_buttons {
 1132:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1133:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1134:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1135:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1136:     return $buttons;
 1137: }
 1138: 
 1139: #     Displays the submissions for one student or a group of students
 1140: sub processGroup {
 1141:     my ($request,$symb)  = @_;
 1142:     my $ctr        = 0;
 1143:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1144:     my $total      = scalar(@stuchecked)-1;
 1145: 
 1146:     foreach my $student (@stuchecked) {
 1147: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1148: 	$env{'form.student'}        = $uname;
 1149: 	$env{'form.userdom'}        = $udom;
 1150: 	$env{'form.fullname'}       = $fullname;
 1151: 	&submission($request,$ctr,$total,$symb);
 1152: 	$ctr++;
 1153:     }
 1154:     return '';
 1155: }
 1156: 
 1157: #------------------------------------------------------------------------------------
 1158: #
 1159: #-------------------------- Next few routines handles grading by student, essentially
 1160: #                           handles essay response type problem/part
 1161: #
 1162: #--- Javascript to handle the submission page functionality ---
 1163: sub sub_page_js {
 1164:     my $request = shift;
 1165: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1166:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1167:     function updateRadio(formname,id,weight) {
 1168: 	var gradeBox = formname["GD_BOX"+id];
 1169: 	var radioButton = formname["RADVAL"+id];
 1170: 	var oldpts = formname["oldpts"+id].value;
 1171: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1172: 	gradeBox.value = pts;
 1173: 	var resetbox = false;
 1174: 	if (isNaN(pts) || pts < 0) {
 1175: 	    alert("$alertmsg"+pts);
 1176: 	    for (var i=0; i<radioButton.length; i++) {
 1177: 		if (radioButton[i].checked) {
 1178: 		    gradeBox.value = i;
 1179: 		    resetbox = true;
 1180: 		}
 1181: 	    }
 1182: 	    if (!resetbox) {
 1183: 		formtextbox.value = "";
 1184: 	    }
 1185: 	    return;
 1186: 	}
 1187: 
 1188: 	if (pts > weight) {
 1189: 	    var resp = confirm("You entered a value ("+pts+
 1190: 			       ") greater than the weight for the part. Accept?");
 1191: 	    if (resp == false) {
 1192: 		gradeBox.value = oldpts;
 1193: 		return;
 1194: 	    }
 1195: 	}
 1196: 
 1197: 	for (var i=0; i<radioButton.length; i++) {
 1198: 	    radioButton[i].checked=false;
 1199: 	    if (pts == i && pts != "") {
 1200: 		radioButton[i].checked=true;
 1201: 	    }
 1202: 	}
 1203: 	updateSelect(formname,id);
 1204: 	formname["stores"+id].value = "0";
 1205:     }
 1206: 
 1207:     function writeBox(formname,id,pts) {
 1208: 	var gradeBox = formname["GD_BOX"+id];
 1209: 	if (checkSolved(formname,id) == 'update') {
 1210: 	    gradeBox.value = pts;
 1211: 	} else {
 1212: 	    var oldpts = formname["oldpts"+id].value;
 1213: 	    gradeBox.value = oldpts;
 1214: 	    var radioButton = formname["RADVAL"+id];
 1215: 	    for (var i=0; i<radioButton.length; i++) {
 1216: 		radioButton[i].checked=false;
 1217: 		if (i == oldpts) {
 1218: 		    radioButton[i].checked=true;
 1219: 		}
 1220: 	    }
 1221: 	}
 1222: 	formname["stores"+id].value = "0";
 1223: 	updateSelect(formname,id);
 1224: 	return;
 1225:     }
 1226: 
 1227:     function clearRadBox(formname,id) {
 1228: 	if (checkSolved(formname,id) == 'noupdate') {
 1229: 	    updateSelect(formname,id);
 1230: 	    return;
 1231: 	}
 1232: 	gradeSelect = formname["GD_SEL"+id];
 1233: 	for (var i=0; i<gradeSelect.length; i++) {
 1234: 	    if (gradeSelect[i].selected) {
 1235: 		var selectx=i;
 1236: 	    }
 1237: 	}
 1238: 	var stores = formname["stores"+id];
 1239: 	if (selectx == stores.value) { return };
 1240: 	var gradeBox = formname["GD_BOX"+id];
 1241: 	gradeBox.value = "";
 1242: 	var radioButton = formname["RADVAL"+id];
 1243: 	for (var i=0; i<radioButton.length; i++) {
 1244: 	    radioButton[i].checked=false;
 1245: 	}
 1246: 	stores.value = selectx;
 1247:     }
 1248: 
 1249:     function checkSolved(formname,id) {
 1250: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1251: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1252: 	    if (!reply) {return "noupdate";}
 1253: 	    formname.overRideScore.value = 'yes';
 1254: 	}
 1255: 	return "update";
 1256:     }
 1257: 
 1258:     function updateSelect(formname,id) {
 1259: 	formname["GD_SEL"+id][0].selected = true;
 1260: 	return;
 1261:     }
 1262: 
 1263: //=========== Check that a point is assigned for all the parts  ============
 1264:     function checksubmit(formname,val,total,parttot) {
 1265: 	formname.gradeOpt.value = val;
 1266: 	if (val == "Save & Next") {
 1267: 	    for (i=0;i<=total;i++) {
 1268: 		for (j=0;j<parttot;j++) {
 1269: 		    var partid = formname["partid"+i+"_"+j].value;
 1270: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1271: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1272: 			if (points == "") {
 1273: 			    var name = formname["name"+i].value;
 1274: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1275: 			    var resp = confirm("You did not assign a score for "+studentID+
 1276: 					       ", part "+partid+". Continue?");
 1277: 			    if (resp == false) {
 1278: 				formname["GD_BOX"+i+"_"+partid].focus();
 1279: 				return false;
 1280: 			    }
 1281: 			}
 1282: 		    }
 1283: 		    
 1284: 		}
 1285: 	    }
 1286: 	    
 1287: 	}
 1288: 	formname.submit();
 1289:     }
 1290: 
 1291: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1292:     function checkSubmitPage(formname,total) {
 1293: 	noscore = new Array(100);
 1294: 	var ptr = 0;
 1295: 	for (i=1;i<total;i++) {
 1296: 	    var partid = formname["q_"+i].value;
 1297: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1298: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1299: 		var status = formname["solved"+i+"_"+partid].value;
 1300: 		if (points == "" && status != "correct_by_student") {
 1301: 		    noscore[ptr] = i;
 1302: 		    ptr++;
 1303: 		}
 1304: 	    }
 1305: 	}
 1306: 	if (ptr != 0) {
 1307: 	    var sense = ptr == 1 ? ": " : "s: ";
 1308: 	    var prolist = "";
 1309: 	    if (ptr == 1) {
 1310: 		prolist = noscore[0];
 1311: 	    } else {
 1312: 		var i = 0;
 1313: 		while (i < ptr-1) {
 1314: 		    prolist += noscore[i]+", ";
 1315: 		    i++;
 1316: 		}
 1317: 		prolist += "and "+noscore[i];
 1318: 	    }
 1319: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1320: 	    if (resp == false) {
 1321: 		return false;
 1322: 	    }
 1323: 	}
 1324: 
 1325: 	formname.submit();
 1326:     }
 1327: SUBJAVASCRIPT
 1328: }
 1329: 
 1330: #--- javascript for essay type problem --
 1331: sub sub_page_kw_js {
 1332:     my $request = shift;
 1333:     my $iconpath = $request->dir_config('lonIconsURL');
 1334:     &commonJSfunctions($request);
 1335: 
 1336:     my $inner_js_msg_central= (<<INNERJS);
 1337: <script type="text/javascript">
 1338:     function checkInput() {
 1339:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1340:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1341:       var usrctr = document.msgcenter.usrctr.value;
 1342:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1343:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1344: 
 1345:       var msgchk = "";
 1346:       if (document.msgcenter.subchk.checked) {
 1347:          msgchk = "msgsub,";
 1348:       }
 1349:       var includemsg = 0;
 1350:       for (var i=1; i<=nmsg; i++) {
 1351:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1352:           var frmmsg = document.msgcenter["msg"+i];
 1353:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1354:           var showflg = opener.document.SCORE["shownOnce"+i];
 1355:           showflg.value = "1";
 1356:           var chkbox = document.msgcenter["msgn"+i];
 1357:           if (chkbox.checked) {
 1358:              msgchk += "savemsg"+i+",";
 1359:              includemsg = 1;
 1360:           }
 1361:       }
 1362:       if (document.msgcenter.newmsgchk.checked) {
 1363:          msgchk += "newmsg"+usrctr;
 1364:          includemsg = 1;
 1365:       }
 1366:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1367:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1368:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1369:       includemsg.value = msgchk;
 1370: 
 1371:       self.close()
 1372: 
 1373:     }
 1374: </script>
 1375: INNERJS
 1376: 
 1377:     my $inner_js_highlight_central= (<<INNERJS);
 1378: <script type="text/javascript">
 1379:     function updateChoice(flag) {
 1380:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1381:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1382:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1383:       opener.document.SCORE.refresh.value = "on";
 1384:       if (opener.document.SCORE.keywords.value!=""){
 1385:          opener.document.SCORE.submit();
 1386:       }
 1387:       self.close()
 1388:     }
 1389: </script>
 1390: INNERJS
 1391: 
 1392:     my $start_page_msg_central = 
 1393:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1394: 				       {'js_ready'  => 1,
 1395: 					'only_body' => 1,
 1396: 					'bgcolor'   =>'#FFFFFF',});
 1397:     my $end_page_msg_central = 
 1398: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1399: 
 1400: 
 1401:     my $start_page_highlight_central = 
 1402:         &Apache::loncommon::start_page('Highlight Central',
 1403: 				       $inner_js_highlight_central,
 1404: 				       {'js_ready'  => 1,
 1405: 					'only_body' => 1,
 1406: 					'bgcolor'   =>'#FFFFFF',});
 1407:     my $end_page_highlight_central = 
 1408: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1409: 
 1410:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1411:     $docopen=~s/^document\.//;
 1412:     my %lt = &Apache::lonlocal::texthash(
 1413:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1414:                 plse => 'Please select a word or group of words from document and then click this link.',
 1415:                 adds => 'Add selection to keyword list? Edit if desired.',
 1416:                 comp => 'Compose Message for: ',
 1417:                 incl => 'Include',
 1418:                 type => 'Type',
 1419:                 subj => 'Subject',
 1420:                 mesa => 'Message',
 1421:                 new  => 'New',
 1422:                 save => 'Save',
 1423:                 canc => 'Cancel',
 1424:                 kehi => 'Keyword Highlight Options',
 1425:                 txtc => 'Text Color',
 1426:                 font => 'Font Size',
 1427:                 fnst => 'Font Style',
 1428:              );
 1429:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1430: 
 1431: //===================== Show list of keywords ====================
 1432:   function keywords(formname) {
 1433:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
 1434:     if (nret==null) return;
 1435:     formname.keywords.value = nret;
 1436: 
 1437:     if (formname.keywords.value != "") {
 1438: 	formname.refresh.value = "on";
 1439: 	formname.submit();
 1440:     }
 1441:     return;
 1442:   }
 1443: 
 1444: //===================== Script to view submitted by ==================
 1445:   function viewSubmitter(submitter) {
 1446:     document.SCORE.refresh.value = "on";
 1447:     document.SCORE.NCT.value = "1";
 1448:     document.SCORE.unamedom0.value = submitter;
 1449:     document.SCORE.submit();
 1450:     return;
 1451:   }
 1452: 
 1453: //===================== Script to add keyword(s) ==================
 1454:   function getSel() {
 1455:     if (document.getSelection) txt = document.getSelection();
 1456:     else if (document.selection) txt = document.selection.createRange().text;
 1457:     else return;
 1458:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1459:     if (cleantxt=="") {
 1460: 	alert("$lt{'plse'}");
 1461: 	return;
 1462:     }
 1463:     var nret = prompt("$lt{'adds'}",cleantxt);
 1464:     if (nret==null) return;
 1465:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1466:     if (document.SCORE.keywords.value != "") {
 1467: 	document.SCORE.refresh.value = "on";
 1468: 	document.SCORE.submit();
 1469:     }
 1470:     return;
 1471:   }
 1472: 
 1473: //====================== Script for composing message ==============
 1474:    // preload images
 1475:    img1 = new Image();
 1476:    img1.src = "$iconpath/mailbkgrd.gif";
 1477:    img2 = new Image();
 1478:    img2.src = "$iconpath/mailto.gif";
 1479: 
 1480:   function msgCenter(msgform,usrctr,fullname) {
 1481:     var Nmsg  = msgform.savemsgN.value;
 1482:     savedMsgHeader(Nmsg,usrctr,fullname);
 1483:     var subject = msgform.msgsub.value;
 1484:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1485:     re = /msgsub/;
 1486:     var shwsel = "";
 1487:     if (re.test(msgchk)) { shwsel = "checked" }
 1488:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1489:     displaySubject(checkEntities(subject),shwsel);
 1490:     for (var i=1; i<=Nmsg; i++) {
 1491: 	var testmsg = "savemsg"+i+",";
 1492: 	re = new RegExp(testmsg,"g");
 1493: 	shwsel = "";
 1494: 	if (re.test(msgchk)) { shwsel = "checked" }
 1495: 	var message = document.SCORE["savemsg"+i].value;
 1496: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1497: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1498: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1499:     }
 1500:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1501:     shwsel = "";
 1502:     re = /newmsg/;
 1503:     if (re.test(msgchk)) { shwsel = "checked" }
 1504:     newMsg(newmsg,shwsel);
 1505:     msgTail(); 
 1506:     return;
 1507:   }
 1508: 
 1509:   function checkEntities(strx) {
 1510:     if (strx.length == 0) return strx;
 1511:     var orgStr = ["&", "<", ">", '"']; 
 1512:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1513:     var counter = 0;
 1514:     while (counter < 4) {
 1515: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1516: 	counter++;
 1517:     }
 1518:     return strx;
 1519:   }
 1520: 
 1521:   function strReplace(strx, orgStr, newStr) {
 1522:     return strx.split(orgStr).join(newStr);
 1523:   }
 1524: 
 1525:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1526:     var height = 70*Nmsg+250;
 1527:     if (height > 600) {
 1528: 	height = 600;
 1529:     }
 1530:     var xpos = (screen.width-600)/2;
 1531:     xpos = (xpos < 0) ? '0' : xpos;
 1532:     var ypos = (screen.height-height)/2-30;
 1533:     ypos = (ypos < 0) ? '0' : ypos;
 1534: 
 1535:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1536:     pWin.focus();
 1537:     pDoc = pWin.document;
 1538:     pDoc.$docopen;
 1539:     pDoc.write('$start_page_msg_central');
 1540: 
 1541:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1542:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1543:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
 1544: 
 1545:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1546:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1547:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
 1548: }
 1549:     function displaySubject(msg,shwsel) {
 1550:     pDoc = pWin.document;
 1551:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1552:     pDoc.write("<td>$lt{'subj'}<\\/td>");
 1553:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1554:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1555: }
 1556: 
 1557:   function displaySavedMsg(ctr,msg,shwsel) {
 1558:     pDoc = pWin.document;
 1559:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1560:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1561:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1562:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1563: }
 1564: 
 1565:   function newMsg(newmsg,shwsel) {
 1566:     pDoc = pWin.document;
 1567:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1568:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
 1569:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1570:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1571: }
 1572: 
 1573:   function msgTail() {
 1574:     pDoc = pWin.document;
 1575:     pDoc.write("<\\/table>");
 1576:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1577:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1578:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1579:     pDoc.write("<\\/form>");
 1580:     pDoc.write('$end_page_msg_central');
 1581:     pDoc.close();
 1582: }
 1583: 
 1584: //====================== Script for keyword highlight options ==============
 1585:   function kwhighlight() {
 1586:     var kwclr    = document.SCORE.kwclr.value;
 1587:     var kwsize   = document.SCORE.kwsize.value;
 1588:     var kwstyle  = document.SCORE.kwstyle.value;
 1589:     var redsel = "";
 1590:     var grnsel = "";
 1591:     var blusel = "";
 1592:     if (kwclr=="red")   {var redsel="checked"};
 1593:     if (kwclr=="green") {var grnsel="checked"};
 1594:     if (kwclr=="blue")  {var blusel="checked"};
 1595:     var sznsel = "";
 1596:     var sz1sel = "";
 1597:     var sz2sel = "";
 1598:     if (kwsize=="0")  {var sznsel="checked"};
 1599:     if (kwsize=="+1") {var sz1sel="checked"};
 1600:     if (kwsize=="+2") {var sz2sel="checked"};
 1601:     var synsel = "";
 1602:     var syisel = "";
 1603:     var sybsel = "";
 1604:     if (kwstyle=="")    {var synsel="checked"};
 1605:     if (kwstyle=="<i>") {var syisel="checked"};
 1606:     if (kwstyle=="<b>") {var sybsel="checked"};
 1607:     highlightCentral();
 1608:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1609:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1610:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1611:     highlightend();
 1612:     return;
 1613:   }
 1614: 
 1615:   function highlightCentral() {
 1616: //    if (window.hwdWin) window.hwdWin.close();
 1617:     var xpos = (screen.width-400)/2;
 1618:     xpos = (xpos < 0) ? '0' : xpos;
 1619:     var ypos = (screen.height-330)/2-30;
 1620:     ypos = (ypos < 0) ? '0' : ypos;
 1621: 
 1622:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1623:     hwdWin.focus();
 1624:     var hDoc = hwdWin.document;
 1625:     hDoc.$docopen;
 1626:     hDoc.write('$start_page_highlight_central');
 1627:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1628:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
 1629: 
 1630:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1631:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1632:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
 1633:   }
 1634: 
 1635:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1636:     var hDoc = hwdWin.document;
 1637:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1638:     hDoc.write("<td align=\\"left\\">");
 1639:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1640:     hDoc.write("<td align=\\"left\\">");
 1641:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1642:     hDoc.write("<td align=\\"left\\">");
 1643:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1644:     hDoc.write("<\\/tr>");
 1645:   }
 1646: 
 1647:   function highlightend() { 
 1648:     var hDoc = hwdWin.document;
 1649:     hDoc.write("<\\/table>");
 1650:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1651:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1652:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1653:     hDoc.write("<\\/form>");
 1654:     hDoc.write('$end_page_highlight_central');
 1655:     hDoc.close();
 1656:   }
 1657: 
 1658: SUBJAVASCRIPT
 1659: }
 1660: 
 1661: sub get_increment {
 1662:     my $increment = $env{'form.increment'};
 1663:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1664:         $increment != .1) {
 1665:         $increment = 1;
 1666:     }
 1667:     return $increment;
 1668: }
 1669: 
 1670: sub gradeBox_start {
 1671:     return (
 1672:         &Apache::loncommon::start_data_table()
 1673:        .&Apache::loncommon::start_data_table_header_row()
 1674:        .'<th>'.&mt('Part').'</th>'
 1675:        .'<th>'.&mt('Points').'</th>'
 1676:        .'<th>&nbsp;</th>'
 1677:        .'<th>'.&mt('Assign Grade').'</th>'
 1678:        .'<th>'.&mt('Weight').'</th>'
 1679:        .'<th>'.&mt('Grade Status').'</th>'
 1680:        .&Apache::loncommon::end_data_table_header_row()
 1681:     );
 1682: }
 1683: 
 1684: sub gradeBox_end {
 1685:     return (
 1686:         &Apache::loncommon::end_data_table()
 1687:     );
 1688: }
 1689: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1690: sub gradeBox {
 1691:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1692:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1693: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1694:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1695:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1696:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1697:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1698:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1699: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1700:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1701:     my $display_part= &get_display_part($partid,$symb);
 1702:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1703: 				       [$partid]);
 1704:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1705:     if ($last_resets{$partid}) {
 1706:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1707:     }
 1708:     $result.=&Apache::loncommon::start_data_table_row();
 1709:     my $ctr = 0;
 1710:     my $thisweight = 0;
 1711:     my $increment = &get_increment();
 1712: 
 1713:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1714:     while ($thisweight<=$wgt) {
 1715: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1716:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1717: 	    $thisweight.')" value="'.$thisweight.'" '.
 1718: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1719: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1720:         $thisweight += $increment;
 1721: 	$ctr++;
 1722:     }
 1723:     $radio.='</tr></table>';
 1724: 
 1725:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1726: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1727: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1728: 	$wgt.')" /></td>'."\n";
 1729:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1730: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1731: 	' </td>'."\n";
 1732:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1733: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1734:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1735: 	$line.='<option></option>'.
 1736: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1737:     } else {
 1738: 	$line.='<option selected="selected"></option>'.
 1739: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1740:     }
 1741:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1742: 
 1743: 
 1744:     $result .= 
 1745: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1746:     $result.=&Apache::loncommon::end_data_table_row();
 1747:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1748: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1749: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1750: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1751:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1752:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1753:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1754:         $aggtries.'" />'."\n";
 1755:     my $res_error;
 1756:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1757:     if ($res_error) {
 1758:         return &navmap_errormsg();
 1759:     }
 1760:     return $result;
 1761: }
 1762: 
 1763: sub handback_box {
 1764:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1765:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1766:     my (@respids);
 1767:     my @part_response_id = &flatten_responseType($responseType);
 1768:     foreach my $part_response_id (@part_response_id) {
 1769:     	my ($part,$resp) = @{ $part_response_id };
 1770:         if ($part eq $partid) {
 1771:             push(@respids,$resp);
 1772:         }
 1773:     }
 1774:     my $result;
 1775:     foreach my $respid (@respids) {
 1776: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1777: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1778: 	next if (!@$files);
 1779: 	my $file_counter = 0;
 1780: 	foreach my $file (@$files) {
 1781: 	    if ($file =~ /\/portfolio\//) {
 1782:                 $file_counter++;
 1783:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1784:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1785:     	        $file_disp = "$name.$ext";
 1786:     	        $file = $file_path.$file_disp;
 1787:     	        $result.=&mt('Return commented version of [_1] to student.',
 1788:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1789:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1790:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1791: 	    }
 1792: 	}
 1793:         if ($file_counter) {
 1794:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1795:                        '<span class="LC_info">'.
 1796:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1797:         }
 1798:     }
 1799:     return $result;    
 1800: }
 1801: 
 1802: sub show_problem {
 1803:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1804:     my $rendered;
 1805:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1806:     &Apache::lonxml::remember_problem_counter();
 1807:     if ($mode eq 'both' or $mode eq 'text') {
 1808: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1809: 						       $env{'request.course.id'},
 1810: 						       undef,\%form);
 1811:     }
 1812:     if ($removeform) {
 1813: 	$rendered=~s|<form(.*?)>||g;
 1814: 	$rendered=~s|</form>||g;
 1815: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1816:     }
 1817:     my $companswer;
 1818:     if ($mode eq 'both' or $mode eq 'answer') {
 1819: 	&Apache::lonxml::restore_problem_counter();
 1820: 	$companswer=
 1821: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1822: 						    $env{'request.course.id'},
 1823: 						    %form);
 1824:     }
 1825:     if ($removeform) {
 1826: 	$companswer=~s|<form(.*?)>||g;
 1827: 	$companswer=~s|</form>||g;
 1828: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1829:     }
 1830:     my $renderheading = &mt('View of the problem');
 1831:     my $answerheading = &mt('Correct answer');
 1832:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1833:         my $stu_fullname = $env{'form.fullname'};
 1834:         if ($stu_fullname eq '') {
 1835:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1836:         }
 1837:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1838:         if ($forwhom ne '') {
 1839:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1840:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1841:         }
 1842:     }
 1843:     $rendered=
 1844:         '<div class="LC_Box">'
 1845:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1846:        .$rendered
 1847:        .'</div>';
 1848:     $companswer=
 1849:         '<div class="LC_Box">'
 1850:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1851:        .$companswer
 1852:        .'</div>';
 1853:     my $result;
 1854:     if ($mode eq 'both') {
 1855:         $result=$rendered.$companswer;
 1856:     } elsif ($mode eq 'text') {
 1857:         $result=$rendered;
 1858:     } elsif ($mode eq 'answer') {
 1859:         $result=$companswer;
 1860:     }
 1861:     return $result;
 1862: }
 1863: 
 1864: sub files_exist {
 1865:     my ($r, $symb) = @_;
 1866:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1867: 
 1868:     foreach my $student (@students) {
 1869:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1870:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1871: 					      $udom,$uname);
 1872:         my ($string,$timestamp)= &get_last_submission(\%record);
 1873:         foreach my $submission (@$string) {
 1874:             my ($partid,$respid) =
 1875: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1876:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1877: 					   \%record);
 1878:             return 1 if (@$files);
 1879:         }
 1880:     }
 1881:     return 0;
 1882: }
 1883: 
 1884: sub download_all_link {
 1885:     my ($r,$symb) = @_;
 1886:     unless (&files_exist($r, $symb)) {
 1887:        $r->print(&mt('There are currently no submitted documents.'));
 1888:        return;
 1889:     }
 1890: 
 1891:     my $all_students = 
 1892: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1893: 
 1894:     my $parts =
 1895: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1896: 
 1897:     my $identifier = &Apache::loncommon::get_cgi_id();
 1898:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1899:                              'cgi.'.$identifier.'.symb' => $symb,
 1900:                              'cgi.'.$identifier.'.parts' => $parts,});
 1901:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1902: 	      &mt('Download All Submitted Documents').'</a>');
 1903:     return;
 1904: }
 1905: 
 1906: sub submit_download_link {
 1907:     my ($request,$symb) = @_;
 1908:     if (!$symb) { return ''; }
 1909: #FIXME: Figure out which type of problem this is and provide appropriate download
 1910:     &download_all_link($request,$symb);
 1911: }
 1912: 
 1913: sub build_section_inputs {
 1914:     my $section_inputs;
 1915:     if ($env{'form.section'} eq '') {
 1916:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1917:     } else {
 1918:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1919:         foreach my $section (@sections) {
 1920:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1921:         }
 1922:     }
 1923:     return $section_inputs;
 1924: }
 1925: 
 1926: # --------------------------- show submissions of a student, option to grade 
 1927: sub submission {
 1928:     my ($request,$counter,$total,$symb) = @_;
 1929:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1930:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1931:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1932:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1933: 
 1934:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 1935:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1936: 
 1937:     if (!&canview($usec)) {
 1938: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1939: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1940: 			$env{'request.course.id'}.')</span>');
 1941: 	return;
 1942:     }
 1943: 
 1944:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1945:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1946:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1947:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1948:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1949: 	'" src="'.$request->dir_config('lonIconsURL').
 1950: 	'/check.gif" height="16" border="0" />';
 1951: 
 1952:     my %old_essays;
 1953:     # header info
 1954:     if ($counter == 0) {
 1955: 	&sub_page_js($request);
 1956: 	&sub_page_kw_js($request);
 1957: 
 1958: 	# option to display problem, only once else it cause problems 
 1959:         # with the form later since the problem has a form.
 1960: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1961: 	    my $mode;
 1962: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1963: 		$mode='both';
 1964: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1965: 		$mode='text';
 1966: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1967: 		$mode='answer';
 1968: 	    }
 1969: 	    &Apache::lonxml::clear_problem_counter();
 1970: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1971: 	}
 1972: 
 1973: 	# kwclr is the only variable that is guaranteed to be non blank 
 1974:         # if this subroutine has been called once.
 1975: 	my %keyhash = ();
 1976: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1977:         if (1) {
 1978: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1979: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1980: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1981: 
 1982: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1983: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1984: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1985: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1986: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1987: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1988: 		$keyhash{$symb.'_subject'} : $probtitle;
 1989: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1990: 	}
 1991: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1992: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1993: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1994: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1995: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1996: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1997: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1998: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1999: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2000: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2001: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2002: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2003: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2004: 			&build_section_inputs().
 2005: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2006: 			'<input type="hidden" name="NCT"'.
 2007: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2008: #	if ($env{'form.handgrade'} eq 'yes') {
 2009:         if (1) {
 2010: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2011: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2012: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2013: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2014: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2015: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2016: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2017: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2018: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2019: 	    }
 2020: 	}
 2021: 	
 2022: 	my ($cts,$prnmsg) = (1,'');
 2023: 	while ($cts <= $env{'form.savemsgN'}) {
 2024: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2025: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2026: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2027: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2028: 		'" />'."\n".
 2029: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2030: 	    $cts++;
 2031: 	}
 2032: 	$request->print($prnmsg);
 2033: 
 2034: #	if ($env{'form.handgrade'} eq 'yes') {
 2035:         if (1) {
 2036: 
 2037:             my %lt = &Apache::lonlocal::texthash(
 2038:                           keyw => 'Keyword Options',
 2039:                           list => 'List',
 2040:                           past => 'Paste Selection to List',
 2041:                           high => 'Highlight Attribute',
 2042:                      );    
 2043: #
 2044: # Print out the keyword options line
 2045: #
 2046: 	    $request->print(<<KEYWORDS);
 2047: <br /><b>$lt{'keyw'}:</b>&nbsp;
 2048: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
 2049: <a href="#" onmousedown="javascript:getSel(); return false"
 2050:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
 2051: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
 2052: KEYWORDS
 2053: #
 2054: # Load the other essays for similarity check
 2055: #
 2056:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2057: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2058: 	    $apath=&escape($apath);
 2059: 	    $apath=~s/\W/\_/gs;
 2060: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2061:         }
 2062:     }
 2063: 
 2064: # This is where output for one specific student would start
 2065:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2066:     $request->print(
 2067:         "\n\n"
 2068:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2069:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2070:        ."\n"
 2071:     );
 2072: 
 2073:     # Show additional functions if allowed
 2074:     if ($perm{'vgr'}) {
 2075:         $request->print(
 2076:             &Apache::loncommon::track_student_link(
 2077:                 &mt('View recent activity'),
 2078:                 $uname,$udom,'check')
 2079:            .' '
 2080:         );
 2081:     }
 2082:     if ($perm{'opa'}) {
 2083:         $request->print(
 2084:             &Apache::loncommon::pprmlink(
 2085:                 &mt('Set/Change parameters'),
 2086:                 $uname,$udom,$symb,'check'));
 2087:     }
 2088: 
 2089:     # Show Problem
 2090:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2091: 	my $mode;
 2092: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2093: 	    $mode='both';
 2094: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2095: 	    $mode='text';
 2096: 	} elsif ($env{'form.vAns'} eq 'all') {
 2097: 	    $mode='answer';
 2098: 	}
 2099: 	&Apache::lonxml::clear_problem_counter();
 2100: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2101:     }
 2102: 
 2103:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2104:     my $res_error;
 2105:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2106:     if ($res_error) {
 2107:         $request->print(&navmap_errormsg());
 2108:         return;
 2109:     }
 2110: 
 2111:     # Display student info
 2112:     $request->print(($counter == 0 ? '' : '<br />'));
 2113: 
 2114:     my $result='<div class="LC_Box">'
 2115:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2116:     $result.='<input type="hidden" name="name'.$counter.
 2117:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2118: #    if ($env{'form.handgrade'} eq 'no') {
 2119:     if (1) {
 2120:         $result.='<p class="LC_info">'
 2121:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2122:                 ."</p>\n";
 2123:     }
 2124: 
 2125:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2126:     my $fullname;
 2127:     my $col_fullnames = [];
 2128: #    if ($env{'form.handgrade'} eq 'yes') {
 2129:     if (1) {
 2130: 	(my $sub_result,$fullname,$col_fullnames)=
 2131: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2132: 				 $counter);
 2133: 	$result.=$sub_result;
 2134:     }
 2135:     $request->print($result."\n");
 2136: 
 2137:     # print student answer/submission
 2138:     # Options are (1) Handgraded submission only
 2139:     #             (2) Last submission, includes submission that is not handgraded 
 2140:     #                  (for multi-response type part)
 2141:     #             (3) Last submission plus the parts info
 2142:     #             (4) The whole record for this student
 2143:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2144: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2145: 	
 2146: 	my $lastsubonly;
 2147: 
 2148:         if ($$timestamp eq '') {
 2149:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2150:         } else {
 2151:             $lastsubonly =
 2152:                 '<div class="LC_grade_submissions_body">'
 2153:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2154: 
 2155: 	    my %seenparts;
 2156: 	    my @part_response_id = &flatten_responseType($responseType);
 2157: 	    foreach my $part (@part_response_id) {
 2158: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2159: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2160: 
 2161: 		my ($partid,$respid) = @{ $part };
 2162: 		my $display_part=&get_display_part($partid,$symb);
 2163: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2164: 		    if (exists($seenparts{$partid})) { next; }
 2165: 		    $seenparts{$partid}=1;
 2166: 		    my $submitby='<b>Part:</b> '.$display_part.
 2167: 			' <b>Collaborative submission by:</b> '.
 2168: 			'<a href="javascript:viewSubmitter(\''.
 2169: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2170: 			'\');" target="_self">'.
 2171: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2172: 		    $request->print($submitby);
 2173: 		    next;
 2174: 		}
 2175: 		my $responsetype = $responseType->{$partid}->{$respid};
 2176: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2177:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2178:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2179:                         ' <span class="LC_internal_info">'.
 2180:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2181:                         '</span>&nbsp; &nbsp;'.
 2182: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2183: 		    next;
 2184: 		}
 2185: 		foreach my $submission (@$string) {
 2186: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2187: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2188: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2189: 		    # Similarity check
 2190: 		    my $similar='';
 2191:                     my ($type,$trial,$rndseed);
 2192:                     if ($hide eq 'rand') {
 2193:                         $type = 'randomizetry';
 2194:                         $trial = $record{"resource.$partid.tries"};
 2195:                         $rndseed = $record{"resource.$partid.rndseed"};
 2196:                     }
 2197: 		    if($env{'form.checkPlag'}){
 2198: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2199: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2200: 			if ($osim) {
 2201: 			    $osim=int($osim*100.0);
 2202: 			    my %old_course_desc = 
 2203: 				&Apache::lonnet::coursedescription($ocrsid,
 2204: 								   {'one_time' => 1});
 2205: 
 2206:                             if ($hide eq 'anon') {
 2207:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2208:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2209:                             } else {
 2210: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2211: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2212: 				        $osim,
 2213: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2214: 				        $old_course_desc{'description'},
 2215: 				        $old_course_desc{'num'},
 2216: 				        $old_course_desc{'domain'}).
 2217: 				    '</span></h3><blockquote><i>'.
 2218: 				    &keywords_highlight($oessay).
 2219: 				    '</i></blockquote><hr />';
 2220:                             }
 2221: 			}
 2222: 		    }
 2223: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2224:                                          undef,$type,$trial,$rndseed);
 2225: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2226: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2227: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2228: 			my $display_part=&get_display_part($partid,$symb);
 2229:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2230:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2231:                             ' <span class="LC_internal_info">'.
 2232:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2233:                             '</span>&nbsp; &nbsp;';
 2234: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2235: 			if (@$files) {
 2236:                             if ($hide eq 'anon') {
 2237:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2238:                             } else {
 2239:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2240:                                 foreach my $file (@$files) {
 2241:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2242:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2243:                                 }
 2244:                             }
 2245: 			    $lastsubonly.='<br />';
 2246: 			}
 2247:                         if ($hide eq 'anon') {
 2248:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2249:                         } else {
 2250: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2251: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2252: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2253:                         }
 2254: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2255: 			$lastsubonly.='</div>';
 2256: 		    }
 2257: 		}
 2258: 	    }
 2259: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2260: 	}
 2261: 	$request->print($lastsubonly);
 2262:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2263:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2264: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2265:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2266: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2267: 								 $env{'request.course.id'},
 2268: 								 $last,'.submission',
 2269: 								 'Apache::grades::keywords_highlight'));
 2270:     }
 2271:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2272: 	.$udom.'" />'."\n");
 2273:     # return if view submission with no grading option
 2274:     if (!&canmodify($usec)) {
 2275: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2276: 	return;
 2277:     } else {
 2278: 	$request->print('</div>'."\n");
 2279:     }
 2280: 
 2281:     # essay grading message center
 2282: #    if ($env{'form.handgrade'} eq 'yes') {
 2283:     if (1) {
 2284: 	my $result='<div class="LC_grade_message_center">';
 2285:     
 2286: 	$result.='<div class="LC_grade_message_center_header">'.
 2287: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2288: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2289: 	my $msgfor = $givenn.' '.$lastname;
 2290: 	if (scalar(@$col_fullnames) > 0) {
 2291: 	    my $lastone = pop(@$col_fullnames);
 2292: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2293: 	}
 2294: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2295: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2296: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2297: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2298: 	    ',\''.$msgfor.'\');" target="_self">'.
 2299: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2300: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2301: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2302: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2303: 	    '<br />&nbsp;('.
 2304: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2305: 	$result.='</div></div>';
 2306: 	$request->print($result);
 2307:     }
 2308: 
 2309:     my %seen = ();
 2310:     my @partlist;
 2311:     my @gradePartRespid;
 2312:     my @part_response_id = &flatten_responseType($responseType);
 2313:     $request->print(
 2314:         '<div class="LC_Box">'
 2315:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2316:     );
 2317:     $request->print(&gradeBox_start());
 2318:     foreach my $part_response_id (@part_response_id) {
 2319:     	my ($partid,$respid) = @{ $part_response_id };
 2320: 	my $part_resp = join('_',@{ $part_response_id });
 2321: 	next if ($seen{$partid} > 0);
 2322: 	$seen{$partid}++;
 2323: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2324: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2325: 	push(@partlist,$partid);
 2326: 	push(@gradePartRespid,$partid.'.'.$respid);
 2327: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2328:     }
 2329:     $request->print(&gradeBox_end()); # </div>
 2330:     $request->print('</div>');
 2331: 
 2332:     $request->print('<div class="LC_grade_info_links">');
 2333:     $request->print('</div>');
 2334: 
 2335:     $result='<input type="hidden" name="partlist'.$counter.
 2336: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2337:     $result.='<input type="hidden" name="gradePartRespid'.
 2338: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2339:     my $ctr = 0;
 2340:     while ($ctr < scalar(@partlist)) {
 2341: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2342: 	    $partlist[$ctr].'" />'."\n";
 2343: 	$ctr++;
 2344:     }
 2345:     $request->print($result.''."\n");
 2346: 
 2347: # Done with printing info for one student
 2348: 
 2349:     $request->print('</div>');#LC_grade_show_user
 2350: 
 2351: 
 2352:     # print end of form
 2353:     if ($counter == $total) {
 2354:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2355: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2356: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2357: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2358: 	my $ntstu ='<select name="NTSTU">'.
 2359: 	    '<option>1</option><option>2</option>'.
 2360: 	    '<option>3</option><option>5</option>'.
 2361: 	    '<option>7</option><option>10</option></select>'."\n";
 2362: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2363: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2364:         $endform.=&mt('[_1]student(s)',$ntstu);
 2365: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2366: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2367: 	    '<input type="button" value="'.&mt('Next').'" '.
 2368: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2369:         $endform.='<span class="LC_warning">'.
 2370:                   &mt('(Next and Previous (student) do not save the scores.)').
 2371:                   '</span>'."\n" ;
 2372:         $endform.="<input type='hidden' value='".&get_increment().
 2373:             "' name='increment' />";
 2374: 	$endform.='</td></tr></table></form>';
 2375: 	$request->print($endform);
 2376:     }
 2377:     return '';
 2378: }
 2379: 
 2380: sub check_collaborators {
 2381:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2382:     my ($result,@col_fullnames);
 2383:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2384:     foreach my $part (keys(%$handgrade)) {
 2385: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2386: 					'.maxcollaborators',
 2387: 					$symb,$udom,$uname);
 2388: 	next if ($ncol <= 0);
 2389: 	$part =~ s/\_/\./g;
 2390: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2391: 	my (@good_collaborators, @bad_collaborators);
 2392: 	foreach my $possible_collaborator
 2393: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2394: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2395: 	    next if ($possible_collaborator eq '');
 2396: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2397: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2398: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2399: 	    # Doing this grep allows 'fuzzy' specification
 2400: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2401: 			       keys(%$classlist));
 2402: 	    if (! scalar(@matches)) {
 2403: 		push(@bad_collaborators, $possible_collaborator);
 2404: 	    } else {
 2405: 		push(@good_collaborators, @matches);
 2406: 	    }
 2407: 	}
 2408: 	if (scalar(@good_collaborators) != 0) {
 2409: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2410: 	    foreach my $name (@good_collaborators) {
 2411: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2412: 		push(@col_fullnames, $givenn.' '.$lastname);
 2413: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2414: 	    }
 2415: 	    $result.='</ol><br />'."\n";
 2416: 	    my ($part)=split(/\./,$part);
 2417: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2418: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2419: 		"\n";
 2420: 	}
 2421: 	if (scalar(@bad_collaborators) > 0) {
 2422: 	    $result.='<div class="LC_warning">';
 2423: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2424: 	    $result .= '</div>';
 2425: 	}         
 2426: 	if (scalar(@bad_collaborators > $ncol)) {
 2427: 	    $result .= '<div class="LC_warning">';
 2428: 	    $result .= &mt('This student has submitted too many '.
 2429: 		'collaborators.  Maximum is [_1].',$ncol);
 2430: 	    $result .= '</div>';
 2431: 	}
 2432:     }
 2433:     return ($result,$fullname,\@col_fullnames);
 2434: }
 2435: 
 2436: #--- Retrieve the last submission for all the parts
 2437: sub get_last_submission {
 2438:     my ($returnhash)=@_;
 2439:     my (@string,$timestamp,%lasthidden);
 2440:     if ($$returnhash{'version'}) {
 2441: 	my %lasthash=();
 2442: 	my ($version);
 2443: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2444: 	    foreach my $key (sort(split(/\:/,
 2445: 					$$returnhash{$version.':keys'}))) {
 2446: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2447: 		$timestamp = 
 2448: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2449: 	    }
 2450: 	}
 2451:         my (%typeparts,%randombytry);
 2452:         my $showsurv = 
 2453:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2454:         foreach my $key (sort(keys(%lasthash))) {
 2455:             if ($key =~ /\.type$/) {
 2456:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2457:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2458:                     ($lasthash{$key} eq 'randomizetry')) {
 2459:                     my ($ign,@parts) = split(/\./,$key);
 2460:                     pop(@parts);
 2461:                     my $id = join('.',@parts);
 2462:                     if ($lasthash{$key} eq 'randomizetry') {
 2463:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2464:                     } else {
 2465:                         unless ($showsurv) {
 2466:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2467:                         }
 2468:                     }
 2469:                     delete($lasthash{$key});
 2470:                 }
 2471:             }
 2472:         }
 2473:         my @hidden = keys(%typeparts);
 2474:         my @randomize = keys(%randombytry);
 2475: 	foreach my $key (keys(%lasthash)) {
 2476: 	    next if ($key !~ /\.submission$/);
 2477:             my $hide;
 2478:             if (@hidden) {
 2479:                 foreach my $id (@hidden) {
 2480:                     if ($key =~ /^\Q$id\E/) {
 2481:                         $hide = 'anon';
 2482:                         last;
 2483:                     }
 2484:                 }
 2485:             }
 2486:             unless ($hide) {
 2487:                 if (@randomize) {
 2488:                     foreach my $id (@hidden) {
 2489:                         if ($key =~ /^\Q$id\E/) {
 2490:                             $hide = 'rand';
 2491:                             last;
 2492:                         }
 2493:                     }
 2494:                 }
 2495:             }
 2496: 	    my ($partid,$foo) = split(/submission$/,$key);
 2497: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2498: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2499: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2500: 	}
 2501:     }
 2502:     if (!@string) {
 2503: 	$string[0] =
 2504: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2505:     }
 2506:     return (\@string,\$timestamp);
 2507: }
 2508: 
 2509: #--- High light keywords, with style choosen by user.
 2510: sub keywords_highlight {
 2511:     my $string    = shift;
 2512:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2513:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2514:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2515:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2516:     foreach my $keyword (@keylist) {
 2517: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2518:     }
 2519:     return $string;
 2520: }
 2521: 
 2522: # For Tasks provide a mechanism to display previous version for one specific student
 2523: 
 2524: sub show_previous_task_version {
 2525:     my ($request,$symb) = @_;
 2526:     if ($symb eq '') {
 2527:         $request->print("Unable to handle ambiguous references.");
 2528: 
 2529:         return '';
 2530:     }
 2531:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2532:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2533:     if (!&canview($usec)) {
 2534:         $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
 2535:                         $uname.':'.$udom.' in section '.$usec.' in course id '.
 2536:                         $env{'request.course.id'}.')</span>');
 2537:         return;
 2538:     }
 2539:     my $mode = 'both';
 2540:     my $isTask = ($symb =~/\.task$/);
 2541:     if ($isTask) {
 2542:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2543:             if ($env{'form.fullname'} eq '') {
 2544:                 $env{'form.fullname'} =
 2545:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2546:             }
 2547:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2548:             $request->print("\n\n".
 2549:                             '<div class="LC_grade_show_user">'.
 2550:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2551:                             '</h2>'."\n");
 2552:             &Apache::lonxml::clear_problem_counter();
 2553:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2554:                             {'previousversion' => $env{'form.previousversion'} }));
 2555:             $request->print("\n</div>");
 2556:         }
 2557:     }
 2558:     return;
 2559: }
 2560: 
 2561: sub choose_task_version_form {
 2562:     my ($symb,$uname,$udom,$nomenu) = @_;
 2563:     my $isTask = ($symb =~/\.task$/);
 2564:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2565:     if ($isTask) {
 2566:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2567:                                               $udom,$uname);
 2568:         if (($record{'resource.0.version'} eq '') ||
 2569:             ($record{'resource.0.version'} < 2)) {
 2570:             return ($record{'resource.0.version'},
 2571:                     $record{'resource.0.version'},$result,$js);
 2572:         } else {
 2573:             $current = $record{'resource.0.version'};
 2574:         }
 2575:         if ($env{'form.previousversion'}) {
 2576:             $displayed = $env{'form.previousversion'};
 2577:             $rowtitle = &mt('Choose another version:')
 2578:         } else {
 2579:             $displayed = $current;
 2580:             $rowtitle = &mt('Show earlier version:');
 2581:         }
 2582:         $result = '<div class="LC_left_float">';
 2583:         my $list;
 2584:         my $numversions = 0;
 2585:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2586:             if ($i == $current) {
 2587:                 if (!$env{'form.previousversion'} || $nomenu) {
 2588:                     next;
 2589:                 } else {
 2590:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2591:                     $numversions ++;
 2592:                 }
 2593:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2594:                 unless ($i == $env{'form.previousversion'}) {
 2595:                     $numversions ++;
 2596:                 }
 2597:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2598:             }
 2599:         }
 2600:         if ($numversions) {
 2601:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2602:             $result .=
 2603:                 '<form name="getprev" method="post" action=""'.
 2604:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2605:                 &Apache::loncommon::start_data_table().
 2606:                 &Apache::loncommon::start_data_table_row().
 2607:                 '<th align="left">'.$rowtitle.'</th>'.
 2608:                 '<td><select name="version">'.
 2609:                 '<option>'.&mt('Select').'</option>'.
 2610:                 $list.
 2611:                 '</select></td>'.
 2612:                 &Apache::loncommon::end_data_table_row();
 2613:             unless ($nomenu) {
 2614:                 $result .= &Apache::loncommon::start_data_table_row().
 2615:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2616:                 '<td><span class="LC_nobreak">'.
 2617:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2618:                 &mt('Yes').'</label>'.
 2619:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2620:                 '</span></td>'.
 2621:                 &Apache::loncommon::end_data_table_row();
 2622:             }
 2623:             $result .=
 2624:                 &Apache::loncommon::start_data_table_row().
 2625:                 '<th align="left">&nbsp;</th>'.
 2626:                 '<td>'.
 2627:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2628:                 '</td>'.
 2629:                 &Apache::loncommon::end_data_table_row().
 2630:                 &Apache::loncommon::end_data_table().
 2631:                 '</form>';
 2632:             $js = &previous_display_javascript($nomenu,$current);
 2633:         } elsif ($displayed && $nomenu) {
 2634:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2635:         } else {
 2636:             $result .= &mt('No previous versions to show for this student');
 2637:         }
 2638:         $result .= '</div>';
 2639:     }
 2640:     return ($current,$displayed,$result,$js);
 2641: }
 2642: 
 2643: sub previous_display_javascript {
 2644:     my ($nomenu,$current) = @_;
 2645:     my $js = <<"JSONE";
 2646: <script type="text/javascript">
 2647: // <![CDATA[
 2648: function previousVersion(uname,udom,symb) {
 2649:     var current = '$current';
 2650:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2651:     var prevstr = new RegExp("^\\\\d+\$");
 2652:     if (!prevstr.test(version)) {
 2653:         return false;
 2654:     }
 2655:     var url = '';
 2656:     if (version == current) {
 2657:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2658:     } else {
 2659:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2660:     }
 2661: JSONE
 2662:     if ($nomenu) {
 2663:         $js .= <<"JSTWO";
 2664:     document.location.href = url;
 2665: JSTWO
 2666:     } else {
 2667:         $js .= <<"JSTHREE";
 2668:     var newwin = 0;
 2669:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2670:         if (document.getprev.prevwin[i].checked == true) {
 2671:             newwin = document.getprev.prevwin[i].value;
 2672:         }
 2673:     }
 2674:     if (newwin == 1) {
 2675:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2676:         url = url+'&inhibitmenu=yes';
 2677:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2678:             previousWin = window.open(url,'',options,1);
 2679:         } else {
 2680:             previousWin.location.href = url;
 2681:         }
 2682:         previousWin.focus();
 2683:         return false;
 2684:     } else {
 2685:         document.location.href = url;
 2686:         return false;
 2687:     }
 2688: JSTHREE
 2689:     }
 2690:     $js .= <<"ENDJS";
 2691:     return false;
 2692: }
 2693: // ]]>
 2694: </script>
 2695: ENDJS
 2696: 
 2697: }
 2698: 
 2699: #--- Called from submission routine
 2700: sub processHandGrade {
 2701:     my ($request,$symb) = @_;
 2702:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2703:     my $button = $env{'form.gradeOpt'};
 2704:     my $ngrade = $env{'form.NCT'};
 2705:     my $ntstu  = $env{'form.NTSTU'};
 2706:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2707:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2708: 
 2709:     if ($button eq 'Save & Next') {
 2710: 	my $ctr = 0;
 2711: 	while ($ctr < $ngrade) {
 2712: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2713: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2714: 	    if ($errorflag eq 'no_score') {
 2715: 		$ctr++;
 2716: 		next;
 2717: 	    }
 2718: 	    if ($errorflag eq 'not_allowed') {
 2719: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2720: 		$ctr++;
 2721: 		next;
 2722: 	    }
 2723: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2724: 	    my ($subject,$message,$msgstatus) = ('','','');
 2725: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2726:             my ($feedurl,$showsymb) =
 2727: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2728: 	    my $messagetail;
 2729: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2730: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2731: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2732: 		$subject.=' ['.$restitle.']';
 2733: 		my (@msgnum) = split(/,/,$includemsg);
 2734: 		foreach (@msgnum) {
 2735: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2736: 		}
 2737: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2738: 		if ($env{'form.withgrades'.$ctr}) {
 2739: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2740: 		    $messagetail = " for <a href=\"".
 2741: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2742: 		}
 2743: 		$msgstatus = 
 2744:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2745: 						     $message.$messagetail,
 2746:                                                      undef,$feedurl,undef,
 2747:                                                      undef,undef,$showsymb,
 2748:                                                      $restitle);
 2749: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2750: 				$msgstatus.'<br />');
 2751: 	    }
 2752: 	    if ($env{'form.collaborator'.$ctr}) {
 2753: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2754: 		foreach my $collabstr (@collabstrs) {
 2755: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2756: 		    foreach my $collaborator (@collaborators) {
 2757: 			my ($errorflag,$pts,$wgt) = 
 2758: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2759: 					   $env{'form.unamedom'.$ctr},$part);
 2760: 			if ($errorflag eq 'not_allowed') {
 2761: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2762: 			    next;
 2763: 			} elsif ($message ne '') {
 2764: 			    my ($baseurl,$showsymb) = 
 2765: 				&get_feedurl_and_symb($symb,$collaborator,
 2766: 						      $udom);
 2767: 			    if ($env{'form.withgrades'.$ctr}) {
 2768: 				$messagetail = " for <a href=\"".
 2769:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 2770: 			    }
 2771: 			    $msgstatus = 
 2772: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2773: 			}
 2774: 		    }
 2775: 		}
 2776: 	    }
 2777: 	    $ctr++;
 2778: 	}
 2779:     }
 2780: 
 2781: #    if ($env{'form.handgrade'} eq 'yes') {
 2782:     if (1) {
 2783: 	# Keywords sorted in alphabatical order
 2784: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2785: 	my %keyhash = ();
 2786: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2787: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2788: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2789: 	$env{'form.keywords'} = join(' ',@keywords);
 2790: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2791: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2792: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2793: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2794: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2795: 
 2796: 	# message center - Order of message gets changed. Blank line is eliminated.
 2797: 	# New messages are saved in env for the next student.
 2798: 	# All messages are saved in nohist_handgrade.db
 2799: 	my ($ctr,$idx) = (1,1);
 2800: 	while ($ctr <= $env{'form.savemsgN'}) {
 2801: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2802: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2803: 		$idx++;
 2804: 	    }
 2805: 	    $ctr++;
 2806: 	}
 2807: 	$ctr = 0;
 2808: 	while ($ctr < $ngrade) {
 2809: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2810: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2811: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2812: 		$idx++;
 2813: 	    }
 2814: 	    $ctr++;
 2815: 	}
 2816: 	$env{'form.savemsgN'} = --$idx;
 2817: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2818: 	my $putresult = &Apache::lonnet::put
 2819: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2820:     }
 2821:     # Called by Save & Refresh from Highlight Attribute Window
 2822:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2823:     if ($env{'form.refresh'} eq 'on') {
 2824: 	my ($ctr,$total) = (0,0);
 2825: 	while ($ctr < $ngrade) {
 2826: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2827: 	    $ctr++;
 2828: 	}
 2829: 	$env{'form.NTSTU'}=$ngrade;
 2830: 	$ctr = 0;
 2831: 	while ($ctr < $total) {
 2832: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2833: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2834: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2835: 	    &submission($request,$ctr,$total-1,$symb);
 2836: 	    $ctr++;
 2837: 	}
 2838: 	return '';
 2839:     }
 2840: 
 2841:     # Get the next/previous one or group of students
 2842:     my $firststu = $env{'form.unamedom0'};
 2843:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2844:     my $ctr = 2;
 2845:     while ($laststu eq '') {
 2846: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2847: 	$ctr++;
 2848: 	$laststu = $firststu if ($ctr > $ngrade);
 2849:     }
 2850: 
 2851:     my (@parsedlist,@nextlist);
 2852:     my ($nextflg) = 0;
 2853:     foreach my $item (sort 
 2854: 	     {
 2855: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2856: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2857: 		 }
 2858: 		 return $a cmp $b;
 2859: 	     } (keys(%$fullname))) {
 2860: # FIXME: this is fishy, looks like the button label
 2861: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2862: 	    push(@parsedlist,$item);
 2863: 	}
 2864: 	$nextflg = 1 if ($item eq $laststu);
 2865: 	if ($button eq 'Previous') {
 2866: 	    last if ($item eq $firststu);
 2867: 	    push(@parsedlist,$item);
 2868: 	}
 2869:     }
 2870:     $ctr = 0;
 2871: # FIXME: this is fishy, looks like the button label
 2872:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2873:     my $res_error;
 2874:     my ($partlist) = &response_type($symb,\$res_error);
 2875:     if ($res_error) {
 2876:         $request->print(&navmap_errormsg());
 2877:         return;
 2878:     }
 2879:     foreach my $student (@parsedlist) {
 2880: 	my $submitonly=$env{'form.submitonly'};
 2881: 	my ($uname,$udom) = split(/:/,$student);
 2882: 	
 2883: 	if ($submitonly eq 'queued') {
 2884: 	    my %queue_status = 
 2885: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2886: 							$udom,$uname);
 2887: 	    next if (!defined($queue_status{'gradingqueue'}));
 2888: 	}
 2889: 
 2890: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2891: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2892: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2893: 	    my $submitted = 0;
 2894: 	    my $ungraded = 0;
 2895: 	    my $incorrect = 0;
 2896: 	    foreach my $item (keys(%status)) {
 2897: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2898: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2899: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2900: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2901: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2902: 		    $submitted = 0;
 2903: 		}
 2904: 	    }
 2905: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2906: 				     $submitonly eq 'incorrect' ||
 2907: 				     $submitonly eq 'graded'));
 2908: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2909: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2910: 	}
 2911: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2912: 	last if ($ctr == $ntstu);
 2913: 	$ctr++;
 2914:     }
 2915: 
 2916:     $ctr = 0;
 2917:     my $total = scalar(@nextlist)-1;
 2918: 
 2919:     foreach (sort(@nextlist)) {
 2920: 	my ($uname,$udom,$submitter) = split(/:/);
 2921: 	$env{'form.student'}  = $uname;
 2922: 	$env{'form.userdom'}  = $udom;
 2923: 	$env{'form.fullname'} = $$fullname{$_};
 2924: 	&submission($request,$ctr,$total,$symb);
 2925: 	$ctr++;
 2926:     }
 2927:     if ($total < 0) {
 2928: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 2929: 	$request->print($the_end);
 2930:     }
 2931:     return '';
 2932: }
 2933: 
 2934: #---- Save the score and award for each student, if changed
 2935: sub saveHandGrade {
 2936:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2937:     my @version_parts;
 2938:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2939: 					   $env{'request.course.id'});
 2940:     if (!&canmodify($usec)) { return('not_allowed'); }
 2941:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2942:     my @parts_graded;
 2943:     my %newrecord  = ();
 2944:     my ($pts,$wgt) = ('','');
 2945:     my %aggregate = ();
 2946:     my $aggregateflag = 0;
 2947:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2948:     foreach my $new_part (@parts) {
 2949: 	#collaborator ($submi may vary for different parts
 2950: 	if ($submitter && $new_part ne $part) { next; }
 2951: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2952: 	if ($dropMenu eq 'excused') {
 2953: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2954: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2955: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2956: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2957: 		}
 2958: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2959: 	    }
 2960: 	} elsif ($dropMenu eq 'reset status'
 2961: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2962: 	    foreach my $key (keys(%record)) {
 2963: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2964: 	    }
 2965: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2966: 		"$env{'user.name'}:$env{'user.domain'}";
 2967:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2968: 
 2969:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2970: 					       [$new_part]);
 2971:             my $aggtries =$totaltries;
 2972:             if ($last_resets{$new_part}) {
 2973:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2974: 					   $new_part);
 2975:             }
 2976: 
 2977:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2978:             if ($aggtries > 0) {
 2979:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2980:                 $aggregateflag = 1;
 2981:             }
 2982: 	} elsif ($dropMenu eq '') {
 2983: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2984: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2985: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2986: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2987: 		next;
 2988: 	    }
 2989: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2990: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2991: 	    my $partial= $pts/$wgt;
 2992: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2993: 		#do not update score for part if not changed.
 2994:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2995: 		next;
 2996: 	    } else {
 2997: 	        push(@parts_graded,$new_part);
 2998: 	    }
 2999: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3000: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3001: 	    }
 3002: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3003: 	    if ($partial == 0) {
 3004: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3005: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3006: 		}
 3007: 	    } else {
 3008: 		if ($record{$reckey} ne 'correct_by_override') {
 3009: 		    $newrecord{$reckey} = 'correct_by_override';
 3010: 		}
 3011: 	    }	    
 3012: 	    if ($submitter && 
 3013: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3014: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3015: 	    }
 3016: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3017: 		"$env{'user.name'}:$env{'user.domain'}";
 3018: 	}
 3019: 	# unless problem has been graded, set flag to version the submitted files
 3020: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3021: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3022: 	        $dropMenu eq 'reset status')
 3023: 	   {
 3024: 	    push(@version_parts,$new_part);
 3025: 	}
 3026:     }
 3027:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3028:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3029: 
 3030:     if (%newrecord) {
 3031:         if (@version_parts) {
 3032:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3033:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3034: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3035: 	    foreach my $new_part (@version_parts) {
 3036: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3037: 				$new_part,\%newrecord);
 3038: 	    }
 3039:         }
 3040: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3041: 				$env{'request.course.id'},$domain,$stuname);
 3042: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3043: 				     $cdom,$cnum,$domain,$stuname);
 3044:     }
 3045:     if ($aggregateflag) {
 3046:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3047: 			      $cdom,$cnum);
 3048:     }
 3049:     return ('',$pts,$wgt);
 3050: }
 3051: 
 3052: sub check_and_remove_from_queue {
 3053:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3054:     my @ungraded_parts;
 3055:     foreach my $part (@{$parts}) {
 3056: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3057: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3058: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3059: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3060: 		) {
 3061: 	    push(@ungraded_parts, $part);
 3062: 	}
 3063:     }
 3064:     if ( !@ungraded_parts ) {
 3065: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3066: 					       $cnum,$domain,$stuname);
 3067:     }
 3068: }
 3069: 
 3070: sub handback_files {
 3071:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3072:     my $portfolio_root = '/userfiles/portfolio';
 3073:     my $res_error;
 3074:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3075:     if ($res_error) {
 3076:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3077:         return;
 3078:     }
 3079:     my @handedback;
 3080:     my $file_msg;
 3081:     my @part_response_id = &flatten_responseType($responseType);
 3082:     foreach my $part_response_id (@part_response_id) {
 3083:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3084: 	my $part_resp = join('_',@{ $part_response_id });
 3085:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3086:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3087:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3088:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3089:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3090:                     my ($directory,$answer_file) = 
 3091:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3092:                     my ($answer_name,$answer_ver,$answer_ext) =
 3093: 		        &file_name_version_ext($answer_file);
 3094: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3095:                     my $getpropath = 1;
 3096:                     my ($dir_list,$listerror) = 
 3097:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3098:                                                  $domain,$stuname,$getpropath);
 3099: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3100:                     # fix file name
 3101:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3102:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3103:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3104:             	                                $save_file_name);
 3105:                     if ($result !~ m|^/uploaded/|) {
 3106:                         $request->print('<br /><span class="LC_error">'.
 3107:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3108:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3109:                                         '</span>');
 3110:                     } else {
 3111:                         # mark the file as read only
 3112:                         push(@handedback,$save_file_name);
 3113: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3114: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3115: 			}
 3116:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3117: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3118:                     }
 3119:                     $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3120:                 }
 3121:             }
 3122:         }
 3123:     }
 3124:     if (@handedback > 0) {
 3125:         $request->print('<br />');
 3126:         my @what = ($symb,$env{'request.course.id'},'handback');
 3127:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3128:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3129:         my ($subject,$message);
 3130:         if (scalar(@handedback) == 1) {
 3131:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3132:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3133:         } else {
 3134:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3135:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3136:         }
 3137:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3138:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3139:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3140:         my ($feedurl,$showsymb) =
 3141:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3142:         my $restitle = &Apache::lonnet::gettitle($symb);
 3143:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3144:         my $msgstatus =
 3145:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3146:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3147:                  $restitle);
 3148:         if ($msgstatus) {
 3149:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3150:         }
 3151:     }
 3152:     return;
 3153: }
 3154: 
 3155: sub get_feedurl_and_symb {
 3156:     my ($symb,$uname,$udom) = @_;
 3157:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3158:     $url = &Apache::lonnet::clutter($url);
 3159:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3160: 					$symb,$udom,$uname);
 3161:     if ($encrypturl =~ /^yes$/i) {
 3162: 	&Apache::lonenc::encrypted(\$url,1);
 3163: 	&Apache::lonenc::encrypted(\$symb,1);
 3164:     }
 3165:     return ($url,$symb);
 3166: }
 3167: 
 3168: sub get_submitted_files {
 3169:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3170:     my @files;
 3171:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3172:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3173:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3174:     	    push(@files,$file_url.$file);
 3175:         }
 3176:     }
 3177:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3178:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3179:     }
 3180:     return (\@files);
 3181: }
 3182: 
 3183: # ----------- Provides number of tries since last reset.
 3184: sub get_num_tries {
 3185:     my ($record,$last_reset,$part) = @_;
 3186:     my $timestamp = '';
 3187:     my $num_tries = 0;
 3188:     if ($$record{'version'}) {
 3189:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3190:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3191:                 $timestamp = $$record{$version.':timestamp'};
 3192:                 if ($timestamp > $last_reset) {
 3193:                     $num_tries ++;
 3194:                 } else {
 3195:                     last;
 3196:                 }
 3197:             }
 3198:         }
 3199:     }
 3200:     return $num_tries;
 3201: }
 3202: 
 3203: # ----------- Determine decrements required in aggregate totals 
 3204: sub decrement_aggs {
 3205:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3206:     my %decrement = (
 3207:                         attempts => 0,
 3208:                         users => 0,
 3209:                         correct => 0
 3210:                     );
 3211:     $decrement{'attempts'} = $aggtries;
 3212:     if ($solvedstatus =~ /^correct/) {
 3213:         $decrement{'correct'} = 1;
 3214:     }
 3215:     if ($aggtries == $totaltries) {
 3216:         $decrement{'users'} = 1;
 3217:     }
 3218:     foreach my $type (keys(%decrement)) {
 3219:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3220:     }
 3221:     return;
 3222: }
 3223: 
 3224: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3225: sub get_last_resets {
 3226:     my ($symb,$courseid,$partids) =@_;
 3227:     my %last_resets;
 3228:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3229:     my $cname = $env{'course.'.$courseid.'.num'};
 3230:     my @keys;
 3231:     foreach my $part (@{$partids}) {
 3232: 	push(@keys,"$symb\0$part\0resettime");
 3233:     }
 3234:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3235: 				     $cdom,$cname);
 3236:     foreach my $part (@{$partids}) {
 3237: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3238:     }
 3239:     return %last_resets;
 3240: }
 3241: 
 3242: # ----------- Handles creating versions for portfolio files as answers
 3243: sub version_portfiles {
 3244:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3245:     my $version_parts = join('|',@$v_flag);
 3246:     my @returned_keys;
 3247:     my $parts = join('|', @$parts_graded);
 3248:     my $portfolio_root = '/userfiles/portfolio';
 3249:     foreach my $key (keys(%$record)) {
 3250:         my $new_portfiles;
 3251:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3252:             my @versioned_portfiles;
 3253:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3254:             foreach my $file (@portfiles) {
 3255:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3256:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3257: 		my ($answer_name,$answer_ver,$answer_ext) =
 3258: 		    &file_name_version_ext($answer_file);
 3259:                 my $getpropath = 1;    
 3260:                 my ($dir_list,$listerror) = 
 3261:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3262:                                              $stu_name,$getpropath);
 3263:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3264:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3265:                 if ($new_answer ne 'problem getting file') {
 3266:                     push(@versioned_portfiles, $directory.$new_answer);
 3267:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3268:                         [$directory.$new_answer],
 3269:                         [$symb,$env{'request.course.id'},'graded']);
 3270:                 }
 3271:             }
 3272:             $$record{$key} = join(',',@versioned_portfiles);
 3273:             push(@returned_keys,$key);
 3274:         }
 3275:     } 
 3276:     return (@returned_keys);   
 3277: }
 3278: 
 3279: sub get_next_version {
 3280:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3281:     my $version;
 3282:     if (ref($dir_list) eq 'ARRAY') {
 3283:         foreach my $row (@{$dir_list}) {
 3284:             my ($file) = split(/\&/,$row,2);
 3285:             my ($file_name,$file_version,$file_ext) =
 3286: 	        &file_name_version_ext($file);
 3287:             if (($file_name eq $answer_name) && 
 3288: 	        ($file_ext eq $answer_ext)) {
 3289:                      # gets here if filename and extension match, 
 3290:                      # regardless of version
 3291:                 if ($file_version ne '') {
 3292:                     # a versioned file is found  so save it for later
 3293:                     if ($file_version > $version) {
 3294: 		        $version = $file_version;
 3295: 	            }
 3296:                 }
 3297:             }
 3298:         }
 3299:     }
 3300:     $version ++;
 3301:     return($version);
 3302: }
 3303: 
 3304: sub version_selected_portfile {
 3305:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3306:     my ($answer_name,$answer_ver,$answer_ext) =
 3307:         &file_name_version_ext($file_name);
 3308:     my $new_answer;
 3309:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3310:     if($env{'form.copy'} eq '-1') {
 3311:         $new_answer = 'problem getting file';
 3312:     } else {
 3313:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3314:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3315:                             $stu_name,$domain,'copy',
 3316: 		        '/portfolio'.$directory.$new_answer);
 3317:     }    
 3318:     return ($new_answer);
 3319: }
 3320: 
 3321: sub file_name_version_ext {
 3322:     my ($file)=@_;
 3323:     my @file_parts = split(/\./, $file);
 3324:     my ($name,$version,$ext);
 3325:     if (@file_parts > 1) {
 3326: 	$ext=pop(@file_parts);
 3327: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3328: 	    $version=pop(@file_parts);
 3329: 	}
 3330: 	$name=join('.',@file_parts);
 3331:     } else {
 3332: 	$name=join('.',@file_parts);
 3333:     }
 3334:     return($name,$version,$ext);
 3335: }
 3336: 
 3337: #--------------------------------------------------------------------------------------
 3338: #
 3339: #-------------------------- Next few routines handles grading by section or whole class
 3340: #
 3341: #--- Javascript to handle grading by section or whole class
 3342: sub viewgrades_js {
 3343:     my ($request) = shift;
 3344: 
 3345:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3346:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3347:    function writePoint(partid,weight,point) {
 3348: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3349: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3350: 	if (point == "textval") {
 3351: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3352: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3353: 		alert("$alertmsg"+parseFloat(point));
 3354: 		var resetbox = false;
 3355: 		for (var i=0; i<radioButton.length; i++) {
 3356: 		    if (radioButton[i].checked) {
 3357: 			textbox.value = i;
 3358: 			resetbox = true;
 3359: 		    }
 3360: 		}
 3361: 		if (!resetbox) {
 3362: 		    textbox.value = "";
 3363: 		}
 3364: 		return;
 3365: 	    }
 3366: 	    if (parseFloat(point) > parseFloat(weight)) {
 3367: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3368: 				   ") greater than the weight for the part. Accept?");
 3369: 		if (resp == false) {
 3370: 		    textbox.value = "";
 3371: 		    return;
 3372: 		}
 3373: 	    }
 3374: 	    for (var i=0; i<radioButton.length; i++) {
 3375: 		radioButton[i].checked=false;
 3376: 		if (parseFloat(point) == i) {
 3377: 		    radioButton[i].checked=true;
 3378: 		}
 3379: 	    }
 3380: 
 3381: 	} else {
 3382: 	    textbox.value = parseFloat(point);
 3383: 	}
 3384: 	for (i=0;i<document.classgrade.total.value;i++) {
 3385: 	    var user = document.classgrade["ctr"+i].value;
 3386: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3387: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3388: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3389: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3390: 	    if (saveval != "correct") {
 3391: 		scorename.value = point;
 3392: 		if (selname[0].selected != true) {
 3393: 		    selname[0].selected = true;
 3394: 		}
 3395: 	    }
 3396: 	}
 3397: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3398:     }
 3399: 
 3400:     function writeRadText(partid,weight) {
 3401: 	var selval   = document.classgrade["SELVAL_"+partid];
 3402: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3403:         var override = document.classgrade["FORCE_"+partid].checked;
 3404: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3405: 	if (selval[1].selected || selval[2].selected) {
 3406: 	    for (var i=0; i<radioButton.length; i++) {
 3407: 		radioButton[i].checked=false;
 3408: 
 3409: 	    }
 3410: 	    textbox.value = "";
 3411: 
 3412: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3413: 		var user = document.classgrade["ctr"+i].value;
 3414: 		user = user.replace(new RegExp(':', 'g'),"_");
 3415: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3416: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3417: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3418: 		if ((saveval != "correct") || override) {
 3419: 		    scorename.value = "";
 3420: 		    if (selval[1].selected) {
 3421: 			selname[1].selected = true;
 3422: 		    } else {
 3423: 			selname[2].selected = true;
 3424: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3425: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3426: 		    }
 3427: 		}
 3428: 	    }
 3429: 	} else {
 3430: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3431: 		var user = document.classgrade["ctr"+i].value;
 3432: 		user = user.replace(new RegExp(':', 'g'),"_");
 3433: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3434: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3435: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3436: 		if ((saveval != "correct") || override) {
 3437: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3438: 		    selname[0].selected = true;
 3439: 		}
 3440: 	    }
 3441: 	}	    
 3442:     }
 3443: 
 3444:     function changeSelect(partid,user) {
 3445: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3446: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3447: 	var point  = textbox.value;
 3448: 	var weight = document.classgrade["weight_"+partid].value;
 3449: 
 3450: 	if (isNaN(point) || parseFloat(point) < 0) {
 3451: 	    alert("$alertmsg"+parseFloat(point));
 3452: 	    textbox.value = "";
 3453: 	    return;
 3454: 	}
 3455: 	if (parseFloat(point) > parseFloat(weight)) {
 3456: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3457: 			       ") greater than the weight of the part. Accept?");
 3458: 	    if (resp == false) {
 3459: 		textbox.value = "";
 3460: 		return;
 3461: 	    }
 3462: 	}
 3463: 	selval[0].selected = true;
 3464:     }
 3465: 
 3466:     function changeOneScore(partid,user) {
 3467: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3468: 	if (selval[1].selected || selval[2].selected) {
 3469: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3470: 	    if (selval[2].selected) {
 3471: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3472: 	    }
 3473:         }
 3474:     }
 3475: 
 3476:     function resetEntry(numpart) {
 3477: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3478: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3479: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3480: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3481: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3482: 	    for (var i=0; i<radioButton.length; i++) {
 3483: 		radioButton[i].checked=false;
 3484: 
 3485: 	    }
 3486: 	    textbox.value = "";
 3487: 	    selval[0].selected = true;
 3488: 
 3489: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3490: 		var user = document.classgrade["ctr"+i].value;
 3491: 		user = user.replace(new RegExp(':', 'g'),"_");
 3492: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3493: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3494: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3495: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3496: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3497: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3498: 		if (saveselval == "excused") {
 3499: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3500: 		} else {
 3501: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3502: 		}
 3503: 	    }
 3504: 	}
 3505:     }
 3506: 
 3507: VIEWJAVASCRIPT
 3508: }
 3509: 
 3510: #--- show scores for a section or whole class w/ option to change/update a score
 3511: sub viewgrades {
 3512:     my ($request,$symb) = @_;
 3513:     &viewgrades_js($request);
 3514: 
 3515:     #need to make sure we have the correct data for later EXT calls, 
 3516:     #thus invalidate the cache
 3517:     &Apache::lonnet::devalidatecourseresdata(
 3518:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3519:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3520:     &Apache::lonnet::clear_EXT_cache_status();
 3521: 
 3522:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3523: 
 3524:     #view individual student submission form - called using Javascript viewOneStudent
 3525:     $result.=&jscriptNform($symb);
 3526: 
 3527:     #beginning of class grading form
 3528:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3529:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3530: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3531: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3532: 	&build_section_inputs().
 3533: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3534: 
 3535:     my ($common_header,$specific_header);
 3536:     if ($env{'form.section'} eq 'all') {
 3537: 	$common_header = &mt('Assign Common Grade to Class');
 3538:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3539:     } elsif ($env{'form.section'} eq 'none') {
 3540:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3541: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3542:     } else {
 3543:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3544:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3545: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3546:     }
 3547:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3548:     #radio buttons/text box for assigning points for a section or class.
 3549:     #handles different parts of a problem
 3550:     my $res_error;
 3551:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3552:     if ($res_error) {
 3553:         return &navmap_errormsg();
 3554:     }
 3555:     my %weight = ();
 3556:     my $ctsparts = 0;
 3557:     my %seen = ();
 3558:     my @part_response_id = &flatten_responseType($responseType);
 3559:     foreach my $part_response_id (@part_response_id) {
 3560:     	my ($partid,$respid) = @{ $part_response_id };
 3561: 	my $part_resp = join('_',@{ $part_response_id });
 3562: 	next if $seen{$partid};
 3563: 	$seen{$partid}++;
 3564: 	my $handgrade=$$handgrade{$part_resp};
 3565: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3566: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3567: 
 3568: 	my $display_part=&get_display_part($partid,$symb);
 3569: 	my $radio.='<table border="0"><tr>';  
 3570: 	my $ctr = 0;
 3571: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3572: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3573: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3574: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3575: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3576: 	    $ctr++;
 3577: 	}
 3578: 	$radio.='</tr></table>';
 3579: 	my $line = '<input type="text" name="TEXTVAL_'.
 3580: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3581: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3582: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3583: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3584: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3585: 		$weight{$partid}.')"> '.
 3586: 	    '<option selected="selected"> </option>'.
 3587: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3588: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3589: 	    '</select></td>'.
 3590:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3591: 	$line.='<input type="hidden" name="partid_'.
 3592: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3593: 	$line.='<input type="hidden" name="weight_'.
 3594: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3595: 
 3596: 	$result.=
 3597: 	    &Apache::loncommon::start_data_table_row()."\n".
 3598: 	    '<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>'.
 3599: 	    &Apache::loncommon::end_data_table_row()."\n";
 3600: 	$ctsparts++;
 3601:     }
 3602:     $result.=&Apache::loncommon::end_data_table()."\n".
 3603: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3604:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3605: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3606: 
 3607:     #table listing all the students in a section/class
 3608:     #header of table
 3609:     $result.= '<h3>'.$specific_header.'</h3>'.
 3610:               &Apache::loncommon::start_data_table().
 3611: 	      &Apache::loncommon::start_data_table_header_row().
 3612: 	      '<th>'.&mt('No.').'</th>'.
 3613: 	      '<th>'.&nameUserString('header')."</th>\n";
 3614:     my $partserror;
 3615:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3616:     if ($partserror) {
 3617:         return &navmap_errormsg();
 3618:     }
 3619:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3620:     my @partids = ();
 3621:     foreach my $part (@parts) {
 3622: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3623:         my $narrowtext = &mt('Tries');
 3624: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3625: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3626: 	my ($partid) = &split_part_type($part);
 3627:         push(@partids,$partid);
 3628: #
 3629: # FIXME: Looks like $display looks at English text
 3630: #
 3631: 	my $display_part=&get_display_part($partid,$symb);
 3632: 	if ($display =~ /^Partial Credit Factor/) {
 3633: 	    $result.='<th>'.
 3634: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3635: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3636: 	    next;
 3637: 	    
 3638: 	} else {
 3639: 	    if ($display =~ /Problem Status/) {
 3640: 		my $grade_status_mt = &mt('Grade Status');
 3641: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3642: 	    }
 3643: 	    my $part_mt = &mt('Part:');
 3644: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3645: 	}
 3646: 
 3647: 	$result.='<th>'.$display.'</th>'."\n";
 3648:     }
 3649:     $result.=&Apache::loncommon::end_data_table_header_row();
 3650: 
 3651:     my %last_resets = 
 3652: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3653: 
 3654:     #get info for each student
 3655:     #list all the students - with points and grade status
 3656:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3657:     my $ctr = 0;
 3658:     foreach (sort 
 3659: 	     {
 3660: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3661: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3662: 		 }
 3663: 		 return $a cmp $b;
 3664: 	     } (keys(%$fullname))) {
 3665: 	$ctr++;
 3666: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3667: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3668:     }
 3669:     $result.=&Apache::loncommon::end_data_table();
 3670:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3671:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3672: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3673:     if (scalar(%$fullname) eq 0) {
 3674: 	my $colspan=3+scalar(@parts);
 3675: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3676:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3677: 	$result='<span class="LC_warning">'.
 3678: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3679: 	        $section_display, $stu_status).
 3680: 	    '</span>';
 3681:     }
 3682:     return $result;
 3683: }
 3684: 
 3685: #--- call by previous routine to display each student
 3686: sub viewstudentgrade {
 3687:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3688:     my ($uname,$udom) = split(/:/,$student);
 3689:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3690:     my %aggregates = (); 
 3691:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3692: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3693: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3694: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3695: 	'\');" target="_self">'.$fullname.'</a> '.
 3696: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3697:     $student=~s/:/_/; # colon doen't work in javascript for names
 3698:     foreach my $apart (@$parts) {
 3699: 	my ($part,$type) = &split_part_type($apart);
 3700: 	my $score=$record{"resource.$part.$type"};
 3701:         $result.='<td align="center">';
 3702:         my ($aggtries,$totaltries);
 3703:         unless (exists($aggregates{$part})) {
 3704: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3705: 
 3706: 	    $aggtries = $totaltries;
 3707:             if ($$last_resets{$part}) {  
 3708:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3709: 					   $part);
 3710:             }
 3711:             $result.='<input type="hidden" name="'.
 3712:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3713:             $result.='<input type="hidden" name="'.
 3714:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3715:             $aggregates{$part} = 1;
 3716:         }
 3717: 	if ($type eq 'awarded') {
 3718: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3719: 	    $result.='<input type="hidden" name="'.
 3720: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3721: 	    $result.='<input type="text" name="'.
 3722: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3723:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3724: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3725: 	} elsif ($type eq 'solved') {
 3726: 	    my ($status,$foo)=split(/_/,$score,2);
 3727: 	    $status = 'nothing' if ($status eq '');
 3728: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3729: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3730: 	    $result.='&nbsp;<select name="'.
 3731: 		'GD_'.$student.'_'.$part.'_solved" '.
 3732:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3733: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3734: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3735: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3736: 	    $result.="</select>&nbsp;</td>\n";
 3737: 	} else {
 3738: 	    $result.='<input type="hidden" name="'.
 3739: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3740: 		    "\n";
 3741: 	    $result.='<input type="text" name="'.
 3742: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3743: 		'value="'.$score.'" size="4" /></td>'."\n";
 3744: 	}
 3745:     }
 3746:     $result.=&Apache::loncommon::end_data_table_row();
 3747:     return $result;
 3748: }
 3749: 
 3750: #--- change scores for all the students in a section/class
 3751: #    record does not get update if unchanged
 3752: sub editgrades {
 3753:     my ($request,$symb) = @_;
 3754: 
 3755:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3756:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3757:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3758: 
 3759:     my $result= &Apache::loncommon::start_data_table().
 3760: 	&Apache::loncommon::start_data_table_header_row().
 3761: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3762: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3763:     my %scoreptr = (
 3764: 		    'correct'  =>'correct_by_override',
 3765: 		    'incorrect'=>'incorrect_by_override',
 3766: 		    'excused'  =>'excused',
 3767: 		    'ungraded' =>'ungraded_attempted',
 3768:                     'credited' =>'credit_attempted',
 3769: 		    'nothing'  => '',
 3770: 		    );
 3771:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3772: 
 3773:     my (@partid);
 3774:     my %weight = ();
 3775:     my %columns = ();
 3776:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3777: 
 3778:     my $partserror;
 3779:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3780:     if ($partserror) {
 3781:         return &navmap_errormsg();
 3782:     }
 3783:     my $header;
 3784:     while ($ctr < $env{'form.totalparts'}) {
 3785: 	my $partid = $env{'form.partid_'.$ctr};
 3786: 	push(@partid,$partid);
 3787: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3788: 	$ctr++;
 3789:     }
 3790:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3791:     foreach my $partid (@partid) {
 3792: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3793: 	    '<th align="center">'.&mt('New Score').'</th>';
 3794: 	$columns{$partid}=2;
 3795: 	foreach my $stores (@parts) {
 3796: 	    my ($part,$type) = &split_part_type($stores);
 3797: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3798: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3799: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3800: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3801:             my $narrowtext = &mt('Tries');
 3802: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3803: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3804: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3805: 	    $columns{$partid}+=2;
 3806: 	}
 3807:     }
 3808:     foreach my $partid (@partid) {
 3809: 	my $display_part=&get_display_part($partid,$symb);
 3810: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3811: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3812: 	    '</th>';
 3813: 
 3814:     }
 3815:     $result .= &Apache::loncommon::end_data_table_header_row().
 3816: 	&Apache::loncommon::start_data_table_header_row().
 3817: 	$header.
 3818: 	&Apache::loncommon::end_data_table_header_row();
 3819:     my @noupdate;
 3820:     my ($updateCtr,$noupdateCtr) = (1,1);
 3821:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3822: 	my $line;
 3823: 	my $user = $env{'form.ctr'.$i};
 3824: 	my ($uname,$udom)=split(/:/,$user);
 3825: 	my %newrecord;
 3826: 	my $updateflag = 0;
 3827: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3828: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3829: 	if (!&canmodify($usec)) {
 3830: 	    my $numcols=scalar(@partid)*4+2;
 3831: 	    push(@noupdate,
 3832: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3833: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3834: 	    next;
 3835: 	}
 3836:         my %aggregate = ();
 3837:         my $aggregateflag = 0;
 3838: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3839: 	foreach (@partid) {
 3840: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3841: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3842: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3843: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3844: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3845: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3846: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3847: 	    my $score;
 3848: 	    if ($partial eq '') {
 3849: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3850: 	    } elsif ($partial > 0) {
 3851: 		$score = 'correct_by_override';
 3852: 	    } elsif ($partial == 0) {
 3853: 		$score = 'incorrect_by_override';
 3854: 	    }
 3855: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3856: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3857: 
 3858: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3859: 		"$env{'user.name'}:$env{'user.domain'}";
 3860: 	    if ($dropMenu eq 'reset status' &&
 3861: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3862: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3863: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3864: 		$newrecord{'resource.'.$_.'.award'} = '';
 3865: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3866: 		$updateflag = 1;
 3867:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3868:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3869:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3870:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3871:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3872:                     $aggregateflag = 1;
 3873:                 }
 3874: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3875: 		$updateflag = 1;
 3876: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3877: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3878: 		$rec_update++;
 3879: 	    }
 3880: 
 3881: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3882: 		'<td align="center">'.$awarded.
 3883: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3884: 
 3885: 
 3886: 	    my $partid=$_;
 3887: 	    foreach my $stores (@parts) {
 3888: 		my ($part,$type) = &split_part_type($stores);
 3889: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3890: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3891: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3892: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3893: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3894: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3895: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3896: 		    $updateflag=1;
 3897: 		}
 3898: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3899: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3900: 	    }
 3901: 	}
 3902: 	$line.="\n";
 3903: 
 3904: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3905: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3906: 
 3907: 	if ($updateflag) {
 3908: 	    $count++;
 3909: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3910: 				    $udom,$uname);
 3911: 
 3912: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3913: 					      $cnum,$udom,$uname)) {
 3914: 		# need to figure out if should be in queue.
 3915: 		my %record =  
 3916: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3917: 					     $udom,$uname);
 3918: 		my $all_graded = 1;
 3919: 		my $none_graded = 1;
 3920: 		foreach my $part (@parts) {
 3921: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3922: 			$all_graded = 0;
 3923: 		    } else {
 3924: 			$none_graded = 0;
 3925: 		    }
 3926: 		}
 3927: 
 3928: 		if ($all_graded || $none_graded) {
 3929: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3930: 							   $symb,$cdom,$cnum,
 3931: 							   $udom,$uname);
 3932: 		}
 3933: 	    }
 3934: 
 3935: 	    $result.=&Apache::loncommon::start_data_table_row().
 3936: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3937: 		&Apache::loncommon::end_data_table_row();
 3938: 	    $updateCtr++;
 3939: 	} else {
 3940: 	    push(@noupdate,
 3941: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3942: 	    $noupdateCtr++;
 3943: 	}
 3944:         if ($aggregateflag) {
 3945:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3946: 				  $cdom,$cnum);
 3947:         }
 3948:     }
 3949:     if (@noupdate) {
 3950: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3951: 	my $numcols=scalar(@partid)*4+2;
 3952: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3953: 	    '<td align="center" colspan="'.$numcols.'">'.
 3954: 	    &mt('No Changes Occurred For the Students Below').
 3955: 	    '</td>'.
 3956: 	    &Apache::loncommon::end_data_table_row();
 3957: 	foreach my $line (@noupdate) {
 3958: 	    $result.=
 3959: 		&Apache::loncommon::start_data_table_row().
 3960: 		$line.
 3961: 		&Apache::loncommon::end_data_table_row();
 3962: 	}
 3963:     }
 3964:     $result .= &Apache::loncommon::end_data_table();
 3965:     my $msg = '<p><b>'.
 3966: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3967: 	    $rec_update,$count).'</b><br />'.
 3968: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3969: 	'</b></p>';
 3970:     return $title.$msg.$result;
 3971: }
 3972: 
 3973: sub split_part_type {
 3974:     my ($partstr) = @_;
 3975:     my ($temp,@allparts)=split(/_/,$partstr);
 3976:     my $type=pop(@allparts);
 3977:     my $part=join('_',@allparts);
 3978:     return ($part,$type);
 3979: }
 3980: 
 3981: #------------- end of section for handling grading by section/class ---------
 3982: #
 3983: #----------------------------------------------------------------------------
 3984: 
 3985: 
 3986: #----------------------------------------------------------------------------
 3987: #
 3988: #-------------------------- Next few routines handles grading by csv upload
 3989: #
 3990: #--- Javascript to handle csv upload
 3991: sub csvupload_javascript_reverse_associate {
 3992:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3993:     my $error2=&mt('You need to specify at least one grading field');
 3994:   return(<<ENDPICK);
 3995:   function verify(vf) {
 3996:     var foundsomething=0;
 3997:     var founduname=0;
 3998:     var foundID=0;
 3999:     for (i=0;i<=vf.nfields.value;i++) {
 4000:       tw=eval('vf.f'+i+'.selectedIndex');
 4001:       if (i==0 && tw!=0) { foundID=1; }
 4002:       if (i==1 && tw!=0) { founduname=1; }
 4003:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4004:     }
 4005:     if (founduname==0 && foundID==0) {
 4006: 	alert('$error1');
 4007: 	return;
 4008:     }
 4009:     if (foundsomething==0) {
 4010: 	alert('$error2');
 4011: 	return;
 4012:     }
 4013:     vf.submit();
 4014:   }
 4015:   function flip(vf,tf) {
 4016:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4017:     var i;
 4018:     for (i=0;i<=vf.nfields.value;i++) {
 4019:       //can not pick the same destination field for both name and domain
 4020:       if (((i ==0)||(i ==1)) && 
 4021:           ((tf==0)||(tf==1)) && 
 4022:           (i!=tf) &&
 4023:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4024:         eval('vf.f'+i+'.selectedIndex=0;')
 4025:       }
 4026:     }
 4027:   }
 4028: ENDPICK
 4029: }
 4030: 
 4031: sub csvupload_javascript_forward_associate {
 4032:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4033:     my $error2=&mt('You need to specify at least one grading field');
 4034:   return(<<ENDPICK);
 4035:   function verify(vf) {
 4036:     var foundsomething=0;
 4037:     var founduname=0;
 4038:     var foundID=0;
 4039:     for (i=0;i<=vf.nfields.value;i++) {
 4040:       tw=eval('vf.f'+i+'.selectedIndex');
 4041:       if (tw==1) { foundID=1; }
 4042:       if (tw==2) { founduname=1; }
 4043:       if (tw>3) { foundsomething=1; }
 4044:     }
 4045:     if (founduname==0 && foundID==0) {
 4046: 	alert('$error1');
 4047: 	return;
 4048:     }
 4049:     if (foundsomething==0) {
 4050: 	alert('$error2');
 4051: 	return;
 4052:     }
 4053:     vf.submit();
 4054:   }
 4055:   function flip(vf,tf) {
 4056:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4057:     var i;
 4058:     //can not pick the same destination field twice
 4059:     for (i=0;i<=vf.nfields.value;i++) {
 4060:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4061:         eval('vf.f'+i+'.selectedIndex=0;')
 4062:       }
 4063:     }
 4064:   }
 4065: ENDPICK
 4066: }
 4067: 
 4068: sub csvuploadmap_header {
 4069:     my ($request,$symb,$datatoken,$distotal)= @_;
 4070:     my $javascript;
 4071:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4072: 	$javascript=&csvupload_javascript_reverse_associate();
 4073:     } else {
 4074: 	$javascript=&csvupload_javascript_forward_associate();
 4075:     }
 4076: 
 4077:     $symb = &Apache::lonenc::check_encrypt($symb);
 4078:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4079:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4080:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4081:     my $reverse=&mt("Reverse Association");
 4082:     $request->print(<<ENDPICK);
 4083: <br />
 4084: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4085: <input type="hidden" name="associate"  value="" />
 4086: <input type="hidden" name="phase"      value="three" />
 4087: <input type="hidden" name="datatoken"  value="$datatoken" />
 4088: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4089: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4090: <input type="hidden" name="upfile_associate" 
 4091:                                        value="$env{'form.upfile_associate'}" />
 4092: <input type="hidden" name="symb"       value="$symb" />
 4093: <input type="hidden" name="command"    value="csvuploadoptions" />
 4094: <hr />
 4095: ENDPICK
 4096:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4097:     return '';
 4098: 
 4099: }
 4100: 
 4101: sub csvupload_fields {
 4102:     my ($symb,$errorref) = @_;
 4103:     my (@parts) = &getpartlist($symb,$errorref);
 4104:     if (ref($errorref)) {
 4105:         if ($$errorref) {
 4106:             return;
 4107:         }
 4108:     }
 4109: 
 4110:     my @fields=(['ID','Student/Employee ID'],
 4111: 		['username','Student Username'],
 4112: 		['domain','Student Domain']);
 4113:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4114:     foreach my $part (sort(@parts)) {
 4115: 	my @datum;
 4116: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4117: 	my $name=$part;
 4118: 	if  (!$display) { $display = $name; }
 4119: 	@datum=($name,$display);
 4120: 	if ($name=~/^stores_(.*)_awarded/) {
 4121: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4122: 	}
 4123: 	push(@fields,\@datum);
 4124:     }
 4125:     return (@fields);
 4126: }
 4127: 
 4128: sub csvuploadmap_footer {
 4129:     my ($request,$i,$keyfields) =@_;
 4130:     $request->print(<<ENDPICK);
 4131: </table>
 4132: <input type="hidden" name="nfields" value="$i" />
 4133: <input type="hidden" name="keyfields" value="$keyfields" />
 4134: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 4135: </form>
 4136: ENDPICK
 4137: }
 4138: 
 4139: sub checkforfile_js {
 4140:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4141:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4142:     function checkUpload(formname) {
 4143: 	if (formname.upfile.value == "") {
 4144: 	    alert("$alertmsg");
 4145: 	    return false;
 4146: 	}
 4147: 	formname.submit();
 4148:     }
 4149: CSVFORMJS
 4150:     return $result;
 4151: }
 4152: 
 4153: sub upcsvScores_form {
 4154:     my ($request,$symb) = @_;
 4155:     if (!$symb) {return '';}
 4156:     my $result=&checkforfile_js();
 4157:     $result.=&Apache::loncommon::start_data_table().
 4158:              &Apache::loncommon::start_data_table_header_row().
 4159:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4160:              &Apache::loncommon::end_data_table_header_row().
 4161:              &Apache::loncommon::start_data_table_row().'<td>';
 4162:     my $upload=&mt("Upload Scores");
 4163:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4164:     my $ignore=&mt('Ignore First Line');
 4165:     $symb = &Apache::lonenc::check_encrypt($symb);
 4166:     $result.=<<ENDUPFORM;
 4167: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4168: <input type="hidden" name="symb" value="$symb" />
 4169: <input type="hidden" name="command" value="csvuploadmap" />
 4170: $upfile_select
 4171: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4172: </form>
 4173: ENDUPFORM
 4174:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4175:                            &mt("How do I create a CSV file from a spreadsheet")).
 4176:              '</td>'.
 4177:             &Apache::loncommon::end_data_table_row().
 4178:             &Apache::loncommon::end_data_table();
 4179:     return $result;
 4180: }
 4181: 
 4182: 
 4183: sub csvuploadmap {
 4184:     my ($request,$symb)= @_;
 4185:     if (!$symb) {return '';}
 4186: 
 4187:     my $datatoken;
 4188:     if (!$env{'form.datatoken'}) {
 4189: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4190:     } else {
 4191: 	$datatoken=$env{'form.datatoken'};
 4192: 	&Apache::loncommon::load_tmp_file($request);
 4193:     }
 4194:     my @records=&Apache::loncommon::upfile_record_sep();
 4195:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4196:     my ($i,$keyfields);
 4197:     if (@records) {
 4198:         my $fieldserror;
 4199: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4200:         if ($fieldserror) {
 4201:             $request->print(&navmap_errormsg());
 4202:             return;
 4203:         }
 4204: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4205: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4206: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4207: 							  \@fields);
 4208: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4209: 	    chop($keyfields);
 4210: 	} else {
 4211: 	    unshift(@fields,['none','']);
 4212: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4213: 							    \@fields);
 4214:             foreach my $rec (@records) {
 4215:                 my %temp = &Apache::loncommon::record_sep($rec);
 4216:                 if (%temp) {
 4217:                     $keyfields=join(',',sort(keys(%temp)));
 4218:                     last;
 4219:                 }
 4220:             }
 4221: 	}
 4222:     }
 4223:     &csvuploadmap_footer($request,$i,$keyfields);
 4224: 
 4225:     return '';
 4226: }
 4227: 
 4228: sub csvuploadoptions {
 4229:     my ($request,$symb)= @_;
 4230:     my $overwrite=&mt('Overwrite any existing score');
 4231:     $request->print(<<ENDPICK);
 4232: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4233: <input type="hidden" name="command"    value="csvuploadassign" />
 4234: <p>
 4235: <label>
 4236:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4237:    $overwrite
 4238: </label>
 4239: </p>
 4240: ENDPICK
 4241:     my %fields=&get_fields();
 4242:     if (!defined($fields{'domain'})) {
 4243: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4244: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4245:     }
 4246:     foreach my $key (sort(keys(%env))) {
 4247: 	if ($key !~ /^form\.(.*)$/) { next; }
 4248: 	my $cleankey=$1;
 4249: 	if ($cleankey eq 'command') { next; }
 4250: 	$request->print('<input type="hidden" name="'.$cleankey.
 4251: 			'"  value="'.$env{$key}.'" />'."\n");
 4252:     }
 4253:     # FIXME do a check for any duplicated user ids...
 4254:     # FIXME do a check for any invalid user ids?...
 4255:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4256: <hr /></form>'."\n");
 4257:     return '';
 4258: }
 4259: 
 4260: sub get_fields {
 4261:     my %fields;
 4262:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4263:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4264: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4265: 	    if ($env{'form.f'.$i} ne 'none') {
 4266: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4267: 	    }
 4268: 	} else {
 4269: 	    if ($env{'form.f'.$i} ne 'none') {
 4270: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4271: 	    }
 4272: 	}
 4273:     }
 4274:     return %fields;
 4275: }
 4276: 
 4277: sub csvuploadassign {
 4278:     my ($request,$symb)= @_;
 4279:     if (!$symb) {return '';}
 4280:     my $error_msg = '';
 4281:     &Apache::loncommon::load_tmp_file($request);
 4282:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4283:     my %fields=&get_fields();
 4284:     my $courseid=$env{'request.course.id'};
 4285:     my ($classlist) = &getclasslist('all',0);
 4286:     my @notallowed;
 4287:     my @skipped;
 4288:     my @warnings;
 4289:     my $countdone=0;
 4290:     foreach my $grade (@gradedata) {
 4291: 	my %entries=&Apache::loncommon::record_sep($grade);
 4292: 	my $domain;
 4293: 	if ($entries{$fields{'domain'}}) {
 4294: 	    $domain=$entries{$fields{'domain'}};
 4295: 	} else {
 4296: 	    $domain=$env{'form.default_domain'};
 4297: 	}
 4298: 	$domain=~s/\s//g;
 4299: 	my $username=$entries{$fields{'username'}};
 4300: 	$username=~s/\s//g;
 4301: 	if (!$username) {
 4302: 	    my $id=$entries{$fields{'ID'}};
 4303: 	    $id=~s/\s//g;
 4304: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4305: 	    $username=$ids{$id};
 4306: 	}
 4307: 	if (!exists($$classlist{"$username:$domain"})) {
 4308: 	    my $id=$entries{$fields{'ID'}};
 4309: 	    $id=~s/\s//g;
 4310: 	    if ($id) {
 4311: 		push(@skipped,"$id:$domain");
 4312: 	    } else {
 4313: 		push(@skipped,"$username:$domain");
 4314: 	    }
 4315: 	    next;
 4316: 	}
 4317: 	my $usec=$classlist->{"$username:$domain"}[5];
 4318: 	if (!&canmodify($usec)) {
 4319: 	    push(@notallowed,"$username:$domain");
 4320: 	    next;
 4321: 	}
 4322: 	my %points;
 4323: 	my %grades;
 4324: 	foreach my $dest (keys(%fields)) {
 4325: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4326: 		$dest eq 'domain') { next; }
 4327: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4328: 	    if ($dest=~/stores_(.*)_points/) {
 4329: 		my $part=$1;
 4330: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4331: 					      $symb,$domain,$username);
 4332:                 if ($wgt) {
 4333:                     $entries{$fields{$dest}}=~s/\s//g;
 4334:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4335:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4336:                                           : 'correct_by_override';
 4337:                     if ($pcr>1) {
 4338:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4339:                     }
 4340:                     $grades{"resource.$part.awarded"}=$pcr;
 4341:                     $grades{"resource.$part.solved"}=$award;
 4342:                     $points{$part}=1;
 4343:                 } else {
 4344:                     $error_msg = "<br />" .
 4345:                         &mt("Some point values were assigned"
 4346:                             ." for problems with a weight "
 4347:                             ."of zero. These values were "
 4348:                             ."ignored.");
 4349:                 }
 4350: 	    } else {
 4351: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4352: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4353: 		my $store_key=$dest;
 4354: 		$store_key=~s/^stores/resource/;
 4355: 		$store_key=~s/_/\./g;
 4356: 		$grades{$store_key}=$entries{$fields{$dest}};
 4357: 	    }
 4358: 	}
 4359: 	if (! %grades) { 
 4360:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4361:         } else {
 4362: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4363: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4364: 					   $env{'request.course.id'},
 4365: 					   $domain,$username);
 4366: 	   if ($result eq 'ok') {
 4367: # Successfully stored
 4368: 	      $request->print('.');
 4369: # Remove from grading queue
 4370:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4371:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4372:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4373:                                              $domain,$username);
 4374:               $countdone++;
 4375:            } else {
 4376: 	      $request->print("<p><span class=\"LC_error\">".
 4377:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4378:                                   "$username:$domain",$result)."</span></p>");
 4379: 	   }
 4380: 	   $request->rflush();
 4381:         }
 4382:     }
 4383:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4384:     if (@warnings) {
 4385:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4386:         $request->print(join(', ',@warnings));
 4387:     }
 4388:     if (@skipped) {
 4389: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4390:         $request->print(join(', ',@skipped));
 4391:     }
 4392:     if (@notallowed) {
 4393: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4394: 	$request->print(join(', ',@notallowed));
 4395:     }
 4396:     $request->print("<br />\n");
 4397:     return $error_msg;
 4398: }
 4399: #------------- end of section for handling csv file upload ---------
 4400: #
 4401: #-------------------------------------------------------------------
 4402: #
 4403: #-------------- Next few routines handle grading by page/sequence
 4404: #
 4405: #--- Select a page/sequence and a student to grade
 4406: sub pickStudentPage {
 4407:     my ($request,$symb) = @_;
 4408: 
 4409:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4410:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4411: 
 4412: function checkPickOne(formname) {
 4413:     if (radioSelection(formname.student) == null) {
 4414: 	alert("$alertmsg");
 4415: 	return;
 4416:     }
 4417:     ptr = pullDownSelection(formname.selectpage);
 4418:     formname.page.value = formname["page"+ptr].value;
 4419:     formname.title.value = formname["title"+ptr].value;
 4420:     formname.submit();
 4421: }
 4422: 
 4423: LISTJAVASCRIPT
 4424:     &commonJSfunctions($request);
 4425: 
 4426:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4427:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4428:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4429: 
 4430:     my $result='<h3><span class="LC_info">&nbsp;'.
 4431: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4432: 
 4433:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4434:     my $map_error;
 4435:     my ($titles,$symbx) = &getSymbMap($map_error);
 4436:     if ($map_error) {
 4437:         $request->print(&navmap_errormsg());
 4438:         return; 
 4439:     }
 4440:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4441: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4442: #    my $type=($curpage =~ /\.(page|sequence)/);
 4443:     my $select = '<select name="selectpage">'."\n";
 4444:     my $ctr=0;
 4445:     foreach (@$titles) {
 4446: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4447: 	$select.='<option value="'.$ctr.'" '.
 4448: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4449: 	    '>'.$showtitle.'</option>'."\n";
 4450: 	$ctr++;
 4451:     }
 4452:     $select.= '</select>';
 4453:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4454: 
 4455:     $ctr=0;
 4456:     foreach (@$titles) {
 4457: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4458: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4459: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4460: 	$ctr++;
 4461:     }
 4462:     $result.='<input type="hidden" name="page" />'."\n".
 4463: 	'<input type="hidden" name="title" />'."\n";
 4464: 
 4465:     my $options =
 4466: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4467: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4468:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4469: 
 4470:     $options =
 4471: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4472: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4473: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4474:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4475:     
 4476:     $result.=&build_section_inputs();
 4477:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4478:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4479: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4480: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
 4481: 
 4482:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4483: 
 4484:     $result.='&nbsp;<input type="button" '.
 4485:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4486: 
 4487:     $request->print($result);
 4488: 
 4489:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4490: 	&Apache::loncommon::start_data_table().
 4491: 	&Apache::loncommon::start_data_table_header_row().
 4492: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4493: 	'<th>'.&nameUserString('header').'</th>'.
 4494: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4495: 	'<th>'.&nameUserString('header').'</th>'.
 4496: 	&Apache::loncommon::end_data_table_header_row();
 4497:  
 4498:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4499:     my $ptr = 1;
 4500:     foreach my $student (sort 
 4501: 			 {
 4502: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4503: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4504: 			     }
 4505: 			     return $a cmp $b;
 4506: 			 } (keys(%$fullname))) {
 4507: 	my ($uname,$udom) = split(/:/,$student);
 4508: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4509:                                   : '</td>');
 4510: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4511: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4512: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4513: 	$studentTable.=
 4514: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4515:                          : '');
 4516: 	$ptr++;
 4517:     }
 4518:     if ($ptr%2 == 0) {
 4519: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4520: 	    &Apache::loncommon::end_data_table_row();
 4521:     }
 4522:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4523:     $studentTable.='<input type="button" '.
 4524:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4525: 
 4526:     $request->print($studentTable);
 4527: 
 4528:     return '';
 4529: }
 4530: 
 4531: sub getSymbMap {
 4532:     my ($map_error) = @_;
 4533:     my $navmap = Apache::lonnavmaps::navmap->new();
 4534:     unless (ref($navmap)) {
 4535:         if (ref($map_error)) {
 4536:             $$map_error = 'navmap';
 4537:         }
 4538:         return;
 4539:     }
 4540:     my %symbx = ();
 4541:     my @titles = ();
 4542:     my $minder = 0;
 4543: 
 4544:     # Gather every sequence that has problems.
 4545:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4546: 					       1,0,1);
 4547:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4548: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4549: 	    my $title = $minder.'.'.
 4550: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4551: 	    push(@titles, $title); # minder in case two titles are identical
 4552: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4553: 	    $minder++;
 4554: 	}
 4555:     }
 4556:     return \@titles,\%symbx;
 4557: }
 4558: 
 4559: #
 4560: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4561: sub displayPage {
 4562:     my ($request,$symb) = @_;
 4563:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4564:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4565:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4566:     my $pageTitle = $env{'form.page'};
 4567:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4568:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4569:     my $usec=$classlist->{$env{'form.student'}}[5];
 4570: 
 4571:     #need to make sure we have the correct data for later EXT calls, 
 4572:     #thus invalidate the cache
 4573:     &Apache::lonnet::devalidatecourseresdata(
 4574:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4575:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4576:     &Apache::lonnet::clear_EXT_cache_status();
 4577: 
 4578:     if (!&canview($usec)) {
 4579: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4580: 	return;
 4581:     }
 4582:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4583:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4584: 	'</h3>'."\n";
 4585:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4586:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4587: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4588:     } else {
 4589: 	delete($env{'form.CODE'});
 4590:     }
 4591:     &sub_page_js($request);
 4592:     $request->print($result);
 4593: 
 4594:     my $navmap = Apache::lonnavmaps::navmap->new();
 4595:     unless (ref($navmap)) {
 4596:         $request->print(&navmap_errormsg());
 4597:         return;
 4598:     }
 4599:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4600:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4601:     if (!$map) {
 4602: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4603: 	return; 
 4604:     }
 4605:     my $iterator = $navmap->getIterator($map->map_start(),
 4606: 					$map->map_finish());
 4607: 
 4608:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4609: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4610: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4611: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4612: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4613: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4614: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4615: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 4616: 
 4617:     if (defined($env{'form.CODE'})) {
 4618: 	$studentTable.=
 4619: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4620:     }
 4621:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4622: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4623: 
 4624:     $studentTable.='&nbsp;<span class="LC_info">'.
 4625:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4626:         '</span>'."\n".
 4627: 	&Apache::loncommon::start_data_table().
 4628: 	&Apache::loncommon::start_data_table_header_row().
 4629: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4630: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4631: 	&Apache::loncommon::end_data_table_header_row();
 4632: 
 4633:     &Apache::lonxml::clear_problem_counter();
 4634:     my ($depth,$question,$prob) = (1,1,1);
 4635:     $iterator->next(); # skip the first BEGIN_MAP
 4636:     my $curRes = $iterator->next(); # for "current resource"
 4637:     while ($depth > 0) {
 4638:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4639:         if($curRes == $iterator->END_MAP) { $depth--; }
 4640: 
 4641:         if (ref($curRes) && $curRes->is_problem()) {
 4642: 	    my $parts = $curRes->parts();
 4643:             my $title = $curRes->compTitle();
 4644: 	    my $symbx = $curRes->symb();
 4645: 	    $studentTable.=
 4646: 		&Apache::loncommon::start_data_table_row().
 4647: 		'<td align="center" valign="top" >'.$prob.
 4648: 		(scalar(@{$parts}) == 1 ? '' 
 4649: 		                        : '<br />('.&mt('[_1]parts)',
 4650: 							scalar(@{$parts}).'&nbsp;')
 4651: 		 ).
 4652: 		 '</td>';
 4653: 	    $studentTable.='<td valign="top">';
 4654: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4655: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4656: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4657: 					     undef,'both',\%form);
 4658: 	    } else {
 4659: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4660: 		$companswer =~ s|<form(.*?)>||g;
 4661: 		$companswer =~ s|</form>||g;
 4662: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4663: #		    $companswer =~ s/$1/ /ms;
 4664: #		    $request->print('match='.$1."<br />\n");
 4665: #		}
 4666: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4667: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4668: 	    }
 4669: 
 4670: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4671: 
 4672: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4673: 		if ($record{'version'} eq '') {
 4674: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4675: 		} else {
 4676: 		    my %responseType = ();
 4677: 		    foreach my $partid (@{$parts}) {
 4678: 			my @responseIds =$curRes->responseIds($partid);
 4679: 			my @responseType =$curRes->responseType($partid);
 4680: 			my %responseIds;
 4681: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4682: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4683: 			}
 4684: 			$responseType{$partid} = \%responseIds;
 4685: 		    }
 4686: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4687: 
 4688: 		}
 4689: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4690: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4691: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4692: 									$env{'request.course.id'},
 4693: 									'','.submission');
 4694:  
 4695: 	    }
 4696: 	    if (&canmodify($usec)) {
 4697:             $studentTable.=&gradeBox_start();
 4698: 		foreach my $partid (@{$parts}) {
 4699: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4700: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4701: 		    $question++;
 4702: 		}
 4703:             $studentTable.=&gradeBox_end();
 4704: 		$prob++;
 4705: 	    }
 4706: 	    $studentTable.='</td></tr>';
 4707: 
 4708: 	}
 4709:         $curRes = $iterator->next();
 4710:     }
 4711: 
 4712:     $studentTable.=
 4713:         '</table>'."\n".
 4714:         '<input type="button" value="'.&mt('Save').'" '.
 4715:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4716:         '</form>'."\n";
 4717:     $request->print($studentTable);
 4718: 
 4719:     return '';
 4720: }
 4721: 
 4722: sub displaySubByDates {
 4723:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4724:     my $isCODE=0;
 4725:     my $isTask = ($symb =~/\.task$/);
 4726:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4727:     my $studentTable=&Apache::loncommon::start_data_table().
 4728: 	&Apache::loncommon::start_data_table_header_row().
 4729: 	'<th>'.&mt('Date/Time').'</th>'.
 4730: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4731:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 4732: 	'<th>'.&mt('Submission').'</th>'.
 4733: 	'<th>'.&mt('Status').'</th>'.
 4734: 	&Apache::loncommon::end_data_table_header_row();
 4735:     my ($version);
 4736:     my %mark;
 4737:     my %orders;
 4738:     $mark{'correct_by_student'} = $checkIcon;
 4739:     if (!exists($$record{'1:timestamp'})) {
 4740: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4741:     }
 4742: 
 4743:     my $interaction;
 4744:     my $no_increment = 1;
 4745:     my %lastrndseed;
 4746:     for ($version=1;$version<=$$record{'version'};$version++) {
 4747: 	my $timestamp = 
 4748: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4749: 	if (exists($$record{$version.':resource.0.version'})) {
 4750: 	    $interaction = $$record{$version.':resource.0.version'};
 4751: 	}
 4752:         if ($isTask && $env{'form.previousversion'}) {
 4753:             next unless ($interaction == $env{'form.previousversion'});
 4754:         }
 4755: 	my $where = ($isTask ? "$version:resource.$interaction"
 4756: 		             : "$version:resource");
 4757: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4758: 	    '<td>'.$timestamp.'</td>';
 4759: 	if ($isCODE) {
 4760: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4761: 	}
 4762:         if ($isTask) {
 4763:             $studentTable.='<td>'.$interaction.'</td>';
 4764:         }
 4765: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4766: 	my @displaySub = ();
 4767: 	foreach my $partid (@{$parts}) {
 4768:             my ($hidden,$type);
 4769:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4770:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4771:                 $hidden = 1;
 4772:             }
 4773: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4774: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4775: 	    
 4776: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4777: 	    my $display_part=&get_display_part($partid,$symb);
 4778: 	    foreach my $matchKey (@matchKey) {
 4779: 		if (exists($$record{$version.':'.$matchKey}) &&
 4780: 		    $$record{$version.':'.$matchKey} ne '') {
 4781:                     
 4782: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4783: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4784:                     $displaySub[0].='<span class="LC_nobreak">';
 4785:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4786:                                    .' <span class="LC_internal_info">'
 4787:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 4788:                                    .'</span>'
 4789:                                    .' <b>';
 4790:                     if ($hidden) {
 4791:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4792:                     } else {
 4793:                         my ($trial,$rndseed,$newvariation);
 4794:                         if ($type eq 'randomizetry') {
 4795:                             $trial = $$record{"$where.$partid.tries"};
 4796:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4797:                         }
 4798: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4799: 			    $displaySub[0].=&mt('Trial not counted');
 4800: 		        } else {
 4801: 			    $displaySub[0].=&mt('Trial: [_1]',
 4802: 					    $$record{"$where.$partid.tries"});
 4803:                             if ($rndseed || $lastrndseed{$partid}) {
 4804:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4805:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4806:                                 }
 4807:                             }
 4808:                             $lastrndseed{$partid} = $rndseed;
 4809: 		        }
 4810: 		        my $responseType=($isTask ? 'Task'
 4811:                                               : $responseType->{$partid}->{$responseId});
 4812: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4813: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4814: 			    $orders{$partid}->{$responseId}=
 4815: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4816:                                            $no_increment,$type,$trial,$rndseed);
 4817: 		        }
 4818: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4819: 		        $displaySub[0].='&nbsp; '.
 4820: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4821:                     }
 4822: 		}
 4823: 	    }
 4824: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4825: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4826: 				    $$record{"$where.$partid.checkedin"},
 4827: 				    $$record{"$where.$partid.checkedin.slot"}).
 4828: 					'<br />';
 4829: 	    }
 4830: 	    if (exists $$record{"$where.$partid.award"}) {
 4831: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4832: 		    lc($$record{"$where.$partid.award"}).' '.
 4833: 		    $mark{$$record{"$where.$partid.solved"}}.
 4834: 		    '<br />';
 4835: 	    }
 4836: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4837: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4838: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4839: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4840: 		$displaySub[2].=
 4841: 		    $$record{"$version:resource.$partid.regrader"}.
 4842: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4843: 	    }
 4844: 	}
 4845: 	# needed because old essay regrader has not parts info
 4846: 	if (exists $$record{"$version:resource.regrader"}) {
 4847: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4848: 	}
 4849: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4850: 	if ($displaySub[2]) {
 4851: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4852: 	}
 4853: 	$studentTable.='&nbsp;</td>'.
 4854: 	    &Apache::loncommon::end_data_table_row();
 4855:     }
 4856:     $studentTable.=&Apache::loncommon::end_data_table();
 4857:     return $studentTable;
 4858: }
 4859: 
 4860: sub updateGradeByPage {
 4861:     my ($request,$symb) = @_;
 4862: 
 4863:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4864:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4865:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4866:     my $pageTitle = $env{'form.page'};
 4867:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4868:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4869:     my $usec=$classlist->{$env{'form.student'}}[5];
 4870:     if (!&canmodify($usec)) {
 4871: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4872: 	return;
 4873:     }
 4874:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4875:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4876: 	'</h3>'."\n";
 4877: 
 4878:     $request->print($result);
 4879: 
 4880: 
 4881:     my $navmap = Apache::lonnavmaps::navmap->new();
 4882:     unless (ref($navmap)) {
 4883:         $request->print(&navmap_errormsg());
 4884:         return;
 4885:     }
 4886:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4887:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4888:     if (!$map) {
 4889: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4890: 	return; 
 4891:     }
 4892:     my $iterator = $navmap->getIterator($map->map_start(),
 4893: 					$map->map_finish());
 4894: 
 4895:     my $studentTable=
 4896: 	&Apache::loncommon::start_data_table().
 4897: 	&Apache::loncommon::start_data_table_header_row().
 4898: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4899: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4900: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4901: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4902: 	&Apache::loncommon::end_data_table_header_row();
 4903: 
 4904:     $iterator->next(); # skip the first BEGIN_MAP
 4905:     my $curRes = $iterator->next(); # for "current resource"
 4906:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4907:     while ($depth > 0) {
 4908:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4909:         if($curRes == $iterator->END_MAP) { $depth--; }
 4910: 
 4911:         if (ref($curRes) && $curRes->is_problem()) {
 4912: 	    my $parts = $curRes->parts();
 4913:             my $title = $curRes->compTitle();
 4914: 	    my $symbx = $curRes->symb();
 4915: 	    $studentTable.=
 4916: 		&Apache::loncommon::start_data_table_row().
 4917: 		'<td align="center" valign="top" >'.$prob.
 4918: 		(scalar(@{$parts}) == 1 ? '' 
 4919:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4920: 		.')').'</td>';
 4921: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4922: 
 4923: 	    my %newrecord=();
 4924: 	    my @displayPts=();
 4925:             my %aggregate = ();
 4926:             my $aggregateflag = 0;
 4927: 	    foreach my $partid (@{$parts}) {
 4928: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4929: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4930: 
 4931: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4932: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4933: 		my $partial = $newpts/$wgt;
 4934: 		my $score;
 4935: 		if ($partial > 0) {
 4936: 		    $score = 'correct_by_override';
 4937: 		} elsif ($newpts ne '') { #empty is taken as 0
 4938: 		    $score = 'incorrect_by_override';
 4939: 		}
 4940: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4941: 		if ($dropMenu eq 'excused') {
 4942: 		    $partial = '';
 4943: 		    $score = 'excused';
 4944: 		} elsif ($dropMenu eq 'reset status'
 4945: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4946: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4947: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4948: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4949: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4950: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4951: 		    $changeflag++;
 4952: 		    $newpts = '';
 4953:                     
 4954:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4955:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4956:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4957:                     if ($aggtries > 0) {
 4958:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4959:                         $aggregateflag = 1;
 4960:                     }
 4961: 		}
 4962: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4963: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4964: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4965: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4966: 		    '&nbsp;<br />';
 4967: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4968: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4969: 		    '&nbsp;<br />';
 4970: 		$question++;
 4971: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4972: 
 4973: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4974: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4975: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4976: 		    if (scalar(keys(%newrecord)) > 0);
 4977: 
 4978: 		$changeflag++;
 4979: 	    }
 4980: 	    if (scalar(keys(%newrecord)) > 0) {
 4981: 		my %record = 
 4982: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4983: 					     $udom,$uname);
 4984: 
 4985: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4986: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4987: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4988: 		    $newrecord{'resource.CODE'} = '';
 4989: 		}
 4990: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4991: 					$udom,$uname);
 4992: 		%record = &Apache::lonnet::restore($symbx,
 4993: 						   $env{'request.course.id'},
 4994: 						   $udom,$uname);
 4995: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4996: 					     $cdom,$cnum,$udom,$uname);
 4997: 	    }
 4998: 	    
 4999:             if ($aggregateflag) {
 5000:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5001:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5002:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5003:             }
 5004: 
 5005: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5006: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5007: 		&Apache::loncommon::end_data_table_row();
 5008: 
 5009: 	    $prob++;
 5010: 	}
 5011:         $curRes = $iterator->next();
 5012:     }
 5013: 
 5014:     $studentTable.=&Apache::loncommon::end_data_table();
 5015:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5016: 		  &mt('The scores were changed for [quant,_1,problem].',
 5017: 		  $changeflag));
 5018:     $request->print($grademsg.$studentTable);
 5019: 
 5020:     return '';
 5021: }
 5022: 
 5023: #-------- end of section for handling grading by page/sequence ---------
 5024: #
 5025: #-------------------------------------------------------------------
 5026: 
 5027: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5028: #
 5029: #------ start of section for handling grading by page/sequence ---------
 5030: 
 5031: =pod
 5032: 
 5033: =head1 Bubble sheet grading routines
 5034: 
 5035:   For this documentation:
 5036: 
 5037:    'scanline' refers to the full line of characters
 5038:    from the file that we are parsing that represents one entire sheet
 5039: 
 5040:    'bubble line' refers to the data
 5041:    representing the line of bubbles that are on the physical bubblesheet
 5042: 
 5043: 
 5044: The overall process is that a scanned in bubblesheet data is uploaded
 5045: into a course. When a user wants to grade, they select a
 5046: sequence/folder of resources, a file of bubblesheet info, and pick
 5047: one of the predefined configurations for what each scanline looks
 5048: like.
 5049: 
 5050: Next each scanline is checked for any errors of either 'missing
 5051: bubbles' (it's an error because it may have been mis-scanned
 5052: because too light bubbling), 'double bubble' (each bubble line should
 5053: have no more that one letter picked), invalid or duplicated CODE,
 5054: invalid student/employee ID
 5055: 
 5056: If the CODE option is used that determines the randomization of the
 5057: homework problems, either way the student/employee ID is looked up into a
 5058: username:domain.
 5059: 
 5060: During the validation phase the instructor can choose to skip scanlines. 
 5061: 
 5062: After the validation phase, there are now 3 bubblesheet files
 5063: 
 5064:   scantron_original_filename (unmodified original file)
 5065:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5066:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5067: 
 5068: Also there is a separate hash nohist_scantrondata that contains extra
 5069: correction information that isn't representable in the bubblesheet
 5070: file (see &scantron_getfile() for more information)
 5071: 
 5072: After all scanlines are either valid, marked as valid or skipped, then
 5073: foreach line foreach problem in the picked sequence, an ssi request is
 5074: made that simulates a user submitting their selected letter(s) against
 5075: the homework problem.
 5076: 
 5077: =over 4
 5078: 
 5079: 
 5080: 
 5081: =item defaultFormData
 5082: 
 5083:   Returns html hidden inputs used to hold context/default values.
 5084: 
 5085:  Arguments:
 5086:   $symb - $symb of the current resource 
 5087: 
 5088: =cut
 5089: 
 5090: sub defaultFormData {
 5091:     my ($symb)=@_;
 5092:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5093: }
 5094: 
 5095: 
 5096: =pod 
 5097: 
 5098: =item getSequenceDropDown
 5099: 
 5100:    Return html dropdown of possible sequences to grade
 5101:  
 5102:  Arguments:
 5103:    $symb - $symb of the current resource
 5104:    $map_error - ref to scalar which will container error if
 5105:                 $navmap object is unavailable in &getSymbMap().
 5106: 
 5107: =cut
 5108: 
 5109: sub getSequenceDropDown {
 5110:     my ($symb,$map_error)=@_;
 5111:     my $result='<select name="selectpage">'."\n";
 5112:     my ($titles,$symbx) = &getSymbMap($map_error);
 5113:     if (ref($map_error)) {
 5114:         return if ($$map_error);
 5115:     }
 5116:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5117:     my $ctr=0;
 5118:     foreach (@$titles) {
 5119: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5120: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5121: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5122: 	    '>'.$showtitle.'</option>'."\n";
 5123: 	$ctr++;
 5124:     }
 5125:     $result.= '</select>';
 5126:     return $result;
 5127: }
 5128: 
 5129: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5130:                                    # key is zero-based index - 0, 1, 2 ...
 5131: 
 5132: my %first_bubble_line;             # First bubble line no. for each bubble.
 5133: 
 5134: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5135:                                    # matchresponse or rankresponse, where 
 5136:                                    # an individual response can have multiple 
 5137:                                    # lines
 5138: 
 5139: my %responsetype_per_response;     # responsetype for each response
 5140: 
 5141: # Save and restore the bubble lines array to the form env.
 5142: 
 5143: 
 5144: sub save_bubble_lines {
 5145:     foreach my $line (keys(%bubble_lines_per_response)) {
 5146: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5147: 	$env{"form.scantron.first_bubble_line.$line"} =
 5148: 	    $first_bubble_line{$line};
 5149:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5150:             $subdivided_bubble_lines{$line};
 5151:         $env{"form.scantron.responsetype.$line"} =
 5152:             $responsetype_per_response{$line};
 5153:     }
 5154: }
 5155: 
 5156: 
 5157: sub restore_bubble_lines {
 5158:     my $line = 0;
 5159:     %bubble_lines_per_response = ();
 5160:     while ($env{"form.scantron.bubblelines.$line"}) {
 5161: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5162: 	$bubble_lines_per_response{$line} = $value;
 5163: 	$first_bubble_line{$line}  =
 5164: 	    $env{"form.scantron.first_bubble_line.$line"};
 5165:         $subdivided_bubble_lines{$line} =
 5166:             $env{"form.scantron.sub_bubblelines.$line"};
 5167:         $responsetype_per_response{$line} =
 5168:             $env{"form.scantron.responsetype.$line"};
 5169: 	$line++;
 5170:     }
 5171: }
 5172: 
 5173: #  Given the parsed scanline, get the response for 
 5174: #  'answer' number n:
 5175: 
 5176: sub get_response_bubbles {
 5177:     my ($parsed_line, $response)  = @_;
 5178: 
 5179:     my $bubble_line = $first_bubble_line{$response-1} +1;
 5180:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 5181:     
 5182:     my $selected = "";
 5183: 
 5184:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 5185: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 5186: 	$bubble_line++;
 5187:     }
 5188:     return $selected;
 5189: }
 5190: 
 5191: =pod 
 5192: 
 5193: =item scantron_filenames
 5194: 
 5195:    Returns a list of the scantron files in the current course 
 5196: 
 5197: =cut
 5198: 
 5199: sub scantron_filenames {
 5200:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5201:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5202:     my $getpropath = 1;
 5203:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5204:                                                         $cname,$getpropath);
 5205:     my @possiblenames;
 5206:     if (ref($dirlist) eq 'ARRAY') {
 5207:         foreach my $filename (sort(@{$dirlist})) {
 5208: 	    ($filename)=split(/&/,$filename);
 5209: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5210: 	    $filename=~s/^scantron_orig_//;
 5211: 	    push(@possiblenames,$filename);
 5212:         }
 5213:     }
 5214:     return @possiblenames;
 5215: }
 5216: 
 5217: =pod 
 5218: 
 5219: =item scantron_uploads
 5220: 
 5221:    Returns  html drop-down list of scantron files in current course.
 5222: 
 5223:  Arguments:
 5224:    $file2grade - filename to set as selected in the dropdown
 5225: 
 5226: =cut
 5227: 
 5228: sub scantron_uploads {
 5229:     my ($file2grade) = @_;
 5230:     my $result=	'<select name="scantron_selectfile">';
 5231:     $result.="<option></option>";
 5232:     foreach my $filename (sort(&scantron_filenames())) {
 5233: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5234:     }
 5235:     $result.="</select>";
 5236:     return $result;
 5237: }
 5238: 
 5239: =pod 
 5240: 
 5241: =item scantron_scantab
 5242: 
 5243:   Returns html drop down of the scantron formats in the scantronformat.tab
 5244:   file.
 5245: 
 5246: =cut
 5247: 
 5248: sub scantron_scantab {
 5249:     my $result='<select name="scantron_format">'."\n";
 5250:     $result.='<option></option>'."\n";
 5251:     my @lines = &get_scantronformat_file();
 5252:     if (@lines > 0) {
 5253:         foreach my $line (@lines) {
 5254:             next if (($line =~ /^\#/) || ($line eq ''));
 5255: 	    my ($name,$descrip)=split(/:/,$line);
 5256: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5257:         }
 5258:     }
 5259:     $result.='</select>'."\n";
 5260:     return $result;
 5261: }
 5262: 
 5263: =pod
 5264: 
 5265: =item get_scantronformat_file
 5266: 
 5267:   Returns an array containing lines from the scantron format file for
 5268:   the domain of the course.
 5269: 
 5270:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5271:   lines are from this file.
 5272: 
 5273:   Otherwise, if a default.tab has been published in RES space by the 
 5274:   domainconfig user, lines are from this file.
 5275: 
 5276:   Otherwise, fall back to getting lines from the legacy file on the
 5277:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5278: 
 5279: =cut
 5280: 
 5281: sub get_scantronformat_file {
 5282:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5283:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5284:     my $gottab = 0;
 5285:     my @lines;
 5286:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5287:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5288:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5289:             if ($formatfile ne '-1') {
 5290:                 @lines = split("\n",$formatfile,-1);
 5291:                 $gottab = 1;
 5292:             }
 5293:         }
 5294:     }
 5295:     if (!$gottab) {
 5296:         my $confname = $cdom.'-domainconfig';
 5297:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5298:         my $formatfile =  &Apache::lonnet::getfile($default);
 5299:         if ($formatfile ne '-1') {
 5300:             @lines = split("\n",$formatfile,-1);
 5301:             $gottab = 1;
 5302:         }
 5303:     }
 5304:     if (!$gottab) {
 5305:         my @domains = &Apache::lonnet::current_machine_domains();
 5306:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5307:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5308:             @lines = <$fh>;
 5309:             close($fh);
 5310:         } else {
 5311:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5312:             @lines = <$fh>;
 5313:             close($fh);
 5314:         }
 5315:     }
 5316:     return @lines;
 5317: }
 5318: 
 5319: =pod 
 5320: 
 5321: =item scantron_CODElist
 5322: 
 5323:   Returns html drop down of the saved CODE lists from current course,
 5324:   generated from earlier printings.
 5325: 
 5326: =cut
 5327: 
 5328: sub scantron_CODElist {
 5329:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5330:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5331:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5332:     my $namechoice='<option></option>';
 5333:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5334: 	if ($name =~ /^error: 2 /) { next; }
 5335: 	if ($name =~ /^type\0/) { next; }
 5336: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5337:     }
 5338:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5339:     return $namechoice;
 5340: }
 5341: 
 5342: =pod 
 5343: 
 5344: =item scantron_CODEunique
 5345: 
 5346:   Returns the html for "Each CODE to be used once" radio.
 5347: 
 5348: =cut
 5349: 
 5350: sub scantron_CODEunique {
 5351:     my $result='<span class="LC_nobreak">
 5352:                  <label><input type="radio" name="scantron_CODEunique"
 5353:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5354:                 </span>
 5355:                 <span class="LC_nobreak">
 5356:                  <label><input type="radio" name="scantron_CODEunique"
 5357:                         value="no" />'.&mt('No').' </label>
 5358:                 </span>';
 5359:     return $result;
 5360: }
 5361: 
 5362: =pod 
 5363: 
 5364: =item scantron_selectphase
 5365: 
 5366:   Generates the initial screen to start the bubblesheet process.
 5367:   Allows for - starting a grading run.
 5368:              - downloading existing scan data (original, corrected
 5369:                                                 or skipped info)
 5370: 
 5371:              - uploading new scan data
 5372: 
 5373:  Arguments:
 5374:   $r          - The Apache request object
 5375:   $file2grade - name of the file that contain the scanned data to score
 5376: 
 5377: =cut
 5378: 
 5379: sub scantron_selectphase {
 5380:     my ($r,$file2grade,$symb) = @_;
 5381:     if (!$symb) {return '';}
 5382:     my $map_error;
 5383:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5384:     if ($map_error) {
 5385:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5386:         return;
 5387:     }
 5388:     my $default_form_data=&defaultFormData($symb);
 5389:     my $file_selector=&scantron_uploads($file2grade);
 5390:     my $format_selector=&scantron_scantab();
 5391:     my $CODE_selector=&scantron_CODElist();
 5392:     my $CODE_unique=&scantron_CODEunique();
 5393:     my $result;
 5394: 
 5395:     $ssi_error = 0;
 5396: 
 5397:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5398:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5399: 
 5400: 	# Chunk of form to prompt for a scantron file upload.
 5401: 
 5402:         $r->print('
 5403:     <br />
 5404:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5405:        '.&Apache::loncommon::start_data_table_header_row().'
 5406:             <th>
 5407:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5408:             </th>
 5409:        '.&Apache::loncommon::end_data_table_header_row().'
 5410:        '.&Apache::loncommon::start_data_table_row().'
 5411:             <td>
 5412: ');
 5413:     my $default_form_data=&defaultFormData($symb);
 5414:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5415:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5416:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5417:     function checkUpload(formname) {
 5418: 	if (formname.upfile.value == "") {
 5419: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5420: 	    return false;
 5421: 	}
 5422: 	formname.submit();
 5423:     }'));
 5424:     $r->print('
 5425:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5426:                 '.$default_form_data.'
 5427:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5428:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5429:                 <input name="command" value="scantronupload_save" type="hidden" />
 5430:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5431:                 <br />
 5432:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5433:               </form>
 5434: ');
 5435: 
 5436:         $r->print('
 5437:             </td>
 5438:        '.&Apache::loncommon::end_data_table_row().'
 5439:        '.&Apache::loncommon::end_data_table().'
 5440: ');
 5441:     }
 5442: 
 5443:     # Chunk of form to prompt for a file to grade and how:
 5444: 
 5445:     $result.= '
 5446:     <br />
 5447:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5448:     <input type="hidden" name="command" value="scantron_warning" />
 5449:     '.$default_form_data.'
 5450:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5451:        '.&Apache::loncommon::start_data_table_header_row().'
 5452:             <th colspan="2">
 5453:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5454:             </th>
 5455:        '.&Apache::loncommon::end_data_table_header_row().'
 5456:        '.&Apache::loncommon::start_data_table_row().'
 5457:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5458:        '.&Apache::loncommon::end_data_table_row().'
 5459:        '.&Apache::loncommon::start_data_table_row().'
 5460:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5461:        '.&Apache::loncommon::end_data_table_row().'
 5462:        '.&Apache::loncommon::start_data_table_row().'
 5463:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5464:        '.&Apache::loncommon::end_data_table_row().'
 5465:        '.&Apache::loncommon::start_data_table_row().'
 5466:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5467:        '.&Apache::loncommon::end_data_table_row().'
 5468:        '.&Apache::loncommon::start_data_table_row().'
 5469:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5470:        '.&Apache::loncommon::end_data_table_row().'
 5471:        '.&Apache::loncommon::start_data_table_row().'
 5472: 	    <td> '.&mt('Options:').' </td>
 5473:             <td>
 5474: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5475:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5476:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5477: 	    </td>
 5478:        '.&Apache::loncommon::end_data_table_row().'
 5479:        '.&Apache::loncommon::start_data_table_row().'
 5480:             <td colspan="2">
 5481:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5482:             </td>
 5483:        '.&Apache::loncommon::end_data_table_row().'
 5484:     '.&Apache::loncommon::end_data_table().'
 5485:     </form>
 5486: ';
 5487:    
 5488:     $r->print($result);
 5489: 
 5490: 
 5491: 
 5492:     # Chunk of the form that prompts to view a scoring office file,
 5493:     # corrected file, skipped records in a file.
 5494: 
 5495:     $r->print('
 5496:    <br />
 5497:    <form action="/adm/grades" name="scantron_download">
 5498:      '.$default_form_data.'
 5499:      <input type="hidden" name="command" value="scantron_download" />
 5500:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5501:        '.&Apache::loncommon::start_data_table_header_row().'
 5502:               <th>
 5503:                 &nbsp;'.&mt('Download a scoring office file').'
 5504:               </th>
 5505:        '.&Apache::loncommon::end_data_table_header_row().'
 5506:        '.&Apache::loncommon::start_data_table_row().'
 5507:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5508:                 <br />
 5509:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5510:        '.&Apache::loncommon::end_data_table_row().'
 5511:      '.&Apache::loncommon::end_data_table().'
 5512:    </form>
 5513:    <br />
 5514: ');
 5515: 
 5516:     &Apache::lonpickcode::code_list($r,2);
 5517: 
 5518:     $r->print('<br /><form method="post" name="checkscantron">'.
 5519:              $default_form_data."\n".
 5520:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5521:              &Apache::loncommon::start_data_table_header_row()."\n".
 5522:              '<th colspan="2">
 5523:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5524:              '</th>'."\n".
 5525:               &Apache::loncommon::end_data_table_header_row()."\n".
 5526:               &Apache::loncommon::start_data_table_row()."\n".
 5527:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5528:               '<td> '.$sequence_selector.' </td>'.
 5529:               &Apache::loncommon::end_data_table_row()."\n".
 5530:               &Apache::loncommon::start_data_table_row()."\n".
 5531:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5532:               '<td> '.$file_selector.' </td>'."\n".
 5533:               &Apache::loncommon::end_data_table_row()."\n".
 5534:               &Apache::loncommon::start_data_table_row()."\n".
 5535:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5536:               '<td> '.$format_selector.' </td>'."\n".
 5537:               &Apache::loncommon::end_data_table_row()."\n".
 5538:               &Apache::loncommon::start_data_table_row()."\n".
 5539:               '<td> '.&mt('Options').' </td>'."\n".
 5540:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5541:               &Apache::loncommon::end_data_table_row()."\n".
 5542:               &Apache::loncommon::start_data_table_row()."\n".
 5543:               '<td colspan="2">'."\n".
 5544:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5545:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5546:               '</td>'."\n".
 5547:               &Apache::loncommon::end_data_table_row()."\n".
 5548:               &Apache::loncommon::end_data_table()."\n".
 5549:               '</form><br />');
 5550:     return;
 5551: }
 5552: 
 5553: =pod
 5554: 
 5555: =item get_scantron_config
 5556: 
 5557:    Parse and return the scantron configuration line selected as a
 5558:    hash of configuration file fields.
 5559: 
 5560:  Arguments:
 5561:     which - the name of the configuration to parse from the file.
 5562: 
 5563: 
 5564:  Returns:
 5565:             If the named configuration is not in the file, an empty
 5566:             hash is returned.
 5567:     a hash with the fields
 5568:       name         - internal name for the this configuration setup
 5569:       description  - text to display to operator that describes this config
 5570:       CODElocation - if 0 or the string 'none'
 5571:                           - no CODE exists for this config
 5572:                      if -1 || the string 'letter'
 5573:                           - a CODE exists for this config and is
 5574:                             a string of letters
 5575:                      Unsupported value (but planned for future support)
 5576:                           if a positive integer
 5577:                                - The CODE exists as the first n items from
 5578:                                  the question section of the form
 5579:                           if the string 'number'
 5580:                                - The CODE exists for this config and is
 5581:                                  a string of numbers
 5582:       CODEstart   - (only matter if a CODE exists) column in the line where
 5583:                      the CODE starts
 5584:       CODElength  - length of the CODE
 5585:       IDstart     - column where the student/employee ID starts
 5586:       IDlength    - length of the student/employee ID info
 5587:       Qstart      - column where the information from the bubbled
 5588:                     'questions' start
 5589:       Qlength     - number of columns comprising a single bubble line from
 5590:                     the sheet. (usually either 1 or 10)
 5591:       Qon         - either a single character representing the character used
 5592:                     to signal a bubble was chosen in the positional setup, or
 5593:                     the string 'letter' if the letter of the chosen bubble is
 5594:                     in the final, or 'number' if a number representing the
 5595:                     chosen bubble is in the file (1->A 0->J)
 5596:       Qoff        - the character used to represent that a bubble was
 5597:                     left blank
 5598:       PaperID     - if the scanning process generates a unique number for each
 5599:                     sheet scanned the column that this ID number starts in
 5600:       PaperIDlength - number of columns that comprise the unique ID number
 5601:                       for the sheet of paper
 5602:       FirstName   - column that the first name starts in
 5603:       FirstNameLength - number of columns that the first name spans
 5604:  
 5605:       LastName    - column that the last name starts in
 5606:       LastNameLength - number of columns that the last name spans
 5607:       BubblesPerRow - number of bubbles available in each row used to 
 5608:                       bubble an answer. (If not specified, 10 assumed).
 5609: 
 5610: =cut
 5611: 
 5612: sub get_scantron_config {
 5613:     my ($which) = @_;
 5614:     my @lines = &get_scantronformat_file();
 5615:     my %config;
 5616:     #FIXME probably should move to XML it has already gotten a bit much now
 5617:     foreach my $line (@lines) {
 5618: 	my ($name,$descrip)=split(/:/,$line);
 5619: 	if ($name ne $which ) { next; }
 5620: 	chomp($line);
 5621: 	my @config=split(/:/,$line);
 5622: 	$config{'name'}=$config[0];
 5623: 	$config{'description'}=$config[1];
 5624: 	$config{'CODElocation'}=$config[2];
 5625: 	$config{'CODEstart'}=$config[3];
 5626: 	$config{'CODElength'}=$config[4];
 5627: 	$config{'IDstart'}=$config[5];
 5628: 	$config{'IDlength'}=$config[6];
 5629: 	$config{'Qstart'}=$config[7];
 5630:  	$config{'Qlength'}=$config[8];
 5631: 	$config{'Qoff'}=$config[9];
 5632: 	$config{'Qon'}=$config[10];
 5633: 	$config{'PaperID'}=$config[11];
 5634: 	$config{'PaperIDlength'}=$config[12];
 5635: 	$config{'FirstName'}=$config[13];
 5636: 	$config{'FirstNamelength'}=$config[14];
 5637: 	$config{'LastName'}=$config[15];
 5638: 	$config{'LastNamelength'}=$config[16];
 5639:         $config{'BubblesPerRow'}=$config[17];
 5640: 	last;
 5641:     }
 5642:     return %config;
 5643: }
 5644: 
 5645: =pod 
 5646: 
 5647: =item username_to_idmap
 5648: 
 5649:     creates a hash keyed by student/employee ID with values of the corresponding
 5650:     student username:domain.
 5651: 
 5652:   Arguments:
 5653: 
 5654:     $classlist - reference to the class list hash. This is a hash
 5655:                  keyed by student name:domain  whose elements are references
 5656:                  to arrays containing various chunks of information
 5657:                  about the student. (See loncoursedata for more info).
 5658: 
 5659:   Returns
 5660:     %idmap - the constructed hash
 5661: 
 5662: =cut
 5663: 
 5664: sub username_to_idmap {
 5665:     my ($classlist)= @_;
 5666:     my %idmap;
 5667:     foreach my $student (keys(%$classlist)) {
 5668: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5669: 	    $student;
 5670:     }
 5671:     return %idmap;
 5672: }
 5673: 
 5674: =pod
 5675: 
 5676: =item scantron_fixup_scanline
 5677: 
 5678:    Process a requested correction to a scanline.
 5679: 
 5680:   Arguments:
 5681:     $scantron_config   - hash from &get_scantron_config()
 5682:     $scan_data         - hash of correction information 
 5683:                           (see &scantron_getfile())
 5684:     $line              - existing scanline
 5685:     $whichline         - line number of the passed in scanline
 5686:     $field             - type of change to process 
 5687:                          (either 
 5688:                           'ID'     -> correct the student/employee ID
 5689:                           'CODE'   -> correct the CODE
 5690:                           'answer' -> fixup the submitted answers)
 5691:     
 5692:    $args               - hash of additional info,
 5693:                           - 'ID' 
 5694:                                'newid' -> studentID to use in replacement
 5695:                                           of existing one
 5696:                           - 'CODE' 
 5697:                                'CODE_ignore_dup' - set to true if duplicates
 5698:                                                    should be ignored.
 5699: 	                       'CODE' - is new code or 'use_unfound'
 5700:                                         if the existing unfound code should
 5701:                                         be used as is
 5702:                           - 'answer'
 5703:                                'response' - new answer or 'none' if blank
 5704:                                'question' - the bubble line to change
 5705:                                'questionnum' - the question identifier,
 5706:                                                may include subquestion. 
 5707: 
 5708:   Returns:
 5709:     $line - the modified scanline
 5710: 
 5711:   Side effects: 
 5712:     $scan_data - may be updated
 5713: 
 5714: =cut
 5715: 
 5716: 
 5717: sub scantron_fixup_scanline {
 5718:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5719:     if ($field eq 'ID') {
 5720: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5721: 	    return ($line,1,'New value too large');
 5722: 	}
 5723: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5724: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5725: 				     $args->{'newid'});
 5726: 	}
 5727: 	substr($line,$$scantron_config{'IDstart'}-1,
 5728: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5729: 	if ($args->{'newid'}=~/^\s*$/) {
 5730: 	    &scan_data($scan_data,"$whichline.user",
 5731: 		       $args->{'username'}.':'.$args->{'domain'});
 5732: 	}
 5733:     } elsif ($field eq 'CODE') {
 5734: 	if ($args->{'CODE_ignore_dup'}) {
 5735: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5736: 	}
 5737: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5738: 	if ($args->{'CODE'} ne 'use_unfound') {
 5739: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5740: 		return ($line,1,'New CODE value too large');
 5741: 	    }
 5742: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5743: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5744: 	    }
 5745: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5746: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5747: 	}
 5748:     } elsif ($field eq 'answer') {
 5749: 	my $length=$scantron_config->{'Qlength'};
 5750: 	my $off=$scantron_config->{'Qoff'};
 5751: 	my $on=$scantron_config->{'Qon'};
 5752: 	my $answer=${off}x$length;
 5753: 	if ($args->{'response'} eq 'none') {
 5754: 	    &scan_data($scan_data,
 5755: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5756: 	} else {
 5757: 	    if ($on eq 'letter') {
 5758: 		my @alphabet=('A'..'Z');
 5759: 		$answer=$alphabet[$args->{'response'}];
 5760: 	    } elsif ($on eq 'number') {
 5761: 		$answer=$args->{'response'}+1;
 5762: 		if ($answer == 10) { $answer = '0'; }
 5763: 	    } else {
 5764: 		substr($answer,$args->{'response'},1)=$on;
 5765: 	    }
 5766: 	    &scan_data($scan_data,
 5767: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5768: 	}
 5769: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5770: 	substr($line,$where-1,$length)=$answer;
 5771:     }
 5772:     return $line;
 5773: }
 5774: 
 5775: =pod
 5776: 
 5777: =item scan_data
 5778: 
 5779:     Edit or look up  an item in the scan_data hash.
 5780: 
 5781:   Arguments:
 5782:     $scan_data  - The hash (see scantron_getfile)
 5783:     $key        - shorthand of the key to edit (actual key is
 5784:                   scantronfilename_key).
 5785:     $data        - New value of the hash entry.
 5786:     $delete      - If true, the entry is removed from the hash.
 5787: 
 5788:   Returns:
 5789:     The new value of the hash table field (undefined if deleted).
 5790: 
 5791: =cut
 5792: 
 5793: 
 5794: sub scan_data {
 5795:     my ($scan_data,$key,$value,$delete)=@_;
 5796:     my $filename=$env{'form.scantron_selectfile'};
 5797:     if (defined($value)) {
 5798: 	$scan_data->{$filename.'_'.$key} = $value;
 5799:     }
 5800:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5801:     return $scan_data->{$filename.'_'.$key};
 5802: }
 5803: 
 5804: # ----- These first few routines are general use routines.----
 5805: 
 5806: # Return the number of occurences of a pattern in a string.
 5807: 
 5808: sub occurence_count {
 5809:     my ($string, $pattern) = @_;
 5810: 
 5811:     my @matches = ($string =~ /$pattern/g);
 5812: 
 5813:     return scalar(@matches);
 5814: }
 5815: 
 5816: 
 5817: # Take a string known to have digits and convert all the
 5818: # digits into letters in the range J,A..I.
 5819: 
 5820: sub digits_to_letters {
 5821:     my ($input) = @_;
 5822: 
 5823:     my @alphabet = ('J', 'A'..'I');
 5824: 
 5825:     my @input    = split(//, $input);
 5826:     my $output ='';
 5827:     for (my $i = 0; $i < scalar(@input); $i++) {
 5828: 	if ($input[$i] =~ /\d/) {
 5829: 	    $output .= $alphabet[$input[$i]];
 5830: 	} else {
 5831: 	    $output .= $input[$i];
 5832: 	}
 5833:     }
 5834:     return $output;
 5835: }
 5836: 
 5837: =pod 
 5838: 
 5839: =item scantron_parse_scanline
 5840: 
 5841:   Decodes a scanline from the selected scantron file
 5842: 
 5843:  Arguments:
 5844:     line             - The text of the scantron file line to process
 5845:     whichline        - Line number
 5846:     scantron_config  - Hash describing the format of the scantron lines.
 5847:     scan_data        - Hash of extra information about the scanline
 5848:                        (see scantron_getfile for more information)
 5849:     just_header      - True if should not process question answers but only
 5850:                        the stuff to the left of the answers.
 5851:  Returns:
 5852:    Hash containing the result of parsing the scanline
 5853: 
 5854:    Keys are all proceeded by the string 'scantron.'
 5855: 
 5856:        CODE    - the CODE in use for this scanline
 5857:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5858:                  by the operator
 5859:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5860:                             CODEs were selected, but the usage has been
 5861:                             forced by the operator
 5862:        ID  - student/employee ID
 5863:        PaperID - if used, the ID number printed on the sheet when the 
 5864:                  paper was scanned
 5865:        FirstName - first name from the sheet
 5866:        LastName  - last name from the sheet
 5867: 
 5868:      if just_header was not true these key may also exist
 5869: 
 5870:        missingerror - a list of bubble ranges that are considered to be answers
 5871:                       to a single question that don't have any bubbles filled in.
 5872:                       Of the form questionnumber:firstbubblenumber:count.
 5873:        doubleerror  - a list of bubble ranges that are considered to be answers
 5874:                       to a single question that have more than one bubble filled in.
 5875:                       Of the form questionnumber::firstbubblenumber:count
 5876:    
 5877:                 In the above, count is the number of bubble responses in the
 5878:                 input line needed to represent the possible answers to the question.
 5879:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5880:                 per line would have count = 2.
 5881: 
 5882:        maxquest     - the number of the last bubble line that was parsed
 5883: 
 5884:        (<number> starts at 1)
 5885:        <number>.answer - zero or more letters representing the selected
 5886:                          letters from the scanline for the bubble line 
 5887:                          <number>.
 5888:                          if blank there was either no bubble or there where
 5889:                          multiple bubbles, (consult the keys missingerror and
 5890:                          doubleerror if this is an error condition)
 5891: 
 5892: =cut
 5893: 
 5894: sub scantron_parse_scanline {
 5895:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5896: 
 5897:     my %record;
 5898:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5899:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5900:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5901:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5902: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5903: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5904: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5905: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5906: 	    $record{'scantron.CODE'}=substr($data,
 5907: 					    $$scantron_config{'CODEstart'}-1,
 5908: 					    $$scantron_config{'CODElength'});
 5909: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5910: 		$record{'scantron.useCODE'}=1;
 5911: 	    }
 5912: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5913: 		$record{'scantron.CODE_ignore_dup'}=1;
 5914: 	    }
 5915: 	} else {
 5916: 	    #FIXME interpret first N questions
 5917: 	}
 5918:     }
 5919:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5920: 				  $$scantron_config{'IDlength'});
 5921:     $record{'scantron.PaperID'}=
 5922: 	substr($data,$$scantron_config{'PaperID'}-1,
 5923: 	       $$scantron_config{'PaperIDlength'});
 5924:     $record{'scantron.FirstName'}=
 5925: 	substr($data,$$scantron_config{'FirstName'}-1,
 5926: 	       $$scantron_config{'FirstNamelength'});
 5927:     $record{'scantron.LastName'}=
 5928: 	substr($data,$$scantron_config{'LastName'}-1,
 5929: 	       $$scantron_config{'LastNamelength'});
 5930:     if ($just_header) { return \%record; }
 5931: 
 5932:     my @alphabet=('A'..'Z');
 5933:     my $questnum=0;
 5934:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5935: 
 5936:     chomp($questions);		# Get rid of any trailing \n.
 5937:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5938:     while (length($questions)) {
 5939: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5940:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5941:                              || 1;
 5942:         $questnum++;
 5943:         my $quest_id = $questnum;
 5944:         my $currentquest = substr($questions,0,$answer_length);
 5945:         $questions       = substr($questions,$answer_length);
 5946:         if (length($currentquest) < $answer_length) { next; }
 5947: 
 5948:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5949:             my $subquestnum = 1;
 5950:             my $subquestions = $currentquest;
 5951:             my @subanswers_needed = 
 5952:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5953:             foreach my $subans (@subanswers_needed) {
 5954:                 my $subans_length =
 5955:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5956:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5957:                 $subquestions   = substr($subquestions,$subans_length);
 5958:                 $quest_id = "$questnum.$subquestnum";
 5959:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5960:                     ($$scantron_config{'Qon'} eq 'number')) {
 5961:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5962:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5963:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5964:                 } else {
 5965:                     $ansnum = &scantron_validator_positional($ansnum,
 5966:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5967:                 }
 5968:                 $subquestnum ++;
 5969:             }
 5970:         } else {
 5971:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5972:                 ($$scantron_config{'Qon'} eq 'number')) {
 5973:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5974:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5975:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5976:             } else {
 5977:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5978:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5979:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5980:             }
 5981:         }
 5982:     }
 5983:     $record{'scantron.maxquest'}=$questnum;
 5984:     return \%record;
 5985: }
 5986: 
 5987: sub scantron_validator_lettnum {
 5988:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5989:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5990: 
 5991:     # Qon 'letter' implies for each slot in currquest we have:
 5992:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5993:     #    about anything else (esp. a value of Qoff) for missing
 5994:     #    bubbles.
 5995:     #
 5996:     # Qon 'number' implies each slot gives a digit that indexes the
 5997:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5998:     #    and * or ? for double bubbles on a single line.
 5999:     #
 6000: 
 6001:     my $matchon;
 6002:     if ($$scantron_config{'Qon'} eq 'letter') {
 6003:         $matchon = '[A-Z]';
 6004:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6005:         $matchon = '\d';
 6006:     }
 6007:     my $occurrences = 0;
 6008:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6009:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6010:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6011:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6012:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6013:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6014:         my @singlelines = split('',$currquest);
 6015:         foreach my $entry (@singlelines) {
 6016:             $occurrences = &occurence_count($entry,$matchon);
 6017:             if ($occurrences > 1) {
 6018:                 last;
 6019:             }
 6020:         } 
 6021:     } else {
 6022:         $occurrences = &occurence_count($currquest,$matchon); 
 6023:     }
 6024:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6025:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6026:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6027:             my $bubble = substr($currquest,$ans,1);
 6028:             if ($bubble =~ /$matchon/ ) {
 6029:                 if ($$scantron_config{'Qon'} eq 'number') {
 6030:                     if ($bubble == 0) {
 6031:                         $bubble = 10; 
 6032:                     }
 6033:                     $record->{"scantron.$ansnum.answer"} = 
 6034:                         $alphabet->[$bubble-1];
 6035:                 } else {
 6036:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6037:                 }
 6038:             } else {
 6039:                 $record->{"scantron.$ansnum.answer"}='';
 6040:             }
 6041:             $ansnum++;
 6042:         }
 6043:     } elsif (!defined($currquest)
 6044:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6045:             || (&occurence_count($currquest,$matchon) == 0)) {
 6046:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6047:             $record->{"scantron.$ansnum.answer"}='';
 6048:             $ansnum++;
 6049:         }
 6050:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6051:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6052:         }
 6053:     } else {
 6054:         if ($$scantron_config{'Qon'} eq 'number') {
 6055:             $currquest = &digits_to_letters($currquest);            
 6056:         }
 6057:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6058:             my $bubble = substr($currquest,$ans,1);
 6059:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6060:             $ansnum++;
 6061:         }
 6062:     }
 6063:     return $ansnum;
 6064: }
 6065: 
 6066: sub scantron_validator_positional {
 6067:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6068:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 6069: 
 6070:     # Otherwise there's a positional notation;
 6071:     # each bubble line requires Qlength items, and there are filled in
 6072:     # bubbles for each case where there 'Qon' characters.
 6073:     #
 6074: 
 6075:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6076: 
 6077:     # If the split only gives us one element.. the full length of the
 6078:     # answer string, no bubbles are filled in:
 6079: 
 6080:     if ($answers_needed eq '') {
 6081:         return;
 6082:     }
 6083: 
 6084:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6085:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6086:             $record->{"scantron.$ansnum.answer"}='';
 6087:             $ansnum++;
 6088:         }
 6089:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6090:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6091:         }
 6092:     } elsif (scalar(@array) == 2) {
 6093:         my $location = length($array[0]);
 6094:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6095:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6096:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6097:             if ($ans eq $line_num) {
 6098:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6099:             } else {
 6100:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6101:             }
 6102:             $ansnum++;
 6103:          }
 6104:     } else {
 6105:         #  If there's more than one instance of a bubble character
 6106:         #  That's a double bubble; with positional notation we can
 6107:         #  record all the bubbles filled in as well as the
 6108:         #  fact this response consists of multiple bubbles.
 6109:         #
 6110:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6111:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6112:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6113:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6114:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6115:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6116:             my $doubleerror = 0;
 6117:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6118:                    (!$doubleerror)) {
 6119:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6120:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6121:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6122:                if (length(@currarray) > 2) {
 6123:                    $doubleerror = 1;
 6124:                } 
 6125:             }
 6126:             if ($doubleerror) {
 6127:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6128:             }
 6129:         } else {
 6130:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6131:         }
 6132:         my $item = $ansnum;
 6133:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6134:             $record->{"scantron.$item.answer"} = '';
 6135:             $item ++;
 6136:         }
 6137: 
 6138:         my @ans=@array;
 6139:         my $i=0;
 6140:         my $increment = 0;
 6141:         while ($#ans) {
 6142:             $i+=length($ans[0]) + $increment;
 6143:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6144:             my $bubble = $i%$$scantron_config{'Qlength'};
 6145:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6146:             shift(@ans);
 6147:             $increment = 1;
 6148:         }
 6149:         $ansnum += $answers_needed;
 6150:     }
 6151:     return $ansnum;
 6152: }
 6153: 
 6154: =pod
 6155: 
 6156: =item scantron_add_delay
 6157: 
 6158:    Adds an error message that occurred during the grading phase to a
 6159:    queue of messages to be shown after grading pass is complete
 6160: 
 6161:  Arguments:
 6162:    $delayqueue  - arrary ref of hash ref of error messages
 6163:    $scanline    - the scanline that caused the error
 6164:    $errormesage - the error message
 6165:    $errorcode   - a numeric code for the error
 6166: 
 6167:  Side Effects:
 6168:    updates the $delayqueue to have a new hash ref of the error
 6169: 
 6170: =cut
 6171: 
 6172: sub scantron_add_delay {
 6173:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6174:     push(@$delayqueue,
 6175: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6176: 	  'ecode' => $errorcode }
 6177: 	 );
 6178: }
 6179: 
 6180: =pod
 6181: 
 6182: =item scantron_find_student
 6183: 
 6184:    Finds the username for the current scanline
 6185: 
 6186:   Arguments:
 6187:    $scantron_record - hash result from scantron_parse_scanline
 6188:    $scan_data       - hash of correction information 
 6189:                       (see &scantron_getfile() form more information)
 6190:    $idmap           - hash from &username_to_idmap()
 6191:    $line            - number of current scanline
 6192:  
 6193:   Returns:
 6194:    Either 'username:domain' or undef if unknown
 6195: 
 6196: =cut
 6197: 
 6198: sub scantron_find_student {
 6199:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6200:     my $scanID=$$scantron_record{'scantron.ID'};
 6201:     if ($scanID =~ /^\s*$/) {
 6202:  	return &scan_data($scan_data,"$line.user");
 6203:     }
 6204:     foreach my $id (keys(%$idmap)) {
 6205:  	if (lc($id) eq lc($scanID)) {
 6206:  	    return $$idmap{$id};
 6207:  	}
 6208:     }
 6209:     return undef;
 6210: }
 6211: 
 6212: =pod
 6213: 
 6214: =item scantron_filter
 6215: 
 6216:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6217:    hidden resources was selected
 6218: 
 6219: =cut
 6220: 
 6221: sub scantron_filter {
 6222:     my ($curres)=@_;
 6223: 
 6224:     if (ref($curres) && $curres->is_problem()) {
 6225: 	# if the user has asked to not have either hidden
 6226: 	# or 'randomout' controlled resources to be graded
 6227: 	# don't include them
 6228: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6229: 	    && $curres->randomout) {
 6230: 	    return 0;
 6231: 	}
 6232: 	return 1;
 6233:     }
 6234:     return 0;
 6235: }
 6236: 
 6237: =pod
 6238: 
 6239: =item scantron_process_corrections
 6240: 
 6241:    Gets correction information out of submitted form data and corrects
 6242:    the scanline
 6243: 
 6244: =cut
 6245: 
 6246: sub scantron_process_corrections {
 6247:     my ($r) = @_;
 6248:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6249:     my ($scanlines,$scan_data)=&scantron_getfile();
 6250:     my $classlist=&Apache::loncoursedata::get_classlist();
 6251:     my $which=$env{'form.scantron_line'};
 6252:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6253:     my ($skip,$err,$errmsg);
 6254:     if ($env{'form.scantron_skip_record'}) {
 6255: 	$skip=1;
 6256:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6257: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6258: 	    $env{'form.scantron_domain'};
 6259: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6260: 	($line,$err,$errmsg)=
 6261: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6262: 				     'ID',{'newid'=>$newid,
 6263: 				    'username'=>$env{'form.scantron_username'},
 6264: 				    'domain'=>$env{'form.scantron_domain'}});
 6265:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6266: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6267: 	my $newCODE;
 6268: 	my %args;
 6269: 	if      ($resolution eq 'use_unfound') {
 6270: 	    $newCODE='use_unfound';
 6271: 	} elsif ($resolution eq 'use_found') {
 6272: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6273: 	} elsif ($resolution eq 'use_typed') {
 6274: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6275: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6276: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6277: 	}
 6278: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6279: 	    $args{'CODE_ignore_dup'}=1;
 6280: 	}
 6281: 	$args{'CODE'}=$newCODE;
 6282: 	($line,$err,$errmsg)=
 6283: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6284: 				     'CODE',\%args);
 6285:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6286: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6287: 	    ($line,$err,$errmsg)=
 6288: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6289: 					 $which,'answer',
 6290: 					 { 'question'=>$question,
 6291: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6292:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6293: 	    if ($err) { last; }
 6294: 	}
 6295:     }
 6296:     if ($err) {
 6297: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6298:     } else {
 6299: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6300: 	&scantron_putfile($scanlines,$scan_data);
 6301:     }
 6302: }
 6303: 
 6304: =pod
 6305: 
 6306: =item reset_skipping_status
 6307: 
 6308:    Forgets the current set of remember skipped scanlines (and thus
 6309:    reverts back to considering all lines in the
 6310:    scantron_skipped_<filename> file)
 6311: 
 6312: =cut
 6313: 
 6314: sub reset_skipping_status {
 6315:     my ($scanlines,$scan_data)=&scantron_getfile();
 6316:     &scan_data($scan_data,'remember_skipping',undef,1);
 6317:     &scantron_putfile(undef,$scan_data);
 6318: }
 6319: 
 6320: =pod
 6321: 
 6322: =item start_skipping
 6323: 
 6324:    Marks a scanline to be skipped. 
 6325: 
 6326: =cut
 6327: 
 6328: sub start_skipping {
 6329:     my ($scan_data,$i)=@_;
 6330:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6331:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6332: 	$remembered{$i}=2;
 6333:     } else {
 6334: 	$remembered{$i}=1;
 6335:     }
 6336:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6337: }
 6338: 
 6339: =pod
 6340: 
 6341: =item should_be_skipped
 6342: 
 6343:    Checks whether a scanline should be skipped.
 6344: 
 6345: =cut
 6346: 
 6347: sub should_be_skipped {
 6348:     my ($scanlines,$scan_data,$i)=@_;
 6349:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6350: 	# not redoing old skips
 6351: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6352: 	return 0;
 6353:     }
 6354:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6355: 
 6356:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6357: 	return 0;
 6358:     }
 6359:     return 1;
 6360: }
 6361: 
 6362: =pod
 6363: 
 6364: =item remember_current_skipped
 6365: 
 6366:    Discovers what scanlines are in the scantron_skipped_<filename>
 6367:    file and remembers them into scan_data for later use.
 6368: 
 6369: =cut
 6370: 
 6371: sub remember_current_skipped {
 6372:     my ($scanlines,$scan_data)=&scantron_getfile();
 6373:     my %to_remember;
 6374:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6375: 	if ($scanlines->{'skipped'}[$i]) {
 6376: 	    $to_remember{$i}=1;
 6377: 	}
 6378:     }
 6379: 
 6380:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6381:     &scantron_putfile(undef,$scan_data);
 6382: }
 6383: 
 6384: =pod
 6385: 
 6386: =item check_for_error
 6387: 
 6388:     Checks if there was an error when attempting to remove a specific
 6389:     scantron_.. bubblesheet data file. Prints out an error if
 6390:     something went wrong.
 6391: 
 6392: =cut
 6393: 
 6394: sub check_for_error {
 6395:     my ($r,$result)=@_;
 6396:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6397: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6398:     }
 6399: }
 6400: 
 6401: =pod
 6402: 
 6403: =item scantron_warning_screen
 6404: 
 6405:    Interstitial screen to make sure the operator has selected the
 6406:    correct options before we start the validation phase.
 6407: 
 6408: =cut
 6409: 
 6410: sub scantron_warning_screen {
 6411:     my ($button_text,$symb)=@_;
 6412:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6413:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6414:     my $CODElist;
 6415:     if ($scantron_config{'CODElocation'} &&
 6416: 	$scantron_config{'CODEstart'} &&
 6417: 	$scantron_config{'CODElength'}) {
 6418: 	$CODElist=$env{'form.scantron_CODElist'};
 6419: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6420: 	$CODElist=
 6421: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6422: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6423:     }
 6424:     my $lastbubblepoints;
 6425:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6426:         $lastbubblepoints =
 6427:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 6428:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 6429:     }
 6430:     return ('
 6431: <p>
 6432: <span class="LC_warning">
 6433: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6434: </p>
 6435: <table>
 6436: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6437: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6438: '.$CODElist.$lastbubblepoints.'
 6439: </table>
 6440: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
 6441: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
 6442: 
 6443: <br />
 6444: ');
 6445: }
 6446: 
 6447: =pod
 6448: 
 6449: =item scantron_do_warning
 6450: 
 6451:    Check if the operator has picked something for all required
 6452:    fields. Error out if something is missing.
 6453: 
 6454: =cut
 6455: 
 6456: sub scantron_do_warning {
 6457:     my ($r,$symb)=@_;
 6458:     if (!$symb) {return '';}
 6459:     my $default_form_data=&defaultFormData($symb);
 6460:     $r->print(&scantron_form_start().$default_form_data);
 6461:     if ( $env{'form.selectpage'} eq '' ||
 6462: 	 $env{'form.scantron_selectfile'} eq '' ||
 6463: 	 $env{'form.scantron_format'} eq '' ) {
 6464: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 6465: 	if ( $env{'form.selectpage'} eq '') {
 6466: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6467: 	} 
 6468: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6469: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 6470: 	} 
 6471: 	if ( $env{'form.scantron_format'} eq '') {
 6472: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 6473: 	} 
 6474:     } else {
 6475: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 6476:         my $bubbledbyhand=&hand_bubble_option();
 6477: 	$r->print('
 6478: '.$warning.$bubbledbyhand.'
 6479: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6480: <input type="hidden" name="command" value="scantron_validate" />
 6481: ');
 6482:     }
 6483:     $r->print("</form><br />");
 6484:     return '';
 6485: }
 6486: 
 6487: =pod
 6488: 
 6489: =item scantron_form_start
 6490: 
 6491:     html hidden input for remembering all selected grading options
 6492: 
 6493: =cut
 6494: 
 6495: sub scantron_form_start {
 6496:     my ($max_bubble)=@_;
 6497:     my $result= <<SCANTRONFORM;
 6498: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6499:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6500:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6501:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6502:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6503:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6504:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6505:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6506:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6507:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6508: SCANTRONFORM
 6509: 
 6510:   my $line = 0;
 6511:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6512:        my $chunk =
 6513: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6514:        $chunk .=
 6515: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6516:        $chunk .= 
 6517:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6518:        $chunk .=
 6519:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6520:        $result .= $chunk;
 6521:        $line++;
 6522:    }
 6523:     return $result;
 6524: }
 6525: 
 6526: =pod
 6527: 
 6528: =item scantron_validate_file
 6529: 
 6530:     Dispatch routine for doing validation of a bubblesheet data file.
 6531: 
 6532:     Also processes any necessary information resets that need to
 6533:     occur before validation begins (ignore previous corrections,
 6534:     restarting the skipped records processing)
 6535: 
 6536: =cut
 6537: 
 6538: sub scantron_validate_file {
 6539:     my ($r,$symb) = @_;
 6540:     if (!$symb) {return '';}
 6541:     my $default_form_data=&defaultFormData($symb);
 6542:     
 6543:     # do the detection of only doing skipped records first befroe we delete
 6544:     # them when doing the corrections reset
 6545:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6546: 	&reset_skipping_status();
 6547:     }
 6548:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6549: 	&remember_current_skipped();
 6550: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6551:     }
 6552: 
 6553:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6554: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6555: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6556: 	&check_for_error($r,&scantron_remove_scan_data());
 6557: 	$env{'form.scantron_options_ignore'}='done';
 6558:     }
 6559: 
 6560:     if ($env{'form.scantron_corrections'}) {
 6561: 	&scantron_process_corrections($r);
 6562:     }
 6563:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6564:     #get the student pick code ready
 6565:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6566:     my $nav_error;
 6567:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6568:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 6569:     if ($nav_error) {
 6570:         $r->print(&navmap_errormsg());
 6571:         return '';
 6572:     }
 6573:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6574:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 6575:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 6576:     }
 6577:     $r->print($result);
 6578:     
 6579:     my @validate_phases=( 'sequence',
 6580: 			  'ID',
 6581: 			  'CODE',
 6582: 			  'doublebubble',
 6583: 			  'missingbubbles');
 6584:     if (!$env{'form.validatepass'}) {
 6585: 	$env{'form.validatepass'} = 0;
 6586:     }
 6587:     my $currentphase=$env{'form.validatepass'};
 6588: 
 6589: 
 6590:     my $stop=0;
 6591:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6592: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6593: 	$r->rflush();
 6594: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6595: 	{
 6596: 	    no strict 'refs';
 6597: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6598: 	}
 6599:     }
 6600:     if (!$stop) {
 6601: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 6602: 	$r->print(&mt('Validation process complete.').'<br />'.
 6603:                   $warning.
 6604:                   &mt('Perform verification for each student after storage of submissions?').
 6605:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6606:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6607:                   ('&nbsp;'x3).'<label>'.
 6608:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6609:                   '</label></span><br />'.
 6610:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6611:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 6612:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6613:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6614:     } else {
 6615: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6616: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6617:     }
 6618:     if ($stop) {
 6619: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6620: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6621: 	    $r->print(' '.&mt('this error').' <br />');
 6622: 
 6623: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
 6624: 	} else {
 6625:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6626: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6627:             } else {
 6628:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6629:             }
 6630: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6631: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6632: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6633: 	}
 6634:     }
 6635:     $r->print(" </form><br />");
 6636:     return '';
 6637: }
 6638: 
 6639: 
 6640: =pod
 6641: 
 6642: =item scantron_remove_file
 6643: 
 6644:    Removes the requested bubblesheet data file, makes sure that
 6645:    scantron_original_<filename> is never removed
 6646: 
 6647: 
 6648: =cut
 6649: 
 6650: sub scantron_remove_file {
 6651:     my ($which)=@_;
 6652:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6653:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6654:     my $file='scantron_';
 6655:     if ($which eq 'corrected' || $which eq 'skipped') {
 6656: 	$file.=$which.'_';
 6657:     } else {
 6658: 	return 'refused';
 6659:     }
 6660:     $file.=$env{'form.scantron_selectfile'};
 6661:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6662: }
 6663: 
 6664: 
 6665: =pod
 6666: 
 6667: =item scantron_remove_scan_data
 6668: 
 6669:    Removes all scan_data correction for the requested bubblesheet
 6670:    data file.  (In the case that both the are doing skipped records we need
 6671:    to remember the old skipped lines for the time being so that element
 6672:    persists for a while.)
 6673: 
 6674: =cut
 6675: 
 6676: sub scantron_remove_scan_data {
 6677:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6678:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6679:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6680:     my @todelete;
 6681:     my $filename=$env{'form.scantron_selectfile'};
 6682:     foreach my $key (@keys) {
 6683: 	if ($key=~/^\Q$filename\E_/) {
 6684: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6685: 		$key=~/remember_skipping/) {
 6686: 		next;
 6687: 	    }
 6688: 	    push(@todelete,$key);
 6689: 	}
 6690:     }
 6691:     my $result;
 6692:     if (@todelete) {
 6693: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6694: 				       \@todelete,$cdom,$cname);
 6695:     } else {
 6696: 	$result = 'ok';
 6697:     }
 6698:     return $result;
 6699: }
 6700: 
 6701: 
 6702: =pod
 6703: 
 6704: =item scantron_getfile
 6705: 
 6706:     Fetches the requested bubblesheet data file (all 3 versions), and
 6707:     the scan_data hash
 6708:   
 6709:   Arguments:
 6710:     None
 6711: 
 6712:   Returns:
 6713:     2 hash references
 6714: 
 6715:      - first one has 
 6716:          orig      -
 6717:          corrected -
 6718:          skipped   -  each of which points to an array ref of the specified
 6719:                       file broken up into individual lines
 6720:          count     - number of scanlines
 6721:  
 6722:      - second is the scan_data hash possible keys are
 6723:        ($number refers to scanline numbered $number and thus the key affects
 6724:         only that scanline
 6725:         $bubline refers to the specific bubble line element and the aspects
 6726:         refers to that specific bubble line element)
 6727: 
 6728:        $number.user - username:domain to use
 6729:        $number.CODE_ignore_dup 
 6730:                     - ignore the duplicate CODE error 
 6731:        $number.useCODE
 6732:                     - use the CODE in the scanline as is
 6733:        $number.no_bubble.$bubline
 6734:                     - it is valid that there is no bubbled in bubble
 6735:                       at $number $bubline
 6736:        remember_skipping
 6737:                     - a frozen hash containing keys of $number and values
 6738:                       of either 
 6739:                         1 - we are on a 'do skipped records pass' and plan
 6740:                             on processing this line
 6741:                         2 - we are on a 'do skipped records pass' and this
 6742:                             scanline has been marked to skip yet again
 6743: 
 6744: =cut
 6745: 
 6746: sub scantron_getfile {
 6747:     #FIXME really would prefer a scantron directory
 6748:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6749:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6750:     my $lines;
 6751:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6752: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6753:     my %scanlines;
 6754:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6755:     my $temp=$scanlines{'orig'};
 6756:     $scanlines{'count'}=$#$temp;
 6757: 
 6758:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6759: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6760:     if ($lines eq '-1') {
 6761: 	$scanlines{'corrected'}=[];
 6762:     } else {
 6763: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6764:     }
 6765:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6766: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6767:     if ($lines eq '-1') {
 6768: 	$scanlines{'skipped'}=[];
 6769:     } else {
 6770: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6771:     }
 6772:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6773:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6774:     my %scan_data = @tmp;
 6775:     return (\%scanlines,\%scan_data);
 6776: }
 6777: 
 6778: =pod
 6779: 
 6780: =item lonnet_putfile
 6781: 
 6782:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6783: 
 6784:  Arguments:
 6785:    $contents - data to store
 6786:    $filename - filename to store $contents into
 6787: 
 6788:  Returns:
 6789:    result value from &Apache::lonnet::finishuserfileupload
 6790: 
 6791: =cut
 6792: 
 6793: sub lonnet_putfile {
 6794:     my ($contents,$filename)=@_;
 6795:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6796:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6797:     $env{'form.sillywaytopassafilearound'}=$contents;
 6798:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6799: 
 6800: }
 6801: 
 6802: =pod
 6803: 
 6804: =item scantron_putfile
 6805: 
 6806:     Stores the current version of the bubblesheet data files, and the
 6807:     scan_data hash. (Does not modify the original version only the
 6808:     corrected and skipped versions.
 6809: 
 6810:  Arguments:
 6811:     $scanlines - hash ref that looks like the first return value from
 6812:                  &scantron_getfile()
 6813:     $scan_data - hash ref that looks like the second return value from
 6814:                  &scantron_getfile()
 6815: 
 6816: =cut
 6817: 
 6818: sub scantron_putfile {
 6819:     my ($scanlines,$scan_data) = @_;
 6820:     #FIXME really would prefer a scantron directory
 6821:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6822:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6823:     if ($scanlines) {
 6824: 	my $prefix='scantron_';
 6825: # no need to update orig, shouldn't change
 6826: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6827: #		    $env{'form.scantron_selectfile'});
 6828: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6829: 			$prefix.'corrected_'.
 6830: 			$env{'form.scantron_selectfile'});
 6831: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6832: 			$prefix.'skipped_'.
 6833: 			$env{'form.scantron_selectfile'});
 6834:     }
 6835:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6836: }
 6837: 
 6838: =pod
 6839: 
 6840: =item scantron_get_line
 6841: 
 6842:    Returns the correct version of the scanline
 6843: 
 6844:  Arguments:
 6845:     $scanlines - hash ref that looks like the first return value from
 6846:                  &scantron_getfile()
 6847:     $scan_data - hash ref that looks like the second return value from
 6848:                  &scantron_getfile()
 6849:     $i         - number of the requested line (starts at 0)
 6850: 
 6851:  Returns:
 6852:    A scanline, (either the original or the corrected one if it
 6853:    exists), or undef if the requested scanline should be
 6854:    skipped. (Either because it's an skipped scanline, or it's an
 6855:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6856:    pass.
 6857: 
 6858: =cut
 6859: 
 6860: sub scantron_get_line {
 6861:     my ($scanlines,$scan_data,$i)=@_;
 6862:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6863:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6864:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6865:     return $scanlines->{'orig'}[$i]; 
 6866: }
 6867: 
 6868: =pod
 6869: 
 6870: =item scantron_todo_count
 6871: 
 6872:     Counts the number of scanlines that need processing.
 6873: 
 6874:  Arguments:
 6875:     $scanlines - hash ref that looks like the first return value from
 6876:                  &scantron_getfile()
 6877:     $scan_data - hash ref that looks like the second return value from
 6878:                  &scantron_getfile()
 6879: 
 6880:  Returns:
 6881:     $count - number of scanlines to process
 6882: 
 6883: =cut
 6884: 
 6885: sub get_todo_count {
 6886:     my ($scanlines,$scan_data)=@_;
 6887:     my $count=0;
 6888:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6889: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6890: 	if ($line=~/^[\s\cz]*$/) { next; }
 6891: 	$count++;
 6892:     }
 6893:     return $count;
 6894: }
 6895: 
 6896: =pod
 6897: 
 6898: =item scantron_put_line
 6899: 
 6900:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 6901:     data file.
 6902: 
 6903:  Arguments:
 6904:     $scanlines - hash ref that looks like the first return value from
 6905:                  &scantron_getfile()
 6906:     $scan_data - hash ref that looks like the second return value from
 6907:                  &scantron_getfile()
 6908:     $i         - line number to update
 6909:     $newline   - contents of the updated scanline
 6910:     $skip      - if true make the line for skipping and update the
 6911:                  'skipped' file
 6912: 
 6913: =cut
 6914: 
 6915: sub scantron_put_line {
 6916:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6917:     if ($skip) {
 6918: 	$scanlines->{'skipped'}[$i]=$newline;
 6919: 	&start_skipping($scan_data,$i);
 6920: 	return;
 6921:     }
 6922:     $scanlines->{'corrected'}[$i]=$newline;
 6923: }
 6924: 
 6925: =pod
 6926: 
 6927: =item scantron_clear_skip
 6928: 
 6929:    Remove a line from the 'skipped' file
 6930: 
 6931:  Arguments:
 6932:     $scanlines - hash ref that looks like the first return value from
 6933:                  &scantron_getfile()
 6934:     $scan_data - hash ref that looks like the second return value from
 6935:                  &scantron_getfile()
 6936:     $i         - line number to update
 6937: 
 6938: =cut
 6939: 
 6940: sub scantron_clear_skip {
 6941:     my ($scanlines,$scan_data,$i)=@_;
 6942:     if (exists($scanlines->{'skipped'}[$i])) {
 6943: 	undef($scanlines->{'skipped'}[$i]);
 6944: 	return 1;
 6945:     }
 6946:     return 0;
 6947: }
 6948: 
 6949: =pod
 6950: 
 6951: =item scantron_filter_not_exam
 6952: 
 6953:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6954:    filter out resources that are not marked as 'exam' mode
 6955: 
 6956: =cut
 6957: 
 6958: sub scantron_filter_not_exam {
 6959:     my ($curres)=@_;
 6960:     
 6961:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6962: 	# if the user has asked to not have either hidden
 6963: 	# or 'randomout' controlled resources to be graded
 6964: 	# don't include them
 6965: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6966: 	    && $curres->randomout) {
 6967: 	    return 0;
 6968: 	}
 6969: 	return 1;
 6970:     }
 6971:     return 0;
 6972: }
 6973: 
 6974: =pod
 6975: 
 6976: =item scantron_validate_sequence
 6977: 
 6978:     Validates the selected sequence, checking for resource that are
 6979:     not set to exam mode.
 6980: 
 6981: =cut
 6982: 
 6983: sub scantron_validate_sequence {
 6984:     my ($r,$currentphase) = @_;
 6985: 
 6986:     my $navmap=Apache::lonnavmaps::navmap->new();
 6987:     unless (ref($navmap)) {
 6988:         $r->print(&navmap_errormsg());
 6989:         return (1,$currentphase);
 6990:     }
 6991:     my (undef,undef,$sequence)=
 6992: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6993: 
 6994:     my $map=$navmap->getResourceByUrl($sequence);
 6995: 
 6996:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6997:                                     value="ignore" />');
 6998:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6999: 	my @resources=
 7000: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7001: 	if (@resources) {
 7002: 	    $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>");
 7003: 	    return (1,$currentphase);
 7004: 	}
 7005:     }
 7006: 
 7007:     return (0,$currentphase+1);
 7008: }
 7009: 
 7010: 
 7011: 
 7012: sub scantron_validate_ID {
 7013:     my ($r,$currentphase) = @_;
 7014:     
 7015:     #get student info
 7016:     my $classlist=&Apache::loncoursedata::get_classlist();
 7017:     my %idmap=&username_to_idmap($classlist);
 7018: 
 7019:     #get scantron line setup
 7020:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7021:     my ($scanlines,$scan_data)=&scantron_getfile();
 7022: 
 7023:     my $nav_error;
 7024:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7025:     if ($nav_error) {
 7026:         $r->print(&navmap_errormsg());
 7027:         return(1,$currentphase);
 7028:     }
 7029: 
 7030:     my %found=('ids'=>{},'usernames'=>{});
 7031:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7032: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7033: 	if ($line=~/^[\s\cz]*$/) { next; }
 7034: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7035: 						 $scan_data);
 7036: 	my $id=$$scan_record{'scantron.ID'};
 7037: 	my $found;
 7038: 	foreach my $checkid (keys(%idmap)) {
 7039: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7040: 	}
 7041: 	if ($found) {
 7042: 	    my $username=$idmap{$found};
 7043: 	    if ($found{'ids'}{$found}) {
 7044: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7045: 					 $line,'duplicateID',$found);
 7046: 		return(1,$currentphase);
 7047: 	    } elsif ($found{'usernames'}{$username}) {
 7048: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7049: 					 $line,'duplicateID',$username);
 7050: 		return(1,$currentphase);
 7051: 	    }
 7052: 	    #FIXME store away line we previously saw the ID on to use above
 7053: 	    $found{'ids'}{$found}++;
 7054: 	    $found{'usernames'}{$username}++;
 7055: 	} else {
 7056: 	    if ($id =~ /^\s*$/) {
 7057: 		my $username=&scan_data($scan_data,"$i.user");
 7058: 		if (defined($username) && $found{'usernames'}{$username}) {
 7059: 		    &scantron_get_correction($r,$i,$scan_record,
 7060: 					     \%scantron_config,
 7061: 					     $line,'duplicateID',$username);
 7062: 		    return(1,$currentphase);
 7063: 		} elsif (!defined($username)) {
 7064: 		    &scantron_get_correction($r,$i,$scan_record,
 7065: 					     \%scantron_config,
 7066: 					     $line,'incorrectID');
 7067: 		    return(1,$currentphase);
 7068: 		}
 7069: 		$found{'usernames'}{$username}++;
 7070: 	    } else {
 7071: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7072: 					 $line,'incorrectID');
 7073: 		return(1,$currentphase);
 7074: 	    }
 7075: 	}
 7076:     }
 7077: 
 7078:     return (0,$currentphase+1);
 7079: }
 7080: 
 7081: 
 7082: sub scantron_get_correction {
 7083:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 7084: #FIXME in the case of a duplicated ID the previous line, probably need
 7085: #to show both the current line and the previous one and allow skipping
 7086: #the previous one or the current one
 7087: 
 7088:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7089:         $r->print(
 7090:             '<p class="LC_warning">'
 7091:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7092:                 "<b>$error</b>",
 7093:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7094:            ."</p> \n");
 7095:     } else {
 7096:         $r->print(
 7097:             '<p class="LC_warning">'
 7098:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7099:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7100:            ."</p> \n");
 7101:     }
 7102:     my $message =
 7103:         '<p>'
 7104:        .&mt('The ID on the form is [_1]',
 7105:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7106:        .'<br />'
 7107:        .&mt('The name on the paper is [_1], [_2]',
 7108:             $$scan_record{'scantron.LastName'},
 7109:             $$scan_record{'scantron.FirstName'})
 7110:        .'</p>';
 7111: 
 7112:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7113:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7114:                            # Array populated for doublebubble or
 7115:     my @lines_to_correct;  # missingbubble errors to build javascript
 7116:                            # to validate radio button checking   
 7117: 
 7118:     if ($error =~ /ID$/) {
 7119: 	if ($error eq 'incorrectID') {
 7120:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7121: 		      "</p>\n");
 7122: 	} elsif ($error eq 'duplicateID') {
 7123:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7124: 	}
 7125: 	$r->print($message);
 7126: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7127: 	$r->print("\n<ul><li> ");
 7128: 	#FIXME it would be nice if this sent back the user ID and
 7129: 	#could do partial userID matches
 7130: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7131: 				       'scantron_username','scantron_domain'));
 7132: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7133: 	$r->print("\n@".
 7134: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7135: 
 7136: 	$r->print('</li>');
 7137:     } elsif ($error =~ /CODE$/) {
 7138: 	if ($error eq 'incorrectCODE') {
 7139: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7140: 	} elsif ($error eq 'duplicateCODE') {
 7141: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 7142: 	}
 7143: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7144: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7145:                  ."</p>\n");
 7146: 	$r->print($message);
 7147: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7148: 	$r->print("\n<br /> ");
 7149: 	my $i=0;
 7150: 	if ($error eq 'incorrectCODE' 
 7151: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7152: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7153: 	    if ($closest > 0) {
 7154: 		foreach my $testcode (@{$closest}) {
 7155: 		    my $checked='';
 7156: 		    if (!$i) { $checked=' checked="checked"'; }
 7157: 		    $r->print("
 7158:    <label>
 7159:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7160:        ".&mt("Use the similar CODE [_1] instead.",
 7161: 	    "<b><tt>".$testcode."</tt></b>")."
 7162:     </label>
 7163:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7164: 		    $r->print("\n<br />");
 7165: 		    $i++;
 7166: 		}
 7167: 	    }
 7168: 	}
 7169: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7170: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7171: 	    $r->print("
 7172:     <label>
 7173:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7174:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7175: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7176:     </label>");
 7177: 	    $r->print("\n<br />");
 7178: 	}
 7179: 
 7180: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7181: function change_radio(field) {
 7182:     var slct=document.scantronupload.scantron_CODE_resolution;
 7183:     var i;
 7184:     for (i=0;i<slct.length;i++) {
 7185:         if (slct[i].value==field) { slct[i].checked=true; }
 7186:     }
 7187: }
 7188: ENDSCRIPT
 7189: 	my $href="/adm/pickcode?".
 7190: 	   "form=".&escape("scantronupload").
 7191: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7192: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7193: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7194: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7195: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7196: 	    $r->print("
 7197:     <label>
 7198:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7199:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7200: 	     "<a target='_blank' href='$href'>","</a>")."
 7201:     </label> 
 7202:     ".&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\')" />'));
 7203: 	    $r->print("\n<br />");
 7204: 	}
 7205: 	$r->print("
 7206:     <label>
 7207:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7208:        ".&mt("Use [_1] as the CODE.",
 7209: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7210: 	$r->print("\n<br /><br />");
 7211:     } elsif ($error eq 'doublebubble') {
 7212: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7213: 
 7214: 	# The form field scantron_questions is acutally a list of line numbers.
 7215: 	# represented by this form so:
 7216: 
 7217: 	my $line_list = &questions_to_line_list($arg);
 7218: 
 7219: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7220: 		  $line_list.'" />');
 7221: 	$r->print($message);
 7222: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7223: 	foreach my $question (@{$arg}) {
 7224: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7225:                                                    $scan_record, $error);
 7226:             push(@lines_to_correct,@linenums);
 7227: 	}
 7228:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7229:     } elsif ($error eq 'missingbubble') {
 7230: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7231: 	$r->print($message);
 7232: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7233: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7234: 
 7235: 	# The form field scantron_questions is actually a list of line numbers not
 7236: 	# a list of question numbers. Therefore:
 7237: 	#
 7238: 	
 7239: 	my $line_list = &questions_to_line_list($arg);
 7240: 
 7241: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7242: 		  $line_list.'" />');
 7243: 	foreach my $question (@{$arg}) {
 7244: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7245:                                                    $scan_record, $error);
 7246:             push(@lines_to_correct,@linenums);
 7247: 	}
 7248:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7249:     } else {
 7250: 	$r->print("\n<ul>");
 7251:     }
 7252:     $r->print("\n</li></ul>");
 7253: }
 7254: 
 7255: sub verify_bubbles_checked {
 7256:     my (@ansnums) = @_;
 7257:     my $ansnumstr = join('","',@ansnums);
 7258:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7259:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7260: function verify_bubble_radio(form) {
 7261:     var ansnumArray = new Array ("$ansnumstr");
 7262:     var need_bubble_count = 0;
 7263:     for (var i=0; i<ansnumArray.length; i++) {
 7264:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7265:             var bubble_picked = 0; 
 7266:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7267:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7268:                     bubble_picked = 1;
 7269:                 }
 7270:             }
 7271:             if (bubble_picked == 0) {
 7272:                 need_bubble_count ++;
 7273:             }
 7274:         }
 7275:     }
 7276:     if (need_bubble_count) {
 7277:         alert("$warning");
 7278:         return;
 7279:     }
 7280:     form.submit(); 
 7281: }
 7282: ENDSCRIPT
 7283:     return $output;
 7284: }
 7285: 
 7286: =pod
 7287: 
 7288: =item  questions_to_line_list
 7289: 
 7290: Converts a list of questions into a string of comma separated
 7291: line numbers in the answer sheet used by the questions.  This is
 7292: used to fill in the scantron_questions form field.
 7293: 
 7294:   Arguments:
 7295:      questions    - Reference to an array of questions.
 7296: 
 7297: =cut
 7298: 
 7299: 
 7300: sub questions_to_line_list {
 7301:     my ($questions) = @_;
 7302:     my @lines;
 7303: 
 7304:     foreach my $item (@{$questions}) {
 7305:         my $question = $item;
 7306:         my ($first,$count,$last);
 7307:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7308:             $question = $1;
 7309:             my $subquestion = $2;
 7310:             $first = $first_bubble_line{$question-1} + 1;
 7311:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7312:             my $subcount = 1;
 7313:             while ($subcount<$subquestion) {
 7314:                 $first += $subans[$subcount-1];
 7315:                 $subcount ++;
 7316:             }
 7317:             $count = $subans[$subquestion-1];
 7318:         } else {
 7319: 	    $first   = $first_bubble_line{$question-1} + 1;
 7320: 	    $count   = $bubble_lines_per_response{$question-1};
 7321:         }
 7322:         $last = $first+$count-1;
 7323:         push(@lines, ($first..$last));
 7324:     }
 7325:     return join(',', @lines);
 7326: }
 7327: 
 7328: =pod 
 7329: 
 7330: =item prompt_for_corrections
 7331: 
 7332: Prompts for a potentially multiline correction to the
 7333: user's bubbling (factors out common code from scantron_get_correction
 7334: for multi and missing bubble cases).
 7335: 
 7336:  Arguments:
 7337:    $r           - Apache request object.
 7338:    $question    - The question number to prompt for.
 7339:    $scan_config - The scantron file configuration hash.
 7340:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7341:    $error       - Type of error
 7342: 
 7343:  Implicit inputs:
 7344:    %bubble_lines_per_response   - Starting line numbers for each question.
 7345:                                   Numbered from 0 (but question numbers are from
 7346:                                   1.
 7347:    %first_bubble_line           - Starting bubble line for each question.
 7348:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7349:                                   type problems render as separate sub-questions, 
 7350:                                   in exam mode. This hash contains a 
 7351:                                   comma-separated list of the lines per 
 7352:                                   sub-question.
 7353:    %responsetype_per_response   - essayresponse, formularesponse,
 7354:                                   stringresponse, imageresponse, reactionresponse,
 7355:                                   and organicresponse type problem parts can have
 7356:                                   multiple lines per response if the weight
 7357:                                   assigned exceeds 10.  In this case, only
 7358:                                   one bubble per line is permitted, but more 
 7359:                                   than one line might contain bubbles, e.g.
 7360:                                   bubbling of: line 1 - J, line 2 - J, 
 7361:                                   line 3 - B would assign 22 points.  
 7362: 
 7363: =cut
 7364: 
 7365: sub prompt_for_corrections {
 7366:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7367:     my ($current_line,$lines);
 7368:     my @linenums;
 7369:     my $questionnum = $question;
 7370:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7371:         $question = $1;
 7372:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7373:         my $subquestion = $2;
 7374:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7375:         my $subcount = 1;
 7376:         while ($subcount<$subquestion) {
 7377:             $current_line += $subans[$subcount-1];
 7378:             $subcount ++;
 7379:         }
 7380:         $lines = $subans[$subquestion-1];
 7381:     } else {
 7382:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7383:         $lines        = $bubble_lines_per_response{$question-1};
 7384:     }
 7385:     if ($lines > 1) {
 7386:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7387:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7388:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7389:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7390:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7391:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7392:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7393:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7394:         } else {
 7395:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7396:         }
 7397:     }
 7398:     for (my $i =0; $i < $lines; $i++) {
 7399:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7400: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7401: 	        		  $questionnum,$error,split('', $selected));
 7402:         push(@linenums,$current_line);
 7403: 	$current_line++;
 7404:     }
 7405:     if ($lines > 1) {
 7406: 	$r->print("<hr /><br />");
 7407:     }
 7408:     return @linenums;
 7409: }
 7410: 
 7411: =pod
 7412: 
 7413: =item scantron_bubble_selector
 7414:   
 7415:    Generates the html radiobuttons to correct a single bubble line
 7416:    possibly showing the existing the selected bubbles if known
 7417: 
 7418:  Arguments:
 7419:     $r           - Apache request object
 7420:     $scan_config - hash from &get_scantron_config()
 7421:     $line        - Number of the line being displayed.
 7422:     $questionnum - Question number (may include subquestion)
 7423:     $error       - Type of error.
 7424:     @selected    - Array of bubbles picked on this line.
 7425: 
 7426: =cut
 7427: 
 7428: sub scantron_bubble_selector {
 7429:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7430:     my $max=$$scan_config{'Qlength'};
 7431: 
 7432:     my $scmode=$$scan_config{'Qon'};
 7433:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 7434:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 7435:             ($$scan_config{'BubblesPerRow'} > 0)) {
 7436:             $max=$$scan_config{'BubblesPerRow'};
 7437:             if (($scmode eq 'number') && ($max > 10)) {
 7438:                 $max = 10;
 7439:             } elsif (($scmode eq 'letter') && $max > 26) {
 7440:                 $max = 26;
 7441:             }
 7442:         } else {
 7443:             $max = 10;
 7444:         }
 7445:     }
 7446: 
 7447:     my @alphabet=('A'..'Z');
 7448:     $r->print(&Apache::loncommon::start_data_table().
 7449:               &Apache::loncommon::start_data_table_row());
 7450:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7451:     for (my $i=0;$i<$max+1;$i++) {
 7452: 	$r->print("\n".'<td align="center">');
 7453: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7454: 	else { $r->print('&nbsp;'); }
 7455: 	$r->print('</td>');
 7456:     }
 7457:     $r->print(&Apache::loncommon::end_data_table_row().
 7458:               &Apache::loncommon::start_data_table_row());
 7459:     for (my $i=0;$i<$max;$i++) {
 7460: 	$r->print("\n".
 7461: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7462: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7463:     }
 7464:     my $nobub_checked = ' ';
 7465:     if ($error eq 'missingbubble') {
 7466:         $nobub_checked = ' checked = "checked" ';
 7467:     }
 7468:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7469: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7470:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7471:               $line.'" value="'.$questionnum.'" /></td>');
 7472:     $r->print(&Apache::loncommon::end_data_table_row().
 7473:               &Apache::loncommon::end_data_table());
 7474: }
 7475: 
 7476: =pod
 7477: 
 7478: =item num_matches
 7479: 
 7480:    Counts the number of characters that are the same between the two arguments.
 7481: 
 7482:  Arguments:
 7483:    $orig - CODE from the scanline
 7484:    $code - CODE to match against
 7485: 
 7486:  Returns:
 7487:    $count - integer count of the number of same characters between the
 7488:             two arguments
 7489: 
 7490: =cut
 7491: 
 7492: sub num_matches {
 7493:     my ($orig,$code) = @_;
 7494:     my @code=split(//,$code);
 7495:     my @orig=split(//,$orig);
 7496:     my $same=0;
 7497:     for (my $i=0;$i<scalar(@code);$i++) {
 7498: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7499:     }
 7500:     return $same;
 7501: }
 7502: 
 7503: =pod
 7504: 
 7505: =item scantron_get_closely_matching_CODEs
 7506: 
 7507:    Cycles through all CODEs and finds the set that has the greatest
 7508:    number of same characters as the provided CODE
 7509: 
 7510:  Arguments:
 7511:    $allcodes - hash ref returned by &get_codes()
 7512:    $CODE     - CODE from the current scanline
 7513: 
 7514:  Returns:
 7515:    2 element list
 7516:     - first elements is number of how closely matching the best fit is 
 7517:       (5 means best set has 5 matching characters)
 7518:     - second element is an arrary ref containing the set of valid CODEs
 7519:       that best fit the passed in CODE
 7520: 
 7521: =cut
 7522: 
 7523: sub scantron_get_closely_matching_CODEs {
 7524:     my ($allcodes,$CODE)=@_;
 7525:     my @CODEs;
 7526:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7527: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7528:     }
 7529: 
 7530:     return ($#CODEs,$CODEs[-1]);
 7531: }
 7532: 
 7533: =pod
 7534: 
 7535: =item get_codes
 7536: 
 7537:    Builds a hash which has keys of all of the valid CODEs from the selected
 7538:    set of remembered CODEs.
 7539: 
 7540:  Arguments:
 7541:   $old_name - name of the set of remembered CODEs
 7542:   $cdom     - domain of the course
 7543:   $cnum     - internal course name
 7544: 
 7545:  Returns:
 7546:   %allcodes - keys are the valid CODEs, values are all 1
 7547: 
 7548: =cut
 7549: 
 7550: sub get_codes {
 7551:     my ($old_name, $cdom, $cnum) = @_;
 7552:     if (!$old_name) {
 7553: 	$old_name=$env{'form.scantron_CODElist'};
 7554:     }
 7555:     if (!$cdom) {
 7556: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7557:     }
 7558:     if (!$cnum) {
 7559: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7560:     }
 7561:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7562: 				    $cdom,$cnum);
 7563:     my %allcodes;
 7564:     if ($result{"type\0$old_name"} eq 'number') {
 7565: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7566:     } else {
 7567: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7568:     }
 7569:     return %allcodes;
 7570: }
 7571: 
 7572: =pod
 7573: 
 7574: =item scantron_validate_CODE
 7575: 
 7576:    Validates all scanlines in the selected file to not have any
 7577:    invalid or underspecified CODEs and that none of the codes are
 7578:    duplicated if this was requested.
 7579: 
 7580: =cut
 7581: 
 7582: sub scantron_validate_CODE {
 7583:     my ($r,$currentphase) = @_;
 7584:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7585:     if ($scantron_config{'CODElocation'} &&
 7586: 	$scantron_config{'CODEstart'} &&
 7587: 	$scantron_config{'CODElength'}) {
 7588: 	if (!defined($env{'form.scantron_CODElist'})) {
 7589: 	    &FIXME_blow_up()
 7590: 	}
 7591:     } else {
 7592: 	return (0,$currentphase+1);
 7593:     }
 7594:     
 7595:     my %usedCODEs;
 7596: 
 7597:     my %allcodes=&get_codes();
 7598: 
 7599:     my $nav_error;
 7600:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 7601:     if ($nav_error) {
 7602:         $r->print(&navmap_errormsg());
 7603:         return(1,$currentphase);
 7604:     }
 7605: 
 7606:     my ($scanlines,$scan_data)=&scantron_getfile();
 7607:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7608: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7609: 	if ($line=~/^[\s\cz]*$/) { next; }
 7610: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7611: 						 $scan_data);
 7612: 	my $CODE=$$scan_record{'scantron.CODE'};
 7613: 	my $error=0;
 7614: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7615: 	    &scantron_get_correction($r,$i,$scan_record,
 7616: 				     \%scantron_config,
 7617: 				     $line,'incorrectCODE',\%allcodes);
 7618: 	    return(1,$currentphase);
 7619: 	}
 7620: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7621: 	    && !$$scan_record{'scantron.useCODE'}) {
 7622: 	    &scantron_get_correction($r,$i,$scan_record,
 7623: 				     \%scantron_config,
 7624: 				     $line,'incorrectCODE',\%allcodes);
 7625: 	    return(1,$currentphase);
 7626: 	}
 7627: 	if (exists($usedCODEs{$CODE}) 
 7628: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7629: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7630: 	    &scantron_get_correction($r,$i,$scan_record,
 7631: 				     \%scantron_config,
 7632: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7633: 	    return(1,$currentphase);
 7634: 	}
 7635: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7636:     }
 7637:     return (0,$currentphase+1);
 7638: }
 7639: 
 7640: =pod
 7641: 
 7642: =item scantron_validate_doublebubble
 7643: 
 7644:    Validates all scanlines in the selected file to not have any
 7645:    bubble lines with multiple bubbles marked.
 7646: 
 7647: =cut
 7648: 
 7649: sub scantron_validate_doublebubble {
 7650:     my ($r,$currentphase) = @_;
 7651:     #get student info
 7652:     my $classlist=&Apache::loncoursedata::get_classlist();
 7653:     my %idmap=&username_to_idmap($classlist);
 7654: 
 7655:     #get scantron line setup
 7656:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7657:     my ($scanlines,$scan_data)=&scantron_getfile();
 7658:     my $nav_error;
 7659:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 7660:     if ($nav_error) {
 7661:         $r->print(&navmap_errormsg());
 7662:         return(1,$currentphase);
 7663:     }
 7664: 
 7665:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7666: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7667: 	if ($line=~/^[\s\cz]*$/) { next; }
 7668: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7669: 						 $scan_data);
 7670: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7671: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7672: 				 'doublebubble',
 7673: 				 $$scan_record{'scantron.doubleerror'});
 7674:     	return (1,$currentphase);
 7675:     }
 7676:     return (0,$currentphase+1);
 7677: }
 7678: 
 7679: 
 7680: sub scantron_get_maxbubble {
 7681:     my ($nav_error,$scantron_config) = @_;
 7682:     if (defined($env{'form.scantron_maxbubble'}) &&
 7683: 	$env{'form.scantron_maxbubble'}) {
 7684: 	&restore_bubble_lines();
 7685: 	return $env{'form.scantron_maxbubble'};
 7686:     }
 7687: 
 7688:     my (undef, undef, $sequence) =
 7689: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7690: 
 7691:     my $navmap=Apache::lonnavmaps::navmap->new();
 7692:     unless (ref($navmap)) {
 7693:         if (ref($nav_error)) {
 7694:             $$nav_error = 1;
 7695:         }
 7696:         return;
 7697:     }
 7698:     my $map=$navmap->getResourceByUrl($sequence);
 7699:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7700:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 7701: 
 7702:     &Apache::lonxml::clear_problem_counter();
 7703: 
 7704:     my $uname       = $env{'user.name'};
 7705:     my $udom        = $env{'user.domain'};
 7706:     my $cid         = $env{'request.course.id'};
 7707:     my $total_lines = 0;
 7708:     %bubble_lines_per_response = ();
 7709:     %first_bubble_line         = ();
 7710:     %subdivided_bubble_lines   = ();
 7711:     %responsetype_per_response = ();
 7712: 
 7713:     my $response_number = 0;
 7714:     my $bubble_line     = 0;
 7715:     foreach my $resource (@resources) {
 7716:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
 7717:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7718: 	    foreach my $part_id (@{$parts}) {
 7719:                 my $lines;
 7720: 
 7721: 	        # TODO - make this a persistent hash not an array.
 7722: 
 7723:                 # optionresponse, matchresponse and rankresponse type items 
 7724:                 # render as separate sub-questions in exam mode.
 7725:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7726:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7727:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7728:                     my ($numbub,$numshown);
 7729:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7730:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7731:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7732:                         }
 7733:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7734:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7735:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7736:                         }
 7737:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7738:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7739:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7740:                         }
 7741:                     }
 7742:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7743:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7744:                     }
 7745:                     my $bubbles_per_row =
 7746:                         &bubblesheet_bubbles_per_row($scantron_config);
 7747:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 7748:                     if (($numbub % $bubbles_per_row) != 0) {
 7749:                         $inner_bubble_lines++;
 7750:                     }
 7751:                     for (my $i=0; $i<$numshown; $i++) {
 7752:                         $subdivided_bubble_lines{$response_number} .= 
 7753:                             $inner_bubble_lines.',';
 7754:                     }
 7755:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7756:                     $lines = $numshown * $inner_bubble_lines;
 7757:                 } else {
 7758:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7759:                 }
 7760: 
 7761:                 $first_bubble_line{$response_number} = $bubble_line;
 7762: 	        $bubble_lines_per_response{$response_number} = $lines;
 7763:                 $responsetype_per_response{$response_number} = 
 7764:                     $analysis->{$part_id.'.type'};
 7765: 	        $response_number++;
 7766: 
 7767: 	        $bubble_line +=  $lines;
 7768: 	        $total_lines +=  $lines;
 7769: 	    }
 7770:         }
 7771:     }
 7772:     &Apache::lonnet::delenv('scantron.');
 7773: 
 7774:     &save_bubble_lines();
 7775:     $env{'form.scantron_maxbubble'} =
 7776: 	$total_lines;
 7777:     return $env{'form.scantron_maxbubble'};
 7778: }
 7779: 
 7780: sub bubblesheet_bubbles_per_row {
 7781:     my ($scantron_config) = @_;
 7782:     my $bubbles_per_row;
 7783:     if (ref($scantron_config) eq 'HASH') {
 7784:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 7785:     }
 7786:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 7787:         $bubbles_per_row = 10;
 7788:     }
 7789:     return $bubbles_per_row;
 7790: }
 7791: 
 7792: sub scantron_validate_missingbubbles {
 7793:     my ($r,$currentphase) = @_;
 7794:     #get student info
 7795:     my $classlist=&Apache::loncoursedata::get_classlist();
 7796:     my %idmap=&username_to_idmap($classlist);
 7797: 
 7798:     #get scantron line setup
 7799:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7800:     my ($scanlines,$scan_data)=&scantron_getfile();
 7801:     my $nav_error;
 7802:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7803:     if ($nav_error) {
 7804:         return(1,$currentphase);
 7805:     }
 7806:     if (!$max_bubble) { $max_bubble=2**31; }
 7807:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7808: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7809: 	if ($line=~/^[\s\cz]*$/) { next; }
 7810: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7811: 						 $scan_data);
 7812: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7813: 	my @to_correct;
 7814: 	
 7815: 	# Probably here's where the error is...
 7816: 
 7817: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7818:             my $lastbubble;
 7819:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7820:                my $question = $1;
 7821:                my $subquestion = $2;
 7822:                if (!defined($first_bubble_line{$question -1})) { next; }
 7823:                my $first = $first_bubble_line{$question-1};
 7824:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7825:                my $subcount = 1;
 7826:                while ($subcount<$subquestion) {
 7827:                    $first += $subans[$subcount-1];
 7828:                    $subcount ++;
 7829:                }
 7830:                my $count = $subans[$subquestion-1];
 7831:                $lastbubble = $first + $count;
 7832:             } else {
 7833:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7834:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7835:             }
 7836:             if ($lastbubble > $max_bubble) { next; }
 7837: 	    push(@to_correct,$missing);
 7838: 	}
 7839: 	if (@to_correct) {
 7840: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7841: 				     $line,'missingbubble',\@to_correct);
 7842: 	    return (1,$currentphase);
 7843: 	}
 7844: 
 7845:     }
 7846:     return (0,$currentphase+1);
 7847: }
 7848: 
 7849: sub hand_bubble_option {
 7850:     my (undef, undef, $sequence) =
 7851:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7852:     return if ($sequence eq '');
 7853:     my $navmap = Apache::lonnavmaps::navmap->new();
 7854:     unless (ref($navmap)) {
 7855:         return;
 7856:     }
 7857:     my $needs_hand_bubbles;
 7858:     my $map=$navmap->getResourceByUrl($sequence);
 7859:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7860:     foreach my $res (@resources) {
 7861:         if (ref($res)) {
 7862:             if ($res->is_problem()) {
 7863:                 my $partlist = $res->parts();
 7864:                 foreach my $part (@{ $partlist }) {
 7865:                     my @types = $res->responseType($part);
 7866:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 7867:                         $needs_hand_bubbles = 1;
 7868:                         last;
 7869:                     }
 7870:                 }
 7871:             }
 7872:         }
 7873:     }
 7874:     if ($needs_hand_bubbles) {
 7875:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7876:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 7877:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 7878:                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
 7879:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
 7880:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
 7881:     }
 7882:     return;
 7883: }
 7884: 
 7885: sub scantron_process_students {
 7886:     my ($r,$symb) = @_;
 7887: 
 7888:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7889:     if (!$symb) {
 7890: 	return '';
 7891:     }
 7892:     my $default_form_data=&defaultFormData($symb);
 7893: 
 7894:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7895:     my $bubbles_per_row =
 7896:         &bubblesheet_bubbles_per_row(\%scantron_config);
 7897:     my ($scanlines,$scan_data)=&scantron_getfile();
 7898:     my $classlist=&Apache::loncoursedata::get_classlist();
 7899:     my %idmap=&username_to_idmap($classlist);
 7900:     my $navmap=Apache::lonnavmaps::navmap->new();
 7901:     unless (ref($navmap)) {
 7902:         $r->print(&navmap_errormsg());
 7903:         return '';
 7904:     }  
 7905:     my $map=$navmap->getResourceByUrl($sequence);
 7906:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7907:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7908:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7909:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 7910:     my $resource_error;
 7911:     foreach my $resource (@resources) {
 7912:         my $ressymb;
 7913:         if (ref($resource)) {
 7914:             $ressymb = $resource->symb();
 7915:         } else {
 7916:             $resource_error = 1;
 7917:             last;
 7918:         }
 7919:         my ($analysis,$parts) =
 7920:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7921:                                       $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 7922:         $grader_partids_by_symb{$ressymb} = $parts;
 7923:         if (ref($analysis) eq 'HASH') {
 7924:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7925:                 $grader_randomlists_by_symb{$ressymb} = 
 7926:                     $analysis->{'parts_withrandomlist'};
 7927:             }
 7928:         }
 7929:     }
 7930:     if ($resource_error) {
 7931:         $r->print(&navmap_errormsg());
 7932:         return '';
 7933:     }
 7934: 
 7935:     my ($uname,$udom);
 7936:     my $result= <<SCANTRONFORM;
 7937: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7938:   <input type="hidden" name="command" value="scantron_configphase" />
 7939:   $default_form_data
 7940: SCANTRONFORM
 7941:     $r->print($result);
 7942: 
 7943:     my @delayqueue;
 7944:     my (%completedstudents,%scandata);
 7945:     
 7946:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7947:     my $count=&get_todo_count($scanlines,$scan_data);
 7948:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 7949:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 7950:     $r->print('<br />');
 7951:     my $start=&Time::HiRes::time();
 7952:     my $i=-1;
 7953:     my $started;
 7954: 
 7955:     my $nav_error;
 7956:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 7957:     if ($nav_error) {
 7958:         $r->print(&navmap_errormsg());
 7959:         return '';
 7960:     }
 7961: 
 7962:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7963:     # the user and return.
 7964: 
 7965:     if ($ssi_error) {
 7966: 	$r->print("</form>");
 7967: 	&ssi_print_error($r);
 7968:         &Apache::lonnet::remove_lock($lock);
 7969: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7970:     }
 7971: 
 7972:     my %lettdig = &letter_to_digits();
 7973:     my $numletts = scalar(keys(%lettdig));
 7974: 
 7975:     while ($i<$scanlines->{'count'}) {
 7976:  	($uname,$udom)=('','');
 7977:  	$i++;
 7978:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7979:  	if ($line=~/^[\s\cz]*$/) { next; }
 7980: 	if ($started) {
 7981: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 7982: 	}
 7983: 	$started=1;
 7984:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7985:  						 $scan_data);
 7986:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7987:  					      \%idmap,$i)) {
 7988:   	    &scantron_add_delay(\@delayqueue,$line,
 7989:  				'Unable to find a student that matches',1);
 7990:  	    next;
 7991:   	}
 7992:  	if (exists $completedstudents{$uname}) {
 7993:  	    &scantron_add_delay(\@delayqueue,$line,
 7994:  				'Student '.$uname.' has multiple sheets',2);
 7995:  	    next;
 7996:  	}
 7997:   	($uname,$udom)=split(/:/,$uname);
 7998: 
 7999:         my (%partids_by_symb,$res_error);
 8000:         foreach my $resource (@resources) {
 8001:             my $ressymb;
 8002:             if (ref($resource)) {
 8003:                 $ressymb = $resource->symb();
 8004:             } else {
 8005:                 $res_error = 1;
 8006:                 last;
 8007:             }
 8008:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8009:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8010:                 my ($analysis,$parts) =
 8011:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
 8012:                 $partids_by_symb{$ressymb} = $parts;
 8013:             } else {
 8014:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8015:             }
 8016:         }
 8017: 
 8018:         if ($res_error) {
 8019:             &scantron_add_delay(\@delayqueue,$line,
 8020:                                 'An error occurred while grading student '.$uname,2);
 8021:             next;
 8022:         }
 8023: 
 8024: 	&Apache::lonxml::clear_problem_counter();
 8025:   	&Apache::lonnet::appenv($scan_record);
 8026: 
 8027: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8028: 	    &scantron_putfile($scanlines,$scan_data);
 8029: 	}
 8030: 	
 8031:         my $scancode;
 8032:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8033:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8034:             $scancode = $scan_record->{'scantron.CODE'};
 8035:         } else {
 8036:             $scancode = '';
 8037:         }
 8038: 
 8039:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8040:                                    \@resources,\%partids_by_symb,
 8041:                                    $bubbles_per_row) eq 'ssi_error') {
 8042:             $ssi_error = 0; # So end of handler error message does not trigger.
 8043:             $r->print("</form>");
 8044:             &ssi_print_error($r);
 8045:             &Apache::lonnet::remove_lock($lock);
 8046:             return '';      # Why return ''?  Beats me.
 8047:         }
 8048: 
 8049: 	$completedstudents{$uname}={'line'=>$line};
 8050:         if ($env{'form.verifyrecord'}) {
 8051:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8052:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8053:             chomp($studentdata);
 8054:             $studentdata =~ s/\r$//;
 8055:             my $studentrecord = '';
 8056:             my $counter = -1;
 8057:             foreach my $resource (@resources) {
 8058:                 my $ressymb = $resource->symb();
 8059:                 ($counter,my $recording) =
 8060:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8061:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8062:                                              \%scantron_config,\%lettdig,$numletts);
 8063:                 $studentrecord .= $recording;
 8064:             }
 8065:             if ($studentrecord ne $studentdata) {
 8066:                 &Apache::lonxml::clear_problem_counter();
 8067:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8068:                                            \@resources,\%partids_by_symb,
 8069:                                            $bubbles_per_row) eq 'ssi_error') {
 8070:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8071:                     $r->print("</form>");
 8072:                     &ssi_print_error($r);
 8073:                     &Apache::lonnet::remove_lock($lock);
 8074:                     delete($completedstudents{$uname});
 8075:                     return '';
 8076:                 }
 8077:                 $counter = -1;
 8078:                 $studentrecord = '';
 8079:                 foreach my $resource (@resources) {
 8080:                     my $ressymb = $resource->symb();
 8081:                     ($counter,my $recording) =
 8082:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8083:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8084:                                                  \%scantron_config,\%lettdig,$numletts);
 8085:                     $studentrecord .= $recording;
 8086:                 }
 8087:                 if ($studentrecord ne $studentdata) {
 8088:                     $r->print('<p><span class="LC_warning">');
 8089:                     if ($scancode eq '') {
 8090:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8091:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8092:                     } else {
 8093:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8094:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8095:                     }
 8096:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8097:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8098:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8099:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8100:                               &Apache::loncommon::start_data_table_row().
 8101:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8102:                               '<td><span class="LC_nobreak"><tt>'.$studentdata.'</tt></span></td>'.
 8103:                               &Apache::loncommon::end_data_table_row().
 8104:                               &Apache::loncommon::start_data_table_row().
 8105:                               '<td>'.&mt('Stored submissions').'</td>'.
 8106:                               '<td><span class="LC_nobreak"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8107:                               &Apache::loncommon::end_data_table_row().
 8108:                               &Apache::loncommon::end_data_table().'</p>');
 8109:                 } else {
 8110:                     $r->print('<br /><span class="LC_warning">'.
 8111:                              &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 />'.
 8112:                              &mt("As a consequence, this user's submission history records two tries.").
 8113:                                  '</span><br />');
 8114:                 }
 8115:             }
 8116:         }
 8117:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8118:     } continue {
 8119: 	&Apache::lonxml::clear_problem_counter();
 8120: 	&Apache::lonnet::delenv('scantron.');
 8121:     }
 8122:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8123:     &Apache::lonnet::remove_lock($lock);
 8124: #    my $lasttime = &Time::HiRes::time()-$start;
 8125: #    $r->print("<p>took $lasttime</p>");
 8126: 
 8127:     $r->print("</form>");
 8128:     return '';
 8129: }
 8130: 
 8131: sub graders_resources_pass {
 8132:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8133:         $bubbles_per_row) = @_;
 8134:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8135:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8136:         foreach my $resource (@{$resources}) {
 8137:             my $ressymb = $resource->symb();
 8138:             my ($analysis,$parts) =
 8139:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8140:                                           $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
 8141:             $grader_partids_by_symb->{$ressymb} = $parts;
 8142:             if (ref($analysis) eq 'HASH') {
 8143:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8144:                     $grader_randomlists_by_symb->{$ressymb} =
 8145:                         $analysis->{'parts_withrandomlist'};
 8146:                 }
 8147:             }
 8148:         }
 8149:     }
 8150:     return;
 8151: }
 8152: 
 8153: sub grade_student_bubbles {
 8154:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
 8155: # Walk folder as student here to get resources in order student sees.
 8156:     if (ref($resources) eq 'ARRAY') {
 8157:         my $count = 0;
 8158:         foreach my $resource (@{$resources}) {
 8159:             my $ressymb = $resource->symb();
 8160:             my %form = ('submitted'      => 'scantron',
 8161:                         'grade_target'   => 'grade',
 8162:                         'grade_username' => $uname,
 8163:                         'grade_domain'   => $udom,
 8164:                         'grade_courseid' => $env{'request.course.id'},
 8165:                         'grade_symb'     => $ressymb,
 8166:                         'CODE'           => $scancode
 8167:                        );
 8168:             if ($bubbles_per_row ne '') {
 8169:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 8170:             }
 8171:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 8172:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 8173:             }
 8174:             if (ref($parts) eq 'HASH') {
 8175:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8176:                     foreach my $part (@{$parts->{$ressymb}}) {
 8177:                         $form{'scantron_questnum_start.'.$part} =
 8178:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 8179:                         $count++;
 8180:                     }
 8181:                 }
 8182:             }
 8183:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8184:             return 'ssi_error' if ($ssi_error);
 8185:             last if (&Apache::loncommon::connection_aborted($r));
 8186:         }
 8187:     }
 8188:     return;
 8189: }
 8190: 
 8191: sub scantron_upload_scantron_data {
 8192:     my ($r,$symb)=@_;
 8193:     my $dom = $env{'request.role.domain'};
 8194:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8195:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8196:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8197: 							  'domainid',
 8198: 							  'coursename',$dom);
 8199:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8200:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8201:     my $default_form_data=&defaultFormData($symb);
 8202:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8203:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
 8204:     $r->print(&Apache::lonhtmlcommon::scripttag('
 8205:     function checkUpload(formname) {
 8206: 	if (formname.upfile.value == "") {
 8207: 	    alert("'.$nofile_alert.'");
 8208: 	    return false;
 8209: 	}
 8210:         if (formname.courseid.value == "") {
 8211:             alert("'.$nocourseid_alert.'");
 8212:             return false;
 8213:         }
 8214: 	formname.submit();
 8215:     }
 8216: 
 8217:     function ToSyllabus() {
 8218:         var cdom = '."'$dom'".';
 8219:         var cnum = document.rules.courseid.value;
 8220:         if (cdom == "" || cdom == null) {
 8221:             return;
 8222:         }
 8223:         if (cnum == "" || cnum == null) {
 8224:            return;
 8225:         }
 8226:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8227:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8228:         return;
 8229:     }
 8230: 
 8231: '));
 8232:     $r->print('
 8233: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 8234: 
 8235: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8236: '.$default_form_data.
 8237:   &Apache::lonhtmlcommon::start_pick_box().
 8238:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8239:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8240:   &Apache::lonhtmlcommon::row_closure().
 8241:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8242:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8243:   &Apache::lonhtmlcommon::row_closure().
 8244:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8245:   '<input name="domainid" type="hidden" />'.$domdesc.
 8246:   &Apache::lonhtmlcommon::row_closure().
 8247:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8248:   '<input type="file" name="upfile" size="50" />'.
 8249:   &Apache::lonhtmlcommon::row_closure(1).
 8250:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8251: 
 8252: <input name="command" value="scantronupload_save" type="hidden" />
 8253: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8254: </form>
 8255: ');
 8256:     return '';
 8257: }
 8258: 
 8259: 
 8260: sub scantron_upload_scantron_data_save {
 8261:     my($r,$symb)=@_;
 8262:     my $doanotherupload=
 8263: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8264: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8265: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8266: 	'</form>'."\n";
 8267:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8268: 	!&Apache::lonnet::allowed('usc',
 8269: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8270: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8271: 	unless ($symb) {
 8272: 	    $r->print($doanotherupload);
 8273: 	}
 8274: 	return '';
 8275:     }
 8276:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8277:     my $uploadedfile;
 8278:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8279:     if (length($env{'form.upfile'}) < 2) {
 8280:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8281:     } else {
 8282:         my $result = 
 8283:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8284:                                             $env{'form.courseid'},$env{'form.domainid'});
 8285: 	if ($result =~ m{^/uploaded/}) {
 8286: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8287:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8288: 			  '<span class="LC_filename">'.$result.'</span>'));
 8289:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8290:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8291:                                                        $env{'form.courseid'},$uploadedfile));
 8292: 	} else {
 8293: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8294:                           '<span class="LC_error">','</span>',$result,
 8295: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8296: 	}
 8297:     }
 8298:     if ($symb) {
 8299: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 8300:     } else {
 8301: 	$r->print($doanotherupload);
 8302:     }
 8303:     return '';
 8304: }
 8305: 
 8306: sub validate_uploaded_scantron_file {
 8307:     my ($cdom,$cname,$fname) = @_;
 8308:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8309:     my @lines;
 8310:     if ($scanlines ne '-1') {
 8311:         @lines=split("\n",$scanlines,-1);
 8312:     }
 8313:     my $output;
 8314:     if (@lines) {
 8315:         my (%counts,$max_match_format);
 8316:         my ($max_match_count,$max_match_pct) = (0,0);
 8317:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8318:         my %idmap = &username_to_idmap($classlist);
 8319:         foreach my $key (keys(%idmap)) {
 8320:             my $lckey = lc($key);
 8321:             $idmap{$lckey} = $idmap{$key};
 8322:         }
 8323:         my %unique_formats;
 8324:         my @formatlines = &get_scantronformat_file();
 8325:         foreach my $line (@formatlines) {
 8326:             chomp($line);
 8327:             my @config = split(/:/,$line);
 8328:             my $idstart = $config[5];
 8329:             my $idlength = $config[6];
 8330:             if (($idstart ne '') && ($idlength > 0)) {
 8331:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8332:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8333:                 } else {
 8334:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8335:                 }
 8336:             }
 8337:         }
 8338:         foreach my $key (keys(%unique_formats)) {
 8339:             my ($idstart,$idlength) = split(':',$key);
 8340:             %{$counts{$key}} = (
 8341:                                'found'   => 0,
 8342:                                'total'   => 0,
 8343:                               );
 8344:             foreach my $line (@lines) {
 8345:                 next if ($line =~ /^#/);
 8346:                 next if ($line =~ /^[\s\cz]*$/);
 8347:                 my $id = substr($line,$idstart-1,$idlength);
 8348:                 $id = lc($id);
 8349:                 if (exists($idmap{$id})) {
 8350:                     $counts{$key}{'found'} ++;
 8351:                 }
 8352:                 $counts{$key}{'total'} ++;
 8353:             }
 8354:             if ($counts{$key}{'total'}) {
 8355:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8356:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8357:                     $max_match_pct = $percent_match;
 8358:                     $max_match_format = $key;
 8359:                     $max_match_count = $counts{$key}{'total'};
 8360:                 }
 8361:             }
 8362:         }
 8363:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8364:             my $format_descs;
 8365:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8366:             for (my $i=0; $i<$numwithformat; $i++) {
 8367:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8368:                 if ($i<$numwithformat-2) {
 8369:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8370:                 } elsif ($i==$numwithformat-2) {
 8371:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8372:                 } elsif ($i==$numwithformat-1) {
 8373:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8374:                 }
 8375:             }
 8376:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8377:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8378:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8379:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8380:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8381:                                   '<i>'.$cdom.'</i>').'</li>'.
 8382:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8383:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8384:                        '</ul>';
 8385:         }
 8386:     } else {
 8387:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8388:     }
 8389:     return $output;
 8390: }
 8391: 
 8392: sub valid_file {
 8393:     my ($requested_file)=@_;
 8394:     foreach my $filename (sort(&scantron_filenames())) {
 8395: 	if ($requested_file eq $filename) { return 1; }
 8396:     }
 8397:     return 0;
 8398: }
 8399: 
 8400: sub scantron_download_scantron_data {
 8401:     my ($r,$symb)=@_;
 8402:     my $default_form_data=&defaultFormData($symb);
 8403:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8404:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8405:     my $file=$env{'form.scantron_selectfile'};
 8406:     if (! &valid_file($file)) {
 8407: 	$r->print('
 8408: 	<p>
 8409: 	    '.&mt('The requested file name was invalid.').'
 8410:         </p>
 8411: ');
 8412: 	return;
 8413:     }
 8414:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8415:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8416:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8417:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8418:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8419:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8420:     $r->print('
 8421:     <p>
 8422: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8423: 	      '<a href="'.$orig.'">','</a>').'
 8424:     </p>
 8425:     <p>
 8426: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8427: 	      '<a href="'.$corrected.'">','</a>').'
 8428:     </p>
 8429:     <p>
 8430: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8431: 	      '<a href="'.$skipped.'">','</a>').'
 8432:     </p>
 8433: ');
 8434:     return '';
 8435: }
 8436: 
 8437: sub checkscantron_results {
 8438:     my ($r,$symb) = @_;
 8439:     if (!$symb) {return '';}
 8440:     my $cid = $env{'request.course.id'};
 8441:     my %lettdig = &letter_to_digits();
 8442:     my $numletts = scalar(keys(%lettdig));
 8443:     my $cnum = $env{'course.'.$cid.'.num'};
 8444:     my $cdom = $env{'course.'.$cid.'.domain'};
 8445:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8446:     my %record;
 8447:     my %scantron_config =
 8448:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8449:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8450:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8451:     my $classlist=&Apache::loncoursedata::get_classlist();
 8452:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8453:     my $navmap=Apache::lonnavmaps::navmap->new();
 8454:     unless (ref($navmap)) {
 8455:         $r->print(&navmap_errormsg());
 8456:         return '';
 8457:     }
 8458:     my $map=$navmap->getResourceByUrl($sequence);
 8459:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8460:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8461:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8462: 
 8463:     my ($uname,$udom);
 8464:     my (%scandata,%lastname,%bylast);
 8465:     $r->print('
 8466: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8467: 
 8468:     my @delayqueue;
 8469:     my %completedstudents;
 8470: 
 8471:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8472:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8473:     my ($username,$domain,$started);
 8474:     my $nav_error;
 8475:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8476:     if ($nav_error) {
 8477:         $r->print(&navmap_errormsg());
 8478:         return '';
 8479:     }
 8480: 
 8481:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8482:     my $start=&Time::HiRes::time();
 8483:     my $i=-1;
 8484: 
 8485:     while ($i<$scanlines->{'count'}) {
 8486:         ($username,$domain,$uname)=('','','');
 8487:         $i++;
 8488:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8489:         if ($line=~/^[\s\cz]*$/) { next; }
 8490:         if ($started) {
 8491:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8492:         }
 8493:         $started=1;
 8494:         my $scan_record=
 8495:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8496:                                                      $scan_data);
 8497:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8498:                                                               \%idmap,$i)) {
 8499:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8500:                                 'Unable to find a student that matches',1);
 8501:             next;
 8502:         }
 8503:         if (exists $completedstudents{$uname}) {
 8504:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8505:                                 'Student '.$uname.' has multiple sheets',2);
 8506:             next;
 8507:         }
 8508:         my $pid = $scan_record->{'scantron.ID'};
 8509:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8510:         push(@{$bylast{$lastname{$pid}}},$pid);
 8511:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8512:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8513:         chomp($scandata{$pid});
 8514:         $scandata{$pid} =~ s/\r$//;
 8515:         ($username,$domain)=split(/:/,$uname);
 8516:         my $counter = -1;
 8517:         foreach my $resource (@resources) {
 8518:             my $parts;
 8519:             my $ressymb = $resource->symb();
 8520:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8521:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8522:                 (my $analysis,$parts) =
 8523:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
 8524:             } else {
 8525:                 $parts = $grader_partids_by_symb{$ressymb};
 8526:             }
 8527:             ($counter,my $recording) =
 8528:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8529:                                          $scandata{$pid},$parts,
 8530:                                          \%scantron_config,\%lettdig,$numletts);
 8531:             $record{$pid} .= $recording;
 8532:         }
 8533:     }
 8534:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8535:     $r->print('<br />');
 8536:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8537:     $passed = 0;
 8538:     $failed = 0;
 8539:     $numstudents = 0;
 8540:     foreach my $last (sort(keys(%bylast))) {
 8541:         if (ref($bylast{$last}) eq 'ARRAY') {
 8542:             foreach my $pid (sort(@{$bylast{$last}})) {
 8543:                 my $showscandata = $scandata{$pid};
 8544:                 my $showrecord = $record{$pid};
 8545:                 $showscandata =~ s/\s/&nbsp;/g;
 8546:                 $showrecord =~ s/\s/&nbsp;/g;
 8547:                 if ($scandata{$pid} eq $record{$pid}) {
 8548:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8549:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8550: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8551: '</tr>'."\n".
 8552: '<tr class="'.$css_class.'">'."\n".
 8553: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8554:                     $passed ++;
 8555:                 } else {
 8556:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8557:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8558: '</tr>'."\n".
 8559: '<tr class="'.$css_class.'">'."\n".
 8560: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8561: '</tr>'."\n";
 8562:                     $failed ++;
 8563:                 }
 8564:                 $numstudents ++;
 8565:             }
 8566:         }
 8567:     }
 8568:     $r->print(
 8569:         '<p>'
 8570:        .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
 8571:             '<b>',
 8572:             $numstudents,
 8573:             '</b>',
 8574:             $env{'form.scantron_maxbubble'})
 8575:        .'</p>'
 8576:     );
 8577:     $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>');
 8578:     if ($passed) {
 8579:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8580:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8581:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8582:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8583:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8584:                  $okstudents."\n".
 8585:                  &Apache::loncommon::end_data_table().'<br />');
 8586:     }
 8587:     if ($failed) {
 8588:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8589:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8590:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8591:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8592:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8593:                  $badstudents."\n".
 8594:                  &Apache::loncommon::end_data_table()).'<br />'.
 8595:                  &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');  
 8596:     }
 8597:     $r->print('</form><br />');
 8598:     return;
 8599: }
 8600: 
 8601: sub verify_scantron_grading {
 8602:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8603:         $scantron_config,$lettdig,$numletts) = @_;
 8604:     my ($record,%expected,%startpos);
 8605:     return ($counter,$record) if (!ref($resource));
 8606:     return ($counter,$record) if (!$resource->is_problem());
 8607:     my $symb = $resource->symb();
 8608:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8609:     foreach my $part_id (@{$partids}) {
 8610:         $counter ++;
 8611:         $expected{$part_id} = 0;
 8612:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8613:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8614:             foreach my $item (@sub_lines) {
 8615:                 $expected{$part_id} += $item;
 8616:             }
 8617:         } else {
 8618:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8619:         }
 8620:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8621:     }
 8622:     if ($symb) {
 8623:         my %recorded;
 8624:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8625:         if ($returnhash{'version'}) {
 8626:             my %lasthash=();
 8627:             my $version;
 8628:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8629:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8630:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8631:                 }
 8632:             }
 8633:             foreach my $key (keys(%lasthash)) {
 8634:                 if ($key =~ /\.scantron$/) {
 8635:                     my $value = &unescape($lasthash{$key});
 8636:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8637:                     if ($value eq '') {
 8638:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8639:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8640:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8641:                             }
 8642:                         }
 8643:                     } else {
 8644:                         my @tocheck;
 8645:                         my @items = split(//,$value);
 8646:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8647:                             ($scantron_config->{'Qon'} eq 'number')) {
 8648:                             if (@items < $expected{$part_id}) {
 8649:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8650:                                 my @singles = split(//,$fragment);
 8651:                                 foreach my $pos (@singles) {
 8652:                                     if ($pos eq ' ') {
 8653:                                         push(@tocheck,$pos);
 8654:                                     } else {
 8655:                                         my $next = shift(@items);
 8656:                                         push(@tocheck,$next);
 8657:                                     }
 8658:                                 }
 8659:                             } else {
 8660:                                 @tocheck = @items;
 8661:                             }
 8662:                             foreach my $letter (@tocheck) {
 8663:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8664:                                     if ($letter !~ /^[A-J]$/) {
 8665:                                         $letter = $scantron_config->{'Qoff'};
 8666:                                     }
 8667:                                     $recorded{$part_id} .= $letter;
 8668:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8669:                                     my $digit;
 8670:                                     if ($letter !~ /^[A-J]$/) {
 8671:                                         $digit = $scantron_config->{'Qoff'};
 8672:                                     } else {
 8673:                                         $digit = $lettdig->{$letter};
 8674:                                     }
 8675:                                     $recorded{$part_id} .= $digit;
 8676:                                 }
 8677:                             }
 8678:                         } else {
 8679:                             @tocheck = @items;
 8680:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8681:                                 my $curr_sub = shift(@tocheck);
 8682:                                 my $digit;
 8683:                                 if ($curr_sub =~ /^[A-J]$/) {
 8684:                                     $digit = $lettdig->{$curr_sub}-1;
 8685:                                 }
 8686:                                 if ($curr_sub eq 'J') {
 8687:                                     $digit += scalar($numletts);
 8688:                                 }
 8689:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8690:                                     if ($j == $digit) {
 8691:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8692:                                     } else {
 8693:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8694:                                     }
 8695:                                 }
 8696:                             }
 8697:                         }
 8698:                     }
 8699:                 }
 8700:             }
 8701:         }
 8702:         foreach my $part_id (@{$partids}) {
 8703:             if ($recorded{$part_id} eq '') {
 8704:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8705:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8706:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8707:                     }
 8708:                 }
 8709:             }
 8710:             $record .= $recorded{$part_id};
 8711:         }
 8712:     }
 8713:     return ($counter,$record);
 8714: }
 8715: 
 8716: sub letter_to_digits { 
 8717:     my %lettdig = (
 8718:                     A => 1,
 8719:                     B => 2,
 8720:                     C => 3,
 8721:                     D => 4,
 8722:                     E => 5,
 8723:                     F => 6,
 8724:                     G => 7,
 8725:                     H => 8,
 8726:                     I => 9,
 8727:                     J => 0,
 8728:                   );
 8729:     return %lettdig;
 8730: }
 8731: 
 8732: 
 8733: #-------- end of section for handling grading scantron forms -------
 8734: #
 8735: #-------------------------------------------------------------------
 8736: 
 8737: #-------------------------- Menu interface -------------------------
 8738: #
 8739: #--- Href with symb and command ---
 8740: 
 8741: sub href_symb_cmd {
 8742:     my ($symb,$cmd)=@_;
 8743:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 8744: }
 8745: 
 8746: sub grading_menu {
 8747:     my ($request,$symb) = @_;
 8748:     if (!$symb) {return '';}
 8749: 
 8750:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8751:                   'command'=>'individual');
 8752:     
 8753:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8754: 
 8755:     $fields{'command'}='ungraded';
 8756:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8757: 
 8758:     $fields{'command'}='table';
 8759:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8760: 
 8761:     $fields{'command'}='all_for_one';
 8762:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8763: 
 8764:     $fields{'command'}='downloadfilesselect';
 8765:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8766: 
 8767:     $fields{'command'} = 'csvform';
 8768:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8769:     
 8770:     $fields{'command'} = 'processclicker';
 8771:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8772:     
 8773:     $fields{'command'} = 'scantron_selectphase';
 8774:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8775: 
 8776:     $fields{'command'} = 'initialverifyreceipt';
 8777:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8778:     
 8779:     my @menu = ({	categorytitle=>'Hand Grading',
 8780:             items =>[
 8781:                         {	linktext => 'Select individual students to grade',
 8782:                     		url => $url1a,
 8783:                     		permission => 'F',
 8784:                     		icon => 'grade_students.png',
 8785:                     		linktitle => 'Grade current resource for a selection of students.'
 8786:                         }, 
 8787:                         {       linktext => 'Grade ungraded submissions.',
 8788:                                 url => $url1b,
 8789:                                 permission => 'F',
 8790:                                 icon => 'ungrade_sub.png',
 8791:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 8792:                         },
 8793: 
 8794:                         {       linktext => 'Grading table',
 8795:                                 url => $url1c,
 8796:                                 permission => 'F',
 8797:                                 icon => 'grading_table.png',
 8798:                                 linktitle => 'Grade current resource for all students.'
 8799:                         },
 8800:                         {       linktext => 'Grade page/folder for one student',
 8801:                                 url => $url1d,
 8802:                                 permission => 'F',
 8803:                                 icon => 'grade_PageFolder.png',
 8804:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 8805:                         },
 8806:                         {       linktext => 'Download submissions',
 8807:                                 url => $url1e,
 8808:                                 permission => 'F',
 8809:                                 icon => 'download_sub.png',
 8810:                                 linktitle => 'Download all students submissions.'
 8811:                         }]},
 8812:                          { categorytitle=>'Automated Grading',
 8813:                items =>[
 8814: 
 8815:                 	    {	linktext => 'Upload Scores',
 8816:                     		url => $url2,
 8817:                     		permission => 'F',
 8818:                     		icon => 'uploadscores.png',
 8819:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8820:                 	    },
 8821:                 	    {	linktext => 'Process Clicker',
 8822:                     		url => $url3,
 8823:                     		permission => 'F',
 8824:                     		icon => 'addClickerInfoFile.png',
 8825:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8826:                 	    },
 8827:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8828:                     		url => $url4,
 8829:                     		permission => 'F',
 8830:                     		icon => 'bubblesheet.png',
 8831:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 8832:                 	    },
 8833:                             {   linktext => 'Verify Receipt Number',
 8834:                                 url => $url5,
 8835:                                 permission => 'F',
 8836:                                 icon => 'receipt_number.png',
 8837:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 8838:                             }
 8839: 
 8840:                     ]
 8841:             });
 8842: 
 8843:     # Create the menu
 8844:     my $Str;
 8845:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8846:     $Str .= '<input type="hidden" name="command" value="" />'.
 8847:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8848: 
 8849:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 8850:     return $Str;    
 8851: }
 8852: 
 8853: 
 8854: sub ungraded {
 8855:     my ($request)=@_;
 8856:     &submit_options($request);
 8857: }
 8858: 
 8859: sub submit_options_sequence {
 8860:     my ($request,$symb) = @_;
 8861:     if (!$symb) {return '';}
 8862:     &commonJSfunctions($request);
 8863:     my $result;
 8864: 
 8865:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8866:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8867:     $result.=&selectfield(0).
 8868:             '<input type="hidden" name="command" value="pickStudentPage" />
 8869:             <div>
 8870:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8871:             </div>
 8872:         </div>
 8873:   </form>';
 8874:     return $result;
 8875: }
 8876: 
 8877: sub submit_options_table {
 8878:     my ($request,$symb) = @_;
 8879:     if (!$symb) {return '';}
 8880:     &commonJSfunctions($request);
 8881:     my $result;
 8882: 
 8883:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8884:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8885: 
 8886:     $result.=&selectfield(0).
 8887:             '<input type="hidden" name="command" value="viewgrades" />
 8888:             <div>
 8889:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8890:             </div>
 8891:         </div>
 8892:   </form>';
 8893:     return $result;
 8894: }
 8895: 
 8896: sub submit_options_download {
 8897:     my ($request,$symb) = @_;
 8898:     if (!$symb) {return '';}
 8899: 
 8900:     &commonJSfunctions($request);
 8901: 
 8902:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8903:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8904:     $result.='
 8905: <h2>
 8906:   '.&mt('Select Students for Which to Download Submissions').'
 8907: </h2>'.&selectfield(1).'
 8908:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 8909:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 8910:             </div>
 8911:           </div>
 8912: 
 8913: 
 8914:   </form>';
 8915:     return $result;
 8916: }
 8917: 
 8918: #--- Displays the submissions first page -------
 8919: sub submit_options {
 8920:     my ($request,$symb) = @_;
 8921:     if (!$symb) {return '';}
 8922: 
 8923:     &commonJSfunctions($request);
 8924:     my $result;
 8925: 
 8926:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8927: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 8928:     $result.=&selectfield(1).'
 8929:                 <input type="hidden" name="command" value="submission" /> 
 8930: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 8931:             </div>
 8932:           </div>
 8933: 
 8934: 
 8935:   </form>';
 8936:     return $result;
 8937: }
 8938: 
 8939: sub selectfield {
 8940:    my ($full)=@_;
 8941:    my %options = 
 8942:           (&Apache::lonlocal::texthash(
 8943:              'yes'       => 'with submissions',
 8944:              'queued'    => 'in grading queue',
 8945:              'graded'    => 'with ungraded submissions',
 8946:              'incorrect' => 'with incorrect submissions',
 8947:              'all'       => 'with any status'),
 8948:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
 8949:    my $result='<div class="LC_columnSection">
 8950:   
 8951:     <fieldset>
 8952:       <legend>
 8953:        '.&mt('Sections').'
 8954:       </legend>
 8955:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 8956:     </fieldset>
 8957:   
 8958:     <fieldset>
 8959:       <legend>
 8960:         '.&mt('Groups').'
 8961:       </legend>
 8962:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8963:     </fieldset>
 8964:   
 8965:     <fieldset>
 8966:       <legend>
 8967:         '.&mt('Access Status').'
 8968:       </legend>
 8969:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 8970:     </fieldset>';
 8971:     if ($full) {
 8972:        $result.='
 8973:     <fieldset>
 8974:       <legend>
 8975:         '.&mt('Submission Status').'
 8976:       </legend>'.
 8977:        &Apache::loncommon::select_form('all','submitonly',\%options).
 8978:    '</fieldset>';
 8979:     }
 8980:     $result.='</div><br />';
 8981:     return $result;
 8982: }
 8983: 
 8984: sub reset_perm {
 8985:     undef(%perm);
 8986: }
 8987: 
 8988: sub init_perm {
 8989:     &reset_perm();
 8990:     foreach my $test_perm ('vgr','mgr','opa') {
 8991: 
 8992: 	my $scope = $env{'request.course.id'};
 8993: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8994: 
 8995: 	    $scope .= '/'.$env{'request.course.sec'};
 8996: 	    if ( $perm{$test_perm}=
 8997: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8998: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8999: 	    } else {
 9000: 		delete($perm{$test_perm});
 9001: 	    }
 9002: 	}
 9003:     }
 9004: }
 9005: 
 9006: sub gather_clicker_ids {
 9007:     my %clicker_ids;
 9008: 
 9009:     my $classlist = &Apache::loncoursedata::get_classlist();
 9010: 
 9011:     # Set up a couple variables.
 9012:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 9013:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 9014:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 9015: 
 9016:     foreach my $student (keys(%$classlist)) {
 9017:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 9018:         my $username = $classlist->{$student}->[$username_idx];
 9019:         my $domain   = $classlist->{$student}->[$domain_idx];
 9020:         my $clickers =
 9021: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 9022:         foreach my $id (split(/\,/,$clickers)) {
 9023:             $id=~s/^[\#0]+//;
 9024:             $id=~s/[\-\:]//g;
 9025:             if (exists($clicker_ids{$id})) {
 9026: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 9027:             } else {
 9028: 		$clicker_ids{$id}=$username.':'.$domain;
 9029:             }
 9030:         }
 9031:     }
 9032:     return %clicker_ids;
 9033: }
 9034: 
 9035: sub gather_adv_clicker_ids {
 9036:     my %clicker_ids;
 9037:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 9038:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9039:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 9040:     foreach my $element (sort(keys(%coursepersonnel))) {
 9041:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 9042:             my ($puname,$pudom)=split(/\:/,$person);
 9043:             my $clickers =
 9044: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 9045:             foreach my $id (split(/\,/,$clickers)) {
 9046: 		$id=~s/^[\#0]+//;
 9047:                 $id=~s/[\-\:]//g;
 9048: 		if (exists($clicker_ids{$id})) {
 9049: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 9050: 		} else {
 9051: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 9052: 		}
 9053:             }
 9054:         }
 9055:     }
 9056:     return %clicker_ids;
 9057: }
 9058: 
 9059: sub clicker_grading_parameters {
 9060:     return ('gradingmechanism' => 'scalar',
 9061:             'upfiletype' => 'scalar',
 9062:             'specificid' => 'scalar',
 9063:             'pcorrect' => 'scalar',
 9064:             'pincorrect' => 'scalar');
 9065: }
 9066: 
 9067: sub process_clicker {
 9068:     my ($r,$symb)=@_;
 9069:     if (!$symb) {return '';}
 9070:     my $result=&checkforfile_js();
 9071:     $result.=&Apache::loncommon::start_data_table().
 9072:              &Apache::loncommon::start_data_table_header_row().
 9073:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
 9074:              &Apache::loncommon::end_data_table_header_row().
 9075:              &Apache::loncommon::start_data_table_row()."<td>\n";
 9076: # Attempt to restore parameters from last session, set defaults if not present
 9077:     my %Saveable_Parameters=&clicker_grading_parameters();
 9078:     &Apache::loncommon::restore_course_settings('grades_clicker',
 9079:                                                  \%Saveable_Parameters);
 9080:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 9081:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 9082:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 9083:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 9084: 
 9085:     my %checked;
 9086:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 9087:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 9088:           $checked{$gradingmechanism}=' checked="checked"';
 9089:        }
 9090:     }
 9091: 
 9092:     my $upload=&mt("Evaluate File");
 9093:     my $type=&mt("Type");
 9094:     my $attendance=&mt("Award points just for participation");
 9095:     my $personnel=&mt("Correctness determined from response by course personnel");
 9096:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 9097:     my $given=&mt("Correctness determined from given list of answers").' '.
 9098:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 9099:     my $pcorrect=&mt("Percentage points for correct solution");
 9100:     my $pincorrect=&mt("Percentage points for incorrect solution");
 9101:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 9102: 						   {'iclicker' => 'i>clicker',
 9103:                                                     'interwrite' => 'interwrite PRS',
 9104:                                                     'turning' => 'Turning Technologies'});
 9105:     $symb = &Apache::lonenc::check_encrypt($symb);
 9106:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
 9107: function sanitycheck() {
 9108: // Accept only integer percentages
 9109:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9110:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9111: // Find out grading choice
 9112:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9113:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9114:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9115:       }
 9116:    }
 9117: // By default, new choice equals user selection
 9118:    newgradingchoice=gradingchoice;
 9119: // Not good to give more points for false answers than correct ones
 9120:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9121:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9122:    }
 9123: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9124:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9125:       document.forms.gradesupload.pcorrect.value=100;
 9126:       document.forms.gradesupload.pincorrect.value=100;
 9127:    }
 9128: // If the values are different, cannot be attendance only
 9129:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9130:        (gradingchoice=='attendance')) {
 9131:        newgradingchoice='personnel';
 9132:    }
 9133: // Change grading choice to new one
 9134:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9135:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9136:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9137:       } else {
 9138:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9139:       }
 9140:    }
 9141: // Remember the old state
 9142:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9143: }
 9144: ENDUPFORM
 9145:     $result.= <<ENDUPFORM;
 9146: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9147: <input type="hidden" name="symb" value="$symb" />
 9148: <input type="hidden" name="command" value="processclickerfile" />
 9149: <input type="file" name="upfile" size="50" />
 9150: <br /><label>$type: $selectform</label>
 9151: ENDUPFORM
 9152:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9153:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
 9154:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9155: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9156: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9157: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9158: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9159: <br />&nbsp;&nbsp;&nbsp;
 9160: <input type="text" name="givenanswer" size="50" />
 9161: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9162: ENDGRADINGFORM
 9163:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
 9164:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
 9165:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9166: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9167: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9168: </form>'
 9169: ENDPERCFORM
 9170:     $result.='</td>'.
 9171:              &Apache::loncommon::end_data_table_row().
 9172:              &Apache::loncommon::end_data_table();
 9173:     return $result;
 9174: }
 9175: 
 9176: sub process_clicker_file {
 9177:     my ($r,$symb)=@_;
 9178:     if (!$symb) {return '';}
 9179: 
 9180:     my %Saveable_Parameters=&clicker_grading_parameters();
 9181:     &Apache::loncommon::store_course_settings('grades_clicker',
 9182:                                               \%Saveable_Parameters);
 9183:     my $result='';
 9184:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9185: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9186: 	return $result;
 9187:     }
 9188:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9189:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9190:         return $result;
 9191:     }
 9192:     my $foundgiven=0;
 9193:     if ($env{'form.gradingmechanism'} eq 'given') {
 9194:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9195:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9196:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
 9197:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9198:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9199:         $foundgiven=$#answers+1;
 9200:     }
 9201:     my %clicker_ids=&gather_clicker_ids();
 9202:     my %correct_ids;
 9203:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9204: 	%correct_ids=&gather_adv_clicker_ids();
 9205:     }
 9206:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9207: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9208: 	   $correct_id=~tr/a-z/A-Z/;
 9209: 	   $correct_id=~s/\s//gs;
 9210: 	   $correct_id=~s/^[\#0]+//;
 9211:            $correct_id=~s/[\-\:]//g;
 9212:            if ($correct_id) {
 9213: 	      $correct_ids{$correct_id}='specified';
 9214:            }
 9215:         }
 9216:     }
 9217:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9218: 	$result.=&mt('Score based on attendance only');
 9219:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9220:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9221:     } else {
 9222: 	my $number=0;
 9223: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9224: 	foreach my $id (sort(keys(%correct_ids))) {
 9225: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9226: 	    if ($correct_ids{$id} eq 'specified') {
 9227: 		$result.=&mt('specified');
 9228: 	    } else {
 9229: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9230: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9231: 	    }
 9232: 	    $number++;
 9233: 	}
 9234:         $result.="</p>\n";
 9235: 	if ($number==0) {
 9236: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9237: 	    return $result;
 9238: 	}
 9239:     }
 9240:     if (length($env{'form.upfile'}) < 2) {
 9241:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9242: 		     '<span class="LC_error">',
 9243: 		     '</span>',
 9244: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9245:         return $result;
 9246:     }
 9247: 
 9248: # Were able to get all the info needed, now analyze the file
 9249: 
 9250:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9251:     $symb = &Apache::lonenc::check_encrypt($symb);
 9252:     $result.=&Apache::loncommon::start_data_table().
 9253:              &Apache::loncommon::start_data_table_header_row().
 9254:              '<th>'.&mt('Evaluate clicker file').'</th>'.
 9255:              &Apache::loncommon::end_data_table_header_row().
 9256:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
 9257: <td>
 9258: <form method="post" action="/adm/grades" name="clickeranalysis">
 9259: <input type="hidden" name="symb" value="$symb" />
 9260: <input type="hidden" name="command" value="assignclickergrades" />
 9261: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9262: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9263: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9264: ENDHEADER
 9265:     if ($env{'form.gradingmechanism'} eq 'given') {
 9266:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9267:     } 
 9268:     my %responses;
 9269:     my @questiontitles;
 9270:     my $errormsg='';
 9271:     my $number=0;
 9272:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9273: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9274:     }
 9275:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9276:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9277:     }
 9278:     if ($env{'form.upfiletype'} eq 'turning') {
 9279:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
 9280:     }
 9281:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9282:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9283:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9284:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9285:              '<br />';
 9286:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9287:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9288:        return $result;
 9289:     } 
 9290: # Remember Question Titles
 9291: # FIXME: Possibly need delimiter other than ":"
 9292:     for (my $i=0;$i<$number;$i++) {
 9293:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9294:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9295:     }
 9296:     my $correct_count=0;
 9297:     my $student_count=0;
 9298:     my $unknown_count=0;
 9299: # Match answers with usernames
 9300: # FIXME: Possibly need delimiter other than ":"
 9301:     foreach my $id (keys(%responses)) {
 9302:        if ($correct_ids{$id}) {
 9303:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9304:           $correct_count++;
 9305:        } elsif ($clicker_ids{$id}) {
 9306:           if ($clicker_ids{$id}=~/\,/) {
 9307: # More than one user with the same clicker!
 9308:              $result.="</td>".&Apache::loncommon::end_data_table_row().
 9309:                            &Apache::loncommon::start_data_table_row()."<td>".
 9310:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9311:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9312:                            "<select name='multi".$id."'>";
 9313:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9314:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9315:              }
 9316:              $result.='</select>';
 9317:              $unknown_count++;
 9318:           } else {
 9319: # Good: found one and only one user with the right clicker
 9320:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9321:              $student_count++;
 9322:           }
 9323:        } else {
 9324:           $result.="</td>".&Apache::loncommon::end_data_table_row().
 9325:                            &Apache::loncommon::start_data_table_row()."<td>".
 9326:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9327:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9328:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9329:                    "\n".&mt("Domain").": ".
 9330:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9331:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
 9332:           $unknown_count++;
 9333:        }
 9334:     }
 9335:     $result.='<hr />'.
 9336:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9337:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9338:        if ($correct_count==0) {
 9339:           $errormsg.="Found no correct answers answers for grading!";
 9340:        } elsif ($correct_count>1) {
 9341:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9342:        }
 9343:     }
 9344:     if ($number<1) {
 9345:        $errormsg.="Found no questions.";
 9346:     }
 9347:     if ($errormsg) {
 9348:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9349:     } else {
 9350:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9351:     }
 9352:     $result.='</form></td>'.
 9353:              &Apache::loncommon::end_data_table_row().
 9354:              &Apache::loncommon::end_data_table();
 9355:     return $result;
 9356: }
 9357: 
 9358: sub iclicker_eval {
 9359:     my ($questiontitles,$responses)=@_;
 9360:     my $number=0;
 9361:     my $errormsg='';
 9362:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9363:         my %components=&Apache::loncommon::record_sep($line);
 9364:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9365: 	if ($entries[0] eq 'Question') {
 9366: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9367: 		$$questiontitles[$number]=$entries[$i];
 9368: 		$number++;
 9369: 	    }
 9370: 	}
 9371: 	if ($entries[0]=~/^\#/) {
 9372: 	    my $id=$entries[0];
 9373: 	    my @idresponses;
 9374: 	    $id=~s/^[\#0]+//;
 9375: 	    for (my $i=0;$i<$number;$i++) {
 9376: 		my $idx=3+$i*6;
 9377:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
 9378: 		push(@idresponses,$entries[$idx]);
 9379: 	    }
 9380: 	    $$responses{$id}=join(',',@idresponses);
 9381: 	}
 9382:     }
 9383:     return ($errormsg,$number);
 9384: }
 9385: 
 9386: sub interwrite_eval {
 9387:     my ($questiontitles,$responses)=@_;
 9388:     my $number=0;
 9389:     my $errormsg='';
 9390:     my $skipline=1;
 9391:     my $questionnumber=0;
 9392:     my %idresponses=();
 9393:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9394:         my %components=&Apache::loncommon::record_sep($line);
 9395:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9396:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9397:         if ($entries[1] eq 'Response') { $skipline=1; }
 9398:         next if $skipline;
 9399:         if ($entries[0]!=$questionnumber) {
 9400:            $questionnumber=$entries[0];
 9401:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9402:            $number++;
 9403:         }
 9404:         my $id=$entries[4];
 9405:         $id=~s/^[\#0]+//;
 9406:         $id=~s/^v\d*\://i;
 9407:         $id=~s/[\-\:]//g;
 9408:         $idresponses{$id}[$number]=$entries[6];
 9409:     }
 9410:     foreach my $id (keys(%idresponses)) {
 9411:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9412:        $$responses{$id}=~s/^\s*\,//;
 9413:     }
 9414:     return ($errormsg,$number);
 9415: }
 9416: 
 9417: sub turning_eval {
 9418:     my ($questiontitles,$responses)=@_;
 9419:     my $number=0;
 9420:     my $errormsg='';
 9421:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9422:         my %components=&Apache::loncommon::record_sep($line);
 9423:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9424:         if ($#entries>$number) { $number=$#entries; }
 9425:         my $id=$entries[0];
 9426:         my @idresponses;
 9427:         $id=~s/^[\#0]+//;
 9428:         unless ($id) { next; }
 9429:         for (my $idx=1;$idx<=$#entries;$idx++) {
 9430:             $entries[$idx]=~s/\,/\;/g;
 9431:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
 9432:             push(@idresponses,$entries[$idx]);
 9433:         }
 9434:         $$responses{$id}=join(',',@idresponses);
 9435:     }
 9436:     for (my $i=1; $i<=$number; $i++) {
 9437:         $$questiontitles[$i]=&mt('Question [_1]',$i);
 9438:     }
 9439:     return ($errormsg,$number);
 9440: }
 9441: 
 9442: 
 9443: sub assign_clicker_grades {
 9444:     my ($r,$symb)=@_;
 9445:     if (!$symb) {return '';}
 9446: # See which part we are saving to
 9447:     my $res_error;
 9448:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9449:     if ($res_error) {
 9450:         return &navmap_errormsg();
 9451:     }
 9452: # FIXME: This should probably look for the first handgradeable part
 9453:     my $part=$$partlist[0];
 9454: # Start screen output
 9455:     my $result=&Apache::loncommon::start_data_table().
 9456:              &Apache::loncommon::start_data_table_header_row().
 9457:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
 9458:              &Apache::loncommon::end_data_table_header_row().
 9459:              &Apache::loncommon::start_data_table_row().'<td>';
 9460: # Get correct result
 9461: # FIXME: Possibly need delimiter other than ":"
 9462:     my @correct=();
 9463:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9464:     my $number=$env{'form.number'};
 9465:     if ($gradingmechanism ne 'attendance') {
 9466:        foreach my $key (keys(%env)) {
 9467:           if ($key=~/^form\.correct\:/) {
 9468:              my @input=split(/\,/,$env{$key});
 9469:              for (my $i=0;$i<=$#input;$i++) {
 9470:                  if (($correct[$i]) && ($input[$i]) &&
 9471:                      ($correct[$i] ne $input[$i])) {
 9472:                     $result.='<br /><span class="LC_warning">'.
 9473:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9474:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9475:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
 9476:                     $correct[$i]=$input[$i];
 9477:                  }
 9478:              }
 9479:           }
 9480:        }
 9481:        for (my $i=0;$i<$number;$i++) {
 9482:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
 9483:              $result.='<br /><span class="LC_error">'.
 9484:                       &mt('No correct result given for question "[_1]"!',
 9485:                           $env{'form.question:'.$i}).'</span>';
 9486:           }
 9487:        }
 9488:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
 9489:     }
 9490: # Start grading
 9491:     my $pcorrect=$env{'form.pcorrect'};
 9492:     my $pincorrect=$env{'form.pincorrect'};
 9493:     my $storecount=0;
 9494:     my %users=();
 9495:     foreach my $key (keys(%env)) {
 9496:        my $user='';
 9497:        if ($key=~/^form\.student\:(.*)$/) {
 9498:           $user=$1;
 9499:        }
 9500:        if ($key=~/^form\.unknown\:(.*)$/) {
 9501:           my $id=$1;
 9502:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9503:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9504:           } elsif ($env{'form.multi'.$id}) {
 9505:              $user=$env{'form.multi'.$id};
 9506:           }
 9507:        }
 9508:        if ($user) {
 9509:           if ($users{$user}) {
 9510:              $result.='<br /><span class="LC_warning">'.
 9511:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
 9512:                       '</span><br />';
 9513:           }
 9514:           $users{$user}=1; 
 9515:           my @answer=split(/\,/,$env{$key});
 9516:           my $sum=0;
 9517:           my $realnumber=$number;
 9518:           for (my $i=0;$i<$number;$i++) {
 9519:              if  ($correct[$i] eq '-') {
 9520:                 $realnumber--;
 9521:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
 9522:                 if ($gradingmechanism eq 'attendance') {
 9523:                    $sum+=$pcorrect;
 9524:                 } elsif ($correct[$i] eq '*') {
 9525:                    $sum+=$pcorrect;
 9526:                 } else {
 9527: # We actually grade if correct or not
 9528:                    my $increment=$pincorrect;
 9529: # Special case: numerical answer "0"
 9530:                    if ($correct[$i] eq '0') {
 9531:                       if ($answer[$i]=~/^[0\.]+$/) {
 9532:                          $increment=$pcorrect;
 9533:                       }
 9534: # General numerical answer, both evaluate to something non-zero
 9535:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
 9536:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
 9537:                          $increment=$pcorrect;
 9538:                       }
 9539: # Must be just alphanumeric
 9540:                    } elsif ($answer[$i] eq $correct[$i]) {
 9541:                       $increment=$pcorrect;
 9542:                    }
 9543:                    $sum+=$increment;
 9544:                 }
 9545:              }
 9546:           }
 9547:           my $ave=$sum/(100*$realnumber);
 9548: # Store
 9549:           my ($username,$domain)=split(/\:/,$user);
 9550:           my %grades=();
 9551:           $grades{"resource.$part.solved"}='correct_by_override';
 9552:           $grades{"resource.$part.awarded"}=$ave;
 9553:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9554:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9555:                                                  $env{'request.course.id'},
 9556:                                                  $domain,$username);
 9557:           if ($returncode ne 'ok') {
 9558:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9559:           } else {
 9560:              $storecount++;
 9561:           }
 9562:        }
 9563:     }
 9564: # We are done
 9565:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9566:              '</td>'.
 9567:              &Apache::loncommon::end_data_table_row().
 9568:              &Apache::loncommon::end_data_table();
 9569:     return $result;
 9570: }
 9571: 
 9572: sub navmap_errormsg {
 9573:     return '<div class="LC_error">'.
 9574:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9575:            &mt('It is recommended that you [_1]re-initialize the course[_2] and then return to this grading page.','<a href="/adm/roles?selectrole=1&newrole='.$env{'request.role'}.'">','</a>').
 9576:            '</div>';
 9577: }
 9578: 
 9579: sub startpage {
 9580:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
 9581:     if ($nomenu) {
 9582:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
 9583:     } else {
 9584:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
 9585:         $r->print(&Apache::loncommon::start_page('Grading',$js,
 9586:                                                  {'bread_crumbs' => $crumbs}));
 9587:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
 9588:     }
 9589:     unless ($nodisplayflag) {
 9590:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
 9591:     }
 9592: }
 9593: 
 9594: sub select_problem {
 9595:     my ($r)=@_;
 9596:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
 9597:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
 9598:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
 9599:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
 9600: }
 9601: 
 9602: sub handler {
 9603:     my $request=$_[0];
 9604:     &reset_caches();
 9605:     if ($request->header_only) {
 9606:         &Apache::loncommon::content_type($request,'text/html');
 9607:         $request->send_http_header;
 9608:         return OK;
 9609:     }
 9610:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9611: 
 9612: # see what command we need to execute
 9613: 
 9614:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9615:     my $command=$commands[0];
 9616: 
 9617:     &init_perm();
 9618:     if (!$env{'request.course.id'}) {
 9619:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
 9620:                 ($command =~ /^scantronupload/)) {
 9621:             # Not in a course.
 9622:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
 9623:             return HTTP_NOT_ACCEPTABLE;
 9624:         }
 9625:     } elsif (!%perm) {
 9626:         $request->internal_redirect('/adm/quickgrades');
 9627:     }
 9628:     &Apache::loncommon::content_type($request,'text/html');
 9629:     $request->send_http_header;
 9630: 
 9631:     if ($#commands > 0) {
 9632: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9633:     }
 9634: 
 9635: # see what the symb is
 9636: 
 9637:     my $symb=$env{'form.symb'};
 9638:     unless ($symb) {
 9639:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9640:        $symb=&Apache::lonnet::symbread($url);
 9641:     }
 9642:     &Apache::lonenc::check_decrypt(\$symb);
 9643: 
 9644:     $ssi_error = 0;
 9645:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
 9646: #
 9647: # Not called from a resource, but inside a course
 9648: #    
 9649:         &startpage($request,undef,[],1,1);
 9650:         &select_problem($request);
 9651:     } else {
 9652: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9653:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
 9654:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
 9655:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
 9656:                     &choose_task_version_form($symb,$env{'form.student'},
 9657:                                               $env{'form.userdom'});
 9658:             }
 9659:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
 9660:             if ($versionform) {
 9661:                 $request->print($versionform);
 9662:             }
 9663:             $request->print('<br clear="all" />');
 9664: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
 9665:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
 9666:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
 9667:                 &choose_task_version_form($symb,$env{'form.student'},
 9668:                                           $env{'form.userdom'},
 9669:                                           $env{'form.inhibitmenu'});
 9670:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
 9671:             if ($versionform) {
 9672:                 $request->print($versionform);
 9673:             }
 9674:             $request->print('<br clear="all" />');
 9675:             $request->print(&show_previous_task_version($request,$symb));
 9676: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9677:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9678:                                        {href=>'',text=>'Select student'}],1,1);
 9679: 	    &pickStudentPage($request,$symb);
 9680: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9681:             &startpage($request,$symb,
 9682:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9683:                                        {href=>'',text=>'Select student'},
 9684:                                        {href=>'',text=>'Grade student'}],1,1);
 9685: 	    &displayPage($request,$symb);
 9686: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9687:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
 9688:                                        {href=>'',text=>'Select student'},
 9689:                                        {href=>'',text=>'Grade student'},
 9690:                                        {href=>'',text=>'Store grades'}],1,1);
 9691: 	    &updateGradeByPage($request,$symb);
 9692: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9693:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9694:                                        {href=>'',text=>'Modify grades'}]);
 9695: 	    &processGroup($request,$symb);
 9696: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9697:             &startpage($request,$symb);
 9698: 	    $request->print(&grading_menu($request,$symb));
 9699: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
 9700:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
 9701: 	    $request->print(&submit_options($request,$symb));
 9702:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
 9703:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
 9704:             $request->print(&listStudents($request,$symb,'graded'));
 9705:         } elsif ($command eq 'table' && $perm{'vgr'}) {
 9706:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
 9707:             $request->print(&submit_options_table($request,$symb));
 9708:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
 9709:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
 9710:             $request->print(&submit_options_sequence($request,$symb));
 9711: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9712:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
 9713: 	    $request->print(&viewgrades($request,$symb));
 9714: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9715:             &startpage($request,$symb,[{href=>'',text=>'...'},
 9716:                                        {href=>'',text=>'Store grades'}]);
 9717: 	    $request->print(&processHandGrade($request,$symb));
 9718: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9719:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
 9720:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
 9721:                                                                              text=>"Modify grades"},
 9722:                                        {href=>'', text=>"Store grades"}]);
 9723: 	    $request->print(&editgrades($request,$symb));
 9724:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
 9725:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
 9726:             $request->print(&initialverifyreceipt($request,$symb));
 9727: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9728:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
 9729:                                        {href=>'',text=>'Verification Result'}]);
 9730: 	    $request->print(&verifyreceipt($request,$symb));
 9731:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9732:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
 9733:             $request->print(&process_clicker($request,$symb));
 9734:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9735:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9736:                                        {href=>'', text=>'Process clicker file'}]);
 9737:             $request->print(&process_clicker_file($request,$symb));
 9738:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9739:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
 9740:                                        {href=>'', text=>'Process clicker file'},
 9741:                                        {href=>'', text=>'Store grades'}]);
 9742:             $request->print(&assign_clicker_grades($request,$symb));
 9743: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9744:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9745: 	    $request->print(&upcsvScores_form($request,$symb));
 9746: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9747:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9748: 	    $request->print(&csvupload($request,$symb));
 9749: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9750:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9751: 	    $request->print(&csvuploadmap($request,$symb));
 9752: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9753: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9754:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9755: 		$request->print(&csvuploadoptions($request,$symb));
 9756: 	    } else {
 9757: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9758: 		    $env{'form.upfile_associate'} = 'reverse';
 9759: 		} else {
 9760: 		    $env{'form.upfile_associate'} = 'forward';
 9761: 		}
 9762:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9763: 		$request->print(&csvuploadmap($request,$symb));
 9764: 	    }
 9765: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9766:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
 9767: 	    $request->print(&csvuploadassign($request,$symb));
 9768: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9769:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9770: 	    $request->print(&scantron_selectphase($request,undef,$symb));
 9771:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9772:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9773:  	    $request->print(&scantron_do_warning($request,$symb));
 9774: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9775:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9776: 	    $request->print(&scantron_validate_file($request,$symb));
 9777: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9778:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9779: 	    $request->print(&scantron_process_students($request,$symb));
 9780:  	} elsif ($command eq 'scantronupload' && 
 9781:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9782: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9783:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9784:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
 9785:  	} elsif ($command eq 'scantronupload_save' &&
 9786:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9787: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9788:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9789:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
 9790:  	} elsif ($command eq 'scantron_download' &&
 9791: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9792:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9793:  	    $request->print(&scantron_download_scantron_data($request,$symb));
 9794:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9795:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
 9796:             $request->print(&checkscantron_results($request,$symb));
 9797:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
 9798:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
 9799:             $request->print(&submit_options_download($request,$symb));
 9800:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
 9801:             &startpage($request,$symb,
 9802:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
 9803:     {href=>'', text=>'Download submissions'}]);
 9804:             &submit_download_link($request,$symb);
 9805: 	} elsif ($command) {
 9806:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
 9807: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9808: 	}
 9809:     }
 9810:     if ($ssi_error) {
 9811: 	&ssi_print_error($request);
 9812:     }
 9813:     if ($env{'form.inhibitmenu'}) {
 9814:         $request->print(&Apache::loncommon::end_page());
 9815:     } else {
 9816:         &Apache::lonquickgrades::endGradeScreen($request);
 9817:     }
 9818:     &reset_caches();
 9819:     return OK;
 9820: }
 9821: 
 9822: 1;
 9823: 
 9824: __END__;
 9825: 
 9826: 
 9827: =head1 NAME
 9828: 
 9829: Apache::grades
 9830: 
 9831: =head1 SYNOPSIS
 9832: 
 9833: Handles the viewing of grades.
 9834: 
 9835: This is part of the LearningOnline Network with CAPA project
 9836: described at http://www.lon-capa.org.
 9837: 
 9838: =head1 OVERVIEW
 9839: 
 9840: Do an ssi with retries:
 9841: While I'd love to factor out this with the vesrion in lonprintout,
 9842: 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
 9843: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9844: 
 9845: At least the logic that drives this has been pulled out into loncommon.
 9846: 
 9847: 
 9848: 
 9849: ssi_with_retries - Does the server side include of a resource.
 9850:                      if the ssi call returns an error we'll retry it up to
 9851:                      the number of times requested by the caller.
 9852:                      If we still have a proble, no text is appended to the
 9853:                      output and we set some global variables.
 9854:                      to indicate to the caller an SSI error occurred.  
 9855:                      All of this is supposed to deal with the issues described
 9856:                      in LonCAPA BZ 5631 see:
 9857:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9858:                      by informing the user that this happened.
 9859: 
 9860: Parameters:
 9861:   resource   - The resource to include.  This is passed directly, without
 9862:                interpretation to lonnet::ssi.
 9863:   form       - The form hash parameters that guide the interpretation of the resource
 9864:                
 9865:   retries    - Number of retries allowed before giving up completely.
 9866: Returns:
 9867:   On success, returns the rendered resource identified by the resource parameter.
 9868: Side Effects:
 9869:   The following global variables can be set:
 9870:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9871:                               It is up to the caller to initialize this to false
 9872:                               if desired.
 9873:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9874:                               of the resource that could not be rendered by the ssi
 9875:                               call.
 9876:    ssi_error_message   - The error string fetched from the ssi response
 9877:                               in the event of an error.
 9878: 
 9879: 
 9880: =head1 HANDLER SUBROUTINE
 9881: 
 9882: ssi_with_retries()
 9883: 
 9884: =head1 SUBROUTINES
 9885: 
 9886: =over
 9887: 
 9888: =head1 Routines to display previous version of a Task for a specific student
 9889: 
 9890: Tasks are graded pass/fail. Students who have yet to pass a particular Task
 9891: can receive another opportunity. Access to tasks is slot-based. If a slot
 9892: requires a proctor to check-in the student, a new version of the Task will
 9893: be created when the student is checked in to the new opportunity.
 9894: 
 9895: If a particular student has tried two or more versions of a particular task,
 9896: the submission screen provides a user with vgr privileges (e.g., a Course
 9897: Coordinator) the ability to display a previous version worked on by the
 9898: student.  By default, the current version is displayed. If a previous version
 9899: has been selected for display, submission data are only shown that pertain
 9900: to that particular version, and the interface to submit grades is not shown.
 9901: 
 9902: =over 4
 9903: 
 9904: =item show_previous_task_version()
 9905: 
 9906: Displays a specified version of a student's Task, as the student sees it.
 9907: 
 9908: Inputs: 2
 9909:         request - request object
 9910:         symb    - unique symb for current instance of resource
 9911: 
 9912: Output: None.
 9913: 
 9914: Side Effects: calls &show_problem() to print version of Task, with
 9915:               version contained in form item: $env{'form.previousversion'}
 9916: 
 9917: =item choose_task_version_form()
 9918: 
 9919: Displays a web form used to select which version of a student's view of a
 9920: Task should be displayed.  Either launches a pop-up window, or replaces
 9921: content in existing pop-up, or replaces page in main window.
 9922: 
 9923: Inputs: 4
 9924:         symb    - unique symb for current instance of resource
 9925:         uname   - username of student
 9926:         udom    - domain of student
 9927:         nomenu  - 1 if display is in a pop-up window, and hence no menu
 9928:                   breadcrumbs etc., are displayed
 9929: 
 9930: Output: 4
 9931:         current   - student's current version
 9932:         displayed - student's version being displayed
 9933:         result    - scalar containing HTML for web form used to switch to
 9934:                     a different version (or a link to close window, if pop-up).
 9935:         js        - javascript for processing selection in versions web form
 9936: 
 9937: Side Effects: None.
 9938: 
 9939: =item previous_display_javascript()
 9940: 
 9941: Inputs: 2
 9942:         nomenu  - 1 if display is in a pop-up window, and hence no menu
 9943:                   breadcrumbs etc., are displayed.
 9944:         current - student's current version number.
 9945: 
 9946: Output: 1
 9947:         js      - javascript for processing selection in versions web form.
 9948: 
 9949: Side Effects: None.
 9950: 
 9951: =back
 9952: 
 9953: =head1 Routines to process bubblesheet data.
 9954: 
 9955: =over 4
 9956: 
 9957: =item scantron_get_correction() : 
 9958: 
 9959:    Builds the interface screen to interact with the operator to fix a
 9960:    specific error condition in a specific scanline
 9961: 
 9962:  Arguments:
 9963:     $r           - Apache request object
 9964:     $i           - number of the current scanline
 9965:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9966:     $scan_config - hash ref as returned from &get_scantron_config()
 9967:     $line        - full contents of the current scanline
 9968:     $error       - error condition, valid values are
 9969:                    'incorrectCODE', 'duplicateCODE',
 9970:                    'doublebubble', 'missingbubble',
 9971:                    'duplicateID', 'incorrectID'
 9972:     $arg         - extra information needed
 9973:        For errors:
 9974:          - duplicateID   - paper number that this studentID was seen before on
 9975:          - duplicateCODE - array ref of the paper numbers this CODE was
 9976:                            seen on before
 9977:          - incorrectCODE - current incorrect CODE 
 9978:          - doublebubble  - array ref of the bubble lines that have double
 9979:                            bubble errors
 9980:          - missingbubble - array ref of the bubble lines that have missing
 9981:                            bubble errors
 9982: 
 9983: =item  scantron_get_maxbubble() : 
 9984: 
 9985:    Arguments:
 9986:        $nav_error  - Reference to scalar which is a flag to indicate a
 9987:                       failure to retrieve a navmap object.
 9988:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9989:        calling routine should trap the error condition and display the warning
 9990:        found in &navmap_errormsg().
 9991: 
 9992:        $scantron_config - Reference to bubblesheet format configuration hash.
 9993: 
 9994:    Returns the maximum number of bubble lines that are expected to
 9995:    occur. Does this by walking the selected sequence rendering the
 9996:    resource and then checking &Apache::lonxml::get_problem_counter()
 9997:    for what the current value of the problem counter is.
 9998: 
 9999:    Caches the results to $env{'form.scantron_maxbubble'},
10000:    $env{'form.scantron.bubble_lines.n'}, 
10001:    $env{'form.scantron.first_bubble_line.n'} and
10002:    $env{"form.scantron.sub_bubblelines.n"}
10003:    which are the total number of bubble, lines, the number of bubble
10004:    lines for response n and number of the first bubble line for response n,
10005:    and a comma separated list of numbers of bubble lines for sub-questions
10006:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10007: 
10008: 
10009: =item  scantron_validate_missingbubbles() : 
10010: 
10011:    Validates all scanlines in the selected file to not have any
10012:     answers that don't have bubbles that have not been verified
10013:     to be bubble free.
10014: 
10015: =item  scantron_process_students() : 
10016: 
10017:    Routine that does the actual grading of the bubblesheet information.
10018: 
10019:    The parsed scanline hash is added to %env 
10020: 
10021:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10022:    foreach resource , with the form data of
10023: 
10024: 	'submitted'     =>'scantron' 
10025: 	'grade_target'  =>'grade',
10026: 	'grade_username'=> username of student
10027: 	'grade_domain'  => domain of student
10028: 	'grade_courseid'=> of course
10029: 	'grade_symb'    => symb of resource to grade
10030: 
10031:     This triggers a grading pass. The problem grading code takes care
10032:     of converting the bubbled letter information (now in %env) into a
10033:     valid submission.
10034: 
10035: =item  scantron_upload_scantron_data() :
10036: 
10037:     Creates the screen for adding a new bubblesheet data file to a course.
10038: 
10039: =item  scantron_upload_scantron_data_save() : 
10040: 
10041:    Adds a provided bubble information data file to the course if user
10042:    has the correct privileges to do so. 
10043: 
10044: =item  valid_file() :
10045: 
10046:    Validates that the requested bubble data file exists in the course.
10047: 
10048: =item  scantron_download_scantron_data() : 
10049: 
10050:    Shows a list of the three internal files (original, corrected,
10051:    skipped) for a specific bubblesheet data file that exists in the
10052:    course.
10053: 
10054: =item  scantron_validate_ID() : 
10055: 
10056:    Validates all scanlines in the selected file to not have any
10057:    invalid or underspecified student/employee IDs
10058: 
10059: =item navmap_errormsg() :
10060: 
10061:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10062:    Should be called whenever the request to instantiate a navmap object fails.
10063: 
10064: =back
10065: 
10066: =back
10067: 
10068: =cut

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