File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.793: download - view: text, annotated - select for diffs
Sun Apr 2 03:16:28 2023 UTC (13 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bug 6979
  - Shortcut to student's view of problem etc. from 'View As' item in Functions
  menu above problem.
  - Part of code in &submission() subroutine in grades.pm moved to separate
  subroutine -- &show_last_submission() which can be called by &view_as_user(),
  which in turn is called from lonhomework.pm

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.793 2023/04/02 03:16:28 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 Apache::lontexconvert();
   50: use String::Similarity;
   51: use HTML::Parser();
   52: use File::MMagic;
   53: use LONCAPA;
   54: 
   55: use POSIX qw(floor);
   56: 
   57: 
   58: 
   59: my %perm=();
   60: my %old_essays=();
   61: 
   62: #  These variables are used to recover from ssi errors
   63: 
   64: my $ssi_retries = 5;
   65: my $ssi_error;
   66: my $ssi_error_resource;
   67: my $ssi_error_message;
   68: 
   69: 
   70: sub ssi_with_retries {
   71:     my ($resource, $retries, %form) = @_;
   72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   73:     if ($response->is_error) {
   74: 	$ssi_error          = 1;
   75: 	$ssi_error_resource = $resource;
   76: 	$ssi_error_message  = $response->code . " " . $response->message;
   77:     }
   78: 
   79:     return $content;
   80: 
   81: }
   82: #
   83: #  Prodcuces an ssi retry failure error message to the user:
   84: #
   85: 
   86: sub ssi_print_error {
   87:     my ($r) = @_;
   88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   89:     $r->print('
   90: <br />
   91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   92: <p>
   93: '.&mt('Unable to retrieve a resource from a server:').'<br />
   94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   95: '.&mt('Error:').' '.$ssi_error_message.'
   96: </p>
   97: <p>'.
   98: &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 />'.
   99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  100: '</p>');
  101:     return;
  102: }
  103: 
  104: #
  105: # --- Retrieve the parts from the metadata file.---
  106: # Returns an array of everything that the resources stores away
  107: #
  108: 
  109: sub getpartlist {
  110:     my ($symb,$errorref) = @_;
  111: 
  112:     my $navmap   = Apache::lonnavmaps::navmap->new();
  113:     unless (ref($navmap)) {
  114:         if (ref($errorref)) { 
  115:             $$errorref = 'navmap';
  116:             return;
  117:         }
  118:     }
  119:     my $res      = $navmap->getBySymb($symb);
  120:     my $partlist = $res->parts();
  121:     my $url      = $res->src();
  122:     my $toolsymb;
  123:     if ($url =~ /ext\.tool$/) {
  124:         $toolsymb = $symb;
  125:     }
  126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  127: 
  128:     my @stores;
  129:     foreach my $part (@{ $partlist }) {
  130: 	foreach my $key (@metakeys) {
  131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  132: 	}
  133:     }
  134:     return @stores;
  135: }
  136: 
  137: #--- Format fullname, username:domain if different for display
  138: #--- Use anywhere where the student names are listed
  139: sub nameUserString {
  140:     my ($type,$fullname,$uname,$udom) = @_;
  141:     if ($type eq 'header') {
  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  143:     } else {
  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  146:     }
  147: }
  148: 
  149: #--- Get the partlist and the response type for a given problem. ---
  150: #--- Count responseIDs, essayresponse items, and dropbox items ---
  151: #--- Sets response_error pointer to "1" if navmaps object broken ---
  152: sub response_type {
  153:     my ($symb,$response_error) = @_;
  154: 
  155:     my $navmap = Apache::lonnavmaps::navmap->new();
  156:     unless (ref($navmap)) {
  157:         if (ref($response_error)) {
  158:             $$response_error = 1;
  159:         }
  160:         return;
  161:     }
  162:     my $res = $navmap->getBySymb($symb);
  163:     unless (ref($res)) {
  164:         $$response_error = 1;
  165:         return;
  166:     }
  167:     my $partlist = $res->parts();
  168:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
  169:     my %vPart = 
  170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  171:     my (%response_types,%handgrade);
  172:     foreach my $part (@{ $partlist }) {
  173: 	next if (%vPart && !exists($vPart{$part}));
  174: 
  175: 	my @types = $res->responseType($part);
  176: 	my @ids = $res->responseIds($part);
  177: 	for (my $i=0; $i < scalar(@ids); $i++) {
  178:             $numresp ++;
  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  180:             if ($types[$i] eq 'essay') {
  181:                 $numessay ++;
  182:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
  183:                     $numdropbox ++;
  184:                 }
  185:             }
  186: 	    $handgrade{$part.'_'.$ids[$i]} = 
  187: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  188: 				     '.handgrade',$symb);
  189: 	}
  190:     }
  191:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
  192: }
  193: 
  194: sub flatten_responseType {
  195:     my ($responseType) = @_;
  196:     my @part_response_id =
  197: 	map { 
  198: 	    my $part = $_;
  199: 	    map {
  200: 		[$part,$_]
  201: 		} sort(keys(%{ $responseType->{$part} }));
  202: 	} sort(keys(%$responseType));
  203:     return @part_response_id;
  204: }
  205: 
  206: sub get_display_part {
  207:     my ($partID,$symb)=@_;
  208:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  209:     if (defined($display) and $display ne '') {
  210:         $display.= ' (<span class="LC_internal_info">'
  211:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  212:     } else {
  213: 	$display=$partID;
  214:     }
  215:     return $display;
  216: }
  217: 
  218: #--- Show parts and response type
  219: sub showResourceInfo {
  220:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
  221:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
  222:         return '<br clear="all">';
  223:     }
  224:     my $coltitle = &mt('Problem Part Shown');
  225:     if ($checkboxes) {
  226:         $coltitle = &mt('Problem Part');
  227:     } else {
  228:         my $checkedparts = 0;
  229:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
  230:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
  231:                 $checkedparts ++;
  232:             }
  233:         }
  234:         if ($checkedparts == scalar(@{$partlist})) {
  235:             return '<br clear="all">';
  236:         }
  237:         if ($uploads) {
  238:             $coltitle = &mt('Problem Part Selected');
  239:         }
  240:     }
  241:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
  242:     if ($checkboxes) {
  243:         my $legend = &mt('Parts to display');
  244:         if ($uploads) {
  245:             $legend = &mt('Part(s) with dropbox');
  246:         }
  247:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
  248:                    '<span class="LC_nobreak">'.
  249:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
  250:                    &mt('All parts').'</label>'.('&nbsp;'x2).
  251:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
  252:                    &mt('Selected parts').'</label></span>'.
  253:                    '<div id="LC_partselector" style="display:none">';
  254:     }
  255:     $result .= &Apache::loncommon::start_data_table()
  256:               .&Apache::loncommon::start_data_table_header_row();
  257:     if ($checkboxes) {
  258:         $result .= '<th>'.&mt('Display?').'</th>';
  259:     }
  260:     $result .= '<th>'.$coltitle.'</th>'
  261:               .'<th>'.&mt('Res. ID').'</th>'
  262:               .'<th>'.&mt('Type').'</th>'
  263:               .&Apache::loncommon::end_data_table_header_row();
  264:     my %partsseen;
  265:     foreach my $partID (sort(keys(%$responseType))) {
  266:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  267:             my $responsetype = $responseType->{$partID}->{$resID};
  268:             if ($uploads) {
  269:                 next unless ($responsetype eq 'essay');
  270:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
  271:             }
  272:             my $display_part=&get_display_part($partID,$symb);
  273:             if (exists($partsseen{$partID})) {
  274:                 $result.=&Apache::loncommon::continue_data_table_row();
  275:             } else {
  276:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
  277:                 $result.=&Apache::loncommon::start_data_table_row().
  278:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
  279:                 if ($checkboxes) {
  280:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
  281:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
  282:                 } else {
  283:                     $result.=$display_part.'</td>';
  284:                 }
  285:             }
  286:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  287:                     .'<td>'.&mt($responsetype).'</td>'
  288:                     .&Apache::loncommon::end_data_table_row();
  289:         }
  290:     }
  291:     $result.=&Apache::loncommon::end_data_table();
  292:     if ($checkboxes) {
  293:         $result .= '</div></fieldset>';
  294:     }
  295:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
  296:     if (!keys(%partsseen)) {
  297:         $result = '';
  298:         if ($uploads) {
  299:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
  300:                    '<p class="LC_info">'.
  301:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
  302:                    '</p>';
  303:         } else {
  304:             return '<br clear="all" />';
  305:         }
  306:     }
  307:     return $result;
  308: }
  309: 
  310: sub part_selector_js {
  311:     my $js = <<"END";
  312: function toggleParts(formname) {
  313:     if (document.getElementById('LC_partselector')) {
  314:         var index = '';
  315:         if (document.forms.length) {
  316:             for (var i=0; i<document.forms.length; i++) {
  317:                 if (document.forms[i].name == formname) {
  318:                     index = i;
  319:                     break;
  320:                 }
  321:             }
  322:         }
  323:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  324:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  325:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  326:                    var val = document.forms[index].elements['chooseparts'][i].value;
  327:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  328:                         document.getElementById('LC_partselector').style.display = 'block';
  329:                     } else {
  330:                         document.getElementById('LC_partselector').style.display = 'none';
  331:                     }
  332:                 }
  333:             }
  334:         }
  335:     }
  336: }
  337: END
  338:     return &Apache::lonhtmlcommon::scripttag($js);
  339: }
  340: 
  341: sub reset_caches {
  342:     &reset_analyze_cache();
  343:     &reset_perm();
  344:     &reset_old_essays();
  345: }
  346: 
  347: {
  348:     my %analyze_cache;
  349:     my %analyze_cache_formkeys;
  350: 
  351:     sub reset_analyze_cache {
  352: 	undef(%analyze_cache);
  353:         undef(%analyze_cache_formkeys);
  354:     }
  355: 
  356:     sub get_analyze {
  357: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  358: 	my $key = "$symb\0$uname\0$udom";
  359:         if ($type eq 'randomizetry') {
  360:             if ($trial ne '') {
  361:                 $key .= "\0".$trial;
  362:             }
  363:         }
  364: 	if (exists($analyze_cache{$key})) {
  365:             my $getupdate = 0;
  366:             if (ref($add_to_hash) eq 'HASH') {
  367:                 foreach my $item (keys(%{$add_to_hash})) {
  368:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  369:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  370:                             $getupdate = 1;
  371:                             last;
  372:                         }
  373:                     } else {
  374:                         $getupdate = 1;
  375:                     }
  376:                 }
  377:             }
  378:             if (!$getupdate) {
  379:                 return $analyze_cache{$key};
  380:             }
  381:         }
  382: 
  383: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  384: 	$url=&Apache::lonnet::clutter($url);
  385:         my %form = ('grade_target'      => 'analyze',
  386:                     'grade_domain'      => $udom,
  387:                     'grade_symb'        => $symb,
  388:                     'grade_courseid'    =>  $env{'request.course.id'},
  389:                     'grade_username'    => $uname,
  390:                     'grade_noincrement' => $no_increment);
  391:         if ($bubbles_per_row ne '') {
  392:             $form{'bubbles_per_row'} = $bubbles_per_row;
  393:         }
  394:         if ($type eq 'randomizetry') {
  395:             $form{'grade_questiontype'} = $type;
  396:             if ($rndseed ne '') {
  397:                 $form{'grade_rndseed'} = $rndseed;
  398:             }
  399:         }
  400:         if (ref($add_to_hash)) {
  401:             %form = (%form,%{$add_to_hash});
  402:         }
  403: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  404: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  405: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  406:         if (ref($add_to_hash) eq 'HASH') {
  407:             $analyze_cache_formkeys{$key} = $add_to_hash;
  408:         } else {
  409:             $analyze_cache_formkeys{$key} = {};
  410:         }
  411: 	return $analyze_cache{$key} = \%analyze;
  412:     }
  413: 
  414:     sub get_order {
  415: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  416: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  417: 	return $analyze->{"$partid.$respid.shown"};
  418:     }
  419: 
  420:     sub get_radiobutton_correct_foil {
  421: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  422: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  423:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  424:         if (ref($foils) eq 'ARRAY') {
  425: 	    foreach my $foil (@{$foils}) {
  426: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  427: 		    return $foil;
  428: 	        }
  429: 	    }
  430: 	}
  431:     }
  432: 
  433:     sub scantron_partids_tograde {
  434:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  435:         my (%analysis,@parts);
  436:         if (ref($resource)) {
  437:             my $symb = $resource->symb();
  438:             my $add_to_form;
  439:             if ($check_for_randomlist) {
  440:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  441:             }
  442:             if ($scancode) {
  443:                 if (ref($add_to_form) eq 'HASH') {
  444:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  445:                 } else {
  446:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  447:                 }
  448:             }
  449:             my $analyze =
  450:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  451:                              undef,undef,undef,$bubbles_per_row);
  452:             if (ref($analyze) eq 'HASH') {
  453:                 %analysis = %{$analyze};
  454:             }
  455:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  456:                 foreach my $part (@{$analysis{'parts'}}) {
  457:                     my ($id,$respid) = split(/\./,$part);
  458:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  459:                         push(@parts,$part);
  460:                     }
  461:                 }
  462:             }
  463:         }
  464:         return (\%analysis,\@parts);
  465:     }
  466: 
  467: }
  468: 
  469: #--- Clean response type for display
  470: #--- Currently filters option/rank/radiobutton/match/essay/Task
  471: #        response types only.
  472: sub cleanRecord {
  473:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  474: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  475:     my $grayFont = '<span class="LC_internal_info">';
  476:     if ($response =~ /^(option|rank)$/) {
  477: 	my %answer=&Apache::lonnet::str2hash($answer);
  478:         my @answer = %answer;
  479:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  480: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  481: 	my ($toprow,$bottomrow);
  482: 	foreach my $foil (@$order) {
  483: 	    if ($grading{$foil} == 1) {
  484: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  485: 	    } else {
  486: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  487: 	    }
  488: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  489: 	}
  490: 	return '<blockquote><table border="1">'.
  491: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  492: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  493: 	    $bottomrow.'</tr></table></blockquote>';
  494:     } elsif ($response eq 'match') {
  495: 	my %answer=&Apache::lonnet::str2hash($answer);
  496:         my @answer = %answer;
  497:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  498: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  499: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  500: 	my ($toprow,$middlerow,$bottomrow);
  501: 	foreach my $foil (@$order) {
  502: 	    my $item=shift(@items);
  503: 	    if ($grading{$foil} == 1) {
  504: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  505: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  506: 	    } else {
  507: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  508: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  509: 	    }
  510: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  511: 	}
  512: 	return '<blockquote><table border="1">'.
  513: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  514: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  515: 	    $middlerow.'</tr>'.
  516: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  517: 	    $bottomrow.'</tr></table></blockquote>';
  518:     } elsif ($response eq 'radiobutton') {
  519: 	my %answer=&Apache::lonnet::str2hash($answer);
  520:         my @answer = %answer;
  521:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  522: 	my ($toprow,$bottomrow);
  523: 	my $correct = 
  524: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  525: 	foreach my $foil (@$order) {
  526: 	    if (exists($answer{$foil})) {
  527: 		if ($foil eq $correct) {
  528: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  529: 		} else {
  530: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  531: 		}
  532: 	    } else {
  533: 		$toprow.='<td>'.&mt('false').'</td>';
  534: 	    }
  535: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  536: 	}
  537: 	return '<blockquote><table border="1">'.
  538: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  539: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  540: 	    $bottomrow.'</tr></table></blockquote>';
  541:     } elsif ($response eq 'essay') {
  542: 	if (! exists ($env{'form.'.$symb})) {
  543: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  544: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  545: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  546: 
  547: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  548: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  549: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  550: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  551: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  552: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  553: 	}
  554:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  555: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  556:     } elsif ( $response eq 'organic') {
  557:         my $result=&mt('Smile representation: [_1]',
  558:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  559: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  560: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  561: 	return $result;
  562:     } elsif ( $response eq 'Task') {
  563: 	if ( $answer eq 'SUBMITTED') {
  564: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  565: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  566: 	    return $result;
  567: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  568: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  569: 			       keys(%{$record}));
  570: 	    return join('<br />',($version,@matches));
  571: 			       
  572: 			       
  573: 	} else {
  574: 	    my $result =
  575: 		'<p>'
  576: 		.&mt('Overall result: [_1]',
  577: 		     $record->{$version."resource.$respid.$partid.status"})
  578: 		.'</p>';
  579: 	    
  580: 	    $result .= '<ul>';
  581: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  582: 			     keys(%{$record}));
  583: 	    foreach my $grade (sort(@grade)) {
  584: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  585: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  586: 				     $dim, $record->{$grade}).
  587: 			  '</li>';
  588: 	    }
  589: 	    $result.='</ul>';
  590: 	    return $result;
  591: 	}
  592:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  593:         # Respect multiple input fields, see Bug #5409
  594: 	$answer = 
  595: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  596: 							      $answer);
  597: 	return $answer;
  598:     }
  599:     return &HTML::Entities::encode($answer, '"<>&');
  600: }
  601: 
  602: #-- A couple of common js functions
  603: sub commonJSfunctions {
  604:     my $request = shift;
  605:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  606:     function radioSelection(radioButton) {
  607: 	var selection=null;
  608: 	if (radioButton.length > 1) {
  609: 	    for (var i=0; i<radioButton.length; i++) {
  610: 		if (radioButton[i].checked) {
  611: 		    return radioButton[i].value;
  612: 		}
  613: 	    }
  614: 	} else {
  615: 	    if (radioButton.checked) return radioButton.value;
  616: 	}
  617: 	return selection;
  618:     }
  619: 
  620:     function pullDownSelection(selectOne) {
  621: 	var selection="";
  622: 	if (selectOne.length > 1) {
  623: 	    for (var i=0; i<selectOne.length; i++) {
  624: 		if (selectOne[i].selected) {
  625: 		    return selectOne[i].value;
  626: 		}
  627: 	    }
  628: 	} else {
  629:             // only one value it must be the selected one
  630: 	    return selectOne.value;
  631: 	}
  632:     }
  633: COMMONJSFUNCTIONS
  634: }
  635: 
  636: #--- Dumps the class list with usernames,list of sections,
  637: #--- section, ids and fullnames for each user.
  638: sub getclasslist {
  639:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  640:     my @getsec;
  641:     my @getgroup;
  642:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  643:     if (!ref($getsec)) {
  644: 	if ($getsec ne '' && $getsec ne 'all') {
  645: 	    @getsec=($getsec);
  646: 	}
  647:     } else {
  648: 	@getsec=@{$getsec};
  649:     }
  650:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  651:     if (!ref($getgroup)) {
  652: 	if ($getgroup ne '' && $getgroup ne 'all') {
  653: 	    @getgroup=($getgroup);
  654: 	}
  655:     } else {
  656: 	@getgroup=@{$getgroup};
  657:     }
  658:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  659: 
  660:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  661:     # Bail out if we were unable to get the classlist
  662:     return if (! defined($classlist));
  663:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  664:     #
  665:     my %sections;
  666:     my %fullnames;
  667:     my ($cdom,$cnum,$partlist);
  668:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  669:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  670:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  671:         my $res_error;
  672:         ($partlist) = &response_type($symb,\$res_error);
  673:     }
  674:     foreach my $student (keys(%$classlist)) {
  675:         my $end      = 
  676:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  677:         my $start    = 
  678:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  679:         my $id       = 
  680:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  681:         my $section  = 
  682:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  683:         my $fullname = 
  684:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  685:         my $status   = 
  686:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  687:         my $group   = 
  688:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  689: 	# filter students according to status selected
  690: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  691: 	    if (!($stu_status =~ $status)) {
  692: 		delete($classlist->{$student});
  693: 		next;
  694: 	    }
  695: 	}
  696: 	# filter students according to groups selected
  697: 	my @stu_groups = split(/,/,$group);
  698: 	if (@getgroup) {
  699: 	    my $exclude = 1;
  700: 	    foreach my $grp (@getgroup) {
  701: 	        foreach my $stu_group (@stu_groups) {
  702: 	            if ($stu_group eq $grp) {
  703: 	                $exclude = 0;
  704:     	            } 
  705: 	        }
  706:     	        if (($grp eq 'none') && !$group) {
  707:         	    $exclude = 0;
  708:         	}
  709: 	    }
  710: 	    if ($exclude) {
  711: 	        delete($classlist->{$student});
  712: 		next;
  713: 	    }
  714: 	}
  715:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  716:             my $udom =
  717:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  718:             my $uname =
  719:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  720:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  721:                 if ($submitonly eq 'queued') {
  722:                     my %queue_status =
  723:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  724:                                                                 $udom,$uname);
  725:                     if (!defined($queue_status{'gradingqueue'})) {
  726:                         delete($classlist->{$student});
  727:                         next;
  728:                     }
  729:                 } else {
  730:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  731:                     my $submitted = 0;
  732:                     my $graded = 0;
  733:                     my $incorrect = 0;
  734:                     foreach (keys(%status)) {
  735:                         $submitted = 1 if ($status{$_} ne 'nothing');
  736:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  737:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  738: 
  739:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  740:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  741:                             $submitted = 0;
  742:                         }
  743:                     }
  744:                     if (!$submitted && ($submitonly eq 'yes' ||
  745:                                         $submitonly eq 'incorrect' ||
  746:                                         $submitonly eq 'graded')) {
  747:                         delete($classlist->{$student});
  748:                         next;
  749:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  750:                         delete($classlist->{$student});
  751:                         next;
  752:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  753:                         delete($classlist->{$student});
  754:                         next;
  755:                     }
  756:                 }
  757:             }
  758:         }
  759: 	$section = ($section ne '' ? $section : 'none');
  760: 	if (&canview($section)) {
  761: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  762: 		$sections{$section}++;
  763: 		if ($classlist->{$student}) {
  764: 		    $fullnames{$student}=$fullname;
  765: 		}
  766: 	    } else {
  767: 		delete($classlist->{$student});
  768: 	    }
  769: 	} else {
  770: 	    delete($classlist->{$student});
  771: 	}
  772:     }
  773:     my @sections = sort(keys(%sections));
  774:     return ($classlist,\@sections,\%fullnames);
  775: }
  776: 
  777: sub canmodify {
  778:     my ($sec)=@_;
  779:     if ($perm{'mgr'}) {
  780: 	if (!defined($perm{'mgr_section'})) {
  781: 	    # can modify whole class
  782: 	    return 1;
  783: 	} else {
  784: 	    if ($sec eq $perm{'mgr_section'}) {
  785: 		#can modify the requested section
  786: 		return 1;
  787: 	    } else {
  788: 		# can't modify the requested section
  789: 		return 0;
  790: 	    }
  791: 	}
  792:     }
  793:     #can't modify
  794:     return 0;
  795: }
  796: 
  797: sub canview {
  798:     my ($sec)=@_;
  799:     if ($perm{'vgr'}) {
  800: 	if (!defined($perm{'vgr_section'})) {
  801: 	    # can view whole class
  802: 	    return 1;
  803: 	} else {
  804: 	    if ($sec eq $perm{'vgr_section'}) {
  805: 		#can view the requested section
  806: 		return 1;
  807: 	    } else {
  808: 		# can't view the requested section
  809: 		return 0;
  810: 	    }
  811: 	}
  812:     }
  813:     #can't view
  814:     return 0;
  815: }
  816: 
  817: #--- Retrieve the grade status of a student for all the parts
  818: sub student_gradeStatus {
  819:     my ($symb,$udom,$uname,$partlist) = @_;
  820:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  821:     my %partstatus = ();
  822:     foreach (@$partlist) {
  823: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  824: 	$status              = 'nothing' if ($status eq '');
  825: 	$partstatus{$_}      = $status;
  826: 	my $subkey           = "resource.$_.submitted_by";
  827: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  828:     }
  829:     return %partstatus;
  830: }
  831: 
  832: # hidden form and javascript that calls the form
  833: # Use by verifyscript and viewgrades
  834: # Shows a student's view of problem and submission
  835: sub jscriptNform {
  836:     my ($symb) = @_;
  837:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  838:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  839: 	'    function viewOneStudent(user,domain) {'."\n".
  840: 	'	document.onestudent.student.value = user;'."\n".
  841: 	'	document.onestudent.userdom.value = domain;'."\n".
  842: 	'	document.onestudent.submit();'."\n".
  843: 	'    }'."\n".
  844: 	"\n");
  845:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  846: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  847: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  848: 	'<input type="hidden" name="command" value="submission" />'."\n".
  849: 	'<input type="hidden" name="student" value="" />'."\n".
  850: 	'<input type="hidden" name="userdom" value="" />'."\n".
  851: 	'</form>'."\n";
  852:     return $jscript;
  853: }
  854: 
  855: 
  856: 
  857: # Given the score (as a number [0-1] and the weight) what is the final
  858: # point value? This function will round to the nearest tenth, third,
  859: # or quarter if one of those is within the tolerance of .00001.
  860: sub compute_points {
  861:     my ($score, $weight) = @_;
  862:     
  863:     my $tolerance = .00001;
  864:     my $points = $score * $weight;
  865: 
  866:     # Check for nearness to 1/x.
  867:     my $check_for_nearness = sub {
  868:         my ($factor) = @_;
  869:         my $num = ($points * $factor) + $tolerance;
  870:         my $floored_num = floor($num);
  871:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  872:             return $floored_num / $factor;
  873:         }
  874:         return $points;
  875:     };
  876: 
  877:     $points = $check_for_nearness->(10);
  878:     $points = $check_for_nearness->(3);
  879:     $points = $check_for_nearness->(4);
  880:     
  881:     return $points;
  882: }
  883: 
  884: #------------------ End of general use routines --------------------
  885: 
  886: #
  887: # Find most similar essay
  888: #
  889: 
  890: sub most_similar {
  891:     my ($uname,$udom,$symb,$uessay)=@_;
  892: 
  893:     unless ($symb) { return ''; }
  894: 
  895:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  896: 
  897: # ignore spaces and punctuation
  898: 
  899:     $uessay=~s/\W+/ /gs;
  900: 
  901: # ignore empty submissions (occuring when only files are sent)
  902: 
  903:     unless ($uessay=~/\w+/s) { return ''; }
  904: 
  905: # these will be returned. Do not care if not at least 50 percent similar
  906:     my $limit=0.6;
  907:     my $sname='';
  908:     my $sdom='';
  909:     my $scrsid='';
  910:     my $sessay='';
  911: # go through all essays ...
  912:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  913: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  914: # ... except the same student
  915:         next if (($tname eq $uname) && ($tdom eq $udom));
  916: 	my $tessay=$old_essays{$symb}{$tkey};
  917: 	$tessay=~s/\W+/ /gs;
  918: # String similarity gives up if not even limit
  919: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  920: # Found one
  921: 	if ($tsimilar>$limit) {
  922: 	    $limit=$tsimilar;
  923: 	    $sname=$tname;
  924: 	    $sdom=$tdom;
  925: 	    $scrsid=$tcrsid;
  926: 	    $sessay=$old_essays{$symb}{$tkey};
  927: 	}
  928:     }
  929:     if ($limit>0.6) {
  930:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  931:     } else {
  932:        return ('','','','',0);
  933:     }
  934: }
  935: 
  936: #-------------------------------------------------------------------
  937: 
  938: #------------------------------------ Receipt Verification Routines
  939: #
  940: 
  941: sub initialverifyreceipt {
  942:    my ($request,$symb) = @_;
  943:    &commonJSfunctions($request);
  944:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  945:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  946:         '-<input type="text" name="receipt" size="4" />'.
  947:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  948:         '<input type="hidden" name="command" value="verify" />'.
  949:         "</form>\n";
  950: }
  951: 
  952: #--- Check whether a receipt number is valid.---
  953: sub verifyreceipt {
  954:     my ($request,$symb) = @_;
  955: 
  956:     my $courseid = $env{'request.course.id'};
  957:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  958: 	$env{'form.receipt'};
  959:     $receipt     =~ s/[^\-\d]//g;
  960: 
  961:     my $title =
  962: 	'<h3><span class="LC_info">'.
  963: 	&mt('Verifying Receipt Number [_1]',$receipt).
  964: 	'</span></h3>'."\n";
  965: 
  966:     my ($string,$contents,$matches) = ('','',0);
  967:     my (undef,undef,$fullname) = &getclasslist('all','0');
  968:     
  969:     my $receiptparts=0;
  970:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  971: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  972:     my $parts=['0'];
  973:     if ($receiptparts) {
  974:         my $res_error; 
  975:         ($parts)=&response_type($symb,\$res_error);
  976:         if ($res_error) {
  977:             return &navmap_errormsg();
  978:         } 
  979:     }
  980:     
  981:     my $header = 
  982: 	&Apache::loncommon::start_data_table().
  983: 	&Apache::loncommon::start_data_table_header_row().
  984: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  985: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  986: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  987:     if ($receiptparts) {
  988: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  989:     }
  990:     $header.=
  991: 	&Apache::loncommon::end_data_table_header_row();
  992: 
  993:     foreach (sort 
  994: 	     {
  995: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  996: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  997: 		 }
  998: 		 return $a cmp $b;
  999: 	     } (keys(%$fullname))) {
 1000: 	my ($uname,$udom)=split(/\:/);
 1001: 	foreach my $part (@$parts) {
 1002: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
 1003: 		$contents.=
 1004: 		    &Apache::loncommon::start_data_table_row().
 1005: 		    '<td>&nbsp;'."\n".
 1006: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 1007: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
 1008: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
 1009: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
 1010: 		if ($receiptparts) {
 1011: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1012: 		}
 1013: 		$contents.= 
 1014: 		    &Apache::loncommon::end_data_table_row()."\n";
 1015: 		
 1016: 		$matches++;
 1017: 	    }
 1018: 	}
 1019:     }
 1020:     if ($matches == 0) {
 1021:         $string = $title
 1022:                  .'<p class="LC_warning">'
 1023:                  .&mt('No match found for the above receipt number.')
 1024:                  .'</p>';
 1025:     } else {
 1026: 	$string = &jscriptNform($symb).$title.
 1027: 	    '<p>'.
 1028: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1029: 	    '</p>'.
 1030: 	    $header.
 1031: 	    $contents.
 1032: 	    &Apache::loncommon::end_data_table()."\n";
 1033:     }
 1034:     return $string;
 1035: }
 1036: 
 1037: #--- This is called by a number of programs.
 1038: #--- Called from the Grading Menu - View/Grade an individual student
 1039: #--- Also called directly when one clicks on the subm button 
 1040: #    on the problem page.
 1041: sub listStudents {
 1042:     my ($request,$symb,$submitonly,$divforres) = @_;
 1043: 
 1044:     my $is_tool   = ($symb =~ /ext\.tool$/);
 1045:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1046:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1047:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1048:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1049:     unless ($submitonly) {
 1050:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1051:     }
 1052: 
 1053:     my $result='';
 1054:     my $res_error;
 1055:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1056: 
 1057:     my $table;
 1058:     if (ref($partlist) eq 'ARRAY') {
 1059:         if (scalar(@$partlist) > 1 ) {
 1060:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1061:         } elsif ($divforres) {
 1062:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1063:         } else {
 1064:             $table = '<br clear="all" />';
 1065:         }
 1066:     }
 1067: 
 1068:     my %js_lt = &Apache::lonlocal::texthash (
 1069: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1070: 		'single'   => 'Please select the student before clicking on the Next button.',
 1071: 	     );
 1072:     &js_escape(\%js_lt);
 1073:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1074:     function checkSelect(checkBox) {
 1075: 	var ctr=0;
 1076: 	var sense="";
 1077: 	if (checkBox.length > 1) {
 1078: 	    for (var i=0; i<checkBox.length; i++) {
 1079: 		if (checkBox[i].checked) {
 1080: 		    ctr++;
 1081: 		}
 1082: 	    }
 1083: 	    sense = '$js_lt{'multiple'}';
 1084: 	} else {
 1085: 	    if (checkBox.checked) {
 1086: 		ctr = 1;
 1087: 	    }
 1088: 	    sense = '$js_lt{'single'}';
 1089: 	}
 1090: 	if (ctr == 0) {
 1091: 	    alert(sense);
 1092: 	    return false;
 1093: 	}
 1094: 	document.gradesub.submit();
 1095:     }
 1096: 
 1097:     function reLoadList(formname) {
 1098: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1099: 	formname.command.value = 'submission';
 1100: 	formname.submit();
 1101:     }
 1102: LISTJAVASCRIPT
 1103: 
 1104:     &commonJSfunctions($request);
 1105:     $request->print($result);
 1106: 
 1107:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1108: 	"\n".$table;
 1109: 
 1110:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1111:     unless ($is_tool) {
 1112:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1113:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1114:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1115:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1116:                       .&Apache::lonhtmlcommon::row_closure();
 1117:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1118:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1119:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1120:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1121:                       .&Apache::lonhtmlcommon::row_closure();
 1122:     }
 1123: 
 1124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1125:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1126:     $env{'form.Status'} = $saveStatus;
 1127:     my %optiontext;
 1128:     if ($is_tool) {
 1129:         %optiontext = &Apache::lonlocal::texthash (
 1130:                           lastonly => 'last transaction',
 1131:                           last     => 'last transaction with details',
 1132:                           datesub  => 'all transactions',
 1133:                           all      => 'all transactions with details',
 1134:                       );
 1135:     } else {
 1136:         %optiontext = &Apache::lonlocal::texthash (
 1137:                           lastonly => 'last submission',
 1138:                           last     => 'last submission with details',
 1139:                           datesub  => 'all submissions',
 1140:                           all      => 'all submissions with details',
 1141:                       );
 1142:     }
 1143:     my $submission_options =
 1144:         '<span class="LC_nobreak">'.
 1145:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1146:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1147:         '<span class="LC_nobreak">'.
 1148:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1149:         $optiontext{'last'}.' </label></span>'."\n".
 1150:         '<span class="LC_nobreak">'.
 1151:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1152:         $optiontext{'datesub'}.'</label></span>'."\n".
 1153:         '<span class="LC_nobreak">'.
 1154:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1155:         $optiontext{'all'}.'</label></span>';
 1156:     my $viewtitle;
 1157:     if ($is_tool) {
 1158:         $viewtitle = &mt('View Transactions');
 1159:     } else {
 1160:         $viewtitle = &mt('View Submissions');
 1161:     }
 1162:     my ($compmsg,$nocompmsg);
 1163:     $nocompmsg = ' checked="checked"';
 1164:     if ($numessay) {
 1165:         $compmsg = $nocompmsg;
 1166:         $nocompmsg = '';
 1167:     }
 1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1169:                   .$submission_options;
 1170: # Check if any gradable
 1171:     my $showmore;
 1172:     if ($perm{'mgr'}) {
 1173:         my @sections;
 1174:         if ($env{'request.course.sec'} ne '') {
 1175:             @sections = ($env{'request.course.sec'});
 1176:         } elsif ($env{'form.section'} eq '') {
 1177:             @sections = ('all');
 1178:         } else {
 1179:             @sections = &Apache::loncommon::get_env_multiple('form.section');
 1180:         }
 1181:         if (grep(/^all$/,@sections)) {
 1182:             $showmore = 1;
 1183:         } else {
 1184:             foreach my $sec (@sections) {
 1185:                 if (&canmodify($sec)) {
 1186:                     $showmore = 1;
 1187:                     last;
 1188:                 }
 1189:             }
 1190:         }
 1191:     }
 1192: 
 1193:     if ($showmore) {
 1194:         $gradeTable .=
 1195:                    &Apache::lonhtmlcommon::row_closure()
 1196:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1197:                   .'<span class="LC_nobreak">'
 1198:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1199:                   .&mt('No').('&nbsp;'x2).'</label>'
 1200:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1201:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1202:                   .&Apache::lonhtmlcommon::row_closure();
 1203: 
 1204:         $gradeTable .= 
 1205:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1206:                   .'<select name="increment">'
 1207:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1208:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1209:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1210:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1211:                   .'</select>';
 1212:     }
 1213:     $gradeTable .= 
 1214:         &build_section_inputs().
 1215: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1216: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1217: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1218:     if (exists($env{'form.Status'})) {
 1219: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
 1220:     } else {
 1221:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1222:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1223:                       .&Apache::lonhtmlcommon::StatusOptions(
 1224:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1225:     }
 1226:     if ($numessay) {
 1227:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1228:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1229:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1230:     }
 1231:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1232:                   .&Apache::lonhtmlcommon::end_pick_box();
 1233:     my $regrademsg;
 1234:     if ($is_tool) {
 1235:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1236:     } else {
 1237:         $regrademsg = &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.");
 1238:     }
 1239:     $gradeTable .= '<p>'
 1240:                   .$regrademsg."\n"
 1241:                   .'<input type="hidden" name="command" value="processGroup" />'
 1242:                   .'</p>';
 1243: 
 1244: # checkall buttons
 1245:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1246:     $gradeTable.='<input type="button" '."\n".
 1247:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1248:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1249:     $gradeTable.=&check_buttons();
 1250:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1251:     $gradeTable.= &Apache::loncommon::start_data_table().
 1252: 	&Apache::loncommon::start_data_table_header_row();
 1253:     my $loop = 0;
 1254:     while ($loop < 2) {
 1255: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1256: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1257: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1258: 	    foreach my $part (sort(@$partlist)) {
 1259: 		my $display_part=
 1260: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1261: 		$gradeTable.=
 1262: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1263: 	    }
 1264: 	} elsif ($submitonly eq 'queued') {
 1265: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1266: 	}
 1267: 	$loop++;
 1268: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1269:     }
 1270:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1271: 
 1272:     my $ctr = 0;
 1273:     foreach my $student (sort 
 1274: 			 {
 1275: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1276: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1277: 			     }
 1278: 			     return $a cmp $b;
 1279: 			 }
 1280: 			 (keys(%$fullname))) {
 1281: 	my ($uname,$udom) = split(/:/,$student);
 1282: 
 1283: 	my %status = ();
 1284: 
 1285: 	if ($submitonly eq 'queued') {
 1286: 	    my %queue_status = 
 1287: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1288: 							$udom,$uname);
 1289: 	    next if (!defined($queue_status{'gradingqueue'}));
 1290: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1291: 	}
 1292: 
 1293: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1294: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1295: 	    my $submitted = 0;
 1296: 	    my $graded = 0;
 1297: 	    my $incorrect = 0;
 1298: 	    foreach (keys(%status)) {
 1299: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1300: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1301: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1302: 		
 1303: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1304: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1305: 		    $submitted = 0;
 1306: 		    my ($part)=split(/\./,$partid);
 1307: 		    $gradeTable.='<input type="hidden" name="'.
 1308: 			$student.':'.$part.':submitted_by" value="'.
 1309: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1310: 		}
 1311: 	    }
 1312: 	    
 1313: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1314: 				     $submitonly eq 'incorrect' ||
 1315: 				     $submitonly eq 'graded'));
 1316: 	    next if (!$graded && ($submitonly eq 'graded'));
 1317: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1318: 	}
 1319: 
 1320: 	$ctr++;
 1321: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1322:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1323: 	if ( $perm{'vgr'} eq 'F' ) {
 1324: 	    if ($ctr%2 ==1) {
 1325: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1326: 	    }
 1327: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1328:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1329:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1330: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1331: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1332: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1333: 
 1334: 	    if ($submitonly ne 'all') {
 1335: 		foreach (sort(keys(%status))) {
 1336: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1337: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1338: 		}
 1339: 	    }
 1340: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1341: 	    if ($ctr%2 ==0) {
 1342: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1343: 	    }
 1344: 	}
 1345:     }
 1346:     if ($ctr%2 ==1) {
 1347: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1348: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1349: 		foreach (@$partlist) {
 1350: 		    $gradeTable.='<td>&nbsp;</td>';
 1351: 		}
 1352: 	    } elsif ($submitonly eq 'queued') {
 1353: 		$gradeTable.='<td>&nbsp;</td>';
 1354: 	    }
 1355: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1356:     }
 1357: 
 1358:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1359:         '<input type="button" '.
 1360:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1361:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1362:     if ($ctr == 0) {
 1363: 	my $num_students=(scalar(keys(%$fullname)));
 1364: 	if ($num_students eq 0) {
 1365: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1366: 	} else {
 1367: 	    my $submissions='submissions';
 1368: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1369: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1370: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1371: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1372: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1373: 		    $num_students).
 1374: 		'</span><br />';
 1375: 	}
 1376:     } elsif ($ctr == 1) {
 1377: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1378:     }
 1379:     $request->print($gradeTable);
 1380:     return '';
 1381: }
 1382: 
 1383: #---- Called from the listStudents routine
 1384: 
 1385: sub check_script {
 1386:     my ($form,$type) = @_;
 1387:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1388:     function checkall() {
 1389:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1390:             ele = document.forms.'.$form.'.elements[i];
 1391:             if (ele.name == "'.$type.'") {
 1392:             document.forms.'.$form.'.elements[i].checked=true;
 1393:                                        }
 1394:         }
 1395:     }
 1396: 
 1397:     function checksec() {
 1398:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1399:             ele = document.forms.'.$form.'.elements[i];
 1400:            string = document.forms.'.$form.'.chksec.value;
 1401:            if
 1402:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1403:               document.forms.'.$form.'.elements[i].checked=true;
 1404:             }
 1405:         }
 1406:     }
 1407: 
 1408: 
 1409:     function uncheckall() {
 1410:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1411:             ele = document.forms.'.$form.'.elements[i];
 1412:             if (ele.name == "'.$type.'") {
 1413:             document.forms.'.$form.'.elements[i].checked=false;
 1414:                                        }
 1415:         }
 1416:     }
 1417: 
 1418: '."\n");
 1419:     return $chkallscript;
 1420: }
 1421: 
 1422: sub check_buttons {
 1423:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1424:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1425:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1426:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1427:     return $buttons;
 1428: }
 1429: 
 1430: #     Displays the submissions for one student or a group of students
 1431: sub processGroup {
 1432:     my ($request,$symb) = @_;
 1433:     my $ctr        = 0;
 1434:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1435:     my $total      = scalar(@stuchecked)-1;
 1436: 
 1437:     foreach my $student (@stuchecked) {
 1438: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1439: 	$env{'form.student'}        = $uname;
 1440: 	$env{'form.userdom'}        = $udom;
 1441: 	$env{'form.fullname'}       = $fullname;
 1442: 	&submission($request,$ctr,$total,$symb);
 1443: 	$ctr++;
 1444:     }
 1445:     return '';
 1446: }
 1447: 
 1448: #------------------------------------------------------------------------------------
 1449: #
 1450: #-------------------------- Next few routines handles grading by student, essentially
 1451: #                           handles essay response type problem/part
 1452: #
 1453: #--- Javascript to handle the submission page functionality ---
 1454: sub sub_page_js {
 1455:     my $request = shift;
 1456:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1457:     &js_escape(\$alertmsg);
 1458:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1459:     function updateRadio(formname,id,weight) {
 1460: 	var gradeBox = formname["GD_BOX"+id];
 1461: 	var radioButton = formname["RADVAL"+id];
 1462: 	var oldpts = formname["oldpts"+id].value;
 1463: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1464: 	gradeBox.value = pts;
 1465: 	var resetbox = false;
 1466: 	if (isNaN(pts) || pts < 0) {
 1467: 	    alert("$alertmsg"+pts);
 1468: 	    for (var i=0; i<radioButton.length; i++) {
 1469: 		if (radioButton[i].checked) {
 1470: 		    gradeBox.value = i;
 1471: 		    resetbox = true;
 1472: 		}
 1473: 	    }
 1474: 	    if (!resetbox) {
 1475: 		formtextbox.value = "";
 1476: 	    }
 1477: 	    return;
 1478: 	}
 1479: 
 1480: 	if (pts > weight) {
 1481: 	    var resp = confirm("You entered a value ("+pts+
 1482: 			       ") greater than the weight for the part. Accept?");
 1483: 	    if (resp == false) {
 1484: 		gradeBox.value = oldpts;
 1485: 		return;
 1486: 	    }
 1487: 	}
 1488: 
 1489: 	for (var i=0; i<radioButton.length; i++) {
 1490: 	    radioButton[i].checked=false;
 1491: 	    if (pts == i && pts != "") {
 1492: 		radioButton[i].checked=true;
 1493: 	    }
 1494: 	}
 1495: 	updateSelect(formname,id);
 1496: 	formname["stores"+id].value = "0";
 1497:     }
 1498: 
 1499:     function writeBox(formname,id,pts) {
 1500: 	var gradeBox = formname["GD_BOX"+id];
 1501: 	if (checkSolved(formname,id) == 'update') {
 1502: 	    gradeBox.value = pts;
 1503: 	} else {
 1504: 	    var oldpts = formname["oldpts"+id].value;
 1505: 	    gradeBox.value = oldpts;
 1506: 	    var radioButton = formname["RADVAL"+id];
 1507: 	    for (var i=0; i<radioButton.length; i++) {
 1508: 		radioButton[i].checked=false;
 1509: 		if (i == oldpts) {
 1510: 		    radioButton[i].checked=true;
 1511: 		}
 1512: 	    }
 1513: 	}
 1514: 	formname["stores"+id].value = "0";
 1515: 	updateSelect(formname,id);
 1516: 	return;
 1517:     }
 1518: 
 1519:     function clearRadBox(formname,id) {
 1520: 	if (checkSolved(formname,id) == 'noupdate') {
 1521: 	    updateSelect(formname,id);
 1522: 	    return;
 1523: 	}
 1524: 	gradeSelect = formname["GD_SEL"+id];
 1525: 	for (var i=0; i<gradeSelect.length; i++) {
 1526: 	    if (gradeSelect[i].selected) {
 1527: 		var selectx=i;
 1528: 	    }
 1529: 	}
 1530: 	var stores = formname["stores"+id];
 1531: 	if (selectx == stores.value) { return };
 1532: 	var gradeBox = formname["GD_BOX"+id];
 1533: 	gradeBox.value = "";
 1534: 	var radioButton = formname["RADVAL"+id];
 1535: 	for (var i=0; i<radioButton.length; i++) {
 1536: 	    radioButton[i].checked=false;
 1537: 	}
 1538: 	stores.value = selectx;
 1539:     }
 1540: 
 1541:     function checkSolved(formname,id) {
 1542: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1543: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1544: 	    if (!reply) {return "noupdate";}
 1545: 	    formname.overRideScore.value = 'yes';
 1546: 	}
 1547: 	return "update";
 1548:     }
 1549: 
 1550:     function updateSelect(formname,id) {
 1551: 	formname["GD_SEL"+id][0].selected = true;
 1552: 	return;
 1553:     }
 1554: 
 1555: //=========== Check that a point is assigned for all the parts  ============
 1556:     function checksubmit(formname,val,total,parttot) {
 1557: 	formname.gradeOpt.value = val;
 1558: 	if (val == "Save & Next") {
 1559: 	    for (i=0;i<=total;i++) {
 1560: 		for (j=0;j<parttot;j++) {
 1561: 		    var partid = formname["partid"+i+"_"+j].value;
 1562: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1563: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1564: 			if (points == "") {
 1565: 			    var name = formname["name"+i].value;
 1566: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1567: 			    var resp = confirm("You did not assign a score for "+studentID+
 1568: 					       ", part "+partid+". Continue?");
 1569: 			    if (resp == false) {
 1570: 				formname["GD_BOX"+i+"_"+partid].focus();
 1571: 				return false;
 1572: 			    }
 1573: 			}
 1574: 		    }
 1575: 		}
 1576: 	    }
 1577: 	}
 1578: 	formname.submit();
 1579:     }
 1580: 
 1581: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1582:     function checkSubmitPage(formname,total) {
 1583: 	noscore = new Array(100);
 1584: 	var ptr = 0;
 1585: 	for (i=1;i<total;i++) {
 1586: 	    var partid = formname["q_"+i].value;
 1587: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1588: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1589: 		var status = formname["solved"+i+"_"+partid].value;
 1590: 		if (points == "" && status != "correct_by_student") {
 1591: 		    noscore[ptr] = i;
 1592: 		    ptr++;
 1593: 		}
 1594: 	    }
 1595: 	}
 1596: 	if (ptr != 0) {
 1597: 	    var sense = ptr == 1 ? ": " : "s: ";
 1598: 	    var prolist = "";
 1599: 	    if (ptr == 1) {
 1600: 		prolist = noscore[0];
 1601: 	    } else {
 1602: 		var i = 0;
 1603: 		while (i < ptr-1) {
 1604: 		    prolist += noscore[i]+", ";
 1605: 		    i++;
 1606: 		}
 1607: 		prolist += "and "+noscore[i];
 1608: 	    }
 1609: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1610: 	    if (resp == false) {
 1611: 		return false;
 1612: 	    }
 1613: 	}
 1614: 
 1615: 	formname.submit();
 1616:     }
 1617: SUBJAVASCRIPT
 1618: }
 1619: 
 1620: #--- javascript for grading message center
 1621: sub sub_grademessage_js {
 1622:     my $request = shift;
 1623:     my $iconpath = $request->dir_config('lonIconsURL');
 1624:     &commonJSfunctions($request);
 1625: 
 1626:     my $inner_js_msg_central= (<<INNERJS);
 1627: <script type="text/javascript">
 1628:     function checkInput() {
 1629:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1630:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1631:       var usrctr = document.msgcenter.usrctr.value;
 1632:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1633:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1634: 
 1635:       var msgchk = "";
 1636:       if (document.msgcenter.subchk.checked) {
 1637:          msgchk = "msgsub,";
 1638:       }
 1639:       var includemsg = 0;
 1640:       for (var i=1; i<=nmsg; i++) {
 1641:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1642:           var frmmsg = document.msgcenter["msg"+i];
 1643:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1644:           var showflg = opener.document.SCORE["shownOnce"+i];
 1645:           showflg.value = "1";
 1646:           var chkbox = document.msgcenter["msgn"+i];
 1647:           if (chkbox.checked) {
 1648:              msgchk += "savemsg"+i+",";
 1649:              includemsg = 1;
 1650:           }
 1651:       }
 1652:       if (document.msgcenter.newmsgchk.checked) {
 1653:          msgchk += "newmsg"+usrctr;
 1654:          includemsg = 1;
 1655:       }
 1656:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1657:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1658:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1659:       includemsg.value = msgchk;
 1660: 
 1661:       self.close()
 1662: 
 1663:     }
 1664: </script>
 1665: INNERJS
 1666: 
 1667:     my $start_page_msg_central =
 1668:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1669: 				       {'js_ready'  => 1,
 1670: 					'only_body' => 1,
 1671: 					'bgcolor'   =>'#FFFFFF',});
 1672:     my $end_page_msg_central =
 1673: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1674: 
 1675:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1676:     $docopen=~s/^document\.//;
 1677: 
 1678:     my %html_js_lt = &Apache::lonlocal::texthash(
 1679:                 comp => 'Compose Message for: ',
 1680:                 incl => 'Include',
 1681:                 type => 'Type',
 1682:                 subj => 'Subject',
 1683:                 mesa => 'Message',
 1684:                 new  => 'New',
 1685:                 save => 'Save',
 1686:                 canc => 'Cancel',
 1687:              );
 1688:     &html_escape(\%html_js_lt);
 1689:     &js_escape(\%html_js_lt);
 1690:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1691: 
 1692: //===================== Script to view submitted by ==================
 1693:   function viewSubmitter(submitter) {
 1694:     document.SCORE.refresh.value = "on";
 1695:     document.SCORE.NCT.value = "1";
 1696:     document.SCORE.unamedom0.value = submitter;
 1697:     document.SCORE.submit();
 1698:     return;
 1699:   }
 1700: 
 1701: //====================== Script for composing message ==============
 1702:    // preload images
 1703:    img1 = new Image();
 1704:    img1.src = "$iconpath/mailbkgrd.gif";
 1705:    img2 = new Image();
 1706:    img2.src = "$iconpath/mailto.gif";
 1707: 
 1708:   function msgCenter(msgform,usrctr,fullname) {
 1709:     var Nmsg  = msgform.savemsgN.value;
 1710:     savedMsgHeader(Nmsg,usrctr,fullname);
 1711:     var subject = msgform.msgsub.value;
 1712:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1713:     re = /msgsub/;
 1714:     var shwsel = "";
 1715:     if (re.test(msgchk)) { shwsel = "checked" }
 1716:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1717:     displaySubject(checkEntities(subject),shwsel);
 1718:     for (var i=1; i<=Nmsg; i++) {
 1719: 	var testmsg = "savemsg"+i+",";
 1720: 	re = new RegExp(testmsg,"g");
 1721: 	shwsel = "";
 1722: 	if (re.test(msgchk)) { shwsel = "checked" }
 1723: 	var message = document.SCORE["savemsg"+i].value;
 1724: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1725: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1726: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1727:     }
 1728:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1729:     shwsel = "";
 1730:     re = /newmsg/;
 1731:     if (re.test(msgchk)) { shwsel = "checked" }
 1732:     newMsg(newmsg,shwsel);
 1733:     msgTail(); 
 1734:     return;
 1735:   }
 1736: 
 1737:   function checkEntities(strx) {
 1738:     if (strx.length == 0) return strx;
 1739:     var orgStr = ["&", "<", ">", '"']; 
 1740:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1741:     var counter = 0;
 1742:     while (counter < 4) {
 1743: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1744: 	counter++;
 1745:     }
 1746:     return strx;
 1747:   }
 1748: 
 1749:   function strReplace(strx, orgStr, newStr) {
 1750:     return strx.split(orgStr).join(newStr);
 1751:   }
 1752: 
 1753:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1754:     var height = 70*Nmsg+250;
 1755:     if (height > 600) {
 1756: 	height = 600;
 1757:     }
 1758:     var xpos = (screen.width-600)/2;
 1759:     xpos = (xpos < 0) ? '0' : xpos;
 1760:     var ypos = (screen.height-height)/2-30;
 1761:     ypos = (ypos < 0) ? '0' : ypos;
 1762: 
 1763:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1764:     pWin.focus();
 1765:     pDoc = pWin.document;
 1766:     pDoc.$docopen;
 1767:     pDoc.write('$start_page_msg_central');
 1768: 
 1769:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1770:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1771:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1772: 
 1773:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1774:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1775: }
 1776:     function displaySubject(msg,shwsel) {
 1777:     pDoc = pWin.document;
 1778:     pDoc.write("<tr>");
 1779:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1780:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1781:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1782: }
 1783: 
 1784:   function displaySavedMsg(ctr,msg,shwsel) {
 1785:     pDoc = pWin.document;
 1786:     pDoc.write("<tr>");
 1787:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1788:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1789:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1790: }
 1791: 
 1792:   function newMsg(newmsg,shwsel) {
 1793:     pDoc = pWin.document;
 1794:     pDoc.write("<tr>");
 1795:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1796:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1797:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1798: }
 1799: 
 1800:   function msgTail() {
 1801:     pDoc = pWin.document;
 1802:     //pDoc.write("<\\/table>");
 1803:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1804:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1805:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1806:     pDoc.write("<\\/form>");
 1807:     pDoc.write('$end_page_msg_central');
 1808:     pDoc.close();
 1809: }
 1810: 
 1811: SUBJAVASCRIPT
 1812: }
 1813: 
 1814: #--- javascript for essay type problem --
 1815: sub sub_page_kw_js {
 1816:     my $request = shift;
 1817: 
 1818:     unless ($env{'form.compmsg'}) {
 1819:         &commonJSfunctions($request);
 1820:     }
 1821: 
 1822:     my $inner_js_highlight_central= (<<INNERJS);
 1823: <script type="text/javascript">
 1824:     function updateChoice(flag) {
 1825:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1826:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1827:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1828:       opener.document.SCORE.refresh.value = "on";
 1829:       if (opener.document.SCORE.keywords.value!=""){
 1830:          opener.document.SCORE.submit();
 1831:       }
 1832:       self.close()
 1833:     }
 1834: </script>
 1835: INNERJS
 1836: 
 1837:     my $start_page_highlight_central =
 1838:         &Apache::loncommon::start_page('Highlight Central',
 1839:                                        $inner_js_highlight_central,
 1840:                                        {'js_ready'  => 1,
 1841:                                         'only_body' => 1,
 1842:                                         'bgcolor'   =>'#FFFFFF',});
 1843:     my $end_page_highlight_central =
 1844:         &Apache::loncommon::end_page({'js_ready' => 1});
 1845: 
 1846:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1847:     $docopen=~s/^document\.//;
 1848: 
 1849:     my %js_lt = &Apache::lonlocal::texthash(
 1850:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1851:                 plse => 'Please select a word or group of words from document and then click this link.',
 1852:                 adds => 'Add selection to keyword list? Edit if desired.',
 1853:                 col1 => 'red',
 1854:                 col2 => 'green',
 1855:                 col3 => 'blue',
 1856:                 siz1 => 'normal',
 1857:                 siz2 => '+1',
 1858:                 siz3 => '+2',
 1859:                 sty1 => 'normal',
 1860:                 sty2 => 'italic',
 1861:                 sty3 => 'bold',
 1862:              );
 1863:     my %html_js_lt = &Apache::lonlocal::texthash(
 1864:                 save => 'Save',
 1865:                 canc => 'Cancel',
 1866:                 kehi => 'Keyword Highlight Options',
 1867:                 txtc => 'Text Color',
 1868:                 font => 'Font Size',
 1869:                 fnst => 'Font Style',
 1870:              );
 1871:     &js_escape(\%js_lt);
 1872:     &html_escape(\%html_js_lt);
 1873:     &js_escape(\%html_js_lt);
 1874:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1875: 
 1876: //===================== Show list of keywords ====================
 1877:   function keywords(formname) {
 1878:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1879:     if (nret==null) return;
 1880:     formname.keywords.value = nret;
 1881: 
 1882:     if (formname.keywords.value != "") {
 1883:         formname.refresh.value = "on";
 1884:         formname.submit();
 1885:     }
 1886:     return;
 1887:   }
 1888: 
 1889: //===================== Script to add keyword(s) ==================
 1890:   function getSel() {
 1891:     if (document.getSelection) txt = document.getSelection();
 1892:     else if (document.selection) txt = document.selection.createRange().text;
 1893:     else return;
 1894:     if (typeof(txt) != 'string') {
 1895:         txt = String(txt);
 1896:     }
 1897:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1898:     if (cleantxt=="") {
 1899:         alert("$js_lt{'plse'}");
 1900:         return;
 1901:     }
 1902:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1903:     if (nret==null) return;
 1904:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1905:     if (document.SCORE.keywords.value != "") {
 1906:         document.SCORE.refresh.value = "on";
 1907:         document.SCORE.submit();
 1908:     }
 1909:     return;
 1910:   }
 1911: 
 1912: //====================== Script for keyword highlight options ==============
 1913:   function kwhighlight() {
 1914:     var kwclr    = document.SCORE.kwclr.value;
 1915:     var kwsize   = document.SCORE.kwsize.value;
 1916:     var kwstyle  = document.SCORE.kwstyle.value;
 1917:     var redsel = "";
 1918:     var grnsel = "";
 1919:     var blusel = "";
 1920:     var txtcol1 = "$js_lt{'col1'}";
 1921:     var txtcol2 = "$js_lt{'col2'}";
 1922:     var txtcol3 = "$js_lt{'col3'}";
 1923:     var txtsiz1 = "$js_lt{'siz1'}";
 1924:     var txtsiz2 = "$js_lt{'siz2'}";
 1925:     var txtsiz3 = "$js_lt{'siz3'}";
 1926:     var txtsty1 = "$js_lt{'sty1'}";
 1927:     var txtsty2 = "$js_lt{'sty2'}";
 1928:     var txtsty3 = "$js_lt{'sty3'}";
 1929:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1930:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1931:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1932:     var sznsel = "";
 1933:     var sz1sel = "";
 1934:     var sz2sel = "";
 1935:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1936:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1937:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1938:     var synsel = "";
 1939:     var syisel = "";
 1940:     var sybsel = "";
 1941:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1942:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1943:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1944:     highlightCentral();
 1945:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1946:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1947:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1948:     highlightend();
 1949:     return;
 1950:   }
 1951: 
 1952:   function highlightCentral() {
 1953: //    if (window.hwdWin) window.hwdWin.close();
 1954:     var xpos = (screen.width-400)/2;
 1955:     xpos = (xpos < 0) ? '0' : xpos;
 1956:     var ypos = (screen.height-330)/2-30;
 1957:     ypos = (ypos < 0) ? '0' : ypos;
 1958: 
 1959:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1960:     hwdWin.focus();
 1961:     var hDoc = hwdWin.document;
 1962:     hDoc.$docopen;
 1963:     hDoc.write('$start_page_highlight_central');
 1964:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1965:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1966: 
 1967:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1968:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1969:   }
 1970: 
 1971:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1972:     var hDoc = hwdWin.document;
 1973:     hDoc.write("<tr>");
 1974:     hDoc.write("<td align=\\"left\\">");
 1975:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1976:     hDoc.write("<td align=\\"left\\">");
 1977:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1978:     hDoc.write("<td align=\\"left\\">");
 1979:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1980:     hDoc.write("<\\/tr>");
 1981:   }
 1982: 
 1983:   function highlightend() { 
 1984:     var hDoc = hwdWin.document;
 1985:     hDoc.write("<\\/table><br \\/>");
 1986:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1987:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1988:     hDoc.write("<\\/form>");
 1989:     hDoc.write('$end_page_highlight_central');
 1990:     hDoc.close();
 1991:   }
 1992: 
 1993: SUBJAVASCRIPT
 1994: }
 1995: 
 1996: sub get_increment {
 1997:     my $increment = $env{'form.increment'};
 1998:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1999:         $increment != .1) {
 2000:         $increment = 1;
 2001:     }
 2002:     return $increment;
 2003: }
 2004: 
 2005: sub gradeBox_start {
 2006:     return (
 2007:         &Apache::loncommon::start_data_table()
 2008:        .&Apache::loncommon::start_data_table_header_row()
 2009:        .'<th>'.&mt('Part').'</th>'
 2010:        .'<th>'.&mt('Points').'</th>'
 2011:        .'<th>&nbsp;</th>'
 2012:        .'<th>'.&mt('Assign Grade').'</th>'
 2013:        .'<th>'.&mt('Weight').'</th>'
 2014:        .'<th>'.&mt('Grade Status').'</th>'
 2015:        .&Apache::loncommon::end_data_table_header_row()
 2016:     );
 2017: }
 2018: 
 2019: sub gradeBox_end {
 2020:     return (
 2021:         &Apache::loncommon::end_data_table()
 2022:     );
 2023: }
 2024: #--- displays the grading box, used in essay type problem and grading by page/sequence
 2025: sub gradeBox {
 2026:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 2027:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2028: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2029:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2030:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2031:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2032:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2033:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2034: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2035:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2036:     my $display_part= &get_display_part($partid,$symb);
 2037:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2038: 				       [$partid]);
 2039:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2040:     if ($last_resets{$partid}) {
 2041:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2042:     }
 2043:     my $result=&Apache::loncommon::start_data_table_row();
 2044:     my $ctr = 0;
 2045:     my $thisweight = 0;
 2046:     my $increment = &get_increment();
 2047: 
 2048:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2049:     while ($thisweight<=$wgt) {
 2050: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2051:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2052: 	    $thisweight.')" value="'.$thisweight.'" '.
 2053: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2054: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2055:         $thisweight += $increment;
 2056: 	$ctr++;
 2057:     }
 2058:     $radio.='</tr></table>';
 2059: 
 2060:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2061: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2062: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2063: 	$wgt.')" /></td>'."\n";
 2064:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2065: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2066: 	' </td>'."\n";
 2067:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2068: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2069:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2070: 	$line.='<option></option>'.
 2071: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2072:     } else {
 2073: 	$line.='<option selected="selected"></option>'.
 2074: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2075:     }
 2076:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2077: 
 2078: 
 2079:     $result .= 
 2080: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2081:     $result.=&Apache::loncommon::end_data_table_row();
 2082:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2083:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2084: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2085: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2086: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2087:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2088:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2089:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2090:         $aggtries.'" />'."\n";
 2091:     my $res_error;
 2092:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2093:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2094:     if ($res_error) {
 2095:         return &navmap_errormsg();
 2096:     }
 2097:     return $result;
 2098: }
 2099: 
 2100: sub handback_box {
 2101:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2102:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2103:     return unless ($numessay);
 2104:     my (@respids);
 2105:     my @part_response_id = &flatten_responseType($responseType);
 2106:     foreach my $part_response_id (@part_response_id) {
 2107:     	my ($part,$resp) = @{ $part_response_id };
 2108:         if ($part eq $partid) {
 2109:             push(@respids,$resp);
 2110:         }
 2111:     }
 2112:     my $result;
 2113:     foreach my $respid (@respids) {
 2114: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2115: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2116: 	next if (!@$files);
 2117: 	my $file_counter = 0;
 2118: 	foreach my $file (@$files) {
 2119: 	    if ($file =~ /\/portfolio\//) {
 2120:                 $file_counter++;
 2121:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2122:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 2123:     	        $file_disp = "$name.$ext";
 2124:     	        $file = $file_path.$file_disp;
 2125:     	        $result.=&mt('Return commented version of [_1] to student.',
 2126:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2127:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2128:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2129: 	    }
 2130: 	}
 2131:         if ($file_counter) {
 2132:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2133:                        '<span class="LC_info">'.
 2134:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2135:         }
 2136:     }
 2137:     return $result;    
 2138: }
 2139: 
 2140: sub show_problem {
 2141:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2142:     my $rendered;
 2143:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2144:     &Apache::lonxml::remember_problem_counter();
 2145:     if ($mode eq 'both' or $mode eq 'text') {
 2146: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2147: 						       $env{'request.course.id'},
 2148: 						       undef,\%form);
 2149:     }
 2150:     if ($removeform) {
 2151: 	$rendered=~s|<form(.*?)>||g;
 2152: 	$rendered=~s|</form>||g;
 2153: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2154:     }
 2155:     my $companswer;
 2156:     if ($mode eq 'both' or $mode eq 'answer') {
 2157: 	&Apache::lonxml::restore_problem_counter();
 2158: 	$companswer=
 2159: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2160: 						    $env{'request.course.id'},
 2161: 						    %form);
 2162:     }
 2163:     if ($removeform) {
 2164: 	$companswer=~s|<form(.*?)>||g;
 2165: 	$companswer=~s|</form>||g;
 2166: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2167:     }
 2168:     my $renderheading = &mt('View of the problem');
 2169:     my $answerheading = &mt('Correct answer');
 2170:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2171:         my $stu_fullname = $env{'form.fullname'};
 2172:         if ($stu_fullname eq '') {
 2173:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2174:         }
 2175:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2176:         if ($forwhom ne '') {
 2177:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2178:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2179:         }
 2180:     }
 2181:     $rendered=
 2182:         '<div class="LC_Box">'
 2183:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2184:        .$rendered
 2185:        .'</div>';
 2186:     $companswer=
 2187:         '<div class="LC_Box">'
 2188:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2189:        .$companswer
 2190:        .'</div>';
 2191:     my $result;
 2192:     if ($mode eq 'both') {
 2193:         $result=$rendered.$companswer;
 2194:     } elsif ($mode eq 'text') {
 2195:         $result=$rendered;
 2196:     } elsif ($mode eq 'answer') {
 2197:         $result=$companswer;
 2198:     }
 2199:     return $result;
 2200: }
 2201: 
 2202: sub files_exist {
 2203:     my ($r, $symb) = @_;
 2204:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2205:     foreach my $student (@students) {
 2206:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2207:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2208: 					      $udom,$uname);
 2209:         my ($string)= &get_last_submission(\%record);
 2210:         foreach my $submission (@$string) {
 2211:             my ($partid,$respid) =
 2212: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2213:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2214: 					   \%record);
 2215:             return 1 if (@$files);
 2216:         }
 2217:     }
 2218:     return 0;
 2219: }
 2220: 
 2221: sub download_all_link {
 2222:     my ($r,$symb) = @_;
 2223:     unless (&files_exist($r, $symb)) {
 2224:         $r->print(&mt('There are currently no submitted documents.'));
 2225:         return;
 2226:     }
 2227:     my $all_students = 
 2228: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2229: 
 2230:     my $parts =
 2231: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2232: 
 2233:     my $identifier = &Apache::loncommon::get_cgi_id();
 2234:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2235:                              'cgi.'.$identifier.'.symb' => $symb,
 2236:                              'cgi.'.$identifier.'.parts' => $parts,});
 2237:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2238: 	      &mt('Download All Submitted Documents').'</a>');
 2239:     return;
 2240: }
 2241: 
 2242: sub submit_download_link {
 2243:     my ($request,$symb) = @_;
 2244:     if (!$symb) { return ''; }
 2245:     my $res_error;
 2246:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2247:         &response_type($symb,\$res_error);
 2248:     if ($res_error) {
 2249:         $request->print(&mt('An error occurred retrieving response types'));
 2250:         return;
 2251:     }
 2252:     unless ($numessay) {
 2253:         $request->print(&mt('No essayresponse items found'));
 2254:         return;
 2255:     }
 2256:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2257:     if (@chosenparts) {
 2258:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2259:                                           undef,undef,1));
 2260:     }
 2261:     if ($numessay) {
 2262:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2263:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2264:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2265:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2266:         if (ref($fullname) eq 'HASH') {
 2267:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2268:             if (@students) {
 2269:                 @{$env{'form.stuinfo'}} = @students;
 2270:                 if ($numdropbox) {
 2271:                     &download_all_link($request,$symb);
 2272:                 } else {
 2273:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2274:                 }
 2275: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2276: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2277:             } else {
 2278:                 $request->print(&mt('No students match the criteria you selected'));
 2279:             }
 2280:         } else {
 2281:             $request->print(&mt('Could not retrieve student information'));
 2282:         }
 2283:     } else {
 2284:         $request->print(&mt('No essayresponse items found'));
 2285:     }
 2286:     return;
 2287: }
 2288: 
 2289: sub build_section_inputs {
 2290:     my $section_inputs;
 2291:     if ($env{'form.section'} eq '') {
 2292:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2293:     } else {
 2294:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2295:         foreach my $section (@sections) {
 2296:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2297:         }
 2298:     }
 2299:     return $section_inputs;
 2300: }
 2301: 
 2302: # --------------------------- show submissions of a student, option to grade 
 2303: sub submission {
 2304:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2305:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2306:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2307:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2308:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2309: 
 2310:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2311:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2312:     my $is_tool = ($symb =~ /ext\.tool$/);
 2313:     my ($essayurl,%coursedesc_by_cid);
 2314: 
 2315:     if (!&canview($usec)) {
 2316:         $request->print(
 2317:             '<span class="LC_warning">'.
 2318:             &mt('Unable to view requested student.').
 2319:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2320:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2321:             '</span>');
 2322: 	return;
 2323:     }
 2324: 
 2325:     my $res_error;
 2326:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2327:         &response_type($symb,\$res_error);
 2328:     if ($res_error) {
 2329:         $request->print(&navmap_errormsg());
 2330:         return;
 2331:     }
 2332: 
 2333:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2334:     unless ($is_tool) { 
 2335:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2336:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2337:     }
 2338:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2339:         $env{'form.compmsg'} = 1;
 2340:     }
 2341:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2342:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2343: 	'" src="'.$request->dir_config('lonIconsURL').
 2344: 	'/check.gif" height="16" border="0" />';
 2345: 
 2346:     # header info
 2347:     if ($counter == 0) {
 2348:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2349:         if (@chosenparts) {
 2350:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2351:         } elsif ($divforres) {
 2352:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2353:         } else {
 2354:             $request->print('<br clear="all" />');
 2355:         }
 2356: 	&sub_page_js($request);
 2357:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2358: 	&sub_page_kw_js($request) if ($numessay);
 2359: 
 2360: 	# option to display problem, only once else it cause problems 
 2361:         # with the form later since the problem has a form.
 2362: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2363: 	    my $mode;
 2364: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2365: 		$mode='both';
 2366: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2367: 		$mode='text';
 2368: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2369: 		$mode='answer';
 2370: 	    }
 2371: 	    &Apache::lonxml::clear_problem_counter();
 2372: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2373: 	}
 2374: 
 2375: 	my %keyhash = ();
 2376: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2377: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2378: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2379: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2380: 	}
 2381: 	# kwclr is the only variable that is guaranteed not to be blank
 2382: 	# if this subroutine has been called once.
 2383: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2384: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2385: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2386: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2387: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2388: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2389: 	}
 2390: 	if ($env{'form.compmsg'}) {
 2391: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2392: 		$keyhash{$symb.'_subject'} : $probtitle;
 2393: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2394: 	}
 2395: 
 2396: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2397: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2398: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2399: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2400: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2401: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2402: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2403: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2404: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2405: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2406: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2407: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2408: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2409: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2410: 			&build_section_inputs().
 2411: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2412: 			'<input type="hidden" name="NCT"'.
 2413: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2414: 	if ($env{'form.compmsg'}) {
 2415: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2416: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2417: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2418: 	}
 2419: 	if ($numessay) {
 2420: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2421: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2422: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2423: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2424: 	}
 2425: 
 2426: 	my ($cts,$prnmsg) = (1,'');
 2427: 	while ($cts <= $env{'form.savemsgN'}) {
 2428: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2429: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2430: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2431: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2432: 		'" />'."\n".
 2433: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2434: 	    $cts++;
 2435: 	}
 2436: 	$request->print($prnmsg);
 2437: 
 2438: 	if ($numessay) {
 2439: 
 2440:             my %lt = &Apache::lonlocal::texthash(
 2441:                           keyh => 'Keyword Highlighting for Essays',
 2442:                           keyw => 'Keyword Options',
 2443:                           list => 'List',
 2444:                           past => 'Paste Selection to List',
 2445:                           high => 'Highlight Attribute',
 2446:                      );
 2447: #
 2448: # Print out the keyword options line
 2449: #
 2450: 	    $request->print(
 2451:                 '<div class="LC_columnSection">'
 2452:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2453:                .&Apache::lonhtmlcommon::funclist_from_array(
 2454:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2455:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2456:  class="page">'.$lt{'past'}.'</a>',
 2457:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2458:                     {legend => $lt{'keyw'}})
 2459:                .'</fieldset></div>'
 2460:             );
 2461: 
 2462: #
 2463: # Load the other essays for similarity check
 2464: #
 2465:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2466:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2467:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2468:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2469:                 if ($cdom ne '' && $cnum ne '') {
 2470:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2471:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2472:                         my $apath = $1.'_'.$id;
 2473:                         $apath=~s/\W/\_/gs;
 2474:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2475:                     }
 2476:                 }
 2477:             } else {
 2478: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2479: 	        $apath=&escape($apath);
 2480: 	        $apath=~s/\W/\_/gs;
 2481:                 &init_old_essays($symb,$apath,$adom,$aname);
 2482:             }
 2483:         }
 2484:     }
 2485: 
 2486: # This is where output for one specific student would start
 2487:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2488:     $request->print(
 2489:         "\n\n"
 2490:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2491:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2492:        ."\n"
 2493:     );
 2494: 
 2495:     # Show additional functions if allowed
 2496:     if ($perm{'vgr'}) {
 2497:         $request->print(
 2498:             &Apache::loncommon::track_student_link(
 2499:                 'View recent activity',
 2500:                 $uname,$udom,'check')
 2501:            .' '
 2502:         );
 2503:     }
 2504:     if ($perm{'opa'}) {
 2505:         $request->print(
 2506:             &Apache::loncommon::pprmlink(
 2507:                 &mt('Set/Change parameters'),
 2508:                 $uname,$udom,$symb,'check'));
 2509:     }
 2510: 
 2511:     # Show Problem
 2512:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2513: 	my $mode;
 2514: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2515: 	    $mode='both';
 2516: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2517: 	    $mode='text';
 2518: 	} elsif ($env{'form.vAns'} eq 'all') {
 2519: 	    $mode='answer';
 2520: 	}
 2521: 	&Apache::lonxml::clear_problem_counter();
 2522: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2523:     }
 2524: 
 2525:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2526: 
 2527:     # Display student info
 2528:     $request->print(($counter == 0 ? '' : '<br />'));
 2529: 
 2530:     my $boxtitle = &mt('Submissions');
 2531:     if ($is_tool) {
 2532:         $boxtitle = &mt('Transactions')
 2533:     }
 2534:     my $result='<div class="LC_Box">'
 2535:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2536:     $result.='<input type="hidden" name="name'.$counter.
 2537:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2538:     if (($numresp > $numessay) && !$is_tool) {
 2539:         $result.='<p class="LC_info">'
 2540:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2541:                 ."</p>\n";
 2542:     }
 2543: 
 2544:     # If any part of the problem is an essayresponse, then check for collaborators
 2545:     my $fullname;
 2546:     my $col_fullnames = [];
 2547:     if ($numessay) {
 2548: 	(my $sub_result,$fullname,$col_fullnames)=
 2549: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2550: 				 $counter);
 2551: 	$result.=$sub_result;
 2552:     }
 2553:     $request->print($result."\n");
 2554: 
 2555:     # print student answer/submission
 2556:     # Options are (1) Last submission only
 2557:     #             (2) Last submission (with detailed information for that submission)
 2558:     #             (3) All transactions (by date)
 2559:     #             (4) The whole record (with detailed information for all transactions)
 2560: 
 2561:     my ($lastsubonly,$partinfo) =
 2562:         &show_last_submission($uname,$udom,$symb,$essayurl,$responseType,$env{'form.lastSub'},
 2563:                               $is_tool,$fullname,\%record,\%coursedesc_by_cid);
 2564:     $request->print($partinfo);
 2565:     $request->print($lastsubonly);
 2566: 
 2567:     if ($env{'form.lastSub'} eq 'datesub') {
 2568:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2569: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2570:     }
 2571:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2572:         my $identifier = (&canmodify($usec)? $counter : '');
 2573:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2574: 								 $env{'request.course.id'},
 2575: 								 $last,'.submission',
 2576: 								 'Apache::grades::keywords_highlight',
 2577:                                                                  $usec,$identifier));
 2578:     }
 2579:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2580: 	.$udom.'" />'."\n");
 2581:     # return if view submission with no grading option
 2582:     if (!&canmodify($usec)) {
 2583: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2584: 	return;
 2585:     } else {
 2586: 	$request->print('</div>'."\n");
 2587:     }
 2588: 
 2589:     # grading message center
 2590: 
 2591:     if ($env{'form.compmsg'}) {
 2592:         my $result='<div class="LC_Box">'.
 2593:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2594:                    '<div class="LC_grade_message_center_body">';
 2595:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2596:         my $msgfor = $givenn.' '.$lastname;
 2597:         if (scalar(@$col_fullnames) > 0) {
 2598:             my $lastone = pop(@$col_fullnames);
 2599:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2600:         }
 2601:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2602:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2603:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2604:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2605:                  ',\''.$msgfor.'\');" target="_self">'.
 2606:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2607:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2608:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2609:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2610:                  '<br />&nbsp;('.
 2611:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2612:                  '</div></div>';
 2613:         $request->print($result);
 2614:     }
 2615: 
 2616:     my %seen = ();
 2617:     my @partlist;
 2618:     my @gradePartRespid;
 2619:     my @part_response_id;
 2620:     if ($is_tool) {
 2621:         @part_response_id = ([0,'']);
 2622:     } else {
 2623:         @part_response_id = &flatten_responseType($responseType);
 2624:     }
 2625:     $request->print(
 2626:         '<div class="LC_Box">'
 2627:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2628:     );
 2629:     $request->print(&gradeBox_start());
 2630:     foreach my $part_response_id (@part_response_id) {
 2631:     	my ($partid,$respid) = @{ $part_response_id };
 2632: 	my $part_resp = join('_',@{ $part_response_id });
 2633: 	next if ($seen{$partid} > 0);
 2634: 	$seen{$partid}++;
 2635: 	push(@partlist,$partid);
 2636: 	push(@gradePartRespid,$partid.'.'.$respid);
 2637: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2638:     }
 2639:     $request->print(&gradeBox_end()); # </div>
 2640:     $request->print('</div>');
 2641: 
 2642:     $request->print('<div class="LC_grade_info_links">');
 2643:     $request->print('</div>');
 2644: 
 2645:     $result='<input type="hidden" name="partlist'.$counter.
 2646: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2647:     $result.='<input type="hidden" name="gradePartRespid'.
 2648: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2649:     my $ctr = 0;
 2650:     while ($ctr < scalar(@partlist)) {
 2651: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2652: 	    $partlist[$ctr].'" />'."\n";
 2653: 	$ctr++;
 2654:     }
 2655:     $request->print($result.''."\n");
 2656: 
 2657: # Done with printing info for one student
 2658: 
 2659:     $request->print('</div>');#LC_grade_show_user
 2660: 
 2661: 
 2662:     # print end of form
 2663:     if ($counter == $total) {
 2664:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2665: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2666: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2667: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2668: 	my $ntstu ='<select name="NTSTU">'.
 2669: 	    '<option>1</option><option>2</option>'.
 2670: 	    '<option>3</option><option>5</option>'.
 2671: 	    '<option>7</option><option>10</option></select>'."\n";
 2672: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2673: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2674:         $endform.=&mt('[_1]student(s)',$ntstu);
 2675: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2676: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2677: 	    '<input type="button" value="'.&mt('Next').'" '.
 2678: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2679:         $endform.='<span class="LC_warning">'.
 2680:                   &mt('(Next and Previous (student) do not save the scores.)').
 2681:                   '</span>'."\n" ;
 2682:         $endform.="<input type='hidden' value='".&get_increment().
 2683:             "' name='increment' />";
 2684: 	$endform.='</td></tr></table></form>';
 2685: 	$request->print($endform);
 2686:     }
 2687:     return '';
 2688: }
 2689: 
 2690: sub show_last_submission {
 2691:     my ($uname,$udom,$symb,$essayurl,$responseType,$viewtype,$is_tool,$fullname,
 2692:         $record,$coursedesc_by_cid) = @_;
 2693:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
 2694:         &get_last_submission($record,$is_tool);
 2695: 
 2696:     my ($lastsubonly,$partinfo);
 2697:     if ($timestamp eq '') {
 2698:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>';
 2699:     } elsif ($is_tool) {
 2700:         $lastsubonly =
 2701:             '<div class="LC_grade_submissions_body">'
 2702:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$timestamp."</div>\n";
 2703:     } else {
 2704:         my ($shownsubmdate,$showngradedate);
 2705:         if ($lastsubmittime && $lastgradetime) {
 2706:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
 2707:             if ($lastgradetime > $lastsubmittime) {
 2708:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
 2709:              }
 2710:         } else {
 2711:             $shownsubmdate = $timestamp;
 2712:         }
 2713:         $lastsubonly =
 2714:             '<div class="LC_grade_submissions_body">'
 2715:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
 2716:         if ($showngradedate) {
 2717:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
 2718:         }
 2719: 
 2720:         my %seenparts;
 2721:         my @part_response_id = &flatten_responseType($responseType);
 2722:         foreach my $part (@part_response_id) {
 2723:             my ($partid,$respid) = @{ $part };
 2724:             my $display_part=&get_display_part($partid,$symb);
 2725:             if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2726:                 if (exists($seenparts{$partid})) { next; }
 2727:                 $seenparts{$partid}=1;
 2728:                 $partinfo .=
 2729:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2730:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2731:                                '<a href="javascript:viewSubmitter(\''.
 2732:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2733:                                '\');" target="_self">'.
 2734:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2735:                     '<br />';
 2736:                 next;
 2737:             }
 2738:             my $responsetype = $responseType->{$partid}->{$respid};
 2739:             if (!exists($record->{"resource.$partid.$respid.submission"})) {
 2740:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2741:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2742:                     ' <span class="LC_internal_info">'.
 2743:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2744:                     '</span>&nbsp; &nbsp;'.
 2745:                     '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2746:                 next;
 2747:             }
 2748:             foreach my $submission (@$string) {
 2749:                 my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2750:                 if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2751:                 my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2752:                 # Similarity check
 2753:                 my $similar='';
 2754:                 my ($type,$trial,$rndseed);
 2755:                 if ($hide eq 'rand') {
 2756:                     $type = 'randomizetry';
 2757:                     $trial = $record->{"resource.$partid.tries"};
 2758:                     $rndseed = $record->{"resource.$partid.rndseed"};
 2759:                 }
 2760:                 if ($env{'form.checkPlag'}) {
 2761:                     my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2762:                     &most_similar($uname,$udom,$symb,$subval);
 2763:                     if ($osim) {
 2764:                         $osim=int($osim*100.0);
 2765:                         if ($hide eq 'anon') {
 2766:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2767:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2768:                         } else {
 2769:                             $similar='<hr />';
 2770:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2771:                                 $similar .= '<h3><span class="LC_warning">'.
 2772:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2773:                                                 $osim,
 2774:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2775:                                             '</span></h3>';
 2776:                             } else {
 2777:                                 my %old_course_desc;
 2778:                                 if ($ocrsid ne '') {
 2779:                                     if (ref($coursedesc_by_cid->{$ocrsid}) eq 'HASH') {
 2780:                                         %old_course_desc = %{$coursedesc_by_cid->{$ocrsid}};
 2781:                                     } else {
 2782:                                         my $args;
 2783:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2784:                                             $args = {'one_time' => 1};
 2785:                                         }
 2786:                                         %old_course_desc =
 2787:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2788:                                         $coursedesc_by_cid->{$ocrsid} = \%old_course_desc;
 2789:                                     }
 2790:                                     $similar .=
 2791:                                         '<h3><span class="LC_warning">'.
 2792:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2793:                                             $osim,
 2794:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2795:                                             $old_course_desc{'description'},
 2796:                                             $old_course_desc{'num'},
 2797:                                             $old_course_desc{'domain'}).
 2798:                                         '</span></h3>';
 2799:                                 } else {
 2800:                                     $similar .=
 2801:                                         '<h3><span class="LC_warning">'.
 2802:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2803:                                             $osim,
 2804:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2805:                                         '</span></h3>';
 2806:                                 }
 2807:                             }
 2808:                             $similar .= '<blockquote><i>'.
 2809:                                         &keywords_highlight($oessay).
 2810:                                         '</i></blockquote><hr />';
 2811:                         }
 2812:                     }
 2813:                 }
 2814:                 my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2815:                                      undef,$type,$trial,$rndseed);
 2816:                 if (($viewtype eq 'lastonly') ||
 2817:                     ($viewtype eq 'datesub')  ||
 2818:                     ($viewtype =~ /^(last|all)$/)) {
 2819:                     my $display_part=&get_display_part($partid,$symb);
 2820:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2821:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2822:                         ' <span class="LC_internal_info">'.
 2823:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2824:                         '</span>&nbsp; &nbsp;';
 2825:                     my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2826:                     if (@$files) {
 2827:                         if ($hide eq 'anon') {
 2828:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2829:                         } else {
 2830:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2831:                                         .'<br /><span class="LC_warning">';
 2832:                             if(@$files == 1) {
 2833:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2834:                             } else {
 2835:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2836:                             }
 2837:                             $lastsubonly .= '</span>';
 2838:                             foreach my $file (@$files) {
 2839:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2840:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2841:                             }
 2842:                         }
 2843:                         $lastsubonly.='<br />';
 2844:                     }
 2845:                     if ($hide eq 'anon') {
 2846:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
 2847:                     } else {
 2848:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2849:                         if ($draft) {
 2850:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2851:                         }
 2852:                         $subval =
 2853:                             &cleanRecord($subval,$responsetype,$symb,$partid,
 2854:                                          $respid,$record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2855:                         if ($responsetype eq 'essay') {
 2856:                             $subval =~ s{\n}{<br />}g;
 2857:                         }
 2858:                         $lastsubonly.=$subval."\n";
 2859:                     }
 2860:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2861:                     $lastsubonly.='</div>';
 2862:                 }
 2863:             }
 2864:         }
 2865:         $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2866:     }
 2867:     return ($lastsubonly,$partinfo);
 2868: }
 2869: 
 2870: sub check_collaborators {
 2871:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2872:     my ($result,@col_fullnames);
 2873:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2874:     foreach my $part (keys(%$handgrade)) {
 2875: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2876: 					'.maxcollaborators',
 2877: 					$symb,$udom,$uname);
 2878: 	next if ($ncol <= 0);
 2879: 	$part =~ s/\_/\./g;
 2880: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2881: 	my (@good_collaborators, @bad_collaborators);
 2882: 	foreach my $possible_collaborator
 2883: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2884: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2885: 	    next if ($possible_collaborator eq '');
 2886: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2887: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2888: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2889: 	    # Doing this grep allows 'fuzzy' specification
 2890: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2891: 			       keys(%$classlist));
 2892: 	    if (! scalar(@matches)) {
 2893: 		push(@bad_collaborators, $possible_collaborator);
 2894: 	    } else {
 2895: 		push(@good_collaborators, @matches);
 2896: 	    }
 2897: 	}
 2898: 	if (scalar(@good_collaborators) != 0) {
 2899: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2900: 	    foreach my $name (@good_collaborators) {
 2901: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2902: 		push(@col_fullnames, $givenn.' '.$lastname);
 2903: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2904: 	    }
 2905: 	    $result.='</ol><br />'."\n";
 2906: 	    my ($part)=split(/\./,$part);
 2907: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2908: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2909: 		"\n";
 2910: 	}
 2911: 	if (scalar(@bad_collaborators) > 0) {
 2912: 	    $result.='<div class="LC_warning">';
 2913: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2914: 	    $result .= '</div>';
 2915: 	}         
 2916: 	if (scalar(@bad_collaborators > $ncol)) {
 2917: 	    $result .= '<div class="LC_warning">';
 2918: 	    $result .= &mt('This student has submitted too many '.
 2919: 		'collaborators.  Maximum is [_1].',$ncol);
 2920: 	    $result .= '</div>';
 2921: 	}
 2922:     }
 2923:     return ($result,$fullname,\@col_fullnames);
 2924: }
 2925: 
 2926: #--- Retrieve the last submission for all the parts
 2927: sub get_last_submission {
 2928:     my ($returnhash,$is_tool)=@_;
 2929:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
 2930:     if ($$returnhash{'version'}) {
 2931: 	my %lasthash=();
 2932:         my %prevsolved=();
 2933:         my %solved=();
 2934: 	my $version;
 2935: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2936:             my %handgraded = ();
 2937: 	    foreach my $key (sort(split(/\:/,
 2938: 					$$returnhash{$version.':keys'}))) {
 2939: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2940:                 if ($key =~ /\.([^.]+)\.regrader$/) {
 2941:                     $handgraded{$1} = 1;
 2942:                 } elsif ($key =~ /\.portfiles$/) {
 2943:                     if (($$returnhash{$version.':'.$key} ne '') &&
 2944:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
 2945:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2946:                     }
 2947:                 } elsif ($key =~ /\.submission$/) {
 2948:                     if ($$returnhash{$version.':'.$key} ne '') {
 2949:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2950:                     }
 2951:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
 2952:                     $prevsolved{$1} = $solved{$1};
 2953:                     $solved{$1} = $lasthash{$key};
 2954:                 }
 2955:             }
 2956:             foreach my $partid (keys(%handgraded)) {
 2957:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
 2958:                     (($solved{$partid} eq 'incorrect_by_override') ||
 2959:                      ($solved{$partid} eq 'correct_by_override'))) {
 2960:                     $lastgradetime = $$returnhash{$version.':timestamp'};
 2961:                 }
 2962:                 if ($solved{$partid} ne '') {
 2963:                     $prevsolved{$partid} = $solved{$partid};
 2964:                 }
 2965: 	    }
 2966:             $timestamp =
 2967:                 &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2968: 	}
 2969:         my (%typeparts,%randombytry);
 2970:         my $showsurv = 
 2971:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2972:         foreach my $key (sort(keys(%lasthash))) {
 2973:             if ($key =~ /\.type$/) {
 2974:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2975:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2976:                     ($lasthash{$key} eq 'randomizetry')) {
 2977:                     my ($ign,@parts) = split(/\./,$key);
 2978:                     pop(@parts);
 2979:                     my $id = join('.',@parts);
 2980:                     if ($lasthash{$key} eq 'randomizetry') {
 2981:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2982:                     } else {
 2983:                         unless ($showsurv) {
 2984:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2985:                         }
 2986:                     }
 2987:                     delete($lasthash{$key});
 2988:                 }
 2989:             }
 2990:         }
 2991:         my @hidden = keys(%typeparts);
 2992:         my @randomize = keys(%randombytry);
 2993: 	foreach my $key (keys(%lasthash)) {
 2994: 	    next if ($key !~ /\.submission$/);
 2995:             my $hide;
 2996:             if (@hidden) {
 2997:                 foreach my $id (@hidden) {
 2998:                     if ($key =~ /^\Q$id\E/) {
 2999:                         $hide = 'anon';
 3000:                         last;
 3001:                     }
 3002:                 }
 3003:             }
 3004:             unless ($hide) {
 3005:                 if (@randomize) {
 3006:                     foreach my $id (@randomize) {
 3007:                         if ($key =~ /^\Q$id\E/) {
 3008:                             $hide = 'rand';
 3009:                             last;
 3010:                         }
 3011:                     }
 3012:                 }
 3013:             }
 3014: 	    my ($partid,$foo) = split(/submission$/,$key);
 3015: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 3016:             push(@string, join(':', $key, $hide, $draft, (
 3017:                 ref($lasthash{$key}) eq 'ARRAY' ?
 3018:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 3019: 	}
 3020:     }
 3021:     if (!@string) {
 3022:         my $msg;
 3023:         if ($is_tool) {
 3024:             $msg = &mt('No grade passed back.');
 3025:         } else {
 3026:             $msg = &mt('Nothing submitted - no attempts.');
 3027:         }
 3028: 	$string[0] =
 3029: 	    '<span class="LC_warning">'.$msg.'</span>';
 3030:     }
 3031:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
 3032: }
 3033: 
 3034: #--- High light keywords, with style choosen by user.
 3035: sub keywords_highlight {
 3036:     my $string    = shift;
 3037:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 3038:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 3039:     (my $styleoff = $styleon) =~ s/\</\<\//;
 3040:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 3041:     foreach my $keyword (@keylist) {
 3042: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 3043:     }
 3044:     return $string;
 3045: }
 3046: 
 3047: # For Tasks provide a mechanism to display previous version for one specific student
 3048: 
 3049: sub show_previous_task_version {
 3050:     my ($request,$symb) = @_;
 3051:     if ($symb eq '') {
 3052:         $request->print(
 3053:             '<span class="LC_error">'.
 3054:             &mt('Unable to handle ambiguous references.').
 3055:             '</span>');
 3056:         return '';
 3057:     }
 3058:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 3059:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 3060:     if (!&canview($usec)) {
 3061:         $request->print(
 3062:             '<span class="LC_warning">'.
 3063:             &mt('Unable to view previous version for requested student.').
 3064:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 3065:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 3066:             '</span>');
 3067:         return;
 3068:     }
 3069:     my $mode = 'both';
 3070:     my $isTask = ($symb =~/\.task$/);
 3071:     if ($isTask) {
 3072:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 3073:             if ($env{'form.fullname'} eq '') {
 3074:                 $env{'form.fullname'} =
 3075:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 3076:             }
 3077:             my $probtitle=&Apache::lonnet::gettitle($symb);
 3078:             $request->print("\n\n".
 3079:                             '<div class="LC_grade_show_user">'.
 3080:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3081:                             '</h2>'."\n");
 3082:             &Apache::lonxml::clear_problem_counter();
 3083:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 3084:                             {'previousversion' => $env{'form.previousversion'} }));
 3085:             $request->print("\n</div>");
 3086:         }
 3087:     }
 3088:     return;
 3089: }
 3090: 
 3091: sub choose_task_version_form {
 3092:     my ($symb,$uname,$udom,$nomenu) = @_;
 3093:     my $isTask = ($symb =~/\.task$/);
 3094:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3095:     if ($isTask) {
 3096:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3097:                                               $udom,$uname);
 3098:         if (($record{'resource.0.version'} eq '') ||
 3099:             ($record{'resource.0.version'} < 2)) {
 3100:             return ($record{'resource.0.version'},
 3101:                     $record{'resource.0.version'},$result,$js);
 3102:         } else {
 3103:             $current = $record{'resource.0.version'};
 3104:         }
 3105:         if ($env{'form.previousversion'}) {
 3106:             $displayed = $env{'form.previousversion'};
 3107:             $rowtitle = &mt('Choose another version:')
 3108:         } else {
 3109:             $displayed = $current;
 3110:             $rowtitle = &mt('Show earlier version:');
 3111:         }
 3112:         $result = '<div class="LC_left_float">';
 3113:         my $list;
 3114:         my $numversions = 0;
 3115:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3116:             if ($i == $current) {
 3117:                 if (!$env{'form.previousversion'} || $nomenu) {
 3118:                     next;
 3119:                 } else {
 3120:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3121:                     $numversions ++;
 3122:                 }
 3123:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3124:                 unless ($i == $env{'form.previousversion'}) {
 3125:                     $numversions ++;
 3126:                 }
 3127:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3128:             }
 3129:         }
 3130:         if ($numversions) {
 3131:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3132:             $result .=
 3133:                 '<form name="getprev" method="post" action=""'.
 3134:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3135:                 &Apache::loncommon::start_data_table().
 3136:                 &Apache::loncommon::start_data_table_row().
 3137:                 '<th align="left">'.$rowtitle.'</th>'.
 3138:                 '<td><select name="version">'.
 3139:                 '<option>'.&mt('Select').'</option>'.
 3140:                 $list.
 3141:                 '</select></td>'.
 3142:                 &Apache::loncommon::end_data_table_row();
 3143:             unless ($nomenu) {
 3144:                 $result .= &Apache::loncommon::start_data_table_row().
 3145:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3146:                 '<td><span class="LC_nobreak">'.
 3147:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3148:                 &mt('Yes').'</label>'.
 3149:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3150:                 '</span></td>'.
 3151:                 &Apache::loncommon::end_data_table_row();
 3152:             }
 3153:             $result .=
 3154:                 &Apache::loncommon::start_data_table_row().
 3155:                 '<th align="left">&nbsp;</th>'.
 3156:                 '<td>'.
 3157:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3158:                 '</td>'.
 3159:                 &Apache::loncommon::end_data_table_row().
 3160:                 &Apache::loncommon::end_data_table().
 3161:                 '</form>';
 3162:             $js = &previous_display_javascript($nomenu,$current);
 3163:         } elsif ($displayed && $nomenu) {
 3164:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3165:         } else {
 3166:             $result .= &mt('No previous versions to show for this student');
 3167:         }
 3168:         $result .= '</div>';
 3169:     }
 3170:     return ($current,$displayed,$result,$js);
 3171: }
 3172: 
 3173: sub previous_display_javascript {
 3174:     my ($nomenu,$current) = @_;
 3175:     my $js = <<"JSONE";
 3176: <script type="text/javascript">
 3177: // <![CDATA[
 3178: function previousVersion(uname,udom,symb) {
 3179:     var current = '$current';
 3180:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3181:     var prevstr = new RegExp("^\\\\d+\$");
 3182:     if (!prevstr.test(version)) {
 3183:         return false;
 3184:     }
 3185:     var url = '';
 3186:     if (version == current) {
 3187:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3188:     } else {
 3189:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3190:     }
 3191: JSONE
 3192:     if ($nomenu) {
 3193:         $js .= <<"JSTWO";
 3194:     document.location.href = url;
 3195: JSTWO
 3196:     } else {
 3197:         $js .= <<"JSTHREE";
 3198:     var newwin = 0;
 3199:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3200:         if (document.getprev.prevwin[i].checked == true) {
 3201:             newwin = document.getprev.prevwin[i].value;
 3202:         }
 3203:     }
 3204:     if (newwin == 1) {
 3205:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3206:         url = url+'&inhibitmenu=yes';
 3207:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3208:             previousWin = window.open(url,'',options,1);
 3209:         } else {
 3210:             previousWin.location.href = url;
 3211:         }
 3212:         previousWin.focus();
 3213:         return false;
 3214:     } else {
 3215:         document.location.href = url;
 3216:         return false;
 3217:     }
 3218: JSTHREE
 3219:     }
 3220:     $js .= <<"ENDJS";
 3221:     return false;
 3222: }
 3223: // ]]>
 3224: </script>
 3225: ENDJS
 3226: 
 3227: }
 3228: 
 3229: #--- Called from submission routine
 3230: sub processHandGrade {
 3231:     my ($request,$symb) = @_;
 3232:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3233:     my $button = $env{'form.gradeOpt'};
 3234:     my $ngrade = $env{'form.NCT'};
 3235:     my $ntstu  = $env{'form.NTSTU'};
 3236:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3237:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3238:     my ($res_error,%queueable);
 3239:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3240:     if ($res_error) {
 3241:         $request->print(&navmap_errormsg());
 3242:         return;
 3243:     } else {
 3244:         foreach my $part (@{$partlist}) {
 3245:             if (ref($responseType->{$part}) eq 'HASH') {
 3246:                 foreach my $id (keys(%{$responseType->{$part}})) {
 3247:                     if (($responseType->{$part}->{$id} eq 'essay') ||
 3248:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
 3249:                         $queueable{$part} = 1;
 3250:                         last;
 3251:                     }
 3252:                 }
 3253:             }
 3254:         }
 3255:     }
 3256: 
 3257:     if ($button eq 'Save & Next') {
 3258: 	my $ctr = 0;
 3259: 	while ($ctr < $ngrade) {
 3260: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3261: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3262:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
 3263: 	    if ($errorflag eq 'no_score') {
 3264: 		$ctr++;
 3265: 		next;
 3266: 	    }
 3267: 	    if ($errorflag eq 'not_allowed') {
 3268: 		$request->print(
 3269:                     '<span class="LC_error">'
 3270:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3271:                    .'</span>');
 3272: 		$ctr++;
 3273: 		next;
 3274: 	    }
 3275:             if ($numhidden) {
 3276:                 $request->print(
 3277:                     '<span class="LC_info">'
 3278:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3279:                    .'</span><br />');
 3280:             }
 3281: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3282: 	    my ($subject,$message,$msgstatus) = ('','','');
 3283: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3284:             my ($feedurl,$showsymb) =
 3285: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3286: 	    my $messagetail;
 3287: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3288: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3289: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3290: 		$subject.=' ['.$restitle.']';
 3291: 		my (@msgnum) = split(/,/,$includemsg);
 3292: 		foreach (@msgnum) {
 3293: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3294: 		}
 3295: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3296: 		if ($env{'form.withgrades'.$ctr}) {
 3297: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3298: 		    $messagetail = " for <a href=\"".
 3299: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3300: 		}
 3301: 		$msgstatus = 
 3302:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3303: 						     $message.$messagetail,
 3304:                                                      undef,$feedurl,undef,
 3305:                                                      undef,undef,$showsymb,
 3306:                                                      $restitle);
 3307: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3308: 				$msgstatus.'<br />');
 3309: 	    }
 3310: 	    if ($env{'form.collaborator'.$ctr}) {
 3311: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3312: 		foreach my $collabstr (@collabstrs) {
 3313: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3314: 		    foreach my $collaborator (@collaborators) {
 3315: 			my ($errorflag,$pts,$wgt) = 
 3316: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3317: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
 3318: 			if ($errorflag eq 'not_allowed') {
 3319: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3320: 			    next;
 3321: 			} elsif ($message ne '') {
 3322: 			    my ($baseurl,$showsymb) = 
 3323: 				&get_feedurl_and_symb($symb,$collaborator,
 3324: 						      $udom);
 3325: 			    if ($env{'form.withgrades'.$ctr}) {
 3326: 				$messagetail = " for <a href=\"".
 3327:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3328: 			    }
 3329: 			    $msgstatus = 
 3330: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3331: 			}
 3332: 		    }
 3333: 		}
 3334: 	    }
 3335: 	    $ctr++;
 3336: 	}
 3337:     }
 3338: 
 3339:     my %keyhash = ();
 3340:     if ($numessay) {
 3341: 	# Keywords sorted in alphabatical order
 3342: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3343: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3344: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3345: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3346: 	$env{'form.keywords'} = join(' ',@keywords);
 3347: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3348: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3349: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3350: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3351: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3352:     }
 3353: 
 3354:     if ($env{'form.compmsg'}) {
 3355: 	# message center - Order of message gets changed. Blank line is eliminated.
 3356: 	# New messages are saved in env for the next student.
 3357: 	# All messages are saved in nohist_handgrade.db
 3358: 	my ($ctr,$idx) = (1,1);
 3359: 	while ($ctr <= $env{'form.savemsgN'}) {
 3360: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3361: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3362: 		$idx++;
 3363: 	    }
 3364: 	    $ctr++;
 3365: 	}
 3366: 	$ctr = 0;
 3367: 	while ($ctr < $ngrade) {
 3368: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3369: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3370: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3371: 	        $idx++;
 3372: 	    }
 3373: 	    $ctr++;
 3374: 	}
 3375: 	$env{'form.savemsgN'} = --$idx;
 3376: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3377:     }
 3378:     if (($numessay) || ($env{'form.compmsg'})) {
 3379:         my $putresult = &Apache::lonnet::put
 3380:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3381:     }
 3382: 
 3383:     # Called by Save & Refresh from Highlight Attribute Window
 3384:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3385:     if ($env{'form.refresh'} eq 'on') {
 3386: 	my ($ctr,$total) = (0,0);
 3387: 	while ($ctr < $ngrade) {
 3388: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3389: 	    $ctr++;
 3390: 	}
 3391: 	$env{'form.NTSTU'}=$ngrade;
 3392: 	$ctr = 0;
 3393: 	while ($ctr < $total) {
 3394: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3395: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3396: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3397: 	    &submission($request,$ctr,$total-1,$symb);
 3398: 	    $ctr++;
 3399: 	}
 3400: 	return '';
 3401:     }
 3402: 
 3403:     # Get the next/previous one or group of students
 3404:     my $firststu = $env{'form.unamedom0'};
 3405:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3406:     my $ctr = 2;
 3407:     while ($laststu eq '') {
 3408: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3409: 	$ctr++;
 3410: 	$laststu = $firststu if ($ctr > $ngrade);
 3411:     }
 3412: 
 3413:     my (@parsedlist,@nextlist);
 3414:     my ($nextflg) = 0;
 3415:     foreach my $item (sort 
 3416: 	     {
 3417: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3418: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3419: 		 }
 3420: 		 return $a cmp $b;
 3421: 	     } (keys(%$fullname))) {
 3422: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3423: 	    push(@parsedlist,$item);
 3424: 	}
 3425: 	$nextflg = 1 if ($item eq $laststu);
 3426: 	if ($button eq 'Previous') {
 3427: 	    last if ($item eq $firststu);
 3428: 	    push(@parsedlist,$item);
 3429: 	}
 3430:     }
 3431:     $ctr = 0;
 3432:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3433:     foreach my $student (@parsedlist) {
 3434: 	my $submitonly=$env{'form.submitonly'};
 3435: 	my ($uname,$udom) = split(/:/,$student);
 3436: 	
 3437: 	if ($submitonly eq 'queued') {
 3438: 	    my %queue_status = 
 3439: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3440: 							$udom,$uname);
 3441: 	    next if (!defined($queue_status{'gradingqueue'}));
 3442: 	}
 3443: 
 3444: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3445: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3446: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3447: 	    my $submitted = 0;
 3448: 	    my $ungraded = 0;
 3449: 	    my $incorrect = 0;
 3450: 	    foreach my $item (keys(%status)) {
 3451: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3452: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3453: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3454: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3455: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3456: 		    $submitted = 0;
 3457: 		}
 3458: 	    }
 3459: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3460: 				     $submitonly eq 'incorrect' ||
 3461: 				     $submitonly eq 'graded'));
 3462: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3463: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3464: 	}
 3465: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3466: 	last if ($ctr == $ntstu);
 3467: 	$ctr++;
 3468:     }
 3469: 
 3470:     $ctr = 0;
 3471:     my $total = scalar(@nextlist)-1;
 3472: 
 3473:     foreach (sort(@nextlist)) {
 3474: 	my ($uname,$udom,$submitter) = split(/:/);
 3475: 	$env{'form.student'}  = $uname;
 3476: 	$env{'form.userdom'}  = $udom;
 3477: 	$env{'form.fullname'} = $$fullname{$_};
 3478: 	&submission($request,$ctr,$total,$symb);
 3479: 	$ctr++;
 3480:     }
 3481:     if ($total < 0) {
 3482: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3483: 	$request->print($the_end);
 3484:     }
 3485:     return '';
 3486: }
 3487: 
 3488: #---- Save the score and award for each student, if changed
 3489: sub saveHandGrade {
 3490:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
 3491:     my @version_parts;
 3492:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3493: 					   $env{'request.course.id'});
 3494:     if (!&canmodify($usec)) { return('not_allowed'); }
 3495:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3496:     my @parts_graded;
 3497:     my %newrecord  = ();
 3498:     my ($pts,$wgt,$totchg) = ('','',0);
 3499:     my %aggregate = ();
 3500:     my $aggregateflag = 0;
 3501:     if ($env{'form.HIDE'.$newflg}) {
 3502:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3503:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3504:         $totchg += $numchgs;
 3505:     }
 3506:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3507:     foreach my $new_part (@parts) {
 3508: 	#collaborator ($submi may vary for different parts
 3509: 	if ($submitter && $new_part ne $part) { next; }
 3510: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3511: 	if ($dropMenu eq 'excused') {
 3512: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3513: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3514: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3515: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3516: 		}
 3517: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3518: 	    }
 3519: 	} elsif ($dropMenu eq 'reset status'
 3520: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3521: 	    foreach my $key (keys(%record)) {
 3522: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3523: 	    }
 3524: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3525: 		"$env{'user.name'}:$env{'user.domain'}";
 3526:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3527: 
 3528:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3529: 					       [$new_part]);
 3530:             my $aggtries =$totaltries;
 3531:             if ($last_resets{$new_part}) {
 3532:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3533: 					   $new_part);
 3534:             }
 3535: 
 3536:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3537:             if ($aggtries > 0) {
 3538:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3539:                 $aggregateflag = 1;
 3540:             }
 3541: 	} elsif ($dropMenu eq '') {
 3542: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3543: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3544: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3545: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3546: 		next;
 3547: 	    }
 3548: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3549: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3550: 	    my $partial= $pts/$wgt;
 3551: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3552: 		#do not update score for part if not changed.
 3553:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3554: 		next;
 3555: 	    } else {
 3556: 	        push(@parts_graded,$new_part);
 3557: 	    }
 3558: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3559: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3560: 	    }
 3561: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3562: 	    if ($partial == 0) {
 3563: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3564: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3565: 		}
 3566: 	    } else {
 3567: 		if ($record{$reckey} ne 'correct_by_override') {
 3568: 		    $newrecord{$reckey} = 'correct_by_override';
 3569: 		}
 3570: 	    }	    
 3571: 	    if ($submitter && 
 3572: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3573: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3574: 	    }
 3575: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3576: 		"$env{'user.name'}:$env{'user.domain'}";
 3577: 	}
 3578: 	# unless problem has been graded, set flag to version the submitted files
 3579: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3580: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3581: 	        $dropMenu eq 'reset status')
 3582: 	   {
 3583: 	    push(@version_parts,$new_part);
 3584: 	}
 3585:     }
 3586:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3587:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3588: 
 3589:     if (%newrecord) {
 3590:         if (@version_parts) {
 3591:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3592:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3593: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3594: 	    foreach my $new_part (@version_parts) {
 3595: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3596: 				$new_part,\%newrecord);
 3597: 	    }
 3598:         }
 3599: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3600: 				$env{'request.course.id'},$domain,$stuname);
 3601: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3602: 				     $cdom,$cnum,$domain,$stuname,$queueable);
 3603:     }
 3604:     if ($aggregateflag) {
 3605:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3606: 			      $cdom,$cnum);
 3607:     }
 3608:     return ('',$pts,$wgt,$totchg);
 3609: }
 3610: 
 3611: sub makehidden {
 3612:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3613:     return unless (ref($record) eq 'HASH');
 3614:     my %modified;
 3615:     my $numchanged = 0;
 3616:     if (exists($record->{$version.':keys'})) {
 3617:         my $partsregexp = $parts;
 3618:         $partsregexp =~ s/,/|/g;
 3619:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3620:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3621:                  my $item = $1;
 3622:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3623:                      $modified{$key} = $record->{$version.':'.$key};
 3624:                  }
 3625:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3626:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3627:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3628:                 $modified{$key} = $record->{$version.':'.$key};
 3629:             }
 3630:         }
 3631:         if (keys(%modified)) {
 3632:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3633:                                           $domain,$stuname,$tolog) eq 'ok') {
 3634:                 $numchanged ++;
 3635:             }
 3636:         }
 3637:     }
 3638:     return $numchanged;
 3639: }
 3640: 
 3641: sub check_and_remove_from_queue {
 3642:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
 3643:     my @ungraded_parts;
 3644:     foreach my $part (@{$parts}) {
 3645: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3646: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3647: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3648: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3649: 		) {
 3650:             if ($queueable->{$part}) {
 3651: 	        push(@ungraded_parts, $part);
 3652:             }
 3653: 	}
 3654:     }
 3655:     if ( !@ungraded_parts ) {
 3656: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3657: 					       $cnum,$domain,$stuname);
 3658:     }
 3659: }
 3660: 
 3661: sub handback_files {
 3662:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3663:     my $portfolio_root = '/userfiles/portfolio';
 3664:     my $res_error;
 3665:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3666:     if ($res_error) {
 3667:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3668:         return;
 3669:     }
 3670:     my @handedback;
 3671:     my $file_msg;
 3672:     my @part_response_id = &flatten_responseType($responseType);
 3673:     foreach my $part_response_id (@part_response_id) {
 3674:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3675: 	my $part_resp = join('_',@{ $part_response_id });
 3676:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3677:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3678:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3679:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3680:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3681:                     my ($directory,$answer_file) = 
 3682:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3683:                     my ($answer_name,$answer_ver,$answer_ext) =
 3684: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3685: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3686:                     my $getpropath = 1;
 3687:                     my ($dir_list,$listerror) =
 3688:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3689:                                                  $domain,$stuname,$getpropath);
 3690: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3691:                     # fix filename
 3692:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3693:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3694:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3695:             	                                $save_file_name);
 3696:                     if ($result !~ m|^/uploaded/|) {
 3697:                         $request->print('<br /><span class="LC_error">'.
 3698:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3699:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3700:                                         '</span>');
 3701:                     } else {
 3702:                         # mark the file as read only
 3703:                         push(@handedback,$save_file_name);
 3704: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3705: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3706: 			}
 3707:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3708: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3709:                     }
 3710:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
 3711:                 }
 3712:             }
 3713:         }
 3714:     }
 3715:     if (@handedback > 0) {
 3716:         $request->print('<br />');
 3717:         my @what = ($symb,$env{'request.course.id'},'handback');
 3718:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3719:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3720:         my ($subject,$message);
 3721:         if (scalar(@handedback) == 1) {
 3722:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3723:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3724:         } else {
 3725:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3726:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3727:         }
 3728:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3729:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3730:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3731:         my ($feedurl,$showsymb) =
 3732:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3733:         my $restitle = &Apache::lonnet::gettitle($symb);
 3734:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3735:         my $msgstatus =
 3736:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3737:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3738:                  $restitle);
 3739:         if ($msgstatus) {
 3740:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3741:         }
 3742:     }
 3743:     return;
 3744: }
 3745: 
 3746: sub get_feedurl_and_symb {
 3747:     my ($symb,$uname,$udom) = @_;
 3748:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3749:     $url = &Apache::lonnet::clutter($url);
 3750:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3751: 					$symb,$udom,$uname);
 3752:     if ($encrypturl =~ /^yes$/i) {
 3753: 	&Apache::lonenc::encrypted(\$url,1);
 3754: 	&Apache::lonenc::encrypted(\$symb,1);
 3755:     }
 3756:     return ($url,$symb);
 3757: }
 3758: 
 3759: sub get_submitted_files {
 3760:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3761:     my @files;
 3762:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3763:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3764:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3765:     	    push(@files,$file_url.$file);
 3766:         }
 3767:     }
 3768:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3769:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3770:     }
 3771:     return (\@files);
 3772: }
 3773: 
 3774: # ----------- Provides number of tries since last reset.
 3775: sub get_num_tries {
 3776:     my ($record,$last_reset,$part) = @_;
 3777:     my $timestamp = '';
 3778:     my $num_tries = 0;
 3779:     if ($$record{'version'}) {
 3780:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3781:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3782:                 $timestamp = $$record{$version.':timestamp'};
 3783:                 if ($timestamp > $last_reset) {
 3784:                     $num_tries ++;
 3785:                 } else {
 3786:                     last;
 3787:                 }
 3788:             }
 3789:         }
 3790:     }
 3791:     return $num_tries;
 3792: }
 3793: 
 3794: # ----------- Determine decrements required in aggregate totals 
 3795: sub decrement_aggs {
 3796:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3797:     my %decrement = (
 3798:                         attempts => 0,
 3799:                         users => 0,
 3800:                         correct => 0
 3801:                     );
 3802:     $decrement{'attempts'} = $aggtries;
 3803:     if ($solvedstatus =~ /^correct/) {
 3804:         $decrement{'correct'} = 1;
 3805:     }
 3806:     if ($aggtries == $totaltries) {
 3807:         $decrement{'users'} = 1;
 3808:     }
 3809:     foreach my $type (keys(%decrement)) {
 3810:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3811:     }
 3812:     return;
 3813: }
 3814: 
 3815: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3816: sub get_last_resets {
 3817:     my ($symb,$courseid,$partids) =@_;
 3818:     my %last_resets;
 3819:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3820:     my $cname = $env{'course.'.$courseid.'.num'};
 3821:     my @keys;
 3822:     foreach my $part (@{$partids}) {
 3823: 	push(@keys,"$symb\0$part\0resettime");
 3824:     }
 3825:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3826: 				     $cdom,$cname);
 3827:     foreach my $part (@{$partids}) {
 3828: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3829:     }
 3830:     return %last_resets;
 3831: }
 3832: 
 3833: # ----------- Handles creating versions for portfolio files as answers
 3834: sub version_portfiles {
 3835:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3836:     my $version_parts = join('|',@$v_flag);
 3837:     my @returned_keys;
 3838:     my $parts = join('|', @$parts_graded);
 3839:     foreach my $key (keys(%$record)) {
 3840:         my $new_portfiles;
 3841:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3842:             my @versioned_portfiles;
 3843:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3844:             if (@portfiles) {
 3845:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3846:                                                       \@versioned_portfiles);
 3847:             }
 3848:             $$record{$key} = join(',',@versioned_portfiles);
 3849:             push(@returned_keys,$key);
 3850:         }
 3851:     } 
 3852:     return (@returned_keys);   
 3853: }
 3854: 
 3855: #--------------------------------------------------------------------------------------
 3856: #
 3857: #-------------------------- Next few routines handles grading by section or whole class
 3858: #
 3859: #--- Javascript to handle grading by section or whole class
 3860: sub viewgrades_js {
 3861:     my ($request) = shift;
 3862: 
 3863:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3864:     &js_escape(\$alertmsg);
 3865:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3866:    function writePoint(partid,weight,point) {
 3867: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3868: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3869: 	if (point == "textval") {
 3870: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3871: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3872: 		alert("$alertmsg"+parseFloat(point));
 3873: 		var resetbox = false;
 3874: 		for (var i=0; i<radioButton.length; i++) {
 3875: 		    if (radioButton[i].checked) {
 3876: 			textbox.value = i;
 3877: 			resetbox = true;
 3878: 		    }
 3879: 		}
 3880: 		if (!resetbox) {
 3881: 		    textbox.value = "";
 3882: 		}
 3883: 		return;
 3884: 	    }
 3885: 	    if (parseFloat(point) > parseFloat(weight)) {
 3886: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3887: 				   ") greater than the weight for the part. Accept?");
 3888: 		if (resp == false) {
 3889: 		    textbox.value = "";
 3890: 		    return;
 3891: 		}
 3892: 	    }
 3893: 	    for (var i=0; i<radioButton.length; i++) {
 3894: 		radioButton[i].checked=false;
 3895: 		if (parseFloat(point) == i) {
 3896: 		    radioButton[i].checked=true;
 3897: 		}
 3898: 	    }
 3899: 
 3900: 	} else {
 3901: 	    textbox.value = parseFloat(point);
 3902: 	}
 3903: 	for (i=0;i<document.classgrade.total.value;i++) {
 3904: 	    var user = document.classgrade["ctr"+i].value;
 3905: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3906: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3907: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3908: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3909: 	    if (saveval != "correct") {
 3910: 		scorename.value = point;
 3911: 		if (selname[0].selected != true) {
 3912: 		    selname[0].selected = true;
 3913: 		}
 3914: 	    }
 3915: 	}
 3916: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3917:     }
 3918: 
 3919:     function writeRadText(partid,weight) {
 3920: 	var selval   = document.classgrade["SELVAL_"+partid];
 3921: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3922:         var override = document.classgrade["FORCE_"+partid].checked;
 3923: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3924: 	if (selval[1].selected || selval[2].selected) {
 3925: 	    for (var i=0; i<radioButton.length; i++) {
 3926: 		radioButton[i].checked=false;
 3927: 
 3928: 	    }
 3929: 	    textbox.value = "";
 3930: 
 3931: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3932: 		var user = document.classgrade["ctr"+i].value;
 3933: 		user = user.replace(new RegExp(':', 'g'),"_");
 3934: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3935: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3936: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3937: 		if ((saveval != "correct") || override) {
 3938: 		    scorename.value = "";
 3939: 		    if (selval[1].selected) {
 3940: 			selname[1].selected = true;
 3941: 		    } else {
 3942: 			selname[2].selected = true;
 3943: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3944: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3945: 		    }
 3946: 		}
 3947: 	    }
 3948: 	} else {
 3949: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3950: 		var user = document.classgrade["ctr"+i].value;
 3951: 		user = user.replace(new RegExp(':', 'g'),"_");
 3952: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3953: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3954: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3955: 		if ((saveval != "correct") || override) {
 3956: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3957: 		    selname[0].selected = true;
 3958: 		}
 3959: 	    }
 3960: 	}	    
 3961:     }
 3962: 
 3963:     function changeSelect(partid,user) {
 3964: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3965: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3966: 	var point  = textbox.value;
 3967: 	var weight = document.classgrade["weight_"+partid].value;
 3968: 
 3969: 	if (isNaN(point) || parseFloat(point) < 0) {
 3970: 	    alert("$alertmsg"+parseFloat(point));
 3971: 	    textbox.value = "";
 3972: 	    return;
 3973: 	}
 3974: 	if (parseFloat(point) > parseFloat(weight)) {
 3975: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3976: 			       ") greater than the weight of the part. Accept?");
 3977: 	    if (resp == false) {
 3978: 		textbox.value = "";
 3979: 		return;
 3980: 	    }
 3981: 	}
 3982: 	selval[0].selected = true;
 3983:     }
 3984: 
 3985:     function changeOneScore(partid,user) {
 3986: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3987: 	if (selval[1].selected || selval[2].selected) {
 3988: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3989: 	    if (selval[2].selected) {
 3990: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3991: 	    }
 3992:         }
 3993:     }
 3994: 
 3995:     function resetEntry(numpart) {
 3996: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3997: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3998: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3999: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 4000: 	    var selval  = document.classgrade["SELVAL_"+partid];
 4001: 	    for (var i=0; i<radioButton.length; i++) {
 4002: 		radioButton[i].checked=false;
 4003: 
 4004: 	    }
 4005: 	    textbox.value = "";
 4006: 	    selval[0].selected = true;
 4007: 
 4008: 	    for (i=0;i<document.classgrade.total.value;i++) {
 4009: 		var user = document.classgrade["ctr"+i].value;
 4010: 		user = user.replace(new RegExp(':', 'g'),"_");
 4011: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 4012: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 4013: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 4014: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 4015: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 4016: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 4017: 		if (saveselval == "excused") {
 4018: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 4019: 		} else {
 4020: 		    if (selname[0].selected == false) {selname[0].selected = true};
 4021: 		}
 4022: 	    }
 4023: 	}
 4024:     }
 4025: 
 4026: VIEWJAVASCRIPT
 4027: }
 4028: 
 4029: #--- show scores for a section or whole class w/ option to change/update a score
 4030: sub viewgrades {
 4031:     my ($request,$symb) = @_;
 4032:     my ($is_tool,$toolsymb);
 4033:     if ($symb =~ /ext\.tool$/) {
 4034:         $is_tool = 1;
 4035:         $toolsymb = $symb;
 4036:     }
 4037:     &viewgrades_js($request);
 4038: 
 4039:     #need to make sure we have the correct data for later EXT calls, 
 4040:     #thus invalidate the cache
 4041:     &Apache::lonnet::devalidatecourseresdata(
 4042:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4043:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4044:     &Apache::lonnet::clear_EXT_cache_status();
 4045: 
 4046:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 4047: 
 4048:     #view individual student submission form - called using Javascript viewOneStudent
 4049:     $result.=&jscriptNform($symb);
 4050: 
 4051:     #beginning of class grading form
 4052:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4053:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4054: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4055: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4056: 	&build_section_inputs().
 4057: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4058: 
 4059:     #retrieve selected groups
 4060:     my (@groups,$group_display);
 4061:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4062:     if (grep(/^all$/,@groups)) {
 4063:         @groups = ('all');
 4064:     } elsif (grep(/^none$/,@groups)) {
 4065:         @groups = ('none');
 4066:     } elsif (@groups > 0) {
 4067:         $group_display = join(', ',@groups);
 4068:     }
 4069: 
 4070:     my ($common_header,$specific_header,@sections,$section_display);
 4071:     if ($env{'request.course.sec'} ne '') {
 4072:         @sections = ($env{'request.course.sec'});
 4073:     } else {
 4074:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4075:     }
 4076: 
 4077: # Check if Save button should be usable
 4078:     my $disabled = ' disabled="disabled"';
 4079:     if ($perm{'mgr'}) {
 4080:         if (grep(/^all$/,@sections)) {
 4081:             undef($disabled);
 4082:         } else {
 4083:             foreach my $sec (@sections) {
 4084:                 if (&canmodify($sec)) {
 4085:                     undef($disabled);
 4086:                     last;
 4087:                 }
 4088:             }
 4089:         }
 4090:     }
 4091:     if (grep(/^all$/,@sections)) {
 4092:         @sections = ('all');
 4093:         if ($group_display) {
 4094:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4095:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4096:         } elsif (grep(/^none$/,@groups)) {
 4097:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4098:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4099:         } else {
 4100: 	    $common_header = &mt('Assign Common Grade to Class');
 4101:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4102:         }
 4103:     } elsif (grep(/^none$/,@sections)) {
 4104:         @sections = ('none');
 4105:         if ($group_display) {
 4106:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4107:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4108:         } elsif (grep(/^none$/,@groups)) {
 4109:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4110:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4111:         } else {
 4112:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4113: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4114:         }
 4115:     } else {
 4116:         $section_display = join (", ",@sections);
 4117:         if ($group_display) {
 4118:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4119:                                  $section_display,$group_display);
 4120:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4121:                                    $section_display,$group_display);
 4122:         } elsif (grep(/^none$/,@groups)) {
 4123:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4124:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4125:         } else {
 4126:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4127: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4128:         }
 4129:     }
 4130:     my %submit_types = &substatus_options();
 4131:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4132: 
 4133:     if ($env{'form.submitonly'} eq 'all') {
 4134:         $result.= '<h3>'.$common_header.'</h3>';
 4135:     } else {
 4136:         my $text;
 4137:         if ($is_tool) {
 4138:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4139:         } else {
 4140:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4141:         }
 4142:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 4143:     }
 4144:     $result .= &Apache::loncommon::start_data_table();
 4145:     #radio buttons/text box for assigning points for a section or class.
 4146:     #handles different parts of a problem
 4147:     my $res_error;
 4148:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4149:     if ($res_error) {
 4150:         return &navmap_errormsg();
 4151:     }
 4152:     my %weight = ();
 4153:     my $ctsparts = 0;
 4154:     my %seen = ();
 4155:     my @part_response_id;
 4156:     if ($is_tool) {
 4157:         @part_response_id = ([0,'']);
 4158:     } else {
 4159:         @part_response_id = &flatten_responseType($responseType);
 4160:     }
 4161:     foreach my $part_response_id (@part_response_id) {
 4162:     	my ($partid,$respid) = @{ $part_response_id };
 4163: 	my $part_resp = join('_',@{ $part_response_id });
 4164: 	next if $seen{$partid};
 4165: 	$seen{$partid}++;
 4166: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4167: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4168: 
 4169: 	my $display_part=&get_display_part($partid,$symb);
 4170: 	my $radio.='<table border="0"><tr>';  
 4171: 	my $ctr = 0;
 4172: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4173: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4174: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4175: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4176: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4177: 	    $ctr++;
 4178: 	}
 4179: 	$radio.='</tr></table>';
 4180: 	my $line = '<input type="text" name="TEXTVAL_'.
 4181: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4182: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4183: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4184:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4185:             '<select name="SELVAL_'.$partid.'" '.
 4186:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 4187:                 $weight{$partid}.')"> '.
 4188: 	    '<option selected="selected"> </option>'.
 4189: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4190: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4191: 	    '</select></td>'.
 4192:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4193: 	$line.='<input type="hidden" name="partid_'.
 4194: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4195: 	$line.='<input type="hidden" name="weight_'.
 4196: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4197: 
 4198: 	$result.=
 4199: 	    &Apache::loncommon::start_data_table_row()."\n".
 4200: 	    '<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>'.
 4201: 	    &Apache::loncommon::end_data_table_row()."\n";
 4202: 	$ctsparts++;
 4203:     }
 4204:     $result.=&Apache::loncommon::end_data_table()."\n".
 4205: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4206:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4207: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4208: 
 4209:     #table listing all the students in a section/class
 4210:     #header of table
 4211:     if ($env{'form.submitonly'} eq 'all') {
 4212:         $result.= '<h3>'.$specific_header.'</h3>';
 4213:     } else {
 4214:         my $text;
 4215:         if ($is_tool) {
 4216:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4217:         } else {
 4218:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4219:         }
 4220:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 4221:     }
 4222:     $result.= &Apache::loncommon::start_data_table().
 4223: 	      &Apache::loncommon::start_data_table_header_row().
 4224: 	      '<th>'.&mt('No.').'</th>'.
 4225: 	      '<th>'.&nameUserString('header')."</th>\n";
 4226:     my $partserror;
 4227:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4228:     if ($partserror) {
 4229:         return &navmap_errormsg();
 4230:     }
 4231:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4232:     my @partids = ();
 4233:     foreach my $part (@parts) {
 4234: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4235:         my $narrowtext = &mt('Tries');
 4236: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4237: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 4238: 	my ($partid) = &split_part_type($part);
 4239:         push(@partids,$partid);
 4240: #
 4241: # FIXME: Looks like $display looks at English text
 4242: #
 4243: 	my $display_part=&get_display_part($partid,$symb);
 4244: 	if ($display =~ /^Partial Credit Factor/) {
 4245: 	    $result.='<th>'.
 4246: 		&mt('Score Part: [_1][_2](weight = [_3])',
 4247: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4248: 	    next;
 4249: 	    
 4250: 	} else {
 4251: 	    if ($display =~ /Problem Status/) {
 4252: 		my $grade_status_mt = &mt('Grade Status');
 4253: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4254: 	    }
 4255: 	    my $part_mt = &mt('Part:');
 4256: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4257: 	}
 4258: 
 4259: 	$result.='<th>'.$display.'</th>'."\n";
 4260:     }
 4261:     $result.=&Apache::loncommon::end_data_table_header_row();
 4262: 
 4263:     my %last_resets = 
 4264: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4265: 
 4266:     #get info for each student
 4267:     #list all the students - with points and grade status
 4268:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4269:     my $ctr = 0;
 4270:     foreach (sort 
 4271: 	     {
 4272: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4273: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4274: 		 }
 4275: 		 return $a cmp $b;
 4276: 	     } (keys(%$fullname))) {
 4277: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4278: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4279:     }
 4280:     $result.=&Apache::loncommon::end_data_table();
 4281:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4282:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4283: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4284:     if ($ctr == 0) {
 4285:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4286:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4287:                 '<span class="LC_warning">';
 4288:         if ($env{'form.submitonly'} eq 'all') {
 4289:             if (grep(/^all$/,@sections)) {
 4290:                 if (grep(/^all$/,@groups)) {
 4291:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4292:                                    $stu_status);
 4293:                 } elsif (grep(/^none$/,@groups)) {
 4294:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4295:                                    $stu_status); 
 4296:                 } else {
 4297:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4298:                                    $group_display,$stu_status);
 4299:                 }
 4300:             } elsif (grep(/^none$/,@sections)) {
 4301:                 if (grep(/^all$/,@groups)) {
 4302:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4303:                                    $stu_status);
 4304:                 } elsif (grep(/^none$/,@groups)) {
 4305:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4306:                                    $stu_status);
 4307:                 } else {
 4308:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4309:                                    $group_display,$stu_status);
 4310:                 }
 4311:             } else {
 4312:                 if (grep(/^all$/,@groups)) {
 4313:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4314:                                    $section_display,$stu_status);
 4315:                 } elsif (grep(/^none$/,@groups)) {
 4316:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4317:                                    $section_display,$stu_status);
 4318:                 } else {
 4319:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4320:                                    $section_display,$group_display,$stu_status);
 4321:                 }
 4322:             }
 4323:         } else {
 4324:             if (grep(/^all$/,@sections)) {
 4325:                 if (grep(/^all$/,@groups)) {
 4326:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4327:                                    $stu_status,$submission_status);
 4328:                 } elsif (grep(/^none$/,@groups)) {
 4329:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4330:                                    $stu_status,$submission_status);
 4331:                 } else {
 4332:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4333:                                    $group_display,$stu_status,$submission_status);
 4334:                 }
 4335:             } elsif (grep(/^none$/,@sections)) {
 4336:                 if (grep(/^all$/,@groups)) {
 4337:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4338:                                    $stu_status,$submission_status);
 4339:                 } elsif (grep(/^none$/,@groups)) {
 4340:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4341:                                    $stu_status,$submission_status);
 4342:                 } else {
 4343:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4344:                                    $group_display,$stu_status,$submission_status);
 4345:                 }
 4346:             } else {
 4347:                 if (grep(/^all$/,@groups)) {
 4348: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4349: 	                           $section_display,$stu_status,$submission_status);
 4350:                 } elsif (grep(/^none$/,@groups)) {
 4351:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4352:                                    $section_display,$stu_status,$submission_status);
 4353:                 } else {
 4354:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
 4355:                                    $section_display,$group_display,$stu_status,$submission_status);
 4356:                 }
 4357:             }
 4358:         }
 4359: 	$result .= '</span><br />';
 4360:     }
 4361:     return $result;
 4362: }
 4363: 
 4364: #--- call by previous routine to display each student who satisfies submission filter. 
 4365: sub viewstudentgrade {
 4366:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4367:     my ($uname,$udom) = split(/:/,$student);
 4368:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4369:     my $submitonly = $env{'form.submitonly'};
 4370:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4371:         my %partstatus = ();
 4372:         if (ref($parts) eq 'ARRAY') {
 4373:             foreach my $apart (@{$parts}) {
 4374:                 my ($part,$type) = &split_part_type($apart);
 4375:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4376:                 $status = 'nothing' if ($status eq '');
 4377:                 $partstatus{$part}      = $status;
 4378:                 my $subkey = "resource.$part.submitted_by";
 4379:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4380:             }
 4381:             my $submitted = 0;
 4382:             my $graded = 0;
 4383:             my $incorrect = 0;
 4384:             foreach my $key (keys(%partstatus)) {
 4385:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4386:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4387:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4388: 
 4389:                 my $partid = (split(/\./,$key))[1];
 4390:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4391:                     $submitted = 0;
 4392:                 }
 4393:             }
 4394:             return if (!$submitted && ($submitonly eq 'yes' ||
 4395:                                        $submitonly eq 'incorrect' ||
 4396:                                        $submitonly eq 'graded'));
 4397:             return if (!$graded && ($submitonly eq 'graded'));
 4398:             return if (!$incorrect && $submitonly eq 'incorrect');
 4399:         }
 4400:     }
 4401:     if ($submitonly eq 'queued') {
 4402:         my ($cdom,$cnum) = split(/_/,$courseid);
 4403:         my %queue_status =
 4404:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4405:                                                     $udom,$uname);
 4406:         return if (!defined($queue_status{'gradingqueue'}));
 4407:     }
 4408:     $$ctr++;
 4409:     my %aggregates = ();
 4410:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4411: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4412: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4413: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4414: 	'\');" target="_self">'.$fullname.'</a> '.
 4415: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4416:     $student=~s/:/_/; # colon doen't work in javascript for names
 4417:     foreach my $apart (@$parts) {
 4418: 	my ($part,$type) = &split_part_type($apart);
 4419: 	my $score=$record{"resource.$part.$type"};
 4420:         $result.='<td align="center">';
 4421:         my ($aggtries,$totaltries);
 4422:         unless (exists($aggregates{$part})) {
 4423: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4424: 	    $aggtries = $totaltries;
 4425:             if ($$last_resets{$part}) {  
 4426:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4427: 					   $part);
 4428:             }
 4429:             $result.='<input type="hidden" name="'.
 4430:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4431:             $result.='<input type="hidden" name="'.
 4432:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4433:             $aggregates{$part} = 1;
 4434:         }
 4435: 	if ($type eq 'awarded') {
 4436: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4437: 	    $result.='<input type="hidden" name="'.
 4438: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4439: 	    $result.='<input type="text" name="'.
 4440: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4441:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4442: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4443: 	} elsif ($type eq 'solved') {
 4444: 	    my ($status,$foo)=split(/_/,$score,2);
 4445: 	    $status = 'nothing' if ($status eq '');
 4446: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4447: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4448: 	    $result.='&nbsp;<select name="'.
 4449: 		'GD_'.$student.'_'.$part.'_solved" '.
 4450:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4451: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4452: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4453: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4454: 	    $result.="</select>&nbsp;</td>\n";
 4455: 	} else {
 4456: 	    $result.='<input type="hidden" name="'.
 4457: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4458: 		    "\n";
 4459: 	    $result.='<input type="text" name="'.
 4460: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4461: 		'value="'.$score.'" size="4" /></td>'."\n";
 4462: 	}
 4463:     }
 4464:     $result.=&Apache::loncommon::end_data_table_row();
 4465:     return $result;
 4466: }
 4467: 
 4468: #--- change scores for all the students in a section/class
 4469: #    record does not get update if unchanged
 4470: sub editgrades {
 4471:     my ($request,$symb) = @_;
 4472:     my $toolsymb;
 4473:     if ($symb =~ /ext\.tool$/) {
 4474:         $toolsymb = $symb;
 4475:     }
 4476: 
 4477:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4478:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4479:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4480: 
 4481:     my $result= &Apache::loncommon::start_data_table().
 4482: 	&Apache::loncommon::start_data_table_header_row().
 4483: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4484: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4485:     my %scoreptr = (
 4486: 		    'correct'  =>'correct_by_override',
 4487: 		    'incorrect'=>'incorrect_by_override',
 4488: 		    'excused'  =>'excused',
 4489: 		    'ungraded' =>'ungraded_attempted',
 4490:                     'credited' =>'credit_attempted',
 4491: 		    'nothing'  => '',
 4492: 		    );
 4493:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4494: 
 4495:     my (@partid);
 4496:     my %weight = ();
 4497:     my %columns = ();
 4498:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4499: 
 4500:     my $partserror;
 4501:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4502:     if ($partserror) {
 4503:         return &navmap_errormsg();
 4504:     }
 4505:     my $header;
 4506:     while ($ctr < $env{'form.totalparts'}) {
 4507: 	my $partid = $env{'form.partid_'.$ctr};
 4508: 	push(@partid,$partid);
 4509: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4510: 	$ctr++;
 4511:     }
 4512:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4513:     my $totcolspan = 0;
 4514:     foreach my $partid (@partid) {
 4515: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4516: 	    '<th align="center">'.&mt('New Score').'</th>';
 4517: 	$columns{$partid}=2;
 4518: 	foreach my $stores (@parts) {
 4519: 	    my ($part,$type) = &split_part_type($stores);
 4520: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4521: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4522: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4523: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4524:             my $narrowtext = &mt('Tries');
 4525: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4526: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4527: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4528: 	    $columns{$partid}+=2;
 4529: 	}
 4530:         $totcolspan += $columns{$partid};
 4531:     }
 4532:     foreach my $partid (@partid) {
 4533: 	my $display_part=&get_display_part($partid,$symb);
 4534: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4535: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4536: 	    '</th>';
 4537: 
 4538:     }
 4539:     $result .= &Apache::loncommon::end_data_table_header_row().
 4540: 	&Apache::loncommon::start_data_table_header_row().
 4541: 	$header.
 4542: 	&Apache::loncommon::end_data_table_header_row();
 4543:     my @noupdate;
 4544:     my ($updateCtr,$noupdateCtr) = (1,1);
 4545:     my ($got_types,%queueable);
 4546:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4547: 	my $user = $env{'form.ctr'.$i};
 4548: 	my ($uname,$udom)=split(/:/,$user);
 4549: 	my %newrecord;
 4550: 	my $updateflag = 0;
 4551: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4552: 	my $canmodify = &canmodify($usec);
 4553: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4554: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4555: 	if (!$canmodify) {
 4556: 	    push(@noupdate,
 4557: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4558: 		 &mt('Not allowed to modify student')."</span></td>");
 4559: 	    next;
 4560: 	}
 4561:         my %aggregate = ();
 4562:         my $aggregateflag = 0;
 4563: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4564: 	foreach (@partid) {
 4565: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4566: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4567: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4568: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4569: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4570: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4571: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4572: 	    my $score;
 4573: 	    if ($partial eq '') {
 4574: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4575: 	    } elsif ($partial > 0) {
 4576: 		$score = 'correct_by_override';
 4577: 	    } elsif ($partial == 0) {
 4578: 		$score = 'incorrect_by_override';
 4579: 	    }
 4580: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4581: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4582: 
 4583: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4584: 		"$env{'user.name'}:$env{'user.domain'}";
 4585: 	    if ($dropMenu eq 'reset status' &&
 4586: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4587: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4588: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4589: 		$newrecord{'resource.'.$_.'.award'} = '';
 4590: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4591: 		$updateflag = 1;
 4592:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4593:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4594:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4595:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4596:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4597:                     $aggregateflag = 1;
 4598:                 }
 4599: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4600: 		$updateflag = 1;
 4601: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4602: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4603: 		$rec_update++;
 4604: 	    }
 4605: 
 4606: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4607: 		'<td align="center">'.$awarded.
 4608: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4609: 
 4610: 
 4611: 	    my $partid=$_;
 4612: 	    foreach my $stores (@parts) {
 4613: 		my ($part,$type) = &split_part_type($stores);
 4614: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4615: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4616: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4617: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4618: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4619: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4620: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4621: 		    $updateflag=1;
 4622: 		}
 4623: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4624: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4625: 	    }
 4626: 	}
 4627: 	$line.="\n";
 4628: 
 4629: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4630: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4631: 
 4632: 	if ($updateflag) {
 4633: 	    $count++;
 4634: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4635: 				    $udom,$uname);
 4636: 
 4637: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4638: 					      $cnum,$udom,$uname)) {
 4639: 		# need to figure out if should be in queue.
 4640: 		my %record =  
 4641: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4642: 					     $udom,$uname);
 4643: 		my $all_graded = 1;
 4644: 		my $none_graded = 1;
 4645:                 unless ($got_types) {
 4646:                     my $error;
 4647:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
 4648:                     unless ($error) {
 4649:                         foreach my $part (@parts) {
 4650:                             if (ref($resptype->{$part}) eq 'HASH') {
 4651:                                 foreach my $id (keys(%{$resptype->{$part}})) {
 4652:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
 4653:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
 4654:                                         $queueable{$part} = 1;
 4655:                                         last;
 4656:                                     }
 4657:                                 }
 4658:                             }
 4659:                         }
 4660:                     }
 4661:                     $got_types = 1;
 4662:                 }
 4663: 		foreach my $part (@parts) {
 4664:                     if ($queueable{$part}) {
 4665: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4666: 			    $all_graded = 0;
 4667: 		        } else {
 4668: 			    $none_graded = 0;
 4669: 		        }
 4670: 		    }
 4671:                 }
 4672: 		if ($all_graded || $none_graded) {
 4673: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4674: 							   $symb,$cdom,$cnum,
 4675: 							   $udom,$uname);
 4676: 		}
 4677: 	    }
 4678: 
 4679: 	    $result.=&Apache::loncommon::start_data_table_row().
 4680: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4681: 		&Apache::loncommon::end_data_table_row();
 4682: 	    $updateCtr++;
 4683: 	} else {
 4684: 	    push(@noupdate,
 4685: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4686: 	    $noupdateCtr++;
 4687: 	}
 4688:         if ($aggregateflag) {
 4689:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4690: 				  $cdom,$cnum);
 4691:         }
 4692:     }
 4693:     if (@noupdate) {
 4694:         my $numcols=$totcolspan+2;
 4695: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4696: 	    '<td align="center" colspan="'.$numcols.'">'.
 4697: 	    &mt('No Changes Occurred For the Students Below').
 4698: 	    '</td>'.
 4699: 	    &Apache::loncommon::end_data_table_row();
 4700: 	foreach my $line (@noupdate) {
 4701: 	    $result.=
 4702: 		&Apache::loncommon::start_data_table_row().
 4703: 		$line.
 4704: 		&Apache::loncommon::end_data_table_row();
 4705: 	}
 4706:     }
 4707:     $result .= &Apache::loncommon::end_data_table();
 4708:     my $msg = '<p><b>'.
 4709: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4710: 	    $rec_update,$count).'</b><br />'.
 4711: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4712: 	'</b></p>';
 4713:     return $title.$msg.$result;
 4714: }
 4715: 
 4716: sub split_part_type {
 4717:     my ($partstr) = @_;
 4718:     my ($temp,@allparts)=split(/_/,$partstr);
 4719:     my $type=pop(@allparts);
 4720:     my $part=join('_',@allparts);
 4721:     return ($part,$type);
 4722: }
 4723: 
 4724: #------------- end of section for handling grading by section/class ---------
 4725: #
 4726: #----------------------------------------------------------------------------
 4727: 
 4728: 
 4729: #----------------------------------------------------------------------------
 4730: #
 4731: #-------------------------- Next few routines handles grading by csv upload
 4732: #
 4733: #--- Javascript to handle csv upload
 4734: sub csvupload_javascript_reverse_associate {
 4735:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4736:     my $error2=&mt('You need to specify at least one grading field');
 4737:   &js_escape(\$error1);
 4738:   &js_escape(\$error2);
 4739:   return(<<ENDPICK);
 4740:   function verify(vf) {
 4741:     var foundsomething=0;
 4742:     var founduname=0;
 4743:     var foundID=0;
 4744:     var foundclicker=0;
 4745:     for (i=0;i<=vf.nfields.value;i++) {
 4746:       tw=eval('vf.f'+i+'.selectedIndex');
 4747:       if (i==0 && tw!=0) { foundID=1; }
 4748:       if (i==1 && tw!=0) { founduname=1; }
 4749:       if (i==2 && tw!=0) { foundclicker=1; }
 4750:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4751:     }
 4752:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4753: 	alert('$error1');
 4754: 	return;
 4755:     }
 4756:     if (foundsomething==0) {
 4757: 	alert('$error2');
 4758: 	return;
 4759:     }
 4760:     vf.submit();
 4761:   }
 4762:   function flip(vf,tf) {
 4763:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4764:     var i;
 4765:     for (i=0;i<=vf.nfields.value;i++) {
 4766:       //can not pick the same destination field for both name and domain
 4767:       if (((i ==0)||(i ==1)) && 
 4768:           ((tf==0)||(tf==1)) && 
 4769:           (i!=tf) &&
 4770:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4771:         eval('vf.f'+i+'.selectedIndex=0;')
 4772:       }
 4773:     }
 4774:   }
 4775: ENDPICK
 4776: }
 4777: 
 4778: sub csvupload_javascript_forward_associate {
 4779:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4780:     my $error2=&mt('You need to specify at least one grading field');
 4781:   &js_escape(\$error1);
 4782:   &js_escape(\$error2);
 4783:   return(<<ENDPICK);
 4784:   function verify(vf) {
 4785:     var foundsomething=0;
 4786:     var founduname=0;
 4787:     var foundID=0;
 4788:     var foundclicker=0;
 4789:     for (i=0;i<=vf.nfields.value;i++) {
 4790:       tw=eval('vf.f'+i+'.selectedIndex');
 4791:       if (tw==1) { foundID=1; }
 4792:       if (tw==2) { founduname=1; }
 4793:       if (tw==3) { foundclicker=1; }
 4794:       if (tw>4) { foundsomething=1; }
 4795:     }
 4796:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4797: 	alert('$error1');
 4798: 	return;
 4799:     }
 4800:     if (foundsomething==0) {
 4801: 	alert('$error2');
 4802: 	return;
 4803:     }
 4804:     vf.submit();
 4805:   }
 4806:   function flip(vf,tf) {
 4807:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4808:     var i;
 4809:     //can not pick the same destination field twice
 4810:     for (i=0;i<=vf.nfields.value;i++) {
 4811:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4812:         eval('vf.f'+i+'.selectedIndex=0;')
 4813:       }
 4814:     }
 4815:   }
 4816: ENDPICK
 4817: }
 4818: 
 4819: sub csvuploadmap_header {
 4820:     my ($request,$symb,$datatoken,$distotal)= @_;
 4821:     my $javascript;
 4822:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4823: 	$javascript=&csvupload_javascript_reverse_associate();
 4824:     } else {
 4825: 	$javascript=&csvupload_javascript_forward_associate();
 4826:     }
 4827: 
 4828:     $symb = &Apache::lonenc::check_encrypt($symb);
 4829:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4830:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4831:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4832:     my $reverse=&mt("Reverse Association");
 4833:     $request->print(<<ENDPICK);
 4834: <br />
 4835: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4836: <input type="hidden" name="associate"  value="" />
 4837: <input type="hidden" name="phase"      value="three" />
 4838: <input type="hidden" name="datatoken"  value="$datatoken" />
 4839: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4840: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4841: <input type="hidden" name="upfile_associate" 
 4842:                                        value="$env{'form.upfile_associate'}" />
 4843: <input type="hidden" name="symb"       value="$symb" />
 4844: <input type="hidden" name="command"    value="csvuploadoptions" />
 4845: <hr />
 4846: ENDPICK
 4847:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4848:     return '';
 4849: 
 4850: }
 4851: 
 4852: sub csvupload_fields {
 4853:     my ($symb,$errorref) = @_;
 4854:     my $toolsymb;
 4855:     if ($symb =~ /ext\.tool$/) {
 4856:         $toolsymb = $symb;
 4857:     }
 4858:     my (@parts) = &getpartlist($symb,$errorref);
 4859:     if (ref($errorref)) {
 4860:         if ($$errorref) {
 4861:             return;
 4862:         }
 4863:     }
 4864: 
 4865:     my @fields=(['ID','Student/Employee ID'],
 4866: 		['username','Student Username'],
 4867: 		['clicker','Clicker ID'],
 4868: 		['domain','Student Domain']);
 4869:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4870:     foreach my $part (sort(@parts)) {
 4871: 	my @datum;
 4872: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4873: 	my $name=$part;
 4874: 	if (!$display) { $display = $name; }
 4875: 	@datum=($name,$display);
 4876: 	if ($name=~/^stores_(.*)_awarded/) {
 4877: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4878: 	}
 4879: 	push(@fields,\@datum);
 4880:     }
 4881:     return (@fields);
 4882: }
 4883: 
 4884: sub csvuploadmap_footer {
 4885:     my ($request,$i,$keyfields) =@_;
 4886:     my $buttontext = &mt('Assign Grades');
 4887:     $request->print(<<ENDPICK);
 4888: </table>
 4889: <input type="hidden" name="nfields" value="$i" />
 4890: <input type="hidden" name="keyfields" value="$keyfields" />
 4891: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4892: </form>
 4893: ENDPICK
 4894: }
 4895: 
 4896: sub checkforfile_js {
 4897:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4898:     &js_escape(\$alertmsg);
 4899:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4900:     function checkUpload(formname) {
 4901: 	if (formname.upfile.value == "") {
 4902: 	    alert("$alertmsg");
 4903: 	    return false;
 4904: 	}
 4905: 	formname.submit();
 4906:     }
 4907: CSVFORMJS
 4908:     return $result;
 4909: }
 4910: 
 4911: sub upcsvScores_form {
 4912:     my ($request,$symb) = @_;
 4913:     if (!$symb) {return '';}
 4914:     my $result=&checkforfile_js();
 4915:     $result.=&Apache::loncommon::start_data_table().
 4916:              &Apache::loncommon::start_data_table_header_row().
 4917:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4918:              &Apache::loncommon::end_data_table_header_row().
 4919:              &Apache::loncommon::start_data_table_row().'<td>';
 4920:     my $upload=&mt("Upload Scores");
 4921:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4922:     my $ignore=&mt('Ignore First Line');
 4923:     $symb = &Apache::lonenc::check_encrypt($symb);
 4924:     $result.=<<ENDUPFORM;
 4925: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4926: <input type="hidden" name="symb" value="$symb" />
 4927: <input type="hidden" name="command" value="csvuploadmap" />
 4928: $upfile_select
 4929: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4930: </form>
 4931: ENDUPFORM
 4932:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4933:                            &mt("How do I create a CSV file from a spreadsheet")).
 4934:              '</td>'.
 4935:             &Apache::loncommon::end_data_table_row().
 4936:             &Apache::loncommon::end_data_table();
 4937:     return $result;
 4938: }
 4939: 
 4940: 
 4941: sub csvuploadmap {
 4942:     my ($request,$symb) = @_;
 4943:     if (!$symb) {return '';}
 4944: 
 4945:     my $datatoken;
 4946:     if (!$env{'form.datatoken'}) {
 4947: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4948:     } else {
 4949: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4950:         if ($datatoken ne '') {
 4951: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4952:         }
 4953:     }
 4954:     my @records=&Apache::loncommon::upfile_record_sep();
 4955:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4956:     my ($i,$keyfields);
 4957:     if (@records) {
 4958:         my $fieldserror;
 4959: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4960:         if ($fieldserror) {
 4961:             $request->print(&navmap_errormsg());
 4962:             return;
 4963:         }
 4964: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4965: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4966: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4967: 							  \@fields);
 4968: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4969: 	    chop($keyfields);
 4970: 	} else {
 4971: 	    unshift(@fields,['none','']);
 4972: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4973: 							    \@fields);
 4974:             foreach my $rec (@records) {
 4975:                 my %temp = &Apache::loncommon::record_sep($rec);
 4976:                 if (%temp) {
 4977:                     $keyfields=join(',',sort(keys(%temp)));
 4978:                     last;
 4979:                 }
 4980:             }
 4981: 	}
 4982:     }
 4983:     &csvuploadmap_footer($request,$i,$keyfields);
 4984: 
 4985:     return '';
 4986: }
 4987: 
 4988: sub csvuploadoptions {
 4989:     my ($request,$symb)= @_;
 4990:     my $overwrite=&mt('Overwrite any existing score');
 4991:     $request->print(<<ENDPICK);
 4992: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4993: <input type="hidden" name="command"    value="csvuploadassign" />
 4994: <p>
 4995: <label>
 4996:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4997:    $overwrite
 4998: </label>
 4999: </p>
 5000: ENDPICK
 5001:     my %fields=&get_fields();
 5002:     if (!defined($fields{'domain'})) {
 5003: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 5004: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 5005:     }
 5006:     foreach my $key (sort(keys(%env))) {
 5007: 	if ($key !~ /^form\.(.*)$/) { next; }
 5008: 	my $cleankey=$1;
 5009: 	if ($cleankey eq 'command') { next; }
 5010: 	$request->print('<input type="hidden" name="'.$cleankey.
 5011: 			'"  value="'.$env{$key}.'" />'."\n");
 5012:     }
 5013:     # FIXME do a check for any duplicated user ids...
 5014:     # FIXME do a check for any invalid user ids?...
 5015:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 5016: <hr /></form>'."\n");
 5017:     return '';
 5018: }
 5019: 
 5020: sub get_fields {
 5021:     my %fields;
 5022:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 5023:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 5024: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 5025: 	    if ($env{'form.f'.$i} ne 'none') {
 5026: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 5027: 	    }
 5028: 	} else {
 5029: 	    if ($env{'form.f'.$i} ne 'none') {
 5030: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 5031: 	    }
 5032: 	}
 5033:     }
 5034:     return %fields;
 5035: }
 5036: 
 5037: sub csvuploadassign {
 5038:     my ($request,$symb) = @_;
 5039:     if (!$symb) {return '';}
 5040:     my $error_msg = '';
 5041:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 5042:     if ($datatoken ne '') { 
 5043:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 5044:     }
 5045:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 5046:     my %fields=&get_fields();
 5047:     my $courseid=$env{'request.course.id'};
 5048:     my ($classlist) = &getclasslist('all',0);
 5049:     my @notallowed;
 5050:     my @skipped;
 5051:     my @warnings;
 5052:     my $countdone=0;
 5053:     foreach my $grade (@gradedata) {
 5054: 	my %entries=&Apache::loncommon::record_sep($grade);
 5055: 	my $domain;
 5056: 	if ($entries{$fields{'domain'}}) {
 5057: 	    $domain=$entries{$fields{'domain'}};
 5058: 	} else {
 5059: 	    $domain=$env{'form.default_domain'};
 5060: 	}
 5061: 	$domain=~s/\s//g;
 5062: 	my $username=$entries{$fields{'username'}};
 5063: 	$username=~s/\s//g;
 5064: 	if (!$username) {
 5065: 	    my $id=$entries{$fields{'ID'}};
 5066: 	    $id=~s/\s//g;
 5067:             if ($id ne '') {
 5068: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 5069: 	        $username=$ids{$id};
 5070:             } else {
 5071:                 if ($entries{$fields{'clicker'}}) {
 5072:                     my $clicker = $entries{$fields{'clicker'}};
 5073:                     $clicker=~s/\s//g;
 5074:                     if ($clicker ne '') {
 5075:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 5076:                         if ($clickers{$clicker} ne '') {  
 5077:                             my $match = 0;
 5078:                             my @inclass;
 5079:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 5080:                                 if (exists($$classlist{"$poss:$domain"})) {
 5081:                                     $username = $poss;
 5082:                                     push(@inclass,$poss);
 5083:                                     $match ++;
 5084:                                     
 5085:                                 }
 5086:                             }
 5087:                             if ($match > 1) {
 5088:                                 undef($username); 
 5089:                                 $request->print('<p class="LC_warning">'.
 5090:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 5091:                                                 $clicker,join(', ',@inclass)).'</p>');
 5092:                             }
 5093:                         }
 5094:                     }
 5095:                 }
 5096:             }
 5097: 	}
 5098: 	if (!exists($$classlist{"$username:$domain"})) {
 5099: 	    my $id=$entries{$fields{'ID'}};
 5100: 	    $id=~s/\s//g;
 5101:             my $clicker = $entries{$fields{'clicker'}};
 5102:             $clicker=~s/\s//g;
 5103:             if ($clicker) {
 5104:                 push(@skipped,"$clicker:$domain");
 5105: 	    } elsif ($id) {
 5106: 		push(@skipped,"$id:$domain");
 5107: 	    } else {
 5108: 		push(@skipped,"$username:$domain");
 5109: 	    }
 5110: 	    next;
 5111: 	}
 5112: 	my $usec=$classlist->{"$username:$domain"}[5];
 5113: 	if (!&canmodify($usec)) {
 5114: 	    push(@notallowed,"$username:$domain");
 5115: 	    next;
 5116: 	}
 5117: 	my %points;
 5118: 	my %grades;
 5119: 	foreach my $dest (keys(%fields)) {
 5120: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5121: 		$dest eq 'domain') { next; }
 5122: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5123: 	    if ($dest=~/stores_(.*)_points/) {
 5124: 		my $part=$1;
 5125: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5126: 					      $symb,$domain,$username);
 5127:                 if ($wgt) {
 5128:                     $entries{$fields{$dest}}=~s/\s//g;
 5129:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5130:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5131:                                           : 'correct_by_override';
 5132:                     if ($pcr>1) {
 5133:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5134:                     }
 5135:                     $grades{"resource.$part.awarded"}=$pcr;
 5136:                     $grades{"resource.$part.solved"}=$award;
 5137:                     $points{$part}=1;
 5138:                 } else {
 5139:                     $error_msg = "<br />" .
 5140:                         &mt("Some point values were assigned"
 5141:                             ." for problems with a weight "
 5142:                             ."of zero. These values were "
 5143:                             ."ignored.");
 5144:                 }
 5145: 	    } else {
 5146: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5147: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5148: 		my $store_key=$dest;
 5149: 		$store_key=~s/^stores/resource/;
 5150: 		$store_key=~s/_/\./g;
 5151: 		$grades{$store_key}=$entries{$fields{$dest}};
 5152: 	    }
 5153: 	}
 5154: 	if (! %grades) {
 5155:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5156:         } else {
 5157: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5158: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5159: 					   $env{'request.course.id'},
 5160: 					   $domain,$username);
 5161: 	   if ($result eq 'ok') {
 5162: # Successfully stored
 5163: 	      $request->print('.');
 5164: # Remove from grading queue
 5165:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5166:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5167:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5168:                                              $domain,$username);
 5169:               $countdone++;
 5170:            } else {
 5171: 	      $request->print("<p><span class=\"LC_error\">".
 5172:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5173:                                   "$username:$domain",$result)."</span></p>");
 5174: 	   }
 5175: 	   $request->rflush();
 5176:         }
 5177:     }
 5178:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5179:     if (@warnings) {
 5180:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5181:         $request->print(join(', ',@warnings));
 5182:     }
 5183:     if (@skipped) {
 5184: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5185:         $request->print(join(', ',@skipped));
 5186:     }
 5187:     if (@notallowed) {
 5188: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5189: 	$request->print(join(', ',@notallowed));
 5190:     }
 5191:     $request->print("<br />\n");
 5192:     return $error_msg;
 5193: }
 5194: #------------- end of section for handling csv file upload ---------
 5195: #
 5196: #-------------------------------------------------------------------
 5197: #
 5198: #-------------- Next few routines handle grading by page/sequence
 5199: #
 5200: #--- Select a page/sequence and a student to grade
 5201: sub pickStudentPage {
 5202:     my ($request,$symb) = @_;
 5203: 
 5204:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5205:     &js_escape(\$alertmsg);
 5206:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5207: 
 5208: function checkPickOne(formname) {
 5209:     if (radioSelection(formname.student) == null) {
 5210: 	alert("$alertmsg");
 5211: 	return;
 5212:     }
 5213:     ptr = pullDownSelection(formname.selectpage);
 5214:     formname.page.value = formname["page"+ptr].value;
 5215:     formname.title.value = formname["title"+ptr].value;
 5216:     formname.submit();
 5217: }
 5218: 
 5219: LISTJAVASCRIPT
 5220:     &commonJSfunctions($request);
 5221: 
 5222:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5223:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5224:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5225:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5226: 
 5227:     my $result='<h3><span class="LC_info">&nbsp;'.
 5228: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5229: 
 5230:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5231:     my $map_error;
 5232:     my ($titles,$symbx) = &getSymbMap($map_error);
 5233:     if ($map_error) {
 5234:         $request->print(&navmap_errormsg());
 5235:         return; 
 5236:     }
 5237:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5238: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5239: #    my $type=($curpage =~ /\.(page|sequence)/);
 5240: 
 5241:     # Collection of hidden fields
 5242:     my $ctr=0;
 5243:     foreach (@$titles) {
 5244:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5245:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5246:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5247:         $ctr++;
 5248:     }
 5249:     $result.='<input type="hidden" name="page" />'."\n".
 5250:         '<input type="hidden" name="title" />'."\n";
 5251: 
 5252:     $result.=&build_section_inputs();
 5253:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5254:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5255: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 5256: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5257: 
 5258:     # Show grading options
 5259:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5260:     my $select = '<select name="selectpage">'."\n";
 5261:     $ctr=0;
 5262:     foreach (@$titles) {
 5263: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5264: 	$select.='<option value="'.$ctr.'"'.
 5265: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5266: 	    '>'.$showtitle.'</option>'."\n";
 5267: 	$ctr++;
 5268:     }
 5269:     $select.= '</select>';
 5270: 
 5271:     $result.=
 5272:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5273:        .$select
 5274:        .&Apache::lonhtmlcommon::row_closure();
 5275: 
 5276:     $result.=
 5277:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5278:        .'<label><input type="radio" name="vProb" value="no"'
 5279:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5280:        .'<label><input type="radio" name="vProb" value="yes" />'
 5281:            .&mt('yes').'</label>'."\n"
 5282:        .&Apache::lonhtmlcommon::row_closure();
 5283: 
 5284:     $result.=
 5285:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5286:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5287:            .&mt('none').' </label>'."\n"
 5288:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5289:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5290:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5291:            .&mt('all submissions with details').' </label>'
 5292:        .&Apache::lonhtmlcommon::row_closure();
 5293:     
 5294:     $result.=
 5295:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5296:        .'<input type="text" name="CODE" value="" />'
 5297:        .&Apache::lonhtmlcommon::row_closure(1)
 5298:        .&Apache::lonhtmlcommon::end_pick_box();
 5299: 
 5300:     # Show list of students to select for grading
 5301:     $result.='<br /><input type="button" '.
 5302:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5303: 
 5304:     $request->print($result);
 5305: 
 5306:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5307: 	&Apache::loncommon::start_data_table().
 5308: 	&Apache::loncommon::start_data_table_header_row().
 5309: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5310: 	'<th>'.&nameUserString('header').'</th>'.
 5311: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5312: 	'<th>'.&nameUserString('header').'</th>'.
 5313: 	&Apache::loncommon::end_data_table_header_row();
 5314:  
 5315:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5316:     my $ptr = 1;
 5317:     foreach my $student (sort 
 5318: 			 {
 5319: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5320: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5321: 			     }
 5322: 			     return $a cmp $b;
 5323: 			 } (keys(%$fullname))) {
 5324: 	my ($uname,$udom) = split(/:/,$student);
 5325: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5326:                                   : '</td>');
 5327: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5328: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5329: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5330: 	$studentTable.=
 5331: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5332:                          : '');
 5333: 	$ptr++;
 5334:     }
 5335:     if ($ptr%2 == 0) {
 5336: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5337: 	    &Apache::loncommon::end_data_table_row();
 5338:     }
 5339:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5340:     $studentTable.='<input type="button" '.
 5341:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5342: 
 5343:     $request->print($studentTable);
 5344: 
 5345:     return '';
 5346: }
 5347: 
 5348: sub getSymbMap {
 5349:     my ($map_error) = @_;
 5350:     my $navmap = Apache::lonnavmaps::navmap->new();
 5351:     unless (ref($navmap)) {
 5352:         if (ref($map_error)) {
 5353:             $$map_error = 'navmap';
 5354:         }
 5355:         return;
 5356:     }
 5357:     my %symbx = ();
 5358:     my @titles = ();
 5359:     my $minder = 0;
 5360: 
 5361:     # Gather every sequence that has problems.
 5362:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5363: 					       1,0,1);
 5364:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5365: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5366: 	    my $title = $minder.'.'.
 5367: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5368: 	    push(@titles, $title); # minder in case two titles are identical
 5369: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5370: 	    $minder++;
 5371: 	}
 5372:     }
 5373:     return \@titles,\%symbx;
 5374: }
 5375: 
 5376: #
 5377: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5378: sub displayPage {
 5379:     my ($request,$symb) = @_;
 5380:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5381:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5382:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5383:     my $pageTitle = $env{'form.page'};
 5384:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5385:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5386:     my $usec=$classlist->{$env{'form.student'}}[5];
 5387: 
 5388:     #need to make sure we have the correct data for later EXT calls, 
 5389:     #thus invalidate the cache
 5390:     &Apache::lonnet::devalidatecourseresdata(
 5391:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5392:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5393:     &Apache::lonnet::clear_EXT_cache_status();
 5394: 
 5395:     if (!&canview($usec)) {
 5396:         $request->print(
 5397:             '<span class="LC_warning">'.
 5398:             &mt('Unable to view requested student. ([_1])',
 5399:                     $env{'form.student'}).
 5400:             '</span>');
 5401:         return;
 5402:     }
 5403:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5404:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5405: 	'</h3>'."\n";
 5406:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5407:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5408: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5409:     } else {
 5410: 	delete($env{'form.CODE'});
 5411:     }
 5412:     &sub_page_js($request);
 5413:     $request->print($result);
 5414: 
 5415:     my $navmap = Apache::lonnavmaps::navmap->new();
 5416:     unless (ref($navmap)) {
 5417:         $request->print(&navmap_errormsg());
 5418:         return;
 5419:     }
 5420:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5421:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5422:     if (!$map) {
 5423: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5424: 	return; 
 5425:     }
 5426:     my $iterator = $navmap->getIterator($map->map_start(),
 5427: 					$map->map_finish());
 5428: 
 5429:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5430: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5431: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5432: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5433: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5434: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5435: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5436: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5437: 
 5438:     if (defined($env{'form.CODE'})) {
 5439: 	$studentTable.=
 5440: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5441:     }
 5442:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5443: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5444: 
 5445:     $studentTable.='&nbsp;<span class="LC_info">'.
 5446:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5447:         '</span>'."\n".
 5448: 	&Apache::loncommon::start_data_table().
 5449: 	&Apache::loncommon::start_data_table_header_row().
 5450: 	'<th>'.&mt('Prob.').'</th>'.
 5451: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5452: 	&Apache::loncommon::end_data_table_header_row();
 5453: 
 5454:     &Apache::lonxml::clear_problem_counter();
 5455:     my ($depth,$question,$prob) = (1,1,1);
 5456:     $iterator->next(); # skip the first BEGIN_MAP
 5457:     my $curRes = $iterator->next(); # for "current resource"
 5458:     while ($depth > 0) {
 5459:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5460:         if($curRes == $iterator->END_MAP) { $depth--; }
 5461: 
 5462:         if (ref($curRes) && $curRes->is_gradable()) {
 5463: 	    my $parts = $curRes->parts();
 5464:             my $title = $curRes->compTitle();
 5465: 	    my $symbx = $curRes->symb();
 5466:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5467: 	    $studentTable.=
 5468: 		&Apache::loncommon::start_data_table_row().
 5469: 		'<td align="center" valign="top" >'.$prob.
 5470: 		(scalar(@{$parts}) == 1 ? '' 
 5471: 		                        : '<br />('.&mt('[_1]parts',
 5472: 							scalar(@{$parts}).'&nbsp;').')'
 5473: 		 ).
 5474: 		 '</td>';
 5475: 	    $studentTable.='<td valign="top">';
 5476: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5477:             if ($is_tool) {
 5478:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5479:             } else {
 5480: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5481: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5482: 					         undef,'both',\%form);
 5483: 	        } else {
 5484: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5485: 		    $companswer =~ s|<form(.*?)>||g;
 5486: 		    $companswer =~ s|</form>||g;
 5487: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5488: #		        $companswer =~ s/$1/ /ms;
 5489: #		        $request->print('match='.$1."<br />\n");
 5490: #		    }
 5491: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5492: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5493: 		}
 5494: 	    }
 5495: 
 5496: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5497: 
 5498: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5499: 		if ($record{'version'} eq '') {
 5500:                     my $msg = &mt('No recorded submission for this problem.');
 5501:                     if ($is_tool) {
 5502:                         $msg = &mt('No recorded transactions for this external tool');
 5503:                     }
 5504: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5505: 		} else {
 5506: 		    my %responseType = ();
 5507: 		    foreach my $partid (@{$parts}) {
 5508: 			my @responseIds =$curRes->responseIds($partid);
 5509: 			my @responseType =$curRes->responseType($partid);
 5510: 			my %responseIds;
 5511: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5512: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5513: 			}
 5514: 			$responseType{$partid} = \%responseIds;
 5515: 		    }
 5516: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5517: 		}
 5518: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5519: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5520:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5521: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5522: 									$env{'request.course.id'},
 5523: 									'','.submission',undef,
 5524:                                                                         $usec,$identifier);
 5525:  
 5526: 	    }
 5527: 	    if (&canmodify($usec)) {
 5528:             $studentTable.=&gradeBox_start();
 5529: 		foreach my $partid (@{$parts}) {
 5530: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5531: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5532: 		    $question++;
 5533: 		}
 5534:             $studentTable.=&gradeBox_end();
 5535: 		$prob++;
 5536: 	    }
 5537: 	    $studentTable.='</td></tr>';
 5538: 
 5539: 	}
 5540:         $curRes = $iterator->next();
 5541:     }
 5542:     my $disabled;
 5543:     unless (&canmodify($usec)) {
 5544:         $disabled = ' disabled="disabled"';
 5545:     }
 5546: 
 5547:     $studentTable.=
 5548:         '</table>'."\n".
 5549:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5550:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5551:         '</form>'."\n";
 5552:     $request->print($studentTable);
 5553: 
 5554:     return '';
 5555: }
 5556: 
 5557: sub displaySubByDates {
 5558:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5559:     my $isCODE=0;
 5560:     my $isTask = ($symb =~/\.task$/);
 5561:     my $is_tool = ($symb =~/\.tool$/);
 5562:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5563:     my $studentTable=&Apache::loncommon::start_data_table().
 5564: 	&Apache::loncommon::start_data_table_header_row().
 5565: 	'<th>'.&mt('Date/Time').'</th>'.
 5566: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5567:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5568: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5569: 	'<th>'.&mt('Status').'</th>'.
 5570: 	&Apache::loncommon::end_data_table_header_row();
 5571:     my ($version);
 5572:     my %mark;
 5573:     my %orders;
 5574:     $mark{'correct_by_student'} = $checkIcon;
 5575:     if (!exists($$record{'1:timestamp'})) {
 5576:         if ($is_tool) {
 5577:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5578:         } else {
 5579:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5580:         }
 5581:     }
 5582: 
 5583:     my $interaction;
 5584:     my $no_increment = 1;
 5585:     my (%lastrndseed,%lasttype);
 5586:     for ($version=1;$version<=$$record{'version'};$version++) {
 5587: 	my $timestamp = 
 5588: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5589: 	if (exists($$record{$version.':resource.0.version'})) {
 5590: 	    $interaction = $$record{$version.':resource.0.version'};
 5591: 	}
 5592:         if ($isTask && $env{'form.previousversion'}) {
 5593:             next unless ($interaction == $env{'form.previousversion'});
 5594:         }
 5595: 	my $where = ($isTask ? "$version:resource.$interaction"
 5596: 		             : "$version:resource");
 5597: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5598: 	    '<td>'.$timestamp.'</td>';
 5599: 	if ($isCODE) {
 5600: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5601: 	}
 5602:         if ($isTask) {
 5603:             $studentTable.='<td>'.$interaction.'</td>';
 5604:         }
 5605: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5606: 	my @displaySub = ();
 5607: 	foreach my $partid (@{$parts}) {
 5608:             my ($hidden,$type);
 5609:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5610:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5611:                 $hidden = 1;
 5612:             }
 5613:             my @matchKey;
 5614:             if ($isTask) {
 5615:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5616:             } elsif ($is_tool) {
 5617:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5618:             } else {
 5619:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5620:             }
 5621: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5622: 	    my $display_part=&get_display_part($partid,$symb);
 5623: 	    foreach my $matchKey (@matchKey) {
 5624: 		if (exists($$record{$version.':'.$matchKey}) &&
 5625: 		    $$record{$version.':'.$matchKey} ne '') {
 5626:                     if ($is_tool) {
 5627:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5628:                     } else {
 5629: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5630: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5631:                         $displaySub[0].='<span class="LC_nobreak">';
 5632:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5633:                                        .' <span class="LC_internal_info">'
 5634:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5635:                                        .'</span>'
 5636:                                        .' <b>';
 5637:                         if ($hidden) {
 5638:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5639:                         } else {
 5640:                             my ($trial,$rndseed,$newvariation);
 5641:                             if ($type eq 'randomizetry') {
 5642:                                 $trial = $$record{"$where.$partid.tries"};
 5643:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5644:                             }
 5645: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5646: 			        $displaySub[0].=&mt('Trial not counted');
 5647: 		            } else {
 5648: 			        $displaySub[0].=&mt('Trial: [_1]',
 5649: 					        $$record{"$where.$partid.tries"});
 5650:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5651:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5652:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5653:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5654:                                     }
 5655:                                 }
 5656:                                 $lastrndseed{$partid} = $rndseed;
 5657:                                 $lasttype{$partid} = $type;
 5658: 		            }
 5659: 		            my $responseType=($isTask ? 'Task'
 5660:                                               : $responseType->{$partid}->{$responseId});
 5661: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5662: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5663: 			        $orders{$partid}->{$responseId}=
 5664: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5665:                                                $no_increment,$type,$trial,$rndseed);
 5666: 		            }
 5667: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5668: 		            $displaySub[0].='&nbsp; '.
 5669: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5670:                         }
 5671:                     }
 5672: 		}
 5673: 	    }
 5674: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5675: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5676: 				    $$record{"$where.$partid.checkedin"},
 5677: 				    $$record{"$where.$partid.checkedin.slot"}).
 5678: 					'<br />';
 5679: 	    }
 5680: 	    if (exists $$record{"$where.$partid.award"}) {
 5681: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5682: 		    lc($$record{"$where.$partid.award"}).' '.
 5683: 		    $mark{$$record{"$where.$partid.solved"}}.
 5684: 		    '<br />';
 5685: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5686: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5687: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5688: 		}
 5689: 	    }
 5690: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5691: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5692: 		unless ($is_tool) {
 5693: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5694: 		}
 5695: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5696: 		$displaySub[2].=
 5697: 		    $$record{"$version:resource.$partid.regrader"};
 5698:                 unless ($is_tool) {
 5699: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5700:                 }
 5701: 	    }
 5702: 	}
 5703: 	# needed because old essay regrader has not parts info
 5704: 	if (exists $$record{"$version:resource.regrader"}) {
 5705: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5706: 	}
 5707: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5708: 	if ($displaySub[2]) {
 5709: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5710: 	}
 5711: 	$studentTable.='&nbsp;</td>'.
 5712: 	    &Apache::loncommon::end_data_table_row();
 5713:     }
 5714:     $studentTable.=&Apache::loncommon::end_data_table();
 5715:     return $studentTable;
 5716: }
 5717: 
 5718: sub updateGradeByPage {
 5719:     my ($request,$symb) = @_;
 5720: 
 5721:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5722:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5723:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5724:     my $pageTitle = $env{'form.page'};
 5725:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5726:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5727:     my $usec=$classlist->{$env{'form.student'}}[5];
 5728:     if (!&canmodify($usec)) {
 5729: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5730: 	return;
 5731:     }
 5732:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5733:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5734: 	'</h3>'."\n";
 5735: 
 5736:     $request->print($result);
 5737: 
 5738: 
 5739:     my $navmap = Apache::lonnavmaps::navmap->new();
 5740:     unless (ref($navmap)) {
 5741:         $request->print(&navmap_errormsg());
 5742:         return;
 5743:     }
 5744:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5745:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5746:     if (!$map) {
 5747: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5748: 	return; 
 5749:     }
 5750:     my $iterator = $navmap->getIterator($map->map_start(),
 5751: 					$map->map_finish());
 5752: 
 5753:     my $studentTable=
 5754: 	&Apache::loncommon::start_data_table().
 5755: 	&Apache::loncommon::start_data_table_header_row().
 5756: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5757: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5758: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5759: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5760: 	&Apache::loncommon::end_data_table_header_row();
 5761: 
 5762:     $iterator->next(); # skip the first BEGIN_MAP
 5763:     my $curRes = $iterator->next(); # for "current resource"
 5764:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5765:     while ($depth > 0) {
 5766:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5767:         if($curRes == $iterator->END_MAP) { $depth--; }
 5768: 
 5769:         if (ref($curRes) && $curRes->is_problem()) {
 5770: 	    my $parts = $curRes->parts();
 5771:             my $title = $curRes->compTitle();
 5772: 	    my $symbx = $curRes->symb();
 5773: 	    $studentTable.=
 5774: 		&Apache::loncommon::start_data_table_row().
 5775: 		'<td align="center" valign="top" >'.$prob.
 5776: 		(scalar(@{$parts}) == 1 ? '' 
 5777:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5778: 		.')').'</td>';
 5779: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5780: 
 5781: 	    my %newrecord=();
 5782: 	    my @displayPts=();
 5783:             my %aggregate = ();
 5784:             my $aggregateflag = 0;
 5785:             my %queueable;
 5786:             if ($env{'form.HIDE'.$prob}) {
 5787:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5788:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5789:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5790:                 $hideflag += $numchgs;
 5791:             }
 5792: 	    foreach my $partid (@{$parts}) {
 5793: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5794: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5795:                 my @types = $curRes->responseType($partid);
 5796:                 if (grep(/^essay$/,@types)) {
 5797:                     $queueable{$partid} = 1;
 5798:                 } else {
 5799:                     my @ids = $curRes->responseIds($partid);
 5800:                     for (my $i=0; $i < scalar(@ids); $i++) {
 5801:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
 5802:                                                           '.handgrade',$symb);
 5803:                         if (lc($hndgrd) eq 'yes') {
 5804:                             $queueable{$partid} = 1;
 5805:                             last;
 5806:                         }
 5807:                     }
 5808:                 }
 5809: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5810: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5811: 		my $partial = $newpts/$wgt;
 5812: 		my $score;
 5813: 		if ($partial > 0) {
 5814: 		    $score = 'correct_by_override';
 5815: 		} elsif ($newpts ne '') { #empty is taken as 0
 5816: 		    $score = 'incorrect_by_override';
 5817: 		}
 5818: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5819: 		if ($dropMenu eq 'excused') {
 5820: 		    $partial = '';
 5821: 		    $score = 'excused';
 5822: 		} elsif ($dropMenu eq 'reset status'
 5823: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5824: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5825: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5826: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5827: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5828: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5829: 		    $changeflag++;
 5830: 		    $newpts = '';
 5831:                     
 5832:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5833:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5834:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5835:                     if ($aggtries > 0) {
 5836:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5837:                         $aggregateflag = 1;
 5838:                     }
 5839: 		}
 5840: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5841: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5842: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5843: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5844: 		    '&nbsp;<br />';
 5845: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5846: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5847: 		    '&nbsp;<br />';
 5848: 		$question++;
 5849: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5850: 
 5851: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5852: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5853: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5854: 		    if (scalar(keys(%newrecord)) > 0);
 5855: 
 5856: 		$changeflag++;
 5857: 	    }
 5858: 	    if (scalar(keys(%newrecord)) > 0) {
 5859: 		my %record = 
 5860: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5861: 					     $udom,$uname);
 5862: 
 5863: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5864: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5865: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5866: 		    $newrecord{'resource.CODE'} = '';
 5867: 		}
 5868: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5869: 					$udom,$uname);
 5870: 		%record = &Apache::lonnet::restore($symbx,
 5871: 						   $env{'request.course.id'},
 5872: 						   $udom,$uname);
 5873: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5874: 					     $cdom,$cnum,$udom,$uname,\%queueable);
 5875: 	    }
 5876: 	    
 5877:             if ($aggregateflag) {
 5878:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5879:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5880:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5881:             }
 5882: 
 5883: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5884: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5885: 		&Apache::loncommon::end_data_table_row();
 5886: 
 5887: 	    $prob++;
 5888: 	}
 5889:         $curRes = $iterator->next();
 5890:     }
 5891: 
 5892:     $studentTable.=&Apache::loncommon::end_data_table();
 5893:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5894: 		  &mt('The scores were changed for [quant,_1,problem].',
 5895: 		  $changeflag).'<br />');
 5896:     my $hidemsg=($hideflag == 0 ? '' :
 5897:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5898:                      $hideflag).'<br />');
 5899:     $request->print($hidemsg.$grademsg.$studentTable);
 5900: 
 5901:     return '';
 5902: }
 5903: 
 5904: #-------- end of section for handling grading by page/sequence ---------
 5905: #
 5906: #-------------------------------------------------------------------
 5907: 
 5908: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5909: #
 5910: #------ start of section for handling grading by page/sequence ---------
 5911: 
 5912: =pod
 5913: 
 5914: =head1 Bubble sheet grading routines
 5915: 
 5916:   For this documentation:
 5917: 
 5918:    'scanline' refers to the full line of characters
 5919:    from the file that we are parsing that represents one entire sheet
 5920: 
 5921:    'bubble line' refers to the data
 5922:    representing the line of bubbles that are on the physical bubblesheet
 5923: 
 5924: 
 5925: The overall process is that a scanned in bubblesheet data is uploaded
 5926: into a course. When a user wants to grade, they select a
 5927: sequence/folder of resources, a file of bubblesheet info, and pick
 5928: one of the predefined configurations for what each scanline looks
 5929: like.
 5930: 
 5931: Next each scanline is checked for any errors of either 'missing
 5932: bubbles' (it's an error because it may have been mis-scanned
 5933: because too light bubbling), 'double bubble' (each bubble line should
 5934: have no more than one letter picked), invalid or duplicated CODE,
 5935: invalid student/employee ID
 5936: 
 5937: If the CODE option is used that determines the randomization of the
 5938: homework problems, either way the student/employee ID is looked up into a
 5939: username:domain.
 5940: 
 5941: During the validation phase the instructor can choose to skip scanlines. 
 5942: 
 5943: After the validation phase, there are now 3 bubblesheet files
 5944: 
 5945:   scantron_original_filename (unmodified original file)
 5946:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5947:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5948: 
 5949: Also there is a separate hash nohist_scantrondata that contains extra
 5950: correction information that isn't representable in the bubblesheet
 5951: file (see &scantron_getfile() for more information)
 5952: 
 5953: After all scanlines are either valid, marked as valid or skipped, then
 5954: foreach line foreach problem in the picked sequence, an ssi request is
 5955: made that simulates a user submitting their selected letter(s) against
 5956: the homework problem.
 5957: 
 5958: =over 4
 5959: 
 5960: 
 5961: 
 5962: =item defaultFormData
 5963: 
 5964:   Returns html hidden inputs used to hold context/default values.
 5965: 
 5966:  Arguments:
 5967:   $symb - $symb of the current resource 
 5968: 
 5969: =cut
 5970: 
 5971: sub defaultFormData {
 5972:     my ($symb)=@_;
 5973:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5974: }
 5975: 
 5976: 
 5977: =pod 
 5978: 
 5979: =item getSequenceDropDown
 5980: 
 5981:    Return html dropdown of possible sequences to grade
 5982:  
 5983:  Arguments:
 5984:    $symb - $symb of the current resource
 5985:    $map_error - ref to scalar which will container error if
 5986:                 $navmap object is unavailable in &getSymbMap().
 5987: 
 5988: =cut
 5989: 
 5990: sub getSequenceDropDown {
 5991:     my ($symb,$map_error)=@_;
 5992:     my $result='<select name="selectpage">'."\n";
 5993:     my ($titles,$symbx) = &getSymbMap($map_error);
 5994:     if (ref($map_error)) {
 5995:         return if ($$map_error);
 5996:     }
 5997:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5998:     my $ctr=0;
 5999:     foreach (@$titles) {
 6000: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 6001: 	$result.='<option value="'.$$symbx{$_}.'" '.
 6002: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 6003: 	    '>'.$showtitle.'</option>'."\n";
 6004: 	$ctr++;
 6005:     }
 6006:     $result.= '</select>';
 6007:     return $result;
 6008: }
 6009: 
 6010: my %bubble_lines_per_response;     # no. bubble lines for each response.
 6011:                                    # key is zero-based index - 0, 1, 2 ...
 6012: 
 6013: my %first_bubble_line;             # First bubble line no. for each bubble.
 6014: 
 6015: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 6016:                                    # matchresponse or rankresponse, where 
 6017:                                    # an individual response can have multiple 
 6018:                                    # lines
 6019: 
 6020: my %responsetype_per_response;     # responsetype for each response
 6021: 
 6022: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 6023:                                    # numbered response. Needed when randomorder
 6024:                                    # or randompick are in use. Key is ID, value 
 6025:                                    # is response number.
 6026: 
 6027: # Save and restore the bubble lines array to the form env.
 6028: 
 6029: 
 6030: sub save_bubble_lines {
 6031:     foreach my $line (keys(%bubble_lines_per_response)) {
 6032: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 6033: 	$env{"form.scantron.first_bubble_line.$line"} =
 6034: 	    $first_bubble_line{$line};
 6035:         $env{"form.scantron.sub_bubblelines.$line"} = 
 6036:             $subdivided_bubble_lines{$line};
 6037:         $env{"form.scantron.responsetype.$line"} =
 6038:             $responsetype_per_response{$line};
 6039:     }
 6040:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 6041:         my $line = $masterseq_id_responsenum{$resid};
 6042:         $env{"form.scantron.residpart.$line"} = $resid;
 6043:     }
 6044: }
 6045: 
 6046: 
 6047: sub restore_bubble_lines {
 6048:     my $line = 0;
 6049:     %bubble_lines_per_response = ();
 6050:     %masterseq_id_responsenum = ();
 6051:     while ($env{"form.scantron.bubblelines.$line"}) {
 6052: 	my $value = $env{"form.scantron.bubblelines.$line"};
 6053: 	$bubble_lines_per_response{$line} = $value;
 6054: 	$first_bubble_line{$line}  =
 6055: 	    $env{"form.scantron.first_bubble_line.$line"};
 6056:         $subdivided_bubble_lines{$line} =
 6057:             $env{"form.scantron.sub_bubblelines.$line"};
 6058:         $responsetype_per_response{$line} =
 6059:             $env{"form.scantron.responsetype.$line"};
 6060:         my $id = $env{"form.scantron.residpart.$line"};
 6061:         $masterseq_id_responsenum{$id} = $line;
 6062: 	$line++;
 6063:     }
 6064: }
 6065: 
 6066: =pod 
 6067: 
 6068: =item scantron_filenames
 6069: 
 6070:    Returns a list of the scantron files in the current course 
 6071: 
 6072: =cut
 6073: 
 6074: sub scantron_filenames {
 6075:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6076:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6077:     my $getpropath = 1;
 6078:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 6079:                                                         $cname,$getpropath);
 6080:     my @possiblenames;
 6081:     if (ref($dirlist) eq 'ARRAY') {
 6082:         foreach my $filename (sort(@{$dirlist})) {
 6083: 	    ($filename)=split(/&/,$filename);
 6084: 	    if ($filename!~/^scantron_orig_/) { next ; }
 6085: 	    $filename=~s/^scantron_orig_//;
 6086: 	    push(@possiblenames,$filename);
 6087:         }
 6088:     }
 6089:     return @possiblenames;
 6090: }
 6091: 
 6092: =pod 
 6093: 
 6094: =item scantron_uploads
 6095: 
 6096:    Returns  html drop-down list of scantron files in current course.
 6097: 
 6098:  Arguments:
 6099:    $file2grade - filename to set as selected in the dropdown
 6100: 
 6101: =cut
 6102: 
 6103: sub scantron_uploads {
 6104:     my ($file2grade) = @_;
 6105:     my $result=	'<select name="scantron_selectfile">';
 6106:     $result.="<option></option>";
 6107:     foreach my $filename (sort(&scantron_filenames())) {
 6108: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 6109:     }
 6110:     $result.="</select>";
 6111:     return $result;
 6112: }
 6113: 
 6114: =pod 
 6115: 
 6116: =item scantron_scantab
 6117: 
 6118:   Returns html drop down of the scantron formats in the scantronformat.tab
 6119:   file.
 6120: 
 6121: =cut
 6122: 
 6123: sub scantron_scantab {
 6124:     my $result='<select name="scantron_format">'."\n";
 6125:     $result.='<option></option>'."\n";
 6126:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6127:     if (@lines > 0) {
 6128:         foreach my $line (@lines) {
 6129:             next if (($line =~ /^\#/) || ($line eq ''));
 6130: 	    my ($name,$descrip)=split(/:/,$line);
 6131: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6132:         }
 6133:     }
 6134:     $result.='</select>'."\n";
 6135:     return $result;
 6136: }
 6137: 
 6138: =pod 
 6139: 
 6140: =item scantron_CODElist
 6141: 
 6142:   Returns html drop down of the saved CODE lists from current course,
 6143:   generated from earlier printings.
 6144: 
 6145: =cut
 6146: 
 6147: sub scantron_CODElist {
 6148:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6149:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6150:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6151:     my $namechoice='<option></option>';
 6152:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6153: 	if ($name =~ /^error: 2 /) { next; }
 6154: 	if ($name =~ /^type\0/) { next; }
 6155: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6156:     }
 6157:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6158:     return $namechoice;
 6159: }
 6160: 
 6161: =pod 
 6162: 
 6163: =item scantron_CODEunique
 6164: 
 6165:   Returns the html for "Each CODE to be used once" radio.
 6166: 
 6167: =cut
 6168: 
 6169: sub scantron_CODEunique {
 6170:     my $result='<span class="LC_nobreak">
 6171:                  <label><input type="radio" name="scantron_CODEunique"
 6172:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6173:                 </span>
 6174:                 <span class="LC_nobreak">
 6175:                  <label><input type="radio" name="scantron_CODEunique"
 6176:                         value="no" />'.&mt('No').' </label>
 6177:                 </span>';
 6178:     return $result;
 6179: }
 6180: 
 6181: =pod 
 6182: 
 6183: =item scantron_selectphase
 6184: 
 6185:   Generates the initial screen to start the bubblesheet process.
 6186:   Allows for - starting a grading run.
 6187:              - downloading existing scan data (original, corrected
 6188:                                                 or skipped info)
 6189: 
 6190:              - uploading new scan data
 6191: 
 6192:  Arguments:
 6193:   $r          - The Apache request object
 6194:   $file2grade - name of the file that contain the scanned data to score
 6195: 
 6196: =cut
 6197: 
 6198: sub scantron_selectphase {
 6199:     my ($r,$file2grade,$symb) = @_;
 6200:     if (!$symb) {return '';}
 6201:     my $map_error;
 6202:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6203:     if ($map_error) {
 6204:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6205:         return;
 6206:     }
 6207:     my $default_form_data=&defaultFormData($symb);
 6208:     my $file_selector=&scantron_uploads($file2grade);
 6209:     my $format_selector=&scantron_scantab();
 6210:     my $CODE_selector=&scantron_CODElist();
 6211:     my $CODE_unique=&scantron_CODEunique();
 6212:     my $result;
 6213: 
 6214:     $ssi_error = 0;
 6215: 
 6216:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 6217: 
 6218: 	# Chunk of form to prompt for a scantron file upload.
 6219: 
 6220:         $r->print('
 6221:     <br />');
 6222:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6223:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6224:     my $csec= $env{'request.course.sec'};
 6225:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6226:     &js_escape(\$alertmsg);
 6227:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6228:     $r->print(&Apache::lonhtmlcommon::scripttag('
 6229:     function checkUpload(formname) {
 6230: 	if (formname.upfile.value == "") {
 6231: 	    alert("'.$alertmsg.'");
 6232: 	    return false;
 6233: 	}
 6234: 	formname.submit();
 6235:     }'."\n".$formatjs));
 6236:     $r->print('
 6237:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6238:                 '.$default_form_data.'
 6239:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6240:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 6241:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6242:                 <input name="command" value="scantronupload_save" type="hidden" />
 6243:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6244:               '.&Apache::loncommon::start_data_table_header_row().'
 6245:                 <th>
 6246:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6247:                 </th>
 6248:               '.&Apache::loncommon::end_data_table_header_row().'
 6249:               '.&Apache::loncommon::start_data_table_row().'
 6250:             <td>
 6251:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6252:     if ($formatoptions) {
 6253:         $r->print('</td>
 6254:                  '.&Apache::loncommon::end_data_table_row().'
 6255:                  '.&Apache::loncommon::start_data_table_row().'
 6256:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6257:                  </td>
 6258:                  '.&Apache::loncommon::end_data_table_row().'
 6259:                  '.&Apache::loncommon::start_data_table_row().'
 6260:                  <td>'
 6261:         );
 6262:     } else {
 6263:         $r->print(' <br />');
 6264:     }
 6265:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6266:               </td>
 6267:              '.&Apache::loncommon::end_data_table_row().'
 6268:              '.&Apache::loncommon::end_data_table().'
 6269:              </form>'
 6270:     );
 6271: 
 6272:     }
 6273: 
 6274:     # Chunk of form to prompt for a file to grade and how:
 6275: 
 6276:     $result.= '
 6277:     <br />
 6278:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6279:     <input type="hidden" name="command" value="scantron_warning" />
 6280:     '.$default_form_data.'
 6281:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6282:        '.&Apache::loncommon::start_data_table_header_row().'
 6283:             <th colspan="2">
 6284:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6285:             </th>
 6286:        '.&Apache::loncommon::end_data_table_header_row().'
 6287:        '.&Apache::loncommon::start_data_table_row().'
 6288:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6289:        '.&Apache::loncommon::end_data_table_row().'
 6290:        '.&Apache::loncommon::start_data_table_row().'
 6291:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6292:        '.&Apache::loncommon::end_data_table_row().'
 6293:        '.&Apache::loncommon::start_data_table_row().'
 6294:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6295:        '.&Apache::loncommon::end_data_table_row().'
 6296:        '.&Apache::loncommon::start_data_table_row().'
 6297:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6298:        '.&Apache::loncommon::end_data_table_row().'
 6299:        '.&Apache::loncommon::start_data_table_row().'
 6300:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6301:        '.&Apache::loncommon::end_data_table_row().'
 6302:        '.&Apache::loncommon::start_data_table_row().'
 6303: 	    <td> '.&mt('Options:').' </td>
 6304:             <td>
 6305: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6306:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6307:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6308: 	    </td>
 6309:        '.&Apache::loncommon::end_data_table_row().'
 6310:        '.&Apache::loncommon::start_data_table_row().'
 6311:             <td colspan="2">
 6312:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6313:             </td>
 6314:        '.&Apache::loncommon::end_data_table_row().'
 6315:     '.&Apache::loncommon::end_data_table().'
 6316:     </form>
 6317: ';
 6318:    
 6319:     $r->print($result);
 6320: 
 6321:     # Chunk of the form that prompts to view a scoring office file,
 6322:     # corrected file, skipped records in a file.
 6323: 
 6324:     $r->print('
 6325:    <br />
 6326:    <form action="/adm/grades" name="scantron_download">
 6327:      '.$default_form_data.'
 6328:      <input type="hidden" name="command" value="scantron_download" />
 6329:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6330:        '.&Apache::loncommon::start_data_table_header_row().'
 6331:               <th>
 6332:                 &nbsp;'.&mt('Download a scoring office file').'
 6333:               </th>
 6334:        '.&Apache::loncommon::end_data_table_header_row().'
 6335:        '.&Apache::loncommon::start_data_table_row().'
 6336:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6337:                 <br />
 6338:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6339:        '.&Apache::loncommon::end_data_table_row().'
 6340:      '.&Apache::loncommon::end_data_table().'
 6341:    </form>
 6342:    <br />
 6343: ');
 6344: 
 6345:     &Apache::lonpickcode::code_list($r,2);
 6346: 
 6347:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6348:              $default_form_data."\n".
 6349:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6350:              &Apache::loncommon::start_data_table_header_row()."\n".
 6351:              '<th colspan="2">
 6352:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6353:              '</th>'."\n".
 6354:               &Apache::loncommon::end_data_table_header_row()."\n".
 6355:               &Apache::loncommon::start_data_table_row()."\n".
 6356:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6357:               '<td> '.$sequence_selector.' </td>'.
 6358:               &Apache::loncommon::end_data_table_row()."\n".
 6359:               &Apache::loncommon::start_data_table_row()."\n".
 6360:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6361:               '<td> '.$file_selector.' </td>'."\n".
 6362:               &Apache::loncommon::end_data_table_row()."\n".
 6363:               &Apache::loncommon::start_data_table_row()."\n".
 6364:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6365:               '<td> '.$format_selector.' </td>'."\n".
 6366:               &Apache::loncommon::end_data_table_row()."\n".
 6367:               &Apache::loncommon::start_data_table_row()."\n".
 6368:               '<td> '.&mt('Options').' </td>'."\n".
 6369:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6370:               &Apache::loncommon::end_data_table_row()."\n".
 6371:               &Apache::loncommon::start_data_table_row()."\n".
 6372:               '<td colspan="2">'."\n".
 6373:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6374:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6375:               '</td>'."\n".
 6376:               &Apache::loncommon::end_data_table_row()."\n".
 6377:               &Apache::loncommon::end_data_table()."\n".
 6378:               '</form><br />');
 6379:     return;
 6380: }
 6381: 
 6382: =pod 
 6383: 
 6384: =item username_to_idmap
 6385: 
 6386:     creates a hash keyed by student/employee ID with values of the corresponding
 6387:     student username:domain. If a single ID occurs for more than one student,
 6388:     the status of the student is checked, and if Active, the value in the hash
 6389:     will be set to the Active student.
 6390: 
 6391:   Arguments:
 6392: 
 6393:     $classlist - reference to the class list hash. This is a hash
 6394:                  keyed by student name:domain  whose elements are references
 6395:                  to arrays containing various chunks of information
 6396:                  about the student. (See loncoursedata for more info).
 6397: 
 6398:   Returns
 6399:     %idmap - the constructed hash
 6400: 
 6401: =cut
 6402: 
 6403: sub username_to_idmap {
 6404:     my ($classlist)= @_;
 6405:     my %idmap;
 6406:     foreach my $student (keys(%$classlist)) {
 6407:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6408:         unless ($id eq '') {
 6409:             if (!exists($idmap{$id})) {
 6410:                 $idmap{$id} = $student;
 6411:             } else {
 6412:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6413:                 if ($status eq 'Active') {
 6414:                     $idmap{$id} = $student;
 6415:                 }
 6416:             }
 6417:         }
 6418:     }
 6419:     return %idmap;
 6420: }
 6421: 
 6422: =pod
 6423: 
 6424: =item scantron_fixup_scanline
 6425: 
 6426:    Process a requested correction to a scanline.
 6427: 
 6428:   Arguments:
 6429:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6430:     $scan_data         - hash of correction information 
 6431:                           (see &scantron_getfile())
 6432:     $line              - existing scanline
 6433:     $whichline         - line number of the passed in scanline
 6434:     $field             - type of change to process 
 6435:                          (either 
 6436:                           'ID'     -> correct the student/employee ID
 6437:                           'CODE'   -> correct the CODE
 6438:                           'answer' -> fixup the submitted answers)
 6439:     
 6440:    $args               - hash of additional info,
 6441:                           - 'ID' 
 6442:                                'newid' -> studentID to use in replacement
 6443:                                           of existing one
 6444:                           - 'CODE' 
 6445:                                'CODE_ignore_dup' - set to true if duplicates
 6446:                                                    should be ignored.
 6447: 	                       'CODE' - is new code or 'use_unfound'
 6448:                                         if the existing unfound code should
 6449:                                         be used as is
 6450:                           - 'answer'
 6451:                                'response' - new answer or 'none' if blank
 6452:                                'question' - the bubble line to change
 6453:                                'questionnum' - the question identifier,
 6454:                                                may include subquestion. 
 6455: 
 6456:   Returns:
 6457:     $line - the modified scanline
 6458: 
 6459:   Side effects: 
 6460:     $scan_data - may be updated
 6461: 
 6462: =cut
 6463: 
 6464: 
 6465: sub scantron_fixup_scanline {
 6466:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6467:     if ($field eq 'ID') {
 6468: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6469: 	    return ($line,1,'New value too large');
 6470: 	}
 6471: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6472: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6473: 				     $args->{'newid'});
 6474: 	}
 6475: 	substr($line,$$scantron_config{'IDstart'}-1,
 6476: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6477: 	if ($args->{'newid'}=~/^\s*$/) {
 6478: 	    &scan_data($scan_data,"$whichline.user",
 6479: 		       $args->{'username'}.':'.$args->{'domain'});
 6480: 	}
 6481:     } elsif ($field eq 'CODE') {
 6482: 	if ($args->{'CODE_ignore_dup'}) {
 6483: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6484: 	}
 6485: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6486: 	if ($args->{'CODE'} ne 'use_unfound') {
 6487: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6488: 		return ($line,1,'New CODE value too large');
 6489: 	    }
 6490: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6491: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6492: 	    }
 6493: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6494: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6495: 	}
 6496:     } elsif ($field eq 'answer') {
 6497: 	my $length=$scantron_config->{'Qlength'};
 6498: 	my $off=$scantron_config->{'Qoff'};
 6499: 	my $on=$scantron_config->{'Qon'};
 6500: 	my $answer=${off}x$length;
 6501: 	if ($args->{'response'} eq 'none') {
 6502: 	    &scan_data($scan_data,
 6503: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6504: 	} else {
 6505: 	    if ($on eq 'letter') {
 6506: 		my @alphabet=('A'..'Z');
 6507: 		$answer=$alphabet[$args->{'response'}];
 6508: 	    } elsif ($on eq 'number') {
 6509: 		$answer=$args->{'response'}+1;
 6510: 		if ($answer == 10) { $answer = '0'; }
 6511: 	    } else {
 6512: 		substr($answer,$args->{'response'},1)=$on;
 6513: 	    }
 6514: 	    &scan_data($scan_data,
 6515: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6516: 	}
 6517: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6518: 	substr($line,$where-1,$length)=$answer;
 6519:     }
 6520:     return $line;
 6521: }
 6522: 
 6523: =pod
 6524: 
 6525: =item scan_data
 6526: 
 6527:     Edit or look up  an item in the scan_data hash.
 6528: 
 6529:   Arguments:
 6530:     $scan_data  - The hash (see scantron_getfile)
 6531:     $key        - shorthand of the key to edit (actual key is
 6532:                   scantronfilename_key).
 6533:     $data        - New value of the hash entry.
 6534:     $delete      - If true, the entry is removed from the hash.
 6535: 
 6536:   Returns:
 6537:     The new value of the hash table field (undefined if deleted).
 6538: 
 6539: =cut
 6540: 
 6541: 
 6542: sub scan_data {
 6543:     my ($scan_data,$key,$value,$delete)=@_;
 6544:     my $filename=$env{'form.scantron_selectfile'};
 6545:     if (defined($value)) {
 6546: 	$scan_data->{$filename.'_'.$key} = $value;
 6547:     }
 6548:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6549:     return $scan_data->{$filename.'_'.$key};
 6550: }
 6551: 
 6552: # ----- These first few routines are general use routines.----
 6553: 
 6554: # Return the number of occurences of a pattern in a string.
 6555: 
 6556: sub occurence_count {
 6557:     my ($string, $pattern) = @_;
 6558: 
 6559:     my @matches = ($string =~ /$pattern/g);
 6560: 
 6561:     return scalar(@matches);
 6562: }
 6563: 
 6564: 
 6565: # Take a string known to have digits and convert all the
 6566: # digits into letters in the range J,A..I.
 6567: 
 6568: sub digits_to_letters {
 6569:     my ($input) = @_;
 6570: 
 6571:     my @alphabet = ('J', 'A'..'I');
 6572: 
 6573:     my @input    = split(//, $input);
 6574:     my $output ='';
 6575:     for (my $i = 0; $i < scalar(@input); $i++) {
 6576: 	if ($input[$i] =~ /\d/) {
 6577: 	    $output .= $alphabet[$input[$i]];
 6578: 	} else {
 6579: 	    $output .= $input[$i];
 6580: 	}
 6581:     }
 6582:     return $output;
 6583: }
 6584: 
 6585: =pod 
 6586: 
 6587: =item scantron_parse_scanline
 6588: 
 6589:   Decodes a scanline from the selected bubblesheet file
 6590: 
 6591:  Arguments:
 6592:     line             - The text of the bubblesheet file line to process
 6593:     whichline        - Line number
 6594:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6595:     scan_data        - Hash of extra information about the scanline
 6596:                        (see scantron_getfile for more information)
 6597:     just_header      - True if should not process question answers but only
 6598:                        the stuff to the left of the answers.
 6599:     randomorder      - True if randomorder in use
 6600:     randompick       - True if randompick in use
 6601:     sequence         - Exam folder URL
 6602:     master_seq       - Ref to array containing symbs in exam folder
 6603:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6604:                        (corresponding values are resource objects)
 6605:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6606:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6607:                        are refs to an array of resource objects, ordered
 6608:                        according to order used for CODE, when randomorder
 6609:                        and or randompick are in use.
 6610:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6611:                        for current line to question number used for same question
 6612:                         in "Master Sequence" (as seen by Course Coordinator).
 6613:     startline        - Ref to hash where key is question number (0 is first)
 6614:                        and value is number of first bubble line for current 
 6615:                        student or code-based randompick and/or randomorder.
 6616:     totalref         - Ref of scalar used to score total number of bubble
 6617:                        lines needed for responses in a scan line (used when
 6618:                        randompick in use. 
 6619:     
 6620:  Returns:
 6621:    Hash containing the result of parsing the scanline
 6622: 
 6623:    Keys are all proceeded by the string 'scantron.'
 6624: 
 6625:        CODE    - the CODE in use for this scanline
 6626:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6627:                  by the operator
 6628:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6629:                             CODEs were selected, but the usage has been
 6630:                             forced by the operator
 6631:        ID  - student/employee ID
 6632:        PaperID - if used, the ID number printed on the sheet when the 
 6633:                  paper was scanned
 6634:        FirstName - first name from the sheet
 6635:        LastName  - last name from the sheet
 6636: 
 6637:      if just_header was not true these key may also exist
 6638: 
 6639:        missingerror - a list of bubble ranges that are considered to be answers
 6640:                       to a single question that don't have any bubbles filled in.
 6641:                       Of the form questionnumber:firstbubblenumber:count.
 6642:        doubleerror  - a list of bubble ranges that are considered to be answers
 6643:                       to a single question that have more than one bubble filled in.
 6644:                       Of the form questionnumber::firstbubblenumber:count
 6645:    
 6646:                 In the above, count is the number of bubble responses in the
 6647:                 input line needed to represent the possible answers to the question.
 6648:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6649:                 per line would have count = 2.
 6650: 
 6651:        maxquest     - the number of the last bubble line that was parsed
 6652: 
 6653:        (<number> starts at 1)
 6654:        <number>.answer - zero or more letters representing the selected
 6655:                          letters from the scanline for the bubble line 
 6656:                          <number>.
 6657:                          if blank there was either no bubble or there where
 6658:                          multiple bubbles, (consult the keys missingerror and
 6659:                          doubleerror if this is an error condition)
 6660: 
 6661: =cut
 6662: 
 6663: sub scantron_parse_scanline {
 6664:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6665:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6666:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6667: 
 6668:     my %record;
 6669:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6670:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6671: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6672: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6673: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6674: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6675: 	    $record{'scantron.CODE'}=substr($data,
 6676: 					    $$scantron_config{'CODEstart'}-1,
 6677: 					    $$scantron_config{'CODElength'});
 6678: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6679: 		$record{'scantron.useCODE'}=1;
 6680: 	    }
 6681: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6682: 		$record{'scantron.CODE_ignore_dup'}=1;
 6683: 	    }
 6684: 	} else {
 6685: 	    #FIXME interpret first N questions
 6686: 	}
 6687:     }
 6688:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6689: 				  $$scantron_config{'IDlength'});
 6690:     $record{'scantron.PaperID'}=
 6691: 	substr($data,$$scantron_config{'PaperID'}-1,
 6692: 	       $$scantron_config{'PaperIDlength'});
 6693:     $record{'scantron.FirstName'}=
 6694: 	substr($data,$$scantron_config{'FirstName'}-1,
 6695: 	       $$scantron_config{'FirstNamelength'});
 6696:     $record{'scantron.LastName'}=
 6697: 	substr($data,$$scantron_config{'LastName'}-1,
 6698: 	       $$scantron_config{'LastNamelength'});
 6699:     if ($just_header) { return \%record; }
 6700: 
 6701:     my @alphabet=('A'..'Z');
 6702:     my $questnum=0;
 6703:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6704: 
 6705:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6706:     if ($randompick || $randomorder) {
 6707:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6708:                                          $master_seq,$symb_to_resource,
 6709:                                          $partids_by_symb,$orderedforcode,
 6710:                                          $respnumlookup,$startline);
 6711:         if ($total) {
 6712:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6713:         }
 6714:         if (ref($totalref)) {
 6715:             $$totalref = $total;
 6716:         }
 6717:     }
 6718:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6719:     chomp($questions);		# Get rid of any trailing \n.
 6720:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6721:     while (length($questions)) {
 6722:         my $answers_needed;
 6723:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6724:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6725:         } else {
 6726: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6727:         }
 6728:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6729:                              || 1;
 6730:         $questnum++;
 6731:         my $quest_id = $questnum;
 6732:         my $currentquest = substr($questions,0,$answer_length);
 6733:         $questions       = substr($questions,$answer_length);
 6734:         if (length($currentquest) < $answer_length) { next; }
 6735: 
 6736:         my $subdivided;
 6737:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6738:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6739:         } else {
 6740:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6741:         }
 6742:         if ($subdivided =~ /,/) {
 6743:             my $subquestnum = 1;
 6744:             my $subquestions = $currentquest;
 6745:             my @subanswers_needed = split(/,/,$subdivided);
 6746:             foreach my $subans (@subanswers_needed) {
 6747:                 my $subans_length =
 6748:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6749:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6750:                 $subquestions   = substr($subquestions,$subans_length);
 6751:                 $quest_id = "$questnum.$subquestnum";
 6752:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6753:                     ($$scantron_config{'Qon'} eq 'number')) {
 6754:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6755:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6756:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6757:                         $randomorder,$randompick,$respnumlookup);
 6758:                 } else {
 6759:                     $ansnum = &scantron_validator_positional($ansnum,
 6760:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6761:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6762:                         $randomorder,$randompick,$respnumlookup);
 6763:                 }
 6764:                 $subquestnum ++;
 6765:             }
 6766:         } else {
 6767:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6768:                 ($$scantron_config{'Qon'} eq 'number')) {
 6769:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6770:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6771:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6772:                     $randomorder,$randompick,$respnumlookup);
 6773:             } else {
 6774:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6775:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6776:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6777:                     $randomorder,$randompick,$respnumlookup);
 6778:             }
 6779:         }
 6780:     }
 6781:     $record{'scantron.maxquest'}=$questnum;
 6782:     return \%record;
 6783: }
 6784: 
 6785: sub get_master_seq {
 6786:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
 6787:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6788:                    (ref($symb_to_resource) eq 'HASH'));
 6789:     if ($need_symb_in_map) {
 6790:         return unless (ref($symb_for_examcode) eq 'HASH');
 6791:     }
 6792:     my $resource_error;
 6793:     foreach my $resource (@{$resources}) {
 6794:         my $ressymb;
 6795:         if (ref($resource)) {
 6796:             $ressymb = $resource->symb();
 6797:             push(@{$master_seq},$ressymb);
 6798:             $symb_to_resource->{$ressymb} = $resource;
 6799:             if ($need_symb_in_map) {
 6800:                 unless ($resource->is_map()) {
 6801:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
 6802:                     unless (exists($symb_for_examcode->{$map})) {
 6803:                         $symb_for_examcode->{$map} = $ressymb;
 6804:                     }
 6805:                 }
 6806:             }
 6807:         } else {
 6808:             $resource_error = 1;
 6809:             last;
 6810:         }
 6811:     }
 6812:     return $resource_error;
 6813: }
 6814: 
 6815: sub get_respnum_lookups {
 6816:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6817:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6818:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6819:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6820:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6821:                    (ref($startline) eq 'HASH'));
 6822:     my ($user,$scancode);
 6823:     if ((exists($record->{'scantron.CODE'})) &&
 6824:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6825:         $scancode = $record->{'scantron.CODE'};
 6826:     } else {
 6827:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6828:     }
 6829:     my @mapresources =
 6830:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6831:                      $orderedforcode);
 6832:     my $total = 0;
 6833:     my $count = 0;
 6834:     foreach my $resource (@mapresources) {
 6835:         my $id = $resource->id();
 6836:         my $symb = $resource->symb();
 6837:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6838:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6839:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6840:                 if ($respnum ne '') {
 6841:                     $respnumlookup->{$count} = $respnum;
 6842:                     $startline->{$count} = $total;
 6843:                     $total += $bubble_lines_per_response{$respnum};
 6844:                     $count ++;
 6845:                 }
 6846:             }
 6847:         }
 6848:     }
 6849:     return $total;
 6850: }
 6851: 
 6852: sub scantron_validator_lettnum {
 6853:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6854:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6855:         $randompick,$respnumlookup) = @_;
 6856: 
 6857:     # Qon 'letter' implies for each slot in currquest we have:
 6858:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6859:     #    about anything else (esp. a value of Qoff) for missing
 6860:     #    bubbles.
 6861:     #
 6862:     # Qon 'number' implies each slot gives a digit that indexes the
 6863:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6864:     #    and * or ? for double bubbles on a single line.
 6865:     #
 6866: 
 6867:     my $matchon;
 6868:     if ($$scantron_config{'Qon'} eq 'letter') {
 6869:         $matchon = '[A-Z]';
 6870:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6871:         $matchon = '\d';
 6872:     }
 6873:     my $occurrences = 0;
 6874:     my $responsenum = $questnum-1;
 6875:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6876:        $responsenum = $respnumlookup->{$questnum-1} 
 6877:     }
 6878:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6879:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6880:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6881:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6882:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6883:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6884:         my @singlelines = split('',$currquest);
 6885:         foreach my $entry (@singlelines) {
 6886:             $occurrences = &occurence_count($entry,$matchon);
 6887:             if ($occurrences > 1) {
 6888:                 last;
 6889:             }
 6890:         }
 6891:     } else {
 6892:         $occurrences = &occurence_count($currquest,$matchon); 
 6893:     }
 6894:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6895:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6896:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6897:             my $bubble = substr($currquest,$ans,1);
 6898:             if ($bubble =~ /$matchon/ ) {
 6899:                 if ($$scantron_config{'Qon'} eq 'number') {
 6900:                     if ($bubble == 0) {
 6901:                         $bubble = 10; 
 6902:                     }
 6903:                     $record->{"scantron.$ansnum.answer"} = 
 6904:                         $alphabet->[$bubble-1];
 6905:                 } else {
 6906:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6907:                 }
 6908:             } else {
 6909:                 $record->{"scantron.$ansnum.answer"}='';
 6910:             }
 6911:             $ansnum++;
 6912:         }
 6913:     } elsif (!defined($currquest)
 6914:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6915:             || (&occurence_count($currquest,$matchon) == 0)) {
 6916:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6917:             $record->{"scantron.$ansnum.answer"}='';
 6918:             $ansnum++;
 6919:         }
 6920:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6921:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6922:         }
 6923:     } else {
 6924:         if ($$scantron_config{'Qon'} eq 'number') {
 6925:             $currquest = &digits_to_letters($currquest);            
 6926:         }
 6927:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6928:             my $bubble = substr($currquest,$ans,1);
 6929:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6930:             $ansnum++;
 6931:         }
 6932:     }
 6933:     return $ansnum;
 6934: }
 6935: 
 6936: sub scantron_validator_positional {
 6937:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6938:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6939:         $randomorder,$randompick,$respnumlookup) = @_;
 6940: 
 6941:     # Otherwise there's a positional notation;
 6942:     # each bubble line requires Qlength items, and there are filled in
 6943:     # bubbles for each case where there 'Qon' characters.
 6944:     #
 6945: 
 6946:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6947: 
 6948:     # If the split only gives us one element.. the full length of the
 6949:     # answer string, no bubbles are filled in:
 6950: 
 6951:     if ($answers_needed eq '') {
 6952:         return;
 6953:     }
 6954: 
 6955:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6956:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6957:             $record->{"scantron.$ansnum.answer"}='';
 6958:             $ansnum++;
 6959:         }
 6960:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6961:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6962:         }
 6963:     } elsif (scalar(@array) == 2) {
 6964:         my $location = length($array[0]);
 6965:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6966:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6967:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6968:             if ($ans eq $line_num) {
 6969:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6970:             } else {
 6971:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6972:             }
 6973:             $ansnum++;
 6974:          }
 6975:     } else {
 6976:         #  If there's more than one instance of a bubble character
 6977:         #  That's a double bubble; with positional notation we can
 6978:         #  record all the bubbles filled in as well as the
 6979:         #  fact this response consists of multiple bubbles.
 6980:         #
 6981:         my $responsenum = $questnum-1;
 6982:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6983:             $responsenum = $respnumlookup->{$questnum-1}
 6984:         }
 6985:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6986:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6987:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6988:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6989:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6990:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6991:             my $doubleerror = 0;
 6992:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6993:                    (!$doubleerror)) {
 6994:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6995:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6996:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6997:                if (length(@currarray) > 2) {
 6998:                    $doubleerror = 1;
 6999:                } 
 7000:             }
 7001:             if ($doubleerror) {
 7002:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 7003:             }
 7004:         } else {
 7005:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 7006:         }
 7007:         my $item = $ansnum;
 7008:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 7009:             $record->{"scantron.$item.answer"} = '';
 7010:             $item ++;
 7011:         }
 7012: 
 7013:         my @ans=@array;
 7014:         my $i=0;
 7015:         my $increment = 0;
 7016:         while ($#ans) {
 7017:             $i+=length($ans[0]) + $increment;
 7018:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 7019:             my $bubble = $i%$$scantron_config{'Qlength'};
 7020:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 7021:             shift(@ans);
 7022:             $increment = 1;
 7023:         }
 7024:         $ansnum += $answers_needed;
 7025:     }
 7026:     return $ansnum;
 7027: }
 7028: 
 7029: =pod
 7030: 
 7031: =item scantron_add_delay
 7032: 
 7033:    Adds an error message that occurred during the grading phase to a
 7034:    queue of messages to be shown after grading pass is complete
 7035: 
 7036:  Arguments:
 7037:    $delayqueue  - arrary ref of hash ref of error messages
 7038:    $scanline    - the scanline that caused the error
 7039:    $errormesage - the error message
 7040:    $errorcode   - a numeric code for the error
 7041: 
 7042:  Side Effects:
 7043:    updates the $delayqueue to have a new hash ref of the error
 7044: 
 7045: =cut
 7046: 
 7047: sub scantron_add_delay {
 7048:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 7049:     push(@$delayqueue,
 7050: 	 {'line' => $scanline, 'emsg' => $errormessage,
 7051: 	  'ecode' => $errorcode }
 7052: 	 );
 7053: }
 7054: 
 7055: =pod
 7056: 
 7057: =item scantron_find_student
 7058: 
 7059:    Finds the username for the current scanline
 7060: 
 7061:   Arguments:
 7062:    $scantron_record - hash result from scantron_parse_scanline
 7063:    $scan_data       - hash of correction information 
 7064:                       (see &scantron_getfile() form more information)
 7065:    $idmap           - hash from &username_to_idmap()
 7066:    $line            - number of current scanline
 7067:  
 7068:   Returns:
 7069:    Either 'username:domain' or undef if unknown
 7070: 
 7071: =cut
 7072: 
 7073: sub scantron_find_student {
 7074:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 7075:     my $scanID=$$scantron_record{'scantron.ID'};
 7076:     if ($scanID =~ /^\s*$/) {
 7077:  	return &scan_data($scan_data,"$line.user");
 7078:     }
 7079:     foreach my $id (keys(%$idmap)) {
 7080:  	if (lc($id) eq lc($scanID)) {
 7081:  	    return $$idmap{$id};
 7082:  	}
 7083:     }
 7084:     return undef;
 7085: }
 7086: 
 7087: =pod
 7088: 
 7089: =item scantron_filter
 7090: 
 7091:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 7092:    hidden resources was selected
 7093: 
 7094: =cut
 7095: 
 7096: sub scantron_filter {
 7097:     my ($curres)=@_;
 7098: 
 7099:     if (ref($curres) && $curres->is_problem()) {
 7100: 	# if the user has asked to not have either hidden
 7101: 	# or 'randomout' controlled resources to be graded
 7102: 	# don't include them
 7103: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7104: 	    && $curres->randomout) {
 7105: 	    return 0;
 7106: 	}
 7107: 	return 1;
 7108:     }
 7109:     return 0;
 7110: }
 7111: 
 7112: =pod
 7113: 
 7114: =item scantron_process_corrections
 7115: 
 7116:    Gets correction information out of submitted form data and corrects
 7117:    the scanline
 7118: 
 7119: =cut
 7120: 
 7121: sub scantron_process_corrections {
 7122:     my ($r) = @_;
 7123:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7124:     my ($scanlines,$scan_data)=&scantron_getfile();
 7125:     my $classlist=&Apache::loncoursedata::get_classlist();
 7126:     my $which=$env{'form.scantron_line'};
 7127:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7128:     my ($skip,$err,$errmsg);
 7129:     if ($env{'form.scantron_skip_record'}) {
 7130: 	$skip=1;
 7131:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7132: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7133: 	    $env{'form.scantron_domain'};
 7134: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7135: 	($line,$err,$errmsg)=
 7136: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7137: 				     'ID',{'newid'=>$newid,
 7138: 				    'username'=>$env{'form.scantron_username'},
 7139: 				    'domain'=>$env{'form.scantron_domain'}});
 7140:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7141: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7142: 	my $newCODE;
 7143: 	my %args;
 7144: 	if      ($resolution eq 'use_unfound') {
 7145: 	    $newCODE='use_unfound';
 7146: 	} elsif ($resolution eq 'use_found') {
 7147: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7148: 	} elsif ($resolution eq 'use_typed') {
 7149: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7150: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7151: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7152: 	}
 7153: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7154: 	    $args{'CODE_ignore_dup'}=1;
 7155: 	}
 7156: 	$args{'CODE'}=$newCODE;
 7157: 	($line,$err,$errmsg)=
 7158: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7159: 				     'CODE',\%args);
 7160:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7161: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7162: 	    ($line,$err,$errmsg)=
 7163: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7164: 					 $which,'answer',
 7165: 					 { 'question'=>$question,
 7166: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7167:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7168: 	    if ($err) { last; }
 7169: 	}
 7170:     }
 7171:     if ($err) {
 7172:         $r->print(
 7173:             '<p class="LC_error">'
 7174:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7175:                 $errmsg)
 7176:            .'</p>');
 7177:     } else {
 7178: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7179: 	&scantron_putfile($scanlines,$scan_data);
 7180:     }
 7181: }
 7182: 
 7183: =pod
 7184: 
 7185: =item reset_skipping_status
 7186: 
 7187:    Forgets the current set of remember skipped scanlines (and thus
 7188:    reverts back to considering all lines in the
 7189:    scantron_skipped_<filename> file)
 7190: 
 7191: =cut
 7192: 
 7193: sub reset_skipping_status {
 7194:     my ($scanlines,$scan_data)=&scantron_getfile();
 7195:     &scan_data($scan_data,'remember_skipping',undef,1);
 7196:     &scantron_putfile(undef,$scan_data);
 7197: }
 7198: 
 7199: =pod
 7200: 
 7201: =item start_skipping
 7202: 
 7203:    Marks a scanline to be skipped. 
 7204: 
 7205: =cut
 7206: 
 7207: sub start_skipping {
 7208:     my ($scan_data,$i)=@_;
 7209:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7210:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7211: 	$remembered{$i}=2;
 7212:     } else {
 7213: 	$remembered{$i}=1;
 7214:     }
 7215:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7216: }
 7217: 
 7218: =pod
 7219: 
 7220: =item should_be_skipped
 7221: 
 7222:    Checks whether a scanline should be skipped.
 7223: 
 7224: =cut
 7225: 
 7226: sub should_be_skipped {
 7227:     my ($scanlines,$scan_data,$i)=@_;
 7228:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7229: 	# not redoing old skips
 7230: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7231: 	return 0;
 7232:     }
 7233:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7234: 
 7235:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7236: 	return 0;
 7237:     }
 7238:     return 1;
 7239: }
 7240: 
 7241: =pod
 7242: 
 7243: =item remember_current_skipped
 7244: 
 7245:    Discovers what scanlines are in the scantron_skipped_<filename>
 7246:    file and remembers them into scan_data for later use.
 7247: 
 7248: =cut
 7249: 
 7250: sub remember_current_skipped {
 7251:     my ($scanlines,$scan_data)=&scantron_getfile();
 7252:     my %to_remember;
 7253:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7254: 	if ($scanlines->{'skipped'}[$i]) {
 7255: 	    $to_remember{$i}=1;
 7256: 	}
 7257:     }
 7258: 
 7259:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7260:     &scantron_putfile(undef,$scan_data);
 7261: }
 7262: 
 7263: =pod
 7264: 
 7265: =item check_for_error
 7266: 
 7267:     Checks if there was an error when attempting to remove a specific
 7268:     scantron_.. bubblesheet data file. Prints out an error if
 7269:     something went wrong.
 7270: 
 7271: =cut
 7272: 
 7273: sub check_for_error {
 7274:     my ($r,$result)=@_;
 7275:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7276: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7277:     }
 7278: }
 7279: 
 7280: =pod
 7281: 
 7282: =item scantron_warning_screen
 7283: 
 7284:    Interstitial screen to make sure the operator has selected the
 7285:    correct options before we start the validation phase.
 7286: 
 7287: =cut
 7288: 
 7289: sub scantron_warning_screen {
 7290:     my ($button_text,$symb)=@_;
 7291:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7292:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7293:     my $CODElist;
 7294:     if ($scantron_config{'CODElocation'} &&
 7295: 	$scantron_config{'CODEstart'} &&
 7296: 	$scantron_config{'CODElength'}) {
 7297: 	$CODElist=$env{'form.scantron_CODElist'};
 7298: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7299: 	$CODElist=
 7300: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7301: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7302:     }
 7303:     my $lastbubblepoints;
 7304:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7305:         $lastbubblepoints =
 7306:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7307:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7308:     }
 7309:     return '
 7310: <p>
 7311: <span class="LC_warning">
 7312: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7313: </p>
 7314: <table>
 7315: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7316: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7317: '.$CODElist.$lastbubblepoints.'
 7318: </table>
 7319: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7320: '.&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>
 7321: ';
 7322: }
 7323: 
 7324: =pod
 7325: 
 7326: =item scantron_do_warning
 7327: 
 7328:    Check if the operator has picked something for all required
 7329:    fields. Error out if something is missing.
 7330: 
 7331: =cut
 7332: 
 7333: sub scantron_do_warning {
 7334:     my ($r,$symb)=@_;
 7335:     if (!$symb) {return '';}
 7336:     my $default_form_data=&defaultFormData($symb);
 7337:     $r->print(&scantron_form_start().$default_form_data);
 7338:     if ( $env{'form.selectpage'} eq '' ||
 7339: 	 $env{'form.scantron_selectfile'} eq '' ||
 7340: 	 $env{'form.scantron_format'} eq '' ) {
 7341: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7342: 	if ( $env{'form.selectpage'} eq '') {
 7343: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7344: 	} 
 7345: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7346: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7347: 	}
 7348: 	if ( $env{'form.scantron_format'} eq '') {
 7349: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7350: 	}
 7351:     } else {
 7352: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7353:         my ($checksec,@possibles) = &gradable_sections();
 7354:         my $gradesections;
 7355:         if ($checksec) {
 7356:             my $file=$env{'form.scantron_selectfile'};
 7357:             if (&valid_file($file)) {
 7358:                 my %bysec = &scantron_get_sections();
 7359:                 my $table;
 7360:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7361:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7362:                     $table = &Apache::loncommon::start_data_table()."\n".
 7363:                              &Apache::loncommon::start_data_table_header_row().
 7364:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7365:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7366:                     if ($bysec{'none'}) {
 7367:                         $table .= &Apache::loncommon::start_data_table_row().
 7368:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7369:                                   &Apache::loncommon::end_data_table_row()."\n";
 7370:                     }
 7371:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7372:                         next if ($sec eq 'none');
 7373:                         $table .= &Apache::loncommon::start_data_table_row().
 7374:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7375:                                   &Apache::loncommon::end_data_table_row()."\n";
 7376:                     }
 7377:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7378:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7379:                                       '<p>'.$table.'</p>';
 7380:                     if (@possibles) {
 7381:                         $gradesections .= '<p>'.
 7382:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7383:                                               scalar(@possibles)).'<br />'.
 7384:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7385:                                               '<i>'.$checksec.'</i>').' ';
 7386:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7387:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7388:                         }
 7389:                         $gradesections .= '</p>';
 7390:                     }
 7391:                 }
 7392:             } else {
 7393:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7394:             }
 7395:         }
 7396:         my $bubbledbyhand=&hand_bubble_option();
 7397: 	$r->print('
 7398: '.$warning.$gradesections.$bubbledbyhand.'
 7399: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7400: <input type="hidden" name="command" value="scantron_validate" />
 7401: ');
 7402:     }
 7403:     $r->print("</form><br />");
 7404:     return '';
 7405: }
 7406: 
 7407: =pod
 7408: 
 7409: =item scantron_form_start
 7410: 
 7411:     html hidden input for remembering all selected grading options
 7412: 
 7413: =cut
 7414: 
 7415: sub scantron_form_start {
 7416:     my ($max_bubble)=@_;
 7417:     my $result= <<SCANTRONFORM;
 7418: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7419:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7420:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7421:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7422:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7423:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7424:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7425:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7426:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7427:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7428: SCANTRONFORM
 7429: 
 7430:   my $line = 0;
 7431:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7432:        my $chunk =
 7433: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7434:        $chunk .=
 7435: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7436:        $chunk .= 
 7437:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7438:        $chunk .=
 7439:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7440:        $chunk .=
 7441:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7442:        $result .= $chunk;
 7443:        $line++;
 7444:     }
 7445:     return $result;
 7446: }
 7447: 
 7448: =pod
 7449: 
 7450: =item scantron_validate_file
 7451: 
 7452:     Dispatch routine for doing validation of a bubblesheet data file.
 7453: 
 7454:     Also processes any necessary information resets that need to
 7455:     occur before validation begins (ignore previous corrections,
 7456:     restarting the skipped records processing)
 7457: 
 7458: =cut
 7459: 
 7460: sub scantron_validate_file {
 7461:     my ($r,$symb) = @_;
 7462:     if (!$symb) {return '';}
 7463:     my $default_form_data=&defaultFormData($symb);
 7464:     
 7465:     # do the detection of only doing skipped records first before we delete
 7466:     # them when doing the corrections reset
 7467:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7468: 	&reset_skipping_status();
 7469:     }
 7470:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7471: 	&remember_current_skipped();
 7472: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7473:     }
 7474: 
 7475:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7476: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7477: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7478: 	&check_for_error($r,&scantron_remove_scan_data());
 7479: 	$env{'form.scantron_options_ignore'}='done';
 7480:     }
 7481: 
 7482:     if ($env{'form.scantron_corrections'}) {
 7483: 	&scantron_process_corrections($r);
 7484:     }
 7485: 
 7486:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7487:     my ($checksec,@gradable);
 7488:     if ($env{'request.course.sec'}) {
 7489:         ($checksec,my @possibles) = &gradable_sections();
 7490:         if ($checksec) {
 7491:             if (@possibles) {
 7492:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7493:                 if (@chosensecs) {
 7494:                     foreach my $sec (@chosensecs) {
 7495:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7496:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7497:                                 push(@gradable,$sec);
 7498:                             }
 7499:                         }
 7500:                     }
 7501:                 }
 7502:             }
 7503:             $r->print('<p><table>');
 7504:             if (@gradable) {
 7505:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7506:                 $r->print(
 7507:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7508:             } else {
 7509:                 $r->print(
 7510:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7511:             }
 7512:             $r->print('</table></p>');
 7513:         }
 7514:     }
 7515:     $r->rflush();
 7516: 
 7517:     #get the student pick code ready
 7518:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7519:     my $nav_error;
 7520:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7521:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7522:     if ($nav_error) {
 7523:         $r->print(&navmap_errormsg());
 7524:         return '';
 7525:     }
 7526:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7527:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7528:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7529:     }
 7530:     $r->print($result);
 7531:     
 7532:     my @validate_phases=( 'sequence',
 7533: 			  'ID',
 7534: 			  'CODE',
 7535: 			  'doublebubble',
 7536: 			  'missingbubbles');
 7537:     if (!$env{'form.validatepass'}) {
 7538: 	$env{'form.validatepass'} = 0;
 7539:     }
 7540:     my $currentphase=$env{'form.validatepass'};
 7541:     my %skipbysec=();
 7542: 
 7543:     my $stop=0;
 7544:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7545: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7546: 	$r->rflush();
 7547:      
 7548: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7549: 	{
 7550: 	    no strict 'refs';
 7551:             my @extras=();
 7552:             if ($validate_phases[$currentphase] eq 'ID') {
 7553:                 @extras = (\%skipbysec,$checksec,@gradable);
 7554:             }
 7555: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7556: 	}
 7557:     }
 7558:     if (!$stop) {
 7559: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7560:         my $secinfo;
 7561:         if (keys(%skipbysec) > 0) {
 7562:             my $seclist = '<ul>';
 7563:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7564:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7565:             }
 7566:             $seclist .= '</ul>';
 7567:             $secinfo = '<p class="LC_info">'.
 7568:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7569:                            $seclist).
 7570:                        '</p>';
 7571:         }
 7572: 	$r->print(&mt('Validation process complete.').'<br />'.
 7573:                   $secinfo.$warning.
 7574:                   &mt('Perform verification for each student after storage of submissions?').
 7575:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7576:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7577:                   ('&nbsp;'x3).'<label>'.
 7578:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7579:                   '</label></span><br />'.
 7580:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7581:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7582:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7583:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7584:     } else {
 7585: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7586: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7587:     }
 7588:     if ($stop) {
 7589: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7590: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7591: 	    $r->print(' '.&mt('this error').' <br />');
 7592: 
 7593: 	    $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>');
 7594: 	} else {
 7595:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7596: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7597:             } else {
 7598:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7599:             }
 7600: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7601: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7602: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7603: 	}
 7604:     }
 7605:     $r->print(" </form><br />");
 7606:     return '';
 7607: }
 7608: 
 7609: 
 7610: =pod
 7611: 
 7612: =item scantron_remove_file
 7613: 
 7614:    Removes the requested bubblesheet data file, makes sure that
 7615:    scantron_original_<filename> is never removed
 7616: 
 7617: 
 7618: =cut
 7619: 
 7620: sub scantron_remove_file {
 7621:     my ($which)=@_;
 7622:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7623:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7624:     my $file='scantron_';
 7625:     if ($which eq 'corrected' || $which eq 'skipped') {
 7626: 	$file.=$which.'_';
 7627:     } else {
 7628: 	return 'refused';
 7629:     }
 7630:     $file.=$env{'form.scantron_selectfile'};
 7631:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7632: }
 7633: 
 7634: 
 7635: =pod
 7636: 
 7637: =item scantron_remove_scan_data
 7638: 
 7639:    Removes all scan_data correction for the requested bubblesheet
 7640:    data file.  (In the case that both the are doing skipped records we need
 7641:    to remember the old skipped lines for the time being so that element
 7642:    persists for a while.)
 7643: 
 7644: =cut
 7645: 
 7646: sub scantron_remove_scan_data {
 7647:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7648:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7649:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7650:     my @todelete;
 7651:     my $filename=$env{'form.scantron_selectfile'};
 7652:     foreach my $key (@keys) {
 7653: 	if ($key=~/^\Q$filename\E_/) {
 7654: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7655: 		$key=~/remember_skipping/) {
 7656: 		next;
 7657: 	    }
 7658: 	    push(@todelete,$key);
 7659: 	}
 7660:     }
 7661:     my $result;
 7662:     if (@todelete) {
 7663: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7664: 				       \@todelete,$cdom,$cname);
 7665:     } else {
 7666: 	$result = 'ok';
 7667:     }
 7668:     return $result;
 7669: }
 7670: 
 7671: 
 7672: =pod
 7673: 
 7674: =item scantron_getfile
 7675: 
 7676:     Fetches the requested bubblesheet data file (all 3 versions), and
 7677:     the scan_data hash
 7678:   
 7679:   Arguments:
 7680:     None
 7681: 
 7682:   Returns:
 7683:     2 hash references
 7684: 
 7685:      - first one has 
 7686:          orig      -
 7687:          corrected -
 7688:          skipped   -  each of which points to an array ref of the specified
 7689:                       file broken up into individual lines
 7690:          count     - number of scanlines
 7691:  
 7692:      - second is the scan_data hash possible keys are
 7693:        ($number refers to scanline numbered $number and thus the key affects
 7694:         only that scanline
 7695:         $bubline refers to the specific bubble line element and the aspects
 7696:         refers to that specific bubble line element)
 7697: 
 7698:        $number.user - username:domain to use
 7699:        $number.CODE_ignore_dup 
 7700:                     - ignore the duplicate CODE error 
 7701:        $number.useCODE
 7702:                     - use the CODE in the scanline as is
 7703:        $number.no_bubble.$bubline
 7704:                     - it is valid that there is no bubbled in bubble
 7705:                       at $number $bubline
 7706:        remember_skipping
 7707:                     - a frozen hash containing keys of $number and values
 7708:                       of either 
 7709:                         1 - we are on a 'do skipped records pass' and plan
 7710:                             on processing this line
 7711:                         2 - we are on a 'do skipped records pass' and this
 7712:                             scanline has been marked to skip yet again
 7713: 
 7714: =cut
 7715: 
 7716: sub scantron_getfile {
 7717:     #FIXME really would prefer a scantron directory
 7718:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7719:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7720:     my $lines;
 7721:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7722: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7723:     my %scanlines;
 7724:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7725:     my $temp=$scanlines{'orig'};
 7726:     $scanlines{'count'}=$#$temp;
 7727: 
 7728:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7729: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7730:     if ($lines eq '-1') {
 7731: 	$scanlines{'corrected'}=[];
 7732:     } else {
 7733: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7734:     }
 7735:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7736: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7737:     if ($lines eq '-1') {
 7738: 	$scanlines{'skipped'}=[];
 7739:     } else {
 7740: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7741:     }
 7742:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7743:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7744:     my %scan_data = @tmp;
 7745:     return (\%scanlines,\%scan_data);
 7746: }
 7747: 
 7748: =pod
 7749: 
 7750: =item lonnet_putfile
 7751: 
 7752:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7753: 
 7754:  Arguments:
 7755:    $contents - data to store
 7756:    $filename - filename to store $contents into
 7757: 
 7758:  Returns:
 7759:    result value from &Apache::lonnet::finishuserfileupload
 7760: 
 7761: =cut
 7762: 
 7763: sub lonnet_putfile {
 7764:     my ($contents,$filename)=@_;
 7765:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7766:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7767:     $env{'form.sillywaytopassafilearound'}=$contents;
 7768:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7769: 
 7770: }
 7771: 
 7772: =pod
 7773: 
 7774: =item scantron_putfile
 7775: 
 7776:     Stores the current version of the bubblesheet data files, and the
 7777:     scan_data hash. (Does not modify the original version only the
 7778:     corrected and skipped versions.
 7779: 
 7780:  Arguments:
 7781:     $scanlines - hash ref that looks like the first return value from
 7782:                  &scantron_getfile()
 7783:     $scan_data - hash ref that looks like the second return value from
 7784:                  &scantron_getfile()
 7785: 
 7786: =cut
 7787: 
 7788: sub scantron_putfile {
 7789:     my ($scanlines,$scan_data) = @_;
 7790:     #FIXME really would prefer a scantron directory
 7791:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7792:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7793:     if ($scanlines) {
 7794: 	my $prefix='scantron_';
 7795: # no need to update orig, shouldn't change
 7796: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7797: #		    $env{'form.scantron_selectfile'});
 7798: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7799: 			$prefix.'corrected_'.
 7800: 			$env{'form.scantron_selectfile'});
 7801: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7802: 			$prefix.'skipped_'.
 7803: 			$env{'form.scantron_selectfile'});
 7804:     }
 7805:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7806: }
 7807: 
 7808: =pod
 7809: 
 7810: =item scantron_get_line
 7811: 
 7812:    Returns the correct version of the scanline
 7813: 
 7814:  Arguments:
 7815:     $scanlines - hash ref that looks like the first return value from
 7816:                  &scantron_getfile()
 7817:     $scan_data - hash ref that looks like the second return value from
 7818:                  &scantron_getfile()
 7819:     $i         - number of the requested line (starts at 0)
 7820: 
 7821:  Returns:
 7822:    A scanline, (either the original or the corrected one if it
 7823:    exists), or undef if the requested scanline should be
 7824:    skipped. (Either because it's an skipped scanline, or it's an
 7825:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7826:    pass.
 7827: 
 7828: =cut
 7829: 
 7830: sub scantron_get_line {
 7831:     my ($scanlines,$scan_data,$i)=@_;
 7832:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7833:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7834:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7835:     return $scanlines->{'orig'}[$i]; 
 7836: }
 7837: 
 7838: =pod
 7839: 
 7840: =item scantron_todo_count
 7841: 
 7842:     Counts the number of scanlines that need processing.
 7843: 
 7844:  Arguments:
 7845:     $scanlines - hash ref that looks like the first return value from
 7846:                  &scantron_getfile()
 7847:     $scan_data - hash ref that looks like the second return value from
 7848:                  &scantron_getfile()
 7849: 
 7850:  Returns:
 7851:     $count - number of scanlines to process
 7852: 
 7853: =cut
 7854: 
 7855: sub get_todo_count {
 7856:     my ($scanlines,$scan_data)=@_;
 7857:     my $count=0;
 7858:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7859: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7860: 	if ($line=~/^[\s\cz]*$/) { next; }
 7861: 	$count++;
 7862:     }
 7863:     return $count;
 7864: }
 7865: 
 7866: =pod
 7867: 
 7868: =item scantron_put_line
 7869: 
 7870:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7871:     data file.
 7872: 
 7873:  Arguments:
 7874:     $scanlines - hash ref that looks like the first return value from
 7875:                  &scantron_getfile()
 7876:     $scan_data - hash ref that looks like the second return value from
 7877:                  &scantron_getfile()
 7878:     $i         - line number to update
 7879:     $newline   - contents of the updated scanline
 7880:     $skip      - if true make the line for skipping and update the
 7881:                  'skipped' file
 7882: 
 7883: =cut
 7884: 
 7885: sub scantron_put_line {
 7886:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7887:     if ($skip) {
 7888: 	$scanlines->{'skipped'}[$i]=$newline;
 7889: 	&start_skipping($scan_data,$i);
 7890: 	return;
 7891:     }
 7892:     $scanlines->{'corrected'}[$i]=$newline;
 7893: }
 7894: 
 7895: =pod
 7896: 
 7897: =item scantron_clear_skip
 7898: 
 7899:    Remove a line from the 'skipped' file
 7900: 
 7901:  Arguments:
 7902:     $scanlines - hash ref that looks like the first return value from
 7903:                  &scantron_getfile()
 7904:     $scan_data - hash ref that looks like the second return value from
 7905:                  &scantron_getfile()
 7906:     $i         - line number to update
 7907: 
 7908: =cut
 7909: 
 7910: sub scantron_clear_skip {
 7911:     my ($scanlines,$scan_data,$i)=@_;
 7912:     if (exists($scanlines->{'skipped'}[$i])) {
 7913: 	undef($scanlines->{'skipped'}[$i]);
 7914: 	return 1;
 7915:     }
 7916:     return 0;
 7917: }
 7918: 
 7919: =pod
 7920: 
 7921: =item scantron_filter_not_exam
 7922: 
 7923:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7924:    filter out resources that are not marked as 'exam' mode
 7925: 
 7926: =cut
 7927: 
 7928: sub scantron_filter_not_exam {
 7929:     my ($curres)=@_;
 7930:     
 7931:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7932: 	# if the user has asked to not have either hidden
 7933: 	# or 'randomout' controlled resources to be graded
 7934: 	# don't include them
 7935: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7936: 	    && $curres->randomout) {
 7937: 	    return 0;
 7938: 	}
 7939: 	return 1;
 7940:     }
 7941:     return 0;
 7942: }
 7943: 
 7944: =pod
 7945: 
 7946: =item scantron_validate_sequence
 7947: 
 7948:     Validates the selected sequence, checking for resource that are
 7949:     not set to exam mode.
 7950: 
 7951: =cut
 7952: 
 7953: sub scantron_validate_sequence {
 7954:     my ($r,$currentphase) = @_;
 7955: 
 7956:     my $navmap=Apache::lonnavmaps::navmap->new();
 7957:     unless (ref($navmap)) {
 7958:         $r->print(&navmap_errormsg());
 7959:         return (1,$currentphase);
 7960:     }
 7961:     my (undef,undef,$sequence)=
 7962: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7963: 
 7964:     my $map=$navmap->getResourceByUrl($sequence);
 7965: 
 7966:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7967:                                     value="ignore" />');
 7968:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7969: 	my @resources=
 7970: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7971: 	if (@resources) {
 7972: 	    $r->print(
 7973:                 '<p class="LC_warning">'
 7974:                .&mt('Some resources in the sequence currently are not set to'
 7975:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7976:                    .' work correctly.')
 7977:                .'</p>'
 7978:             );
 7979: 	    return (1,$currentphase);
 7980: 	}
 7981:     }
 7982: 
 7983:     return (0,$currentphase+1);
 7984: }
 7985: 
 7986: 
 7987: 
 7988: sub scantron_validate_ID {
 7989:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
 7990:     
 7991:     #get student info
 7992:     my $classlist=&Apache::loncoursedata::get_classlist();
 7993:     my %idmap=&username_to_idmap($classlist);
 7994:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7995: 
 7996:     #get scantron line setup
 7997:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7998:     my ($scanlines,$scan_data)=&scantron_getfile();
 7999: 
 8000:     my $nav_error;
 8001:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 8002:     if ($nav_error) {
 8003:         $r->print(&navmap_errormsg());
 8004:         return(1,$currentphase);
 8005:     }
 8006: 
 8007:     my %found=('ids'=>{},'usernames'=>{});
 8008:     my $unsavedskips = 0;
 8009:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8010: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8011: 	if ($line=~/^[\s\cz]*$/) { next; }
 8012: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8013: 						 $scan_data);
 8014: 	my $id=$$scan_record{'scantron.ID'};
 8015: 	my $found;
 8016: 	foreach my $checkid (keys(%idmap)) {
 8017: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 8018: 	}
 8019: 	if ($found) {
 8020: 	    my $username=$idmap{$found};
 8021:             if ($checksec) {
 8022:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 8023:                     my $stusec = $classlist->{$username}->[$secidx];
 8024:                     if ($stusec ne $checksec) {
 8025:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 8026:                             my $skip=1;
 8027:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 8028:                             if (ref($skipbysec) eq 'HASH') {
 8029:                                 if ($stusec eq '') {
 8030:                                     $skipbysec->{'none'} ++;
 8031:                                 } else {
 8032:                                     $skipbysec->{$stusec} ++;
 8033:                                 }
 8034:                             }
 8035:                             $unsavedskips ++;
 8036:                             next;
 8037:                         }
 8038:                     }
 8039:                 }
 8040:             }
 8041: 	    if ($found{'ids'}{$found}) {
 8042: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8043: 					 $line,'duplicateID',$found);
 8044:                 if ($unsavedskips) {
 8045:                     &scantron_putfile($scanlines,$scan_data);
 8046:                     $unsavedskips = 0;
 8047:                 }
 8048: 		return(1,$currentphase);
 8049: 	    } elsif ($found{'usernames'}{$username}) {
 8050: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8051: 					 $line,'duplicateID',$username);
 8052:                 if ($unsavedskips) {
 8053:                     &scantron_putfile($scanlines,$scan_data);
 8054:                     $unsavedskips = 0;
 8055:                 }
 8056: 		return(1,$currentphase);
 8057: 	    }
 8058: 	    #FIXME store away line we previously saw the ID on to use above
 8059: 	    $found{'ids'}{$found}++;
 8060: 	    $found{'usernames'}{$username}++;
 8061: 	} else {
 8062: 	    if ($id =~ /^\s*$/) {
 8063: 		my $username=&scan_data($scan_data,"$i.user");
 8064:                 if (($checksec && $username ne '')) {
 8065:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 8066:                         my $stusec = $classlist->{$username}->[$secidx];
 8067:                         if ($stusec ne $checksec) {
 8068:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 8069:                                 my $skip=1;
 8070:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 8071:                                 if (ref($skipbysec) eq 'HASH') {
 8072:                                     if ($stusec eq '') {
 8073:                                         $skipbysec->{'none'} ++;
 8074:                                     } else {
 8075:                                         $skipbysec->{$stusec} ++;
 8076:                                     }
 8077:                                 }
 8078:                                 $unsavedskips ++;
 8079:                                 next;
 8080:                             }
 8081:                         }
 8082:                     }
 8083: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 8084: 		    &scantron_get_correction($r,$i,$scan_record,
 8085: 					     \%scantron_config,
 8086: 					     $line,'duplicateID',$username);
 8087:                     if ($unsavedskips) {
 8088:                         &scantron_putfile($scanlines,$scan_data);
 8089:                         $unsavedskips = 0;
 8090:                     }
 8091: 		    return(1,$currentphase);
 8092: 		} elsif (!defined($username)) {
 8093: 		    &scantron_get_correction($r,$i,$scan_record,
 8094: 					     \%scantron_config,
 8095: 					     $line,'incorrectID');
 8096:                     if ($unsavedskips) {
 8097:                         &scantron_putfile($scanlines,$scan_data);
 8098:                         $unsavedskips = 0;
 8099:                     }
 8100: 		    return(1,$currentphase);
 8101: 		}
 8102: 		$found{'usernames'}{$username}++;
 8103: 	    } else {
 8104: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8105: 					 $line,'incorrectID');
 8106:                 if ($unsavedskips) {
 8107:                     &scantron_putfile($scanlines,$scan_data);
 8108:                     $unsavedskips = 0;
 8109:                 }
 8110: 		return(1,$currentphase);
 8111: 	    }
 8112: 	}
 8113:     }
 8114:     if ($unsavedskips) {
 8115:         &scantron_putfile($scanlines,$scan_data);
 8116:         $unsavedskips = 0;
 8117:     }
 8118:     return (0,$currentphase+1);
 8119: }
 8120: 
 8121: sub scantron_get_sections {
 8122:     my %bysec;
 8123:     if ($env{'form.scantron_format'} ne '') {
 8124:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8125:         my ($scanlines,$scan_data)=&scantron_getfile();
 8126:         my $classlist=&Apache::loncoursedata::get_classlist();
 8127:         my %idmap=&username_to_idmap($classlist);
 8128:         foreach my $key (keys(%idmap)) {
 8129:             my $lckey = lc($key);
 8130:             $idmap{$lckey} = $idmap{$key};
 8131:         }
 8132:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 8133:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8134:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8135:             if ($line=~/^[\s\cz]*$/) { next; }
 8136:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8137:                                                      $scan_data);
 8138:             my $id=lc($$scan_record{'scantron.ID'});
 8139:             if (exists($idmap{$id})) {
 8140:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 8141:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 8142:                     if ($stusec eq '') {
 8143:                         $bysec{'none'} ++;
 8144:                     } else {
 8145:                         $bysec{$stusec} ++;
 8146:                     }
 8147:                 }
 8148:             }
 8149:         }
 8150:     }
 8151:     return %bysec;
 8152: }
 8153: 
 8154: sub scantron_get_correction {
 8155:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 8156:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 8157: #FIXME in the case of a duplicated ID the previous line, probably need
 8158: #to show both the current line and the previous one and allow skipping
 8159: #the previous one or the current one
 8160: 
 8161:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 8162:         $r->print(
 8163:             '<p class="LC_warning">'
 8164:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 8165:                 "<b>$error</b>",
 8166:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 8167:            ."</p> \n");
 8168:     } else {
 8169:         $r->print(
 8170:             '<p class="LC_warning">'
 8171:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8172:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8173:            ."</p> \n");
 8174:     }
 8175:     my $message =
 8176:         '<p>'
 8177:        .&mt('The ID on the form is [_1]',
 8178:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8179:        .'<br />'
 8180:        .&mt('The name on the paper is [_1], [_2]',
 8181:             $$scan_record{'scantron.LastName'},
 8182:             $$scan_record{'scantron.FirstName'})
 8183:        .'</p>';
 8184: 
 8185:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8186:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8187:                            # Array populated for doublebubble or
 8188:     my @lines_to_correct;  # missingbubble errors to build javascript
 8189:                            # to validate radio button checking   
 8190: 
 8191:     if ($error =~ /ID$/) {
 8192: 	if ($error eq 'incorrectID') {
 8193:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8194: 		      "</p>\n");
 8195: 	} elsif ($error eq 'duplicateID') {
 8196:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8197: 	}
 8198: 	$r->print($message);
 8199: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8200: 	$r->print("\n<ul><li> ");
 8201: 	#FIXME it would be nice if this sent back the user ID and
 8202: 	#could do partial userID matches
 8203: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8204: 				       'scantron_username','scantron_domain'));
 8205: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8206: 	$r->print("\n:\n".
 8207: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8208: 
 8209: 	$r->print('</li>');
 8210:     } elsif ($error =~ /CODE$/) {
 8211: 	if ($error eq 'incorrectCODE') {
 8212: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8213: 	} elsif ($error eq 'duplicateCODE') {
 8214: 	    $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");
 8215: 	}
 8216: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 8217: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8218:                  ."</p>\n");
 8219: 	$r->print($message);
 8220: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8221: 	$r->print("\n<br /> ");
 8222: 	my $i=0;
 8223: 	if ($error eq 'incorrectCODE' 
 8224: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8225: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8226: 	    if ($closest > 0) {
 8227: 		foreach my $testcode (@{$closest}) {
 8228: 		    my $checked='';
 8229: 		    if (!$i) { $checked=' checked="checked"'; }
 8230: 		    $r->print("
 8231:    <label>
 8232:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8233:        ".&mt("Use the similar CODE [_1] instead.",
 8234: 	    "<b><tt>".$testcode."</tt></b>")."
 8235:     </label>
 8236:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8237: 		    $r->print("\n<br />");
 8238: 		    $i++;
 8239: 		}
 8240: 	    }
 8241: 	}
 8242: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8243: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8244: 	    $r->print("
 8245:     <label>
 8246:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8247:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8248: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8249:     </label>");
 8250: 	    $r->print("\n<br />");
 8251: 	}
 8252: 
 8253: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8254: function change_radio(field) {
 8255:     var slct=document.scantronupload.scantron_CODE_resolution;
 8256:     var i;
 8257:     for (i=0;i<slct.length;i++) {
 8258:         if (slct[i].value==field) { slct[i].checked=true; }
 8259:     }
 8260: }
 8261: ENDSCRIPT
 8262: 	my $href="/adm/pickcode?".
 8263: 	   "form=".&escape("scantronupload").
 8264: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8265: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8266: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8267: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8268: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8269: 	    $r->print("
 8270:     <label>
 8271:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8272:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8273: 	     "<a target='_blank' href='$href'>","</a>")."
 8274:     </label> 
 8275:     ".&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\')" />'));
 8276: 	    $r->print("\n<br />");
 8277: 	}
 8278: 	$r->print("
 8279:     <label>
 8280:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8281:        ".&mt("Use [_1] as the CODE.",
 8282: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8283: 	$r->print("\n<br /><br />");
 8284:     } elsif ($error eq 'doublebubble') {
 8285: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8286: 
 8287: 	# The form field scantron_questions is acutally a list of line numbers.
 8288: 	# represented by this form so:
 8289: 
 8290: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8291:                                                 $respnumlookup,$startline);
 8292: 
 8293: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8294: 		  $line_list.'" />');
 8295: 	$r->print($message);
 8296: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8297: 	foreach my $question (@{$arg}) {
 8298: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8299:                                                    $scan_record, $error,
 8300:                                                    $randomorder,$randompick,
 8301:                                                    $respnumlookup,$startline);
 8302:             push(@lines_to_correct,@linenums);
 8303: 	}
 8304:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8305:     } elsif ($error eq 'missingbubble') {
 8306: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8307: 	$r->print($message);
 8308: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8309: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8310: 
 8311: 	# The form field scantron_questions is actually a list of line numbers not
 8312: 	# a list of question numbers. Therefore:
 8313: 	#
 8314: 
 8315: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8316:                                                 $respnumlookup,$startline);
 8317: 
 8318: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8319: 		  $line_list.'" />');
 8320: 	foreach my $question (@{$arg}) {
 8321: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8322:                                                    $scan_record, $error,
 8323:                                                    $randomorder,$randompick,
 8324:                                                    $respnumlookup,$startline);
 8325:             push(@lines_to_correct,@linenums);
 8326: 	}
 8327:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8328:     } else {
 8329: 	$r->print("\n<ul>");
 8330:     }
 8331:     $r->print("\n</li></ul>");
 8332: }
 8333: 
 8334: sub verify_bubbles_checked {
 8335:     my (@ansnums) = @_;
 8336:     my $ansnumstr = join('","',@ansnums);
 8337:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8338:     &js_escape(\$warning);
 8339:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8340: function verify_bubble_radio(form) {
 8341:     var ansnumArray = new Array ("$ansnumstr");
 8342:     var need_bubble_count = 0;
 8343:     for (var i=0; i<ansnumArray.length; i++) {
 8344:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8345:             var bubble_picked = 0; 
 8346:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8347:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8348:                     bubble_picked = 1;
 8349:                 }
 8350:             }
 8351:             if (bubble_picked == 0) {
 8352:                 need_bubble_count ++;
 8353:             }
 8354:         }
 8355:     }
 8356:     if (need_bubble_count) {
 8357:         alert("$warning");
 8358:         return;
 8359:     }
 8360:     form.submit(); 
 8361: }
 8362: ENDSCRIPT
 8363:     return $output;
 8364: }
 8365: 
 8366: =pod
 8367: 
 8368: =item  questions_to_line_list
 8369: 
 8370: Converts a list of questions into a string of comma separated
 8371: line numbers in the answer sheet used by the questions.  This is
 8372: used to fill in the scantron_questions form field.
 8373: 
 8374:   Arguments:
 8375:      questions    - Reference to an array of questions.
 8376:      randomorder  - True if randomorder in use.
 8377:      randompick   - True if randompick in use.
 8378:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8379:                      for current line to question number used for same question
 8380:                      in "Master Seqence" (as seen by Course Coordinator).
 8381:      startline    - Reference to hash where key is question number (0 is first)
 8382:                     and key is number of first bubble line for current student
 8383:                     or code-based randompick and/or randomorder.
 8384: 
 8385: =cut
 8386: 
 8387: 
 8388: sub questions_to_line_list {
 8389:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8390:     my @lines;
 8391: 
 8392:     foreach my $item (@{$questions}) {
 8393:         my $question = $item;
 8394:         my ($first,$count,$last);
 8395:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8396:             $question = $1;
 8397:             my $subquestion = $2;
 8398:             my $responsenum = $question-1;
 8399:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8400:                 $responsenum = $respnumlookup->{$question-1};
 8401:                 if (ref($startline) eq 'HASH') {
 8402:                     $first = $startline->{$question-1} + 1;
 8403:                 }
 8404:             } else {
 8405:                 $first = $first_bubble_line{$responsenum} + 1;
 8406:             }
 8407:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8408:             my $subcount = 1;
 8409:             while ($subcount<$subquestion) {
 8410:                 $first += $subans[$subcount-1];
 8411:                 $subcount ++;
 8412:             }
 8413:             $count = $subans[$subquestion-1];
 8414:         } else {
 8415:             my $responsenum = $question-1;
 8416:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8417:                 $responsenum = $respnumlookup->{$question-1};
 8418:                 if (ref($startline) eq 'HASH') {
 8419:                     $first = $startline->{$question-1} + 1;
 8420:                 }
 8421:             } else {
 8422:                 $first = $first_bubble_line{$responsenum} + 1;
 8423:             }
 8424: 	    $count   = $bubble_lines_per_response{$responsenum};
 8425:         }
 8426:         $last = $first+$count-1;
 8427:         push(@lines, ($first..$last));
 8428:     }
 8429:     return join(',', @lines);
 8430: }
 8431: 
 8432: =pod 
 8433: 
 8434: =item prompt_for_corrections
 8435: 
 8436: Prompts for a potentially multiline correction to the
 8437: user's bubbling (factors out common code from scantron_get_correction
 8438: for multi and missing bubble cases).
 8439: 
 8440:  Arguments:
 8441:    $r           - Apache request object.
 8442:    $question    - The question number to prompt for.
 8443:    $scan_config - The scantron file configuration hash.
 8444:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8445:    $error       - Type of error
 8446:    $randomorder - True if randomorder in use.
 8447:    $randompick  - True if randompick in use.
 8448:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8449:                     for current line to question number used for same question
 8450:                     in "Master Seqence" (as seen by Course Coordinator).
 8451:    $startline   - Reference to hash where key is question number (0 is first)
 8452:                   and value is number of first bubble line for current student
 8453:                   or code-based randompick and/or randomorder.
 8454: 
 8455: 
 8456:  Implicit inputs:
 8457:    %bubble_lines_per_response   - Starting line numbers for each question.
 8458:                                   Numbered from 0 (but question numbers are from
 8459:                                   1.
 8460:    %first_bubble_line           - Starting bubble line for each question.
 8461:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8462:                                   type problems render as separate sub-questions, 
 8463:                                   in exam mode. This hash contains a 
 8464:                                   comma-separated list of the lines per 
 8465:                                   sub-question.
 8466:    %responsetype_per_response   - essayresponse, formularesponse,
 8467:                                   stringresponse, imageresponse, reactionresponse,
 8468:                                   and organicresponse type problem parts can have
 8469:                                   multiple lines per response if the weight
 8470:                                   assigned exceeds 10.  In this case, only
 8471:                                   one bubble per line is permitted, but more 
 8472:                                   than one line might contain bubbles, e.g.
 8473:                                   bubbling of: line 1 - J, line 2 - J, 
 8474:                                   line 3 - B would assign 22 points.  
 8475: 
 8476: =cut
 8477: 
 8478: sub prompt_for_corrections {
 8479:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8480:         $randompick, $respnumlookup, $startline) = @_;
 8481:     my ($current_line,$lines);
 8482:     my @linenums;
 8483:     my $questionnum = $question;
 8484:     my ($first,$responsenum);
 8485:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8486:         $question = $1;
 8487:         my $subquestion = $2;
 8488:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8489:             $responsenum = $respnumlookup->{$question-1};
 8490:             if (ref($startline) eq 'HASH') {
 8491:                 $first = $startline->{$question-1};
 8492:             }
 8493:         } else {
 8494:             $responsenum = $question-1;
 8495:             $first = $first_bubble_line{$responsenum};
 8496:         }
 8497:         $current_line = $first + 1 ;
 8498:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8499:         my $subcount = 1;
 8500:         while ($subcount<$subquestion) {
 8501:             $current_line += $subans[$subcount-1];
 8502:             $subcount ++;
 8503:         }
 8504:         $lines = $subans[$subquestion-1];
 8505:     } else {
 8506:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8507:             $responsenum = $respnumlookup->{$question-1};
 8508:             if (ref($startline) eq 'HASH') { 
 8509:                 $first = $startline->{$question-1};
 8510:             }
 8511:         } else {
 8512:             $responsenum = $question-1;
 8513:             $first = $first_bubble_line{$responsenum};
 8514:         }
 8515:         $current_line = $first + 1;
 8516:         $lines        = $bubble_lines_per_response{$responsenum};
 8517:     }
 8518:     if ($lines > 1) {
 8519:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8520:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8521:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8522:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8523:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8524:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8525:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8526:             $r->print(
 8527:                 &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
 8528:                .'<br /><br />'
 8529:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8530:                .'<br />'
 8531:                .&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.')
 8532:                .'<br />'
 8533:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8534:                .'<br /><br />'
 8535:             );
 8536:         } else {
 8537:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8538:         }
 8539:     }
 8540:     for (my $i =0; $i < $lines; $i++) {
 8541:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8542: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8543: 	        		  $questionnum,$error,split('', $selected));
 8544:         push(@linenums,$current_line);
 8545: 	$current_line++;
 8546:     }
 8547:     if ($lines > 1) {
 8548: 	$r->print("<hr /><br />");
 8549:     }
 8550:     return @linenums;
 8551: }
 8552: 
 8553: =pod
 8554: 
 8555: =item scantron_bubble_selector
 8556:   
 8557:    Generates the html radiobuttons to correct a single bubble line
 8558:    possibly showing the existing the selected bubbles if known
 8559: 
 8560:  Arguments:
 8561:     $r           - Apache request object
 8562:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8563:     $line        - Number of the line being displayed.
 8564:     $questionnum - Question number (may include subquestion)
 8565:     $error       - Type of error.
 8566:     @selected    - Array of bubbles picked on this line.
 8567: 
 8568: =cut
 8569: 
 8570: sub scantron_bubble_selector {
 8571:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8572:     my $max=$$scan_config{'Qlength'};
 8573: 
 8574:     my $scmode=$$scan_config{'Qon'};
 8575:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8576:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8577:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8578:             $max=$$scan_config{'BubblesPerRow'};
 8579:             if (($scmode eq 'number') && ($max > 10)) {
 8580:                 $max = 10;
 8581:             } elsif (($scmode eq 'letter') && $max > 26) {
 8582:                 $max = 26;
 8583:             }
 8584:         } else {
 8585:             $max = 10;
 8586:         }
 8587:     }
 8588: 
 8589:     my @alphabet=('A'..'Z');
 8590:     $r->print(&Apache::loncommon::start_data_table().
 8591:               &Apache::loncommon::start_data_table_row());
 8592:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8593:     for (my $i=0;$i<$max+1;$i++) {
 8594: 	$r->print("\n".'<td align="center">');
 8595: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8596: 	else { $r->print('&nbsp;'); }
 8597: 	$r->print('</td>');
 8598:     }
 8599:     $r->print(&Apache::loncommon::end_data_table_row().
 8600:               &Apache::loncommon::start_data_table_row());
 8601:     for (my $i=0;$i<$max;$i++) {
 8602: 	$r->print("\n".
 8603: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8604: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8605:     }
 8606:     my $nobub_checked = ' ';
 8607:     if ($error eq 'missingbubble') {
 8608:         $nobub_checked = ' checked = "checked" ';
 8609:     }
 8610:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8611: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8612:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8613:               $line.'" value="'.$questionnum.'" /></td>');
 8614:     $r->print(&Apache::loncommon::end_data_table_row().
 8615:               &Apache::loncommon::end_data_table());
 8616: }
 8617: 
 8618: =pod
 8619: 
 8620: =item num_matches
 8621: 
 8622:    Counts the number of characters that are the same between the two arguments.
 8623: 
 8624:  Arguments:
 8625:    $orig - CODE from the scanline
 8626:    $code - CODE to match against
 8627: 
 8628:  Returns:
 8629:    $count - integer count of the number of same characters between the
 8630:             two arguments
 8631: 
 8632: =cut
 8633: 
 8634: sub num_matches {
 8635:     my ($orig,$code) = @_;
 8636:     my @code=split(//,$code);
 8637:     my @orig=split(//,$orig);
 8638:     my $same=0;
 8639:     for (my $i=0;$i<scalar(@code);$i++) {
 8640: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8641:     }
 8642:     return $same;
 8643: }
 8644: 
 8645: =pod
 8646: 
 8647: =item scantron_get_closely_matching_CODEs
 8648: 
 8649:    Cycles through all CODEs and finds the set that has the greatest
 8650:    number of same characters as the provided CODE
 8651: 
 8652:  Arguments:
 8653:    $allcodes - hash ref returned by &get_codes()
 8654:    $CODE     - CODE from the current scanline
 8655: 
 8656:  Returns:
 8657:    2 element list
 8658:     - first elements is number of how closely matching the best fit is 
 8659:       (5 means best set has 5 matching characters)
 8660:     - second element is an arrary ref containing the set of valid CODEs
 8661:       that best fit the passed in CODE
 8662: 
 8663: =cut
 8664: 
 8665: sub scantron_get_closely_matching_CODEs {
 8666:     my ($allcodes,$CODE)=@_;
 8667:     my @CODEs;
 8668:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8669: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8670:     }
 8671: 
 8672:     return ($#CODEs,$CODEs[-1]);
 8673: }
 8674: 
 8675: =pod
 8676: 
 8677: =item get_codes
 8678: 
 8679:    Builds a hash which has keys of all of the valid CODEs from the selected
 8680:    set of remembered CODEs.
 8681: 
 8682:  Arguments:
 8683:   $old_name - name of the set of remembered CODEs
 8684:   $cdom     - domain of the course
 8685:   $cnum     - internal course name
 8686: 
 8687:  Returns:
 8688:   %allcodes - keys are the valid CODEs, values are all 1
 8689: 
 8690: =cut
 8691: 
 8692: sub get_codes {
 8693:     my ($old_name, $cdom, $cnum) = @_;
 8694:     if (!$old_name) {
 8695: 	$old_name=$env{'form.scantron_CODElist'};
 8696:     }
 8697:     if (!$cdom) {
 8698: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8699:     }
 8700:     if (!$cnum) {
 8701: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8702:     }
 8703:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8704: 				    $cdom,$cnum);
 8705:     my %allcodes;
 8706:     if ($result{"type\0$old_name"} eq 'number') {
 8707: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8708:     } else {
 8709: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8710:     }
 8711:     return %allcodes;
 8712: }
 8713: 
 8714: =pod
 8715: 
 8716: =item scantron_validate_CODE
 8717: 
 8718:    Validates all scanlines in the selected file to not have any
 8719:    invalid or underspecified CODEs and that none of the codes are
 8720:    duplicated if this was requested.
 8721: 
 8722: =cut
 8723: 
 8724: sub scantron_validate_CODE {
 8725:     my ($r,$currentphase) = @_;
 8726:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8727:     if ($scantron_config{'CODElocation'} &&
 8728: 	$scantron_config{'CODEstart'} &&
 8729: 	$scantron_config{'CODElength'}) {
 8730: 	if (!defined($env{'form.scantron_CODElist'})) {
 8731: 	    &FIXME_blow_up()
 8732: 	}
 8733:     } else {
 8734: 	return (0,$currentphase+1);
 8735:     }
 8736:     
 8737:     my %usedCODEs;
 8738: 
 8739:     my %allcodes=&get_codes();
 8740: 
 8741:     my $nav_error;
 8742:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8743:     if ($nav_error) {
 8744:         $r->print(&navmap_errormsg());
 8745:         return(1,$currentphase);
 8746:     }
 8747: 
 8748:     my ($scanlines,$scan_data)=&scantron_getfile();
 8749:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8750: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8751: 	if ($line=~/^[\s\cz]*$/) { next; }
 8752: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8753: 						 $scan_data);
 8754: 	my $CODE=$$scan_record{'scantron.CODE'};
 8755: 	my $error=0;
 8756: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8757: 	    &scantron_get_correction($r,$i,$scan_record,
 8758: 				     \%scantron_config,
 8759: 				     $line,'incorrectCODE',\%allcodes);
 8760: 	    return(1,$currentphase);
 8761: 	}
 8762: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8763: 	    && !$$scan_record{'scantron.useCODE'}) {
 8764: 	    &scantron_get_correction($r,$i,$scan_record,
 8765: 				     \%scantron_config,
 8766: 				     $line,'incorrectCODE',\%allcodes);
 8767: 	    return(1,$currentphase);
 8768: 	}
 8769: 	if (exists($usedCODEs{$CODE}) 
 8770: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8771: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8772: 	    &scantron_get_correction($r,$i,$scan_record,
 8773: 				     \%scantron_config,
 8774: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8775: 	    return(1,$currentphase);
 8776: 	}
 8777: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8778:     }
 8779:     return (0,$currentphase+1);
 8780: }
 8781: 
 8782: =pod
 8783: 
 8784: =item scantron_validate_doublebubble
 8785: 
 8786:    Validates all scanlines in the selected file to not have any
 8787:    bubble lines with multiple bubbles marked.
 8788: 
 8789: =cut
 8790: 
 8791: sub scantron_validate_doublebubble {
 8792:     my ($r,$currentphase) = @_;
 8793:     #get student info
 8794:     my $classlist=&Apache::loncoursedata::get_classlist();
 8795:     my %idmap=&username_to_idmap($classlist);
 8796:     my (undef,undef,$sequence)=
 8797:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8798: 
 8799:     #get scantron line setup
 8800:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8801:     my ($scanlines,$scan_data)=&scantron_getfile();
 8802: 
 8803:     my $navmap = Apache::lonnavmaps::navmap->new();
 8804:     unless (ref($navmap)) {
 8805:         $r->print(&navmap_errormsg());
 8806:         return(1,$currentphase);
 8807:     }
 8808:     my $map=$navmap->getResourceByUrl($sequence);
 8809:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8810:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8811:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8812:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8813: 
 8814:     my $nav_error;
 8815:     if (ref($map)) {
 8816:         $randomorder = $map->randomorder();
 8817:         $randompick = $map->randompick();
 8818:         unless ($randomorder || $randompick) {
 8819:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8820:                 if ($res->randomorder()) {
 8821:                     $randomorder = 1;
 8822:                 }
 8823:                 if ($res->randompick()) {
 8824:                     $randompick = 1;
 8825:                 }
 8826:                 last if ($randomorder || $randompick);
 8827:             }
 8828:         }
 8829:         if ($randomorder || $randompick) {
 8830:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8831:             if ($nav_error) {
 8832:                 $r->print(&navmap_errormsg());
 8833:                 return(1,$currentphase);
 8834:             }
 8835:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8836:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8837:         }
 8838:     } else {
 8839:         $r->print(&navmap_errormsg());
 8840:         return(1,$currentphase);
 8841:     }
 8842: 
 8843:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8844:     if ($nav_error) {
 8845:         $r->print(&navmap_errormsg());
 8846:         return(1,$currentphase);
 8847:     }
 8848: 
 8849:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8850: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8851: 	if ($line=~/^[\s\cz]*$/) { next; }
 8852: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8853: 						 $scan_data,undef,\%idmap,$randomorder,
 8854:                                                  $randompick,$sequence,\@master_seq,
 8855:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8856:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8857: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8858: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8859: 				 'doublebubble',
 8860: 				 $$scan_record{'scantron.doubleerror'},
 8861:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8862:     	return (1,$currentphase);
 8863:     }
 8864:     return (0,$currentphase+1);
 8865: }
 8866: 
 8867: 
 8868: sub scantron_get_maxbubble {
 8869:     my ($nav_error,$scantron_config) = @_;
 8870:     if (defined($env{'form.scantron_maxbubble'}) &&
 8871: 	$env{'form.scantron_maxbubble'}) {
 8872: 	&restore_bubble_lines();
 8873: 	return $env{'form.scantron_maxbubble'};
 8874:     }
 8875: 
 8876:     my (undef, undef, $sequence) =
 8877: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8878: 
 8879:     my $navmap=Apache::lonnavmaps::navmap->new();
 8880:     unless (ref($navmap)) {
 8881:         if (ref($nav_error)) {
 8882:             $$nav_error = 1;
 8883:         }
 8884:         return;
 8885:     }
 8886:     my $map=$navmap->getResourceByUrl($sequence);
 8887:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8888:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8889: 
 8890:     &Apache::lonxml::clear_problem_counter();
 8891: 
 8892:     my $uname       = $env{'user.name'};
 8893:     my $udom        = $env{'user.domain'};
 8894:     my $cid         = $env{'request.course.id'};
 8895:     my $total_lines = 0;
 8896:     %bubble_lines_per_response = ();
 8897:     %first_bubble_line         = ();
 8898:     %subdivided_bubble_lines   = ();
 8899:     %responsetype_per_response = ();
 8900:     %masterseq_id_responsenum  = ();
 8901: 
 8902:     my $response_number = 0;
 8903:     my $bubble_line     = 0;
 8904:     foreach my $resource (@resources) {
 8905:         my $resid = $resource->id(); 
 8906:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8907:                                                           $udom,undef,$bubbles_per_row);
 8908:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8909: 	    foreach my $part_id (@{$parts}) {
 8910:                 my $lines;
 8911: 
 8912: 	        # TODO - make this a persistent hash not an array.
 8913: 
 8914:                 # optionresponse, matchresponse and rankresponse type items 
 8915:                 # render as separate sub-questions in exam mode.
 8916:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8917:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8918:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8919:                     my ($numbub,$numshown);
 8920:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8921:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8922:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8923:                         }
 8924:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8925:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8926:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8927:                         }
 8928:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8929:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8930:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8931:                         }
 8932:                     }
 8933:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8934:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8935:                     }
 8936:                     my $bubbles_per_row =
 8937:                         &bubblesheet_bubbles_per_row($scantron_config);
 8938:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8939:                     if (($numbub % $bubbles_per_row) != 0) {
 8940:                         $inner_bubble_lines++;
 8941:                     }
 8942:                     for (my $i=0; $i<$numshown; $i++) {
 8943:                         $subdivided_bubble_lines{$response_number} .= 
 8944:                             $inner_bubble_lines.',';
 8945:                     }
 8946:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8947:                     $lines = $numshown * $inner_bubble_lines;
 8948:                 } else {
 8949:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8950:                 }
 8951: 
 8952:                 $first_bubble_line{$response_number} = $bubble_line;
 8953: 	        $bubble_lines_per_response{$response_number} = $lines;
 8954:                 $responsetype_per_response{$response_number} = 
 8955:                     $analysis->{$part_id.'.type'};
 8956:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8957: 	        $response_number++;
 8958: 
 8959: 	        $bubble_line +=  $lines;
 8960: 	        $total_lines +=  $lines;
 8961: 	    }
 8962:         }
 8963:     }
 8964:     &Apache::lonnet::delenv('scantron.');
 8965: 
 8966:     &save_bubble_lines();
 8967:     $env{'form.scantron_maxbubble'} =
 8968: 	$total_lines;
 8969:     return $env{'form.scantron_maxbubble'};
 8970: }
 8971: 
 8972: sub bubblesheet_bubbles_per_row {
 8973:     my ($scantron_config) = @_;
 8974:     my $bubbles_per_row;
 8975:     if (ref($scantron_config) eq 'HASH') {
 8976:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8977:     }
 8978:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8979:         $bubbles_per_row = 10;
 8980:     }
 8981:     return $bubbles_per_row;
 8982: }
 8983: 
 8984: sub scantron_validate_missingbubbles {
 8985:     my ($r,$currentphase) = @_;
 8986:     #get student info
 8987:     my $classlist=&Apache::loncoursedata::get_classlist();
 8988:     my %idmap=&username_to_idmap($classlist);
 8989:     my (undef,undef,$sequence)=
 8990:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8991: 
 8992:     #get scantron line setup
 8993:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8994:     my ($scanlines,$scan_data)=&scantron_getfile();
 8995: 
 8996:     my $navmap = Apache::lonnavmaps::navmap->new();
 8997:     unless (ref($navmap)) {
 8998:         $r->print(&navmap_errormsg());
 8999:         return(1,$currentphase);
 9000:     }
 9001: 
 9002:     my $map=$navmap->getResourceByUrl($sequence);
 9003:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9004:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9005:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 9006:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9007: 
 9008:     my $nav_error;
 9009:     if (ref($map)) {
 9010:         $randomorder = $map->randomorder();
 9011:         $randompick = $map->randompick();
 9012:         unless ($randomorder || $randompick) {
 9013:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 9014:                 if ($res->randomorder()) {
 9015:                     $randomorder = 1;
 9016:                 }
 9017:                 if ($res->randompick()) {
 9018:                     $randompick = 1;
 9019:                 }
 9020:                 last if ($randomorder || $randompick);
 9021:             }
 9022:         }
 9023:         if ($randomorder || $randompick) {
 9024:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9025:             if ($nav_error) {
 9026:                 $r->print(&navmap_errormsg());
 9027:                 return(1,$currentphase);
 9028:             }
 9029:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9030:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 9031:         }
 9032:     } else {
 9033:         $r->print(&navmap_errormsg());
 9034:         return(1,$currentphase);
 9035:     }
 9036: 
 9037: 
 9038:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 9039:     if ($nav_error) {
 9040:         $r->print(&navmap_errormsg());
 9041:         return(1,$currentphase);
 9042:     }
 9043: 
 9044:     if (!$max_bubble) { $max_bubble=2**31; }
 9045:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 9046: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9047: 	if ($line=~/^[\s\cz]*$/) { next; }
 9048: 	my $scan_record =
 9049:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 9050: 				     $randomorder,$randompick,$sequence,\@master_seq,
 9051:                                      \%symb_to_resource,\%grader_partids_by_symb,
 9052:                                      \%orderedforcode,\%respnumlookup,\%startline);
 9053: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 9054: 	my @to_correct;
 9055: 	
 9056: 	# Probably here's where the error is...
 9057: 
 9058: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 9059:             my $lastbubble;
 9060:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 9061:                my $question = $1;
 9062:                my $subquestion = $2;
 9063:                my ($first,$responsenum);
 9064:                if ($randomorder || $randompick) {
 9065:                    $responsenum = $respnumlookup{$question-1};
 9066:                    $first = $startline{$question-1};
 9067:                } else {
 9068:                    $responsenum = $question-1; 
 9069:                    $first = $first_bubble_line{$responsenum};
 9070:                }
 9071:                if (!defined($first)) { next; }
 9072:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 9073:                my $subcount = 1;
 9074:                while ($subcount<$subquestion) {
 9075:                    $first += $subans[$subcount-1];
 9076:                    $subcount ++;
 9077:                }
 9078:                my $count = $subans[$subquestion-1];
 9079:                $lastbubble = $first + $count;
 9080:             } else {
 9081:                my ($first,$responsenum);
 9082:                if ($randomorder || $randompick) {
 9083:                    $responsenum = $respnumlookup{$missing-1};
 9084:                    $first = $startline{$missing-1};
 9085:                } else {
 9086:                    $responsenum = $missing-1;
 9087:                    $first = $first_bubble_line{$responsenum};
 9088:                }
 9089:                if (!defined($first)) { next; }
 9090:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 9091:             }
 9092:             if ($lastbubble > $max_bubble) { next; }
 9093: 	    push(@to_correct,$missing);
 9094: 	}
 9095: 	if (@to_correct) {
 9096: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 9097: 				     $line,'missingbubble',\@to_correct,
 9098:                                      $randomorder,$randompick,\%respnumlookup,
 9099:                                      \%startline);
 9100: 	    return (1,$currentphase);
 9101: 	}
 9102: 
 9103:     }
 9104:     return (0,$currentphase+1);
 9105: }
 9106: 
 9107: sub hand_bubble_option {
 9108:     my (undef, undef, $sequence) =
 9109:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9110:     return if ($sequence eq '');
 9111:     my $navmap = Apache::lonnavmaps::navmap->new();
 9112:     unless (ref($navmap)) {
 9113:         return;
 9114:     }
 9115:     my $needs_hand_bubbles;
 9116:     my $map=$navmap->getResourceByUrl($sequence);
 9117:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9118:     foreach my $res (@resources) {
 9119:         if (ref($res)) {
 9120:             if ($res->is_problem()) {
 9121:                 my $partlist = $res->parts();
 9122:                 foreach my $part (@{ $partlist }) {
 9123:                     my @types = $res->responseType($part);
 9124:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 9125:                         $needs_hand_bubbles = 1;
 9126:                         last;
 9127:                     }
 9128:                 }
 9129:             }
 9130:         }
 9131:     }
 9132:     if ($needs_hand_bubbles) {
 9133:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9134:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9135:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 9136:                &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 />').
 9137:                '<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;'.
 9138:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 9139:     }
 9140:     return;
 9141: }
 9142: 
 9143: sub scantron_process_students {
 9144:     my ($r,$symb) = @_;
 9145: 
 9146:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 9147:     if (!$symb) {
 9148: 	return '';
 9149:     }
 9150:     my $default_form_data=&defaultFormData($symb);
 9151: 
 9152:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9153:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 9154:     my ($scanlines,$scan_data)=&scantron_getfile();
 9155:     my $classlist=&Apache::loncoursedata::get_classlist();
 9156:     my %idmap=&username_to_idmap($classlist);
 9157:     my $navmap=Apache::lonnavmaps::navmap->new();
 9158:     unless (ref($navmap)) {
 9159:         $r->print(&navmap_errormsg());
 9160:         return '';
 9161:     }
 9162:     my $map=$navmap->getResourceByUrl($sequence);
 9163:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9164:         %grader_randomlists_by_symb,%symb_for_examcode);
 9165:     if (ref($map)) {
 9166:         $randomorder = $map->randomorder();
 9167:         $randompick = $map->randompick();
 9168:         unless ($randomorder || $randompick) {
 9169:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 9170:                 if ($res->randomorder()) {
 9171:                     $randomorder = 1;
 9172:                 }
 9173:                 if ($res->randompick()) {
 9174:                     $randompick = 1;
 9175:                 }
 9176:                 last if ($randomorder || $randompick);
 9177:             }
 9178:         }
 9179:     } else {
 9180:         $r->print(&navmap_errormsg());
 9181:         return '';
 9182:     }
 9183:     my $nav_error;
 9184:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9185:     if ($randomorder || $randompick) {
 9186:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
 9187:         if ($nav_error) {
 9188:             $r->print(&navmap_errormsg());
 9189:             return '';
 9190:         }
 9191:     }
 9192:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9193:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9194: 
 9195:     my ($uname,$udom);
 9196:     my $result= <<SCANTRONFORM;
 9197: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 9198:   <input type="hidden" name="command" value="scantron_configphase" />
 9199:   $default_form_data
 9200: SCANTRONFORM
 9201:     $r->print($result);
 9202: 
 9203:     my ($checksec,@possibles)=&gradable_sections();
 9204:     my @delayqueue;
 9205:     my (%completedstudents,%scandata);
 9206: 
 9207:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9208:     my $count=&get_todo_count($scanlines,$scan_data);
 9209:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9210:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9211:     $r->print('<br />');
 9212:     my $start=&Time::HiRes::time();
 9213:     my $i=-1;
 9214:     my $started;
 9215: 
 9216:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9217:     if ($nav_error) {
 9218:         $r->print(&navmap_errormsg());
 9219:         return '';
 9220:     }
 9221: 
 9222:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9223:     # the user and return.
 9224: 
 9225:     if ($ssi_error) {
 9226: 	$r->print("</form>");
 9227: 	&ssi_print_error($r);
 9228:         &Apache::lonnet::remove_lock($lock);
 9229: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9230:     }
 9231: 
 9232:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9233:     my $numletts = scalar(keys(%lettdig));
 9234:     my %orderedforcode;
 9235: 
 9236:     while ($i<$scanlines->{'count'}) {
 9237:  	($uname,$udom)=('','');
 9238:  	$i++;
 9239:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9240:  	if ($line=~/^[\s\cz]*$/) { next; }
 9241: 	if ($started) {
 9242: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9243: 	}
 9244: 	$started=1;
 9245:         my %respnumlookup = ();
 9246:         my %startline = ();
 9247:         my $total;
 9248:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9249:                                                  $scan_data,undef,\%idmap,$randomorder,
 9250:                                                  $randompick,$sequence,\@master_seq,
 9251:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9252:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9253:                                                  \$total);
 9254:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9255:  					      \%idmap,$i)) {
 9256:   	    &scantron_add_delay(\@delayqueue,$line,
 9257:  				'Unable to find a student that matches',1);
 9258:  	    next;
 9259:   	}
 9260:  	if (exists $completedstudents{$uname}) {
 9261:  	    &scantron_add_delay(\@delayqueue,$line,
 9262:  				'Student '.$uname.' has multiple sheets',2);
 9263:  	    next;
 9264:  	}
 9265:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9266:         if (($checksec ne '') && ($checksec ne $usec)) {
 9267:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 9268:                 &scantron_add_delay(\@delayqueue,$line,
 9269:                                     "No role with manage grades privilege in student's section ($usec)",3);
 9270:                 next;
 9271:             }
 9272:         }
 9273:         my $user = $uname.':'.$usec;
 9274:   	($uname,$udom)=split(/:/,$uname);
 9275: 
 9276:         my $scancode;
 9277:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9278:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9279:             $scancode = $scan_record->{'scantron.CODE'};
 9280:         } else {
 9281:             $scancode = '';
 9282:         }
 9283: 
 9284:         my @mapresources = @resources;
 9285:         if ($randomorder || $randompick) {
 9286:             @mapresources = 
 9287:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9288:                              \%orderedforcode);
 9289:         }
 9290:         my (%partids_by_symb,$res_error);
 9291:         foreach my $resource (@mapresources) {
 9292:             my $ressymb;
 9293:             if (ref($resource)) {
 9294:                 $ressymb = $resource->symb();
 9295:             } else {
 9296:                 $res_error = 1;
 9297:                 last;
 9298:             }
 9299:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9300:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9301:                 my $currcode;
 9302:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9303:                     $currcode = $scancode;
 9304:                 }
 9305:                 my ($analysis,$parts) =
 9306:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9307:                                               $uname,$udom,undef,$bubbles_per_row,
 9308:                                               $currcode);
 9309:                 $partids_by_symb{$ressymb} = $parts;
 9310:             } else {
 9311:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9312:             }
 9313:         }
 9314: 
 9315:         if ($res_error) {
 9316:             &scantron_add_delay(\@delayqueue,$line,
 9317:                                 'An error occurred while grading student '.$uname,2);
 9318:             next;
 9319:         }
 9320: 
 9321: 	&Apache::lonxml::clear_problem_counter();
 9322:   	&Apache::lonnet::appenv($scan_record);
 9323: 
 9324: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9325: 	    &scantron_putfile($scanlines,$scan_data);
 9326: 	}
 9327: 	
 9328:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9329:                                    \@mapresources,\%partids_by_symb,
 9330:                                    $bubbles_per_row,$randomorder,$randompick,
 9331:                                    \%respnumlookup,\%startline) 
 9332:             eq 'ssi_error') {
 9333:             $ssi_error = 0; # So end of handler error message does not trigger.
 9334:             $r->print("</form>");
 9335:             &ssi_print_error($r);
 9336:             &Apache::lonnet::remove_lock($lock);
 9337:             return '';      # Why return ''?  Beats me.
 9338:         }
 9339: 
 9340:         if (($scancode) && ($randomorder || $randompick)) {
 9341:             foreach my $key (keys(%symb_for_examcode)) {
 9342:                 my $symb_in_map = $symb_for_examcode{$key};
 9343:                 if ($symb_in_map ne '') {
 9344:                     my $parmresult =
 9345:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
 9346:                                                                '0_examcode',2,$scancode,
 9347:                                                                'string_examcode',$uname,
 9348:                                                                $udom);
 9349:                 }
 9350:             }
 9351:         }
 9352: 	$completedstudents{$uname}={'line'=>$line};
 9353:         if ($env{'form.verifyrecord'}) {
 9354:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9355:             if ($randompick) {
 9356:                 if ($total) {
 9357:                     $lastpos = $total*$scantron_config{'Qlength'};
 9358:                 }
 9359:             }
 9360: 
 9361:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9362:             chomp($studentdata);
 9363:             $studentdata =~ s/\r$//;
 9364:             my $studentrecord = '';
 9365:             my $counter = -1;
 9366:             foreach my $resource (@mapresources) {
 9367:                 my $ressymb = $resource->symb();
 9368:                 ($counter,my $recording) =
 9369:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9370:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9371:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9372:                                              $randompick,\%respnumlookup,\%startline);
 9373:                 $studentrecord .= $recording;
 9374:             }
 9375:             if ($studentrecord ne $studentdata) {
 9376:                 &Apache::lonxml::clear_problem_counter();
 9377:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9378:                                            \@mapresources,\%partids_by_symb,
 9379:                                            $bubbles_per_row,$randomorder,$randompick,
 9380:                                            \%respnumlookup,\%startline) 
 9381:                     eq 'ssi_error') {
 9382:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9383:                     $r->print("</form>");
 9384:                     &ssi_print_error($r);
 9385:                     &Apache::lonnet::remove_lock($lock);
 9386:                     delete($completedstudents{$uname});
 9387:                     return '';
 9388:                 }
 9389:                 $counter = -1;
 9390:                 $studentrecord = '';
 9391:                 foreach my $resource (@mapresources) {
 9392:                     my $ressymb = $resource->symb();
 9393:                     ($counter,my $recording) =
 9394:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9395:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9396:                                                  \%scantron_config,\%lettdig,$numletts,
 9397:                                                  $randomorder,$randompick,\%respnumlookup,
 9398:                                                  \%startline);
 9399:                     $studentrecord .= $recording;
 9400:                 }
 9401:                 if ($studentrecord ne $studentdata) {
 9402:                     $r->print('<p><span class="LC_warning">');
 9403:                     if ($scancode eq '') {
 9404:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9405:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9406:                     } else {
 9407:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9408:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9409:                     }
 9410:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9411:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9412:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9413:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9414:                               &Apache::loncommon::start_data_table_row().
 9415:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9416:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9417:                               &Apache::loncommon::end_data_table_row().
 9418:                               &Apache::loncommon::start_data_table_row().
 9419:                               '<td>'.&mt('Stored submissions').'</td>'.
 9420:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9421:                               &Apache::loncommon::end_data_table_row().
 9422:                               &Apache::loncommon::end_data_table().'</p>');
 9423:                 } else {
 9424:                     $r->print('<br /><span class="LC_warning">'.
 9425:                              &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 />'.
 9426:                              &mt("As a consequence, this user's submission history records two tries.").
 9427:                                  '</span><br />');
 9428:                 }
 9429:             }
 9430:         }
 9431:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9432:     } continue {
 9433: 	&Apache::lonxml::clear_problem_counter();
 9434: 	&Apache::lonnet::delenv('scantron.');
 9435:     }
 9436:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9437:     &Apache::lonnet::remove_lock($lock);
 9438: #    my $lasttime = &Time::HiRes::time()-$start;
 9439: #    $r->print("<p>took $lasttime</p>");
 9440: 
 9441:     $r->print("</form>");
 9442:     return '';
 9443: }
 9444: 
 9445: sub graders_resources_pass {
 9446:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9447:         $bubbles_per_row) = @_;
 9448:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9449:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9450:         foreach my $resource (@{$resources}) {
 9451:             my $ressymb = $resource->symb();
 9452:             my ($analysis,$parts) =
 9453:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9454:                                           $env{'user.name'},$env{'user.domain'},
 9455:                                           1,$bubbles_per_row);
 9456:             $grader_partids_by_symb->{$ressymb} = $parts;
 9457:             if (ref($analysis) eq 'HASH') {
 9458:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9459:                     $grader_randomlists_by_symb->{$ressymb} =
 9460:                         $analysis->{'parts_withrandomlist'};
 9461:                 }
 9462:             }
 9463:         }
 9464:     }
 9465:     return;
 9466: }
 9467: 
 9468: =pod
 9469: 
 9470: =item users_order
 9471: 
 9472:   Returns array of resources in current map, ordered based on either CODE,
 9473:   if this is a CODEd exam, or based on student's identity if this is a 
 9474:   "NAMEd" exam.
 9475: 
 9476:   Should be used when randomorder and/or randompick applied when the 
 9477:   corresponding exam was printed, prior to students completing bubblesheets 
 9478:   for the version of the exam the student received.
 9479: 
 9480: =cut
 9481: 
 9482: sub users_order  {
 9483:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9484:     my @mapresources;
 9485:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9486:         return @mapresources;
 9487:     }
 9488:     if ($scancode) {
 9489:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9490:             @mapresources = @{$orderedforcode->{$scancode}};
 9491:         } else {
 9492:             $env{'form.CODE'} = $scancode;
 9493:             my $actual_seq =
 9494:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9495:                                                                $master_seq,
 9496:                                                                $user,$scancode,1);
 9497:             if (ref($actual_seq) eq 'ARRAY') {
 9498:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9499:                 if (ref($orderedforcode) eq 'HASH') {
 9500:                     if (@mapresources > 0) { 
 9501:                         $orderedforcode->{$scancode} = \@mapresources;
 9502:                     }
 9503:                 }
 9504:             }
 9505:             delete($env{'form.CODE'});
 9506:         }
 9507:     } else {
 9508:         my $actual_seq =
 9509:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9510:                                                            $master_seq,
 9511:                                                            $user,undef,1);
 9512:         if (ref($actual_seq) eq 'ARRAY') {
 9513:             @mapresources = 
 9514:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9515:         }
 9516:     }
 9517:     return @mapresources;
 9518: }
 9519: 
 9520: sub grade_student_bubbles {
 9521:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9522:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9523:     my $uselookup = 0;
 9524:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9525:         (ref($startline) eq 'HASH')) {
 9526:         $uselookup = 1;
 9527:     }
 9528: 
 9529:     if (ref($resources) eq 'ARRAY') {
 9530:         my $count = 0;
 9531:         foreach my $resource (@{$resources}) {
 9532:             my $ressymb = $resource->symb();
 9533:             my %form = ('submitted'      => 'scantron',
 9534:                         'grade_target'   => 'grade',
 9535:                         'grade_username' => $uname,
 9536:                         'grade_domain'   => $udom,
 9537:                         'grade_courseid' => $env{'request.course.id'},
 9538:                         'grade_symb'     => $ressymb,
 9539:                         'CODE'           => $scancode
 9540:                        );
 9541:             if ($bubbles_per_row ne '') {
 9542:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9543:             }
 9544:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9545:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9546:             }
 9547:             if (ref($parts) eq 'HASH') {
 9548:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9549:                     foreach my $part (@{$parts->{$ressymb}}) {
 9550:                         if ($uselookup) {
 9551:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9552:                         } else {
 9553:                             $form{'scantron_questnum_start.'.$part} =
 9554:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9555:                         }
 9556:                         $count++;
 9557:                     }
 9558:                 }
 9559:             }
 9560:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9561:             return 'ssi_error' if ($ssi_error);
 9562:             last if (&Apache::loncommon::connection_aborted($r));
 9563:         }
 9564:     }
 9565:     return;
 9566: }
 9567: 
 9568: sub scantron_upload_scantron_data {
 9569:     my ($r,$symb) = @_;
 9570:     my $dom = $env{'request.role.domain'};
 9571:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9572:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9573:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9574:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9575: 							  'domainid',
 9576: 							  'coursename',$dom);
 9577:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9578:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9579:     my $default_form_data=&defaultFormData($symb);
 9580:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9581:     &js_escape(\$nofile_alert);
 9582:     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.");
 9583:     &js_escape(\$nocourseid_alert);
 9584:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9585:     function checkUpload(formname) {
 9586: 	if (formname.upfile.value == "") {
 9587: 	    alert("'.$nofile_alert.'");
 9588: 	    return false;
 9589: 	}
 9590:         if (formname.courseid.value == "") {
 9591:             alert("'.$nocourseid_alert.'");
 9592:             return false;
 9593:         }
 9594: 	formname.submit();
 9595:     }
 9596: 
 9597:     function ToSyllabus() {
 9598:         var cdom = '."'$dom'".';
 9599:         var cnum = document.rules.courseid.value;
 9600:         if (cdom == "" || cdom == null) {
 9601:             return;
 9602:         }
 9603:         if (cnum == "" || cnum == null) {
 9604:            return;
 9605:         }
 9606:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9607:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9608:         return;
 9609:     }
 9610: 
 9611:     '.$formatjs.'
 9612: '));
 9613:     $r->print('
 9614: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9615: 
 9616: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9617: '.$default_form_data.
 9618:   &Apache::lonhtmlcommon::start_pick_box().
 9619:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9620:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9621:   &Apache::lonhtmlcommon::row_closure().
 9622:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9623:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9624:   &Apache::lonhtmlcommon::row_closure().
 9625:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9626:   '<input name="domainid" type="hidden" />'.$domdesc.
 9627:   &Apache::lonhtmlcommon::row_closure());
 9628:     if ($formatoptions) {
 9629:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9630:                   &Apache::lonhtmlcommon::row_closure());
 9631:     }
 9632:     $r->print(
 9633:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9634:   '<input type="file" name="upfile" size="50" />'.
 9635:   &Apache::lonhtmlcommon::row_closure(1).
 9636:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9637: 
 9638: <input name="command" value="scantronupload_save" type="hidden" />
 9639: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9640: </form>
 9641: ');
 9642:     return '';
 9643: }
 9644: 
 9645: sub scantron_upload_dataformat {
 9646:     my ($dom) = @_;
 9647:     my ($formatoptions,$formattitle,$formatjs);
 9648:     $formatjs = <<'END';
 9649: function toggleScantab(form) {
 9650:    return;
 9651: }
 9652: END
 9653:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9654:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9655:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9656:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9657:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9658:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9659:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9660:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9661:                             my ($onclick,$formatextra,$singleline);
 9662:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9663:                             my $count = 0;
 9664:                             foreach my $line (@lines) {
 9665:                                 next if (($line =~ /^\#/) || ($line eq ''));
 9666:                                 $singleline = $line;
 9667:                                 $count ++;
 9668:                             }
 9669:                             if ($count > 1) {
 9670:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9671:                                                '<span class="LC_nobreak">'.
 9672:                                                &mt('Bubblesheet type').':&nbsp;'.
 9673:                                                &scantron_scantab().'</span></div>';
 9674:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9675:                                 $formatjs = <<"END";
 9676: function toggleScantab(form) {
 9677:     var divid = 'bubbletype';
 9678:     if (document.getElementById(divid)) {
 9679:         var radioname = 'fileformat';
 9680:         var num = form.elements[radioname].length;
 9681:         if (num) {
 9682:             for (var i=0; i<num; i++) {
 9683:                 if (form.elements[radioname][i].checked) {
 9684:                     var chosen = form.elements[radioname][i].value;
 9685:                     if (chosen == 'dat') {
 9686:                         document.getElementById(divid).style.display = 'none';
 9687:                     } else if (chosen == 'csv') {
 9688:                         document.getElementById(divid).style.display = 'block';
 9689:                     }
 9690:                 }
 9691:             }
 9692:         }
 9693:     }
 9694:     return;
 9695: }
 9696: 
 9697: END
 9698:                             } elsif ($count == 1) {
 9699:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9700:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9701:                             }
 9702:                             $formattitle = &mt('File format');
 9703:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9704:                                              &mt('Plain Text (no delimiters)').
 9705:                                              '</label>'.('&nbsp;'x2).
 9706:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9707:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9708:                         }
 9709:                     }
 9710:                 }
 9711:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9712:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9713:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9714:                         $formattitle = &mt('Bubblesheet type');
 9715:                         $formatoptions = &scantron_scantab();
 9716:                     }
 9717:                 }
 9718:             }
 9719:         }
 9720:     }
 9721:     return ($formatoptions,$formattitle,$formatjs);
 9722: }
 9723: 
 9724: sub scantron_upload_scantron_data_save {
 9725:     my ($r,$symb) = @_;
 9726:     my $doanotherupload=
 9727: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9728: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9729: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9730: 	'</form>'."\n";
 9731:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9732: 	!&Apache::lonnet::allowed('usc',
 9733: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9734:         !&Apache::lonnet::allowed('usc',
 9735:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9736: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9737: 	unless ($symb) {
 9738: 	    $r->print($doanotherupload);
 9739: 	}
 9740: 	return '';
 9741:     }
 9742:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9743:     my $uploadedfile;
 9744:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9745:     if (length($env{'form.upfile'}) < 2) {
 9746:         $r->print(
 9747:             &Apache::lonhtmlcommon::confirm_success(
 9748:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9749:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9750:     } else {
 9751:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9752:         my $parser;
 9753:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9754:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9755:                 my $is_csv;
 9756:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9757:                 if (@possibles > 1) {
 9758:                     if ($env{'form.fileformat'} eq 'csv') {
 9759:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9760:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9761:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9762:                                     $is_csv = 1;
 9763:                                 }
 9764:                             }
 9765:                         }
 9766:                     }
 9767:                 } elsif (@possibles == 1) {
 9768:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9769:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9770:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9771:                                 $is_csv = 1;
 9772:                             }
 9773:                         }
 9774:                     }
 9775:                 }
 9776:                 if ($is_csv) {
 9777:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9778:                 }
 9779:             }
 9780:         }
 9781:         my $result =
 9782:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9783:                                             $env{'form.courseid'},$env{'form.domainid'});
 9784:         if ($result =~ m{^/uploaded/}) {
 9785:             $r->print(
 9786:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9787:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9788:                         (length($env{'form.upfile'})-1),
 9789:                         '<span class="LC_filename">'.$result.'</span>'));
 9790:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9791:             if ($uploadedfile =~ /^scantron_orig_/) {
 9792:                 my $logname = $uploadedfile;
 9793:                 $logname =~ s/^scantron_orig_//;
 9794:                 if ($logname ne '') {
 9795:                     my $now = time;
 9796:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9797:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9798:                 }
 9799:             }
 9800:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9801:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9802:         } else {
 9803:             $r->print(
 9804:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9805:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9806:                           $result,
 9807: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9808: 	}
 9809:     }
 9810:     if ($symb) {
 9811: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9812:     } else {
 9813: 	$r->print($doanotherupload);
 9814:     }
 9815:     return '';
 9816: }
 9817: 
 9818: sub validate_uploaded_scantron_file {
 9819:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9820: 
 9821:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9822:     my @lines;
 9823:     if ($scanlines ne '-1') {
 9824:         @lines=split("\n",$scanlines,-1);
 9825:     }
 9826:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9827:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9828:     if ($context eq 'download') {
 9829:         $priv = 'mgr';
 9830:     } else {
 9831:         $priv = 'usc';
 9832:     }
 9833:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9834:             (($env{'request.course.id'}) &&
 9835:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9836:         if ($env{'request.course.sec'} ne '') {
 9837:             unless (&Apache::lonnet::allowed($priv,
 9838:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9839:                 unless ($context eq 'download') {
 9840:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9841:                 }
 9842:                 return $output;
 9843:             }
 9844:             ($checksec,@possibles)=&gradable_sections();
 9845:         }
 9846:     }
 9847:     if (@lines) {
 9848:         my (%counts,$max_match_format);
 9849:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9850:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9851:         my %idmap = &username_to_idmap($classlist);
 9852:         foreach my $key (keys(%idmap)) {
 9853:             my $lckey = lc($key);
 9854:             $idmap{$lckey} = $idmap{$key};
 9855:         }
 9856:         my %unique_formats;
 9857:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9858:         foreach my $line (@formatlines) {
 9859:             next if (($line =~ /^\#/) || ($line eq ''));
 9860:             my @config = split(/:/,$line);
 9861:             my $idstart = $config[5];
 9862:             my $idlength = $config[6];
 9863:             if (($idstart ne '') && ($idlength > 0)) {
 9864:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9865:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9866:                 } else {
 9867:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9868:                 }
 9869:             }
 9870:         }
 9871:         foreach my $key (keys(%unique_formats)) {
 9872:             my ($idstart,$idlength) = split(':',$key);
 9873:             %{$counts{$key}} = (
 9874:                                'found'   => 0,
 9875:                                'total'   => 0,
 9876:                                'totalanysec' => 0,
 9877:                                'othersec' => 0,
 9878:                               );
 9879:             foreach my $line (@lines) {
 9880:                 next if ($line =~ /^#/);
 9881:                 next if ($line =~ /^[\s\cz]*$/);
 9882:                 my $id = substr($line,$idstart-1,$idlength);
 9883:                 $id = lc($id);
 9884:                 if (exists($idmap{$id})) {
 9885:                     if ($checksec ne '') {
 9886:                         $counts{$key}{'totalanysec'} ++;
 9887:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9888:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9889:                             if ($stusec ne $checksec) {
 9890:                                 if (@possibles) {
 9891:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9892:                                         $counts{$key}{'othersec'} ++;
 9893:                                         next;
 9894:                                     }
 9895:                                 } else {
 9896:                                     $counts{$key}{'othersec'} ++;
 9897:                                     next;
 9898:                                 }
 9899:                             }
 9900:                         }
 9901:                     }
 9902:                     $counts{$key}{'found'} ++;
 9903:                 }
 9904:                 $counts{$key}{'total'} ++;
 9905:             }
 9906:             if ($counts{$key}{'total'}) {
 9907:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9908:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9909:                     $max_match_pct = $percent_match;
 9910:                     $max_match_format = $key;
 9911:                     $found_match_count = $counts{$key}{'found'};
 9912:                     $max_match_count = $counts{$key}{'total'};
 9913:                 }
 9914:             }
 9915:         }
 9916:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9917:             my $format_descs;
 9918:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9919:             for (my $i=0; $i<$numwithformat; $i++) {
 9920:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9921:                 if ($i<$numwithformat-2) {
 9922:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9923:                 } elsif ($i==$numwithformat-2) {
 9924:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9925:                 } elsif ($i==$numwithformat-1) {
 9926:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9927:                 }
 9928:             }
 9929:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9930:             $output .= '<br />';
 9931:             if ($found_match_count == $max_match_count) {
 9932:                 # 100% matching entries
 9933:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9934:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9935:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9936:                 &mt('Comparison of student IDs in the uploaded file with'.
 9937:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9938:                     ' in the file (for the format defined for [_3]).',
 9939:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9940:             } else {
 9941:                 # Not all entries matching? -> Show warning and additional info
 9942:                 $output .=
 9943:                     &Apache::lonhtmlcommon::confirm_success(
 9944:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9945:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9946:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9947:                     &mt('Comparison of student IDs in the uploaded file with'.
 9948:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9949:                         ' in the file (for the format defined for [_3]).',
 9950:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9951:                     '<p class="LC_info">'.
 9952:                     &mt('A low percentage of matches results from one of the following:').
 9953:                     '</p><ul>'.
 9954:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9955:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9956:                                '<i>'.$cdom.'</i>').'</li>'.
 9957:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9958:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9959:                     '</ul>';
 9960:             }
 9961:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9962:                 if ($counts{$max_match_format}{'othersec'}) {
 9963:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9964:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9965:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9966:                     &js_escape(\$confirmdel);
 9967:                     $output .= '<p class="LC_warning">'.
 9968:                                &mt('Comparison of student IDs in the uploaded file with the course roster found [_1][quant,_2,match,matches][_3] for students in section(s) for which none of your role(s) have privileges to modify grades',
 9969:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9970:                                '<br />'.
 9971:                                &mt('Unless you are assigned role(s) which allow modification of grades in additional sections, [_1] of the records in this file will be automatically excluded when you perform bubblesheet grading.','<b>'.$showpct.'</b>').
 9972:                                '</p><p>'.
 9973:                                &mt('If you prefer to delete the file now, use: [_1]').
 9974:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9975:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9976:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9977:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9978:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9979:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9980:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9981:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9982:                                '</form></p>';
 9983:                 }
 9984:             }
 9985:         }
 9986:         if (($context eq 'download') && ($checksec ne '')) {
 9987:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9988:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9989:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9990:             }
 9991:         } 
 9992:     } elsif ($context ne 'download') {
 9993:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9994:     }
 9995:     return $output;
 9996: }
 9997: 
 9998: sub gradable_sections {
 9999:     my $checksec = $env{'request.course.sec'};
10000:     my @oksecs;
10001:     if ($checksec) {
10002:         my %availablesecs = &sections_grade_privs();
10003:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
10004:             foreach my $sec (@{$availablesecs{'mgr'}}) {
10005:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
10006:                     push(@oksecs,$sec);
10007:                 }
10008:             }
10009:             if (grep(/^all$/,@oksecs)) {
10010:                 undef($checksec);
10011:             }
10012:         }
10013:     }
10014:     return($checksec,@oksecs);
10015: }
10016: 
10017: sub sections_grade_privs {
10018:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10019:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10020:     my %availablesecs = (
10021:                           mgr => [],
10022:                           vgr => [],
10023:                           usc => [],
10024:                         );
10025:     my $ccrole = 'cc';
10026:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
10027:         $ccrole = 'co';
10028:     }
10029:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
10030:                                                      'userroles',['active'],
10031:                                                      [$ccrole,'in','cr'],$cdom,1);
10032:     my $crsid = $cnum.':'.$cdom;
10033:     foreach my $item (keys(%crsroleshash)) {
10034:         next unless ($item =~ /^$crsid\:/);
10035:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
10036:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
10037:         if ($sec ne '') {
10038:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
10039:         }
10040:         if (($role eq $ccrole) || ($role eq 'in')) {
10041:             foreach my $priv ('mgr','vgr','usc') { 
10042:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
10043:                     if ($sec eq '') {
10044:                         $availablesecs{$priv} = ['all'];
10045:                     } elsif ($sec ne $env{'request.course.sec'}) {
10046:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
10047:                             push(@{$availablesecs{$priv}},$sec);
10048:                         }
10049:                     }
10050:                 }
10051:             }
10052:         } elsif ($role =~ m{^cr/}) {
10053:             foreach my $priv ('mgr','vgr','usc') {
10054:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
10055:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
10056:                         if ($sec eq '') {
10057:                             $availablesecs{$priv} = ['all'];
10058:                         } elsif ($sec ne $env{'request.course.sec'}) {
10059:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
10060:                                 push(@{$availablesecs{$priv}},$sec);
10061:                             }
10062:                         }
10063:                     }
10064:                 }
10065:             }
10066:         }
10067:     }
10068:     return %availablesecs;
10069: }
10070: 
10071: sub scantron_upload_delete {
10072:     my ($r,$symb) = @_;
10073:     my $filename = $env{'form.uploadedfile'};
10074:     if ($filename =~ /^scantron_orig_/) {
10075:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
10076:             &Apache::lonnet::allowed('usc',
10077:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
10078:             &Apache::lonnet::allowed('usc',
10079:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
10080:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
10081:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
10082:             if ($retrieval eq '-1') {
10083:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10084:                           &mt('File requested for deletion not found.'));
10085:             } else {
10086:                 $filename =~ s/^scantron_orig_//;
10087:                 if ($filename ne '') {
10088:                     my ($is_valid,$numleft);
10089:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
10090:                     if (keys(%info)) {
10091:                         if (ref($info{$filename}) eq 'HASH') {
10092:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
10093:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
10094:                                     $is_valid = 1;
10095:                                     delete($info{$filename}{$timestamp}); 
10096:                                 }
10097:                             }
10098:                             $numleft = scalar(keys(%{$info{$filename}}));
10099:                         }
10100:                     }
10101:                     if ($is_valid) {
10102:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
10103:                         if ($result eq 'ok') {
10104:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
10105:                             if ($numleft) {
10106:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
10107:                             } else {
10108:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
10109:                             }
10110:                         } else {
10111:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10112:                                       &mt('Result was [_1]',$result));
10113:                         }
10114:                     } else {
10115:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10116:                                   &mt('File requested for deletion was uploaded by a different user.'));
10117:                     }
10118:                 } else {
10119:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10120:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
10121:                 }
10122:             }
10123:         } else {
10124:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
10125:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
10126:         }
10127:     } else {
10128:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
10129:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
10130:     }
10131:     return;
10132: }
10133: 
10134: sub valid_file {
10135:     my ($requested_file)=@_;
10136:     foreach my $filename (sort(&scantron_filenames())) {
10137: 	if ($requested_file eq $filename) { return 1; }
10138:     }
10139:     return 0;
10140: }
10141: 
10142: sub scantron_download_scantron_data {
10143:     my ($r,$symb) = @_;
10144:     my $default_form_data=&defaultFormData($symb);
10145:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
10146:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10147:     my $file=$env{'form.scantron_selectfile'};
10148:     if (! &valid_file($file)) {
10149: 	$r->print('
10150: 	<p>
10151: 	    '.&mt('The requested filename was invalid.').'
10152:         </p>
10153: ');
10154: 	return;
10155:     }
10156:     my (%uploader,$is_owner,%counts,$percent);
10157:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
10158:     if (ref($uploader{$file}) eq 'HASH') {
10159:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
10160:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
10161:                 $is_owner = 1;
10162:                 last;
10163:             }
10164:         }
10165:     }
10166:     unless ($is_owner) {
10167:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
10168:         if ($counts{'totalanysec'}) {
10169:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
10170:             if ($percent_othersec >= 10) {
10171:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
10172:                 $r->print('<p class="LC_warning">'.
10173:                           &mt('The original uploaded file includes [_1] or more of records for students for which none of your roles have rights to modify grades, so files are unavailable for download.',$showpct).
10174:                           '</p>');
10175:                 return;
10176:             }
10177:         }
10178:     }
10179:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
10180:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
10181:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
10182:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
10183:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
10184:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
10185:     $r->print('
10186:     <p>
10187: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
10188: 	      '<a href="'.$orig.'">','</a>').'
10189:     </p>
10190:     <p>
10191: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
10192: 	      '<a href="'.$corrected.'">','</a>').'
10193:     </p>
10194:     <p>
10195: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
10196: 	      '<a href="'.$skipped.'">','</a>').'
10197:     </p>
10198: ');
10199:     return '';
10200: }
10201: 
10202: sub checkscantron_results {
10203:     my ($r,$symb) = @_;
10204:     if (!$symb) {return '';}
10205:     my $cid = $env{'request.course.id'};
10206:     my %lettdig = &Apache::lonnet::letter_to_digits();
10207:     my $numletts = scalar(keys(%lettdig));
10208:     my $cnum = $env{'course.'.$cid.'.num'};
10209:     my $cdom = $env{'course.'.$cid.'.domain'};
10210:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
10211:     my %record;
10212:     my %scantron_config =
10213:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
10214:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
10215:     my ($scanlines,$scan_data)=&scantron_getfile();
10216:     my $classlist=&Apache::loncoursedata::get_classlist();
10217:     my %idmap=&Apache::grades::username_to_idmap($classlist);
10218:     my $navmap=Apache::lonnavmaps::navmap->new();
10219:     unless (ref($navmap)) {
10220:         $r->print(&navmap_errormsg());
10221:         return '';
10222:     }
10223:     my $map=$navmap->getResourceByUrl($sequence);
10224:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
10225:         %grader_randomlists_by_symb,%orderedforcode);
10226:     if (ref($map)) { 
10227:         $randomorder=$map->randomorder();
10228:         $randompick=$map->randompick();
10229:         unless ($randomorder || $randompick) {
10230:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
10231:                 if ($res->randomorder()) {
10232:                     $randomorder = 1;
10233:                 }
10234:                 if ($res->randompick()) {
10235:                     $randompick = 1;
10236:                 }
10237:                 last if ($randomorder || $randompick);
10238:             }
10239:         }
10240:     }
10241:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
10242:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
10243:     if ($nav_error) {
10244:         $r->print(&navmap_errormsg());
10245:         return '';
10246:     }
10247:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
10248:                             \%grader_randomlists_by_symb,$bubbles_per_row);
10249:     my ($uname,$udom);
10250:     my (%scandata,%lastname,%bylast);
10251:     $r->print('
10252: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
10253: 
10254:     my @delayqueue;
10255:     my %completedstudents;
10256: 
10257:     my $count=&get_todo_count($scanlines,$scan_data);
10258:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
10259:     my ($username,$domain,$started);
10260:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
10261:     if ($nav_error) {
10262:         $r->print(&navmap_errormsg());
10263:         return '';
10264:     }
10265: 
10266:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
10267:     my $start=&Time::HiRes::time();
10268:     my $i=-1;
10269: 
10270:     while ($i<$scanlines->{'count'}) {
10271:         ($username,$domain,$uname)=('','','');
10272:         $i++;
10273:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
10274:         if ($line=~/^[\s\cz]*$/) { next; }
10275:         if ($started) {
10276:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
10277:         }
10278:         $started=1;
10279:         my $scan_record=
10280:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
10281:                                                      $scan_data);
10282:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
10283:                                               \%idmap,$i)) {
10284:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10285:                                 'Unable to find a student that matches',1);
10286:             next;
10287:         }
10288:         if (exists $completedstudents{$uname}) {
10289:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10290:                                 'Student '.$uname.' has multiple sheets',2);
10291:             next;
10292:         }
10293:         my $pid = $scan_record->{'scantron.ID'};
10294:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
10295:         push(@{$bylast{$lastname{$pid}}},$pid);
10296:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
10297:         my $user = $uname.':'.$usec;
10298:         ($username,$domain)=split(/:/,$uname);
10299: 
10300:         my $scancode;
10301:         if ((exists($scan_record->{'scantron.CODE'})) &&
10302:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
10303:             $scancode = $scan_record->{'scantron.CODE'};
10304:         } else {
10305:             $scancode = '';
10306:         }
10307: 
10308:         my @mapresources = @resources;
10309:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
10310:         my %respnumlookup=();
10311:         my %startline=();
10312:         if ($randomorder || $randompick) {
10313:             @mapresources =
10314:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
10315:                              \%orderedforcode);
10316:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
10317:                                              $scan_record,\@master_seq,\%symb_to_resource,
10318:                                              \%grader_partids_by_symb,\%orderedforcode,
10319:                                              \%respnumlookup,\%startline);
10320:             if ($randompick && $total) {
10321:                 $lastpos = $total*$scantron_config{'Qlength'};
10322:             }
10323:         }
10324:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
10325:         chomp($scandata{$pid});
10326:         $scandata{$pid} =~ s/\r$//;
10327: 
10328:         my $counter = -1;
10329:         foreach my $resource (@mapresources) {
10330:             my $parts;
10331:             my $ressymb = $resource->symb();
10332:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
10333:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
10334:                 my $currcode;
10335:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
10336:                     $currcode = $scancode;
10337:                 }
10338:                 (my $analysis,$parts) =
10339:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
10340:                                               $username,$domain,undef,
10341:                                               $bubbles_per_row,$currcode);
10342:             } else {
10343:                 $parts = $grader_partids_by_symb{$ressymb};
10344:             }
10345:             ($counter,my $recording) =
10346:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
10347:                                          $scandata{$pid},$parts,
10348:                                          \%scantron_config,\%lettdig,$numletts,
10349:                                          $randomorder,$randompick,
10350:                                          \%respnumlookup,\%startline);
10351:             $record{$pid} .= $recording;
10352:         }
10353:     }
10354:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
10355:     $r->print('<br />');
10356:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
10357:     $passed = 0;
10358:     $failed = 0;
10359:     $numstudents = 0;
10360:     foreach my $last (sort(keys(%bylast))) {
10361:         if (ref($bylast{$last}) eq 'ARRAY') {
10362:             foreach my $pid (sort(@{$bylast{$last}})) {
10363:                 my $showscandata = $scandata{$pid};
10364:                 my $showrecord = $record{$pid};
10365:                 $showscandata =~ s/\s/&nbsp;/g;
10366:                 $showrecord =~ s/\s/&nbsp;/g;
10367:                 if ($scandata{$pid} eq $record{$pid}) {
10368:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
10369:                     $okstudents .= '<tr class="'.$css_class.'">'.
10370: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
10371: '</tr>'."\n".
10372: '<tr class="'.$css_class.'">'."\n".
10373: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10374:                     $passed ++;
10375:                 } else {
10376:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10377:                     $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".
10378: '</tr>'."\n".
10379: '<tr class="'.$css_class.'">'."\n".
10380: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10381: '</tr>'."\n";
10382:                     $failed ++;
10383:                 }
10384:                 $numstudents ++;
10385:             }
10386:         }
10387:     }
10388:     $r->print(
10389:         '<p>'
10390:        .&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).',
10391:             '<b>',
10392:             $numstudents,
10393:             '</b>',
10394:             $env{'form.scantron_maxbubble'})
10395:        .'</p>'
10396:     );
10397:     $r->print('<p>'
10398:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10399:              .'<br />'
10400:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10401:              .'</p>'
10402:     );
10403:     if ($passed) {
10404:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10405:         $r->print(&Apache::loncommon::start_data_table()."\n".
10406:                  &Apache::loncommon::start_data_table_header_row()."\n".
10407:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10408:                  &Apache::loncommon::end_data_table_header_row()."\n".
10409:                  $okstudents."\n".
10410:                  &Apache::loncommon::end_data_table().'<br />');
10411:     }
10412:     if ($failed) {
10413:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10414:         $r->print(&Apache::loncommon::start_data_table()."\n".
10415:                  &Apache::loncommon::start_data_table_header_row()."\n".
10416:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10417:                  &Apache::loncommon::end_data_table_header_row()."\n".
10418:                  $badstudents."\n".
10419:                  &Apache::loncommon::end_data_table()).'<br />'.
10420:                  &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.');  
10421:     }
10422:     $r->print('</form><br />');
10423:     return;
10424: }
10425: 
10426: sub verify_scantron_grading {
10427:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10428:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10429:         $respnumlookup,$startline) = @_;
10430:     my ($record,%expected,%startpos);
10431:     return ($counter,$record) if (!ref($resource));
10432:     return ($counter,$record) if (!$resource->is_problem());
10433:     my $symb = $resource->symb();
10434:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10435:     foreach my $part_id (@{$partids}) {
10436:         $counter ++;
10437:         $expected{$part_id} = 0;
10438:         my $respnum = $counter;
10439:         if ($randomorder || $randompick) {
10440:             $respnum = $respnumlookup->{$counter};
10441:             $startpos{$part_id} = $startline->{$counter} + 1;
10442:         } else {
10443:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10444:         }
10445:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10446:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10447:             foreach my $item (@sub_lines) {
10448:                 $expected{$part_id} += $item;
10449:             }
10450:         } else {
10451:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10452:         }
10453:     }
10454:     if ($symb) {
10455:         my %recorded;
10456:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10457:         if ($returnhash{'version'}) {
10458:             my %lasthash=();
10459:             my $version;
10460:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10461:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10462:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10463:                 }
10464:             }
10465:             foreach my $key (keys(%lasthash)) {
10466:                 if ($key =~ /\.scantron$/) {
10467:                     my $value = &unescape($lasthash{$key});
10468:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10469:                     if ($value eq '') {
10470:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10471:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10472:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10473:                             }
10474:                         }
10475:                     } else {
10476:                         my @tocheck;
10477:                         my @items = split(//,$value);
10478:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10479:                             ($scantron_config->{'Qon'} eq 'number')) {
10480:                             if (@items < $expected{$part_id}) {
10481:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10482:                                 my @singles = split(//,$fragment);
10483:                                 foreach my $pos (@singles) {
10484:                                     if ($pos eq ' ') {
10485:                                         push(@tocheck,$pos);
10486:                                     } else {
10487:                                         my $next = shift(@items);
10488:                                         push(@tocheck,$next);
10489:                                     }
10490:                                 }
10491:                             } else {
10492:                                 @tocheck = @items;
10493:                             }
10494:                             foreach my $letter (@tocheck) {
10495:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10496:                                     if ($letter !~ /^[A-J]$/) {
10497:                                         $letter = $scantron_config->{'Qoff'};
10498:                                     }
10499:                                     $recorded{$part_id} .= $letter;
10500:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10501:                                     my $digit;
10502:                                     if ($letter !~ /^[A-J]$/) {
10503:                                         $digit = $scantron_config->{'Qoff'};
10504:                                     } else {
10505:                                         $digit = $lettdig->{$letter};
10506:                                     }
10507:                                     $recorded{$part_id} .= $digit;
10508:                                 }
10509:                             }
10510:                         } else {
10511:                             @tocheck = @items;
10512:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10513:                                 my $curr_sub = shift(@tocheck);
10514:                                 my $digit;
10515:                                 if ($curr_sub =~ /^[A-J]$/) {
10516:                                     $digit = $lettdig->{$curr_sub}-1;
10517:                                 }
10518:                                 if ($curr_sub eq 'J') {
10519:                                     $digit += scalar($numletts);
10520:                                 }
10521:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10522:                                     if ($j == $digit) {
10523:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10524:                                     } else {
10525:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10526:                                     }
10527:                                 }
10528:                             }
10529:                         }
10530:                     }
10531:                 }
10532:             }
10533:         }
10534:         foreach my $part_id (@{$partids}) {
10535:             if ($recorded{$part_id} eq '') {
10536:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10537:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10538:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10539:                     }
10540:                 }
10541:             }
10542:             $record .= $recorded{$part_id};
10543:         }
10544:     }
10545:     return ($counter,$record);
10546: }
10547: 
10548: #-------- end of section for handling grading scantron forms -------
10549: #
10550: #-------------------------------------------------------------------
10551: 
10552: #-------------------------- Menu interface -------------------------
10553: #
10554: #--- Href with symb and command ---
10555: 
10556: sub href_symb_cmd {
10557:     my ($symb,$cmd)=@_;
10558:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10559: }
10560: 
10561: sub grading_menu {
10562:     my ($request,$symb) = @_;
10563:     if (!$symb) {return '';}
10564: 
10565:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10566:                   'command'=>'individual');
10567:     
10568:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10569: 
10570:     $fields{'command'}='ungraded';
10571:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10572: 
10573:     $fields{'command'}='table';
10574:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10575: 
10576:     $fields{'command'}='all_for_one';
10577:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10578: 
10579:     $fields{'command'}='downloadfilesselect';
10580:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10581: 
10582:     $fields{'command'} = 'csvform';
10583:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10584:     
10585:     $fields{'command'} = 'processclicker';
10586:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10587:     
10588:     $fields{'command'} = 'scantron_selectphase';
10589:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10590: 
10591:     $fields{'command'} = 'initialverifyreceipt';
10592:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10593: 
10594:     my %permissions;
10595:     if ($perm{'mgr'}) {
10596:         $permissions{'either'} = 'F';
10597:         $permissions{'mgr'} = 'F';
10598:     }
10599:     if ($perm{'vgr'}) {
10600:         $permissions{'either'} = 'F';
10601:         $permissions{'vgr'} = 'F';
10602:     }
10603: 
10604:     my @menu = ({	categorytitle=>'Hand Grading',
10605:             items =>[
10606:                         {	linktext => 'Select individual students to grade',
10607:                     		url => $url1a,
10608:                     		permission => $permissions{'either'},
10609:                     		icon => 'grade_students.png',
10610:                     		linktitle => 'Grade current resource for a selection of students.'
10611:                         }, 
10612:                         {       linktext => 'Grade ungraded submissions',
10613:                                 url => $url1b,
10614:                                 permission => $permissions{'either'},
10615:                                 icon => 'ungrade_sub.png',
10616:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10617:                         },
10618: 
10619:                         {       linktext => 'Grading table',
10620:                                 url => $url1c,
10621:                                 permission => $permissions{'either'},
10622:                                 icon => 'grading_table.png',
10623:                                 linktitle => 'Grade current resource for all students.'
10624:                         },
10625:                         {       linktext => 'Grade page/folder for one student',
10626:                                 url => $url1d,
10627:                                 permission => $permissions{'either'},
10628:                                 icon => 'grade_PageFolder.png',
10629:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10630:                         },
10631:                         {       linktext => 'Download submissions',
10632:                                 url => $url1e,
10633:                                 permission => $permissions{'either'},
10634:                                 icon => 'download_sub.png',
10635:                                 linktitle => 'Download all students submissions.'
10636:                         }]},
10637:                          { categorytitle=>'Automated Grading',
10638:                items =>[
10639: 
10640:                 	    {	linktext => 'Upload Scores',
10641:                     		url => $url2,
10642:                     		permission => $permissions{'mgr'},
10643:                     		icon => 'uploadscores.png',
10644:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10645:                 	    },
10646:                 	    {	linktext => 'Process Clicker',
10647:                     		url => $url3,
10648:                     		permission => $permissions{'mgr'},
10649:                     		icon => 'addClickerInfoFile.png',
10650:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10651:                 	    },
10652:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10653:                     		url => $url4,
10654:                     		permission => $permissions{'mgr'},
10655:                     		icon => 'bubblesheet.png',
10656:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10657:                 	    },
10658:                             {   linktext => 'Verify Receipt Number',
10659:                                 url => $url5,
10660:                                 permission => $permissions{'either'},
10661:                                 icon => 'receipt_number.png',
10662:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10663:                             }
10664: 
10665:                     ]
10666:             });
10667: 
10668:     # Create the menu
10669:     my $Str;
10670:     $Str .= '<form method="post" action="" name="gradingMenu">';
10671:     $Str .= '<input type="hidden" name="command" value="" />'.
10672:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10673: 
10674:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10675:     return $Str;    
10676: }
10677: 
10678: sub ungraded {
10679:     my ($request)=@_;
10680:     &submit_options($request);
10681: }
10682: 
10683: sub submit_options_sequence {
10684:     my ($request,$symb) = @_;
10685:     if (!$symb) {return '';}
10686:     &commonJSfunctions($request);
10687:     my $result;
10688: 
10689:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10690:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10691:     $result.=&selectfield(0).
10692:             '<input type="hidden" name="command" value="pickStudentPage" />
10693:             <div>
10694:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10695:             </div>
10696:         </div>
10697:   </form>';
10698:     return $result;
10699: }
10700: 
10701: sub submit_options_table {
10702:     my ($request,$symb) = @_;
10703:     if (!$symb) {return '';}
10704:     &commonJSfunctions($request);
10705:     my $is_tool = ($symb =~ /ext\.tool$/);
10706:     my $result;
10707: 
10708:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10709:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10710: 
10711:     $result.=&selectfield(1,$is_tool).
10712:             '<input type="hidden" name="command" value="viewgrades" />
10713:             <div>
10714:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10715:             </div>
10716:         </div>
10717:   </form>';
10718:     return $result;
10719: }
10720: 
10721: sub submit_options_download {
10722:     my ($request,$symb) = @_;
10723:     if (!$symb) {return '';}
10724: 
10725:     my $res_error;
10726:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10727:         &response_type($symb,\$res_error);
10728:     if ($res_error) {
10729:         $request->print(&mt('An error occurred retrieving response types'));
10730:         return;
10731:     }
10732:     unless ($numessay) {
10733:         $request->print(&mt('No essayresponse items found'));
10734:         return;
10735:     }
10736:     my $table;
10737:     if (ref($partlist) eq 'ARRAY') {
10738:         if (scalar(@$partlist) > 1 ) {
10739:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10740:         }
10741:     }
10742: 
10743:     my $is_tool = ($symb =~ /ext\.tool$/);
10744:     &commonJSfunctions($request);
10745: 
10746:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10747:                $table."\n".
10748:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10749:     $result.='
10750: <h2>
10751:   '.&mt('Select Students for whom to Download Submissions').'
10752: </h2>'.&selectfield(1,$is_tool).'
10753:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10754:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10755:             </div>
10756:           </div>
10757: 
10758: 
10759:   </form>';
10760:     return $result;
10761: }
10762: 
10763: #--- Displays the submissions first page -------
10764: sub submit_options {
10765:     my ($request,$symb) = @_;
10766:     if (!$symb) {return '';}
10767: 
10768:     my $is_tool = ($symb =~ /ext\.tool$/);
10769:     &commonJSfunctions($request);
10770:     my $result;
10771: 
10772:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10773: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10774:     $result.=&selectfield(1,$is_tool).'
10775:                 <input type="hidden" name="command" value="submission" /> 
10776: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10777:             </div>
10778:           </div>
10779:   </form>';
10780:     return $result;
10781: }
10782: 
10783: sub selectfield {
10784:    my ($full,$is_tool)=@_;
10785:    my %options;
10786:    if ($is_tool) {
10787:        %options =
10788:            (&transtatus_options,
10789:             'select_form_order' => ['yes','incorrect','all']);
10790:    } else {
10791:        %options = 
10792:            (&substatus_options,
10793:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10794:    }
10795: 
10796:   #
10797:   # PrepareClasslist() needs to be called to avoid getting a sections list
10798:   # for a different course from the @Sections global in lonstatistics.pm, 
10799:   # populated by an earlier request.
10800:   #
10801:    &Apache::lonstatistics::PrepareClasslist();
10802: 
10803:    my $result='<div class="LC_columnSection">
10804:   
10805:     <fieldset>
10806:       <legend>
10807:        '.&mt('Sections').'
10808:       </legend>
10809:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10810:     </fieldset>
10811:   
10812:     <fieldset>
10813:       <legend>
10814:         '.&mt('Groups').'
10815:       </legend>
10816:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10817:     </fieldset>
10818:   
10819:     <fieldset>
10820:       <legend>
10821:         '.&mt('Access Status').'
10822:       </legend>
10823:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10824:     </fieldset>';
10825:     if ($full) {
10826:         my $heading = &mt('Submission Status');
10827:         if ($is_tool) {
10828:             $heading = &mt('Transaction Status');
10829:         }
10830:         $result.='
10831:     <fieldset>
10832:       <legend>
10833:         '.$heading.'
10834:       </legend>'.
10835:        &Apache::loncommon::select_form('all','submitonly',\%options).
10836:    '</fieldset>';
10837:     }
10838:     $result.='</div><br />';
10839:     return $result;
10840: }
10841: 
10842: sub substatus_options {
10843:     return &Apache::lonlocal::texthash(
10844:                                       'yes'       => 'with submissions',
10845:                                       'queued'    => 'in grading queue',
10846:                                       'graded'    => 'with ungraded submissions',
10847:                                       'incorrect' => 'with incorrect submissions',
10848:                                       'all'       => 'with any status',
10849:                                       );
10850: }
10851: 
10852: sub transtatus_options {
10853:     return &Apache::lonlocal::texthash(
10854:                                        'yes'       => 'with score transactions',
10855:                                        'incorrect' => 'with less than full credit',
10856:                                        'all'       => 'with any status',
10857:                                       );
10858: }
10859: 
10860: sub reset_perm {
10861:     undef(%perm);
10862: }
10863: 
10864: sub init_perm {
10865:     &reset_perm();
10866:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10867: 
10868: 	my $scope = $env{'request.course.id'};
10869: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10870: 
10871: 	    $scope .= '/'.$env{'request.course.sec'};
10872: 	    if ( $perm{$test_perm}=
10873: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10874: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10875: 	    } else {
10876: 		delete($perm{$test_perm});
10877: 	    }
10878: 	}
10879:     }
10880: }
10881: 
10882: sub init_old_essays {
10883:     my ($symb,$apath,$adom,$aname) = @_;
10884:     if ($symb ne '') {
10885:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10886:         if (keys(%essays) > 0) {
10887:             $old_essays{$symb} = \%essays;
10888:         }
10889:     }
10890:     return;
10891: }
10892: 
10893: sub reset_old_essays {
10894:     undef(%old_essays);
10895: }
10896: 
10897: sub gather_clicker_ids {
10898:     my %clicker_ids;
10899: 
10900:     my $classlist = &Apache::loncoursedata::get_classlist();
10901: 
10902:     # Set up a couple variables.
10903:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10904:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10905:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10906: 
10907:     foreach my $student (keys(%$classlist)) {
10908:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10909:         my $username = $classlist->{$student}->[$username_idx];
10910:         my $domain   = $classlist->{$student}->[$domain_idx];
10911:         my $clickers =
10912: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10913:         foreach my $id (split(/\,/,$clickers)) {
10914:             $id=~s/^[\#0]+//;
10915:             $id=~s/[\-\:]//g;
10916:             if (exists($clicker_ids{$id})) {
10917: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10918:             } else {
10919: 		$clicker_ids{$id}=$username.':'.$domain;
10920:             }
10921:         }
10922:     }
10923:     return %clicker_ids;
10924: }
10925: 
10926: sub gather_adv_clicker_ids {
10927:     my %clicker_ids;
10928:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10929:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10930:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10931:     foreach my $element (sort(keys(%coursepersonnel))) {
10932:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10933:             my ($puname,$pudom)=split(/\:/,$person);
10934:             my $clickers =
10935: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10936:             foreach my $id (split(/\,/,$clickers)) {
10937: 		$id=~s/^[\#0]+//;
10938:                 $id=~s/[\-\:]//g;
10939: 		if (exists($clicker_ids{$id})) {
10940: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10941: 		} else {
10942: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10943: 		}
10944:             }
10945:         }
10946:     }
10947:     return %clicker_ids;
10948: }
10949: 
10950: sub clicker_grading_parameters {
10951:     return ('gradingmechanism' => 'scalar',
10952:             'upfiletype' => 'scalar',
10953:             'specificid' => 'scalar',
10954:             'pcorrect' => 'scalar',
10955:             'pincorrect' => 'scalar');
10956: }
10957: 
10958: sub process_clicker {
10959:     my ($r,$symb)=@_;
10960:     if (!$symb) {return '';}
10961:     my $result=&checkforfile_js();
10962:     $result.=&Apache::loncommon::start_data_table().
10963:              &Apache::loncommon::start_data_table_header_row().
10964:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10965:              &Apache::loncommon::end_data_table_header_row().
10966:              &Apache::loncommon::start_data_table_row()."<td>\n";
10967: # Attempt to restore parameters from last session, set defaults if not present
10968:     my %Saveable_Parameters=&clicker_grading_parameters();
10969:     &Apache::loncommon::restore_course_settings('grades_clicker',
10970:                                                  \%Saveable_Parameters);
10971:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10972:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10973:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10974:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10975: 
10976:     my %checked;
10977:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10978:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10979:           $checked{$gradingmechanism}=' checked="checked"';
10980:        }
10981:     }
10982: 
10983:     my $upload=&mt("Evaluate File");
10984:     my $type=&mt("Type");
10985:     my $attendance=&mt("Award points just for participation");
10986:     my $personnel=&mt("Correctness determined from response by course personnel");
10987:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10988:     my $given=&mt("Correctness determined from given list of answers").' '.
10989:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10990:     my $pcorrect=&mt("Percentage points for correct solution");
10991:     my $pincorrect=&mt("Percentage points for incorrect solution");
10992:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10993: 						   {'iclicker' => 'i>clicker',
10994:                                                     'interwrite' => 'interwrite PRS',
10995:                                                     'turning' => 'Turning Technologies'});
10996:     $symb = &Apache::lonenc::check_encrypt($symb);
10997:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10998: function sanitycheck() {
10999: // Accept only integer percentages
11000:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
11001:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
11002: // Find out grading choice
11003:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
11004:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
11005:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
11006:       }
11007:    }
11008: // By default, new choice equals user selection
11009:    newgradingchoice=gradingchoice;
11010: // Not good to give more points for false answers than correct ones
11011:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
11012:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
11013:    }
11014: // If new choice is attendance only, and old choice was correctness-based, restore defaults
11015:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
11016:       document.forms.gradesupload.pcorrect.value=100;
11017:       document.forms.gradesupload.pincorrect.value=100;
11018:    }
11019: // If the values are different, cannot be attendance only
11020:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
11021:        (gradingchoice=='attendance')) {
11022:        newgradingchoice='personnel';
11023:    }
11024: // Change grading choice to new one
11025:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
11026:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
11027:          document.forms.gradesupload.gradingmechanism[i].checked=true;
11028:       } else {
11029:          document.forms.gradesupload.gradingmechanism[i].checked=false;
11030:       }
11031:    }
11032: // Remember the old state
11033:    document.forms.gradesupload.waschecked.value=newgradingchoice;
11034: }
11035: ENDUPFORM
11036:     $result.= <<ENDUPFORM;
11037: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
11038: <input type="hidden" name="symb" value="$symb" />
11039: <input type="hidden" name="command" value="processclickerfile" />
11040: <input type="file" name="upfile" size="50" />
11041: <br /><label>$type: $selectform</label>
11042: ENDUPFORM
11043:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
11044:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
11045:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
11046: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
11047: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
11048: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
11049: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
11050: <br />&nbsp;&nbsp;&nbsp;
11051: <input type="text" name="givenanswer" size="50" />
11052: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
11053: ENDGRADINGFORM
11054:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
11055:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
11056:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
11057: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
11058: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
11059: </form>
11060: ENDPERCFORM
11061:     $result.='</td>'.
11062:              &Apache::loncommon::end_data_table_row().
11063:              &Apache::loncommon::end_data_table();
11064:     return $result;
11065: }
11066: 
11067: sub process_clicker_file {
11068:     my ($r,$symb) = @_;
11069:     if (!$symb) {return '';}
11070: 
11071:     my %Saveable_Parameters=&clicker_grading_parameters();
11072:     &Apache::loncommon::store_course_settings('grades_clicker',
11073:                                               \%Saveable_Parameters);
11074:     my $result='';
11075:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
11076: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
11077: 	return $result;
11078:     }
11079:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
11080:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
11081:         return $result;
11082:     }
11083:     my $foundgiven=0;
11084:     if ($env{'form.gradingmechanism'} eq 'given') {
11085:         $env{'form.givenanswer'}=~s/^\s*//gs;
11086:         $env{'form.givenanswer'}=~s/\s*$//gs;
11087:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
11088:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
11089:         my @answers=split(/\,/,$env{'form.givenanswer'});
11090:         $foundgiven=$#answers+1;
11091:     }
11092:     my %clicker_ids=&gather_clicker_ids();
11093:     my %correct_ids;
11094:     if ($env{'form.gradingmechanism'} eq 'personnel') {
11095: 	%correct_ids=&gather_adv_clicker_ids();
11096:     }
11097:     if ($env{'form.gradingmechanism'} eq 'specific') {
11098: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
11099: 	   $correct_id=~tr/a-z/A-Z/;
11100: 	   $correct_id=~s/\s//gs;
11101: 	   $correct_id=~s/^[\#0]+//;
11102:            $correct_id=~s/[\-\:]//g;
11103:            if ($correct_id) {
11104: 	      $correct_ids{$correct_id}='specified';
11105:            }
11106:         }
11107:     }
11108:     if ($env{'form.gradingmechanism'} eq 'attendance') {
11109: 	$result.=&mt('Score based on attendance only');
11110:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
11111:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
11112:     } else {
11113: 	my $number=0;
11114: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
11115: 	foreach my $id (sort(keys(%correct_ids))) {
11116: 	    $result.='<br /><tt>'.$id.'</tt> - ';
11117: 	    if ($correct_ids{$id} eq 'specified') {
11118: 		$result.=&mt('specified');
11119: 	    } else {
11120: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
11121: 		$result.=&Apache::loncommon::plainname($uname,$udom);
11122: 	    }
11123: 	    $number++;
11124: 	}
11125:         $result.="</p>\n";
11126:         if ($number==0) {
11127:             $result .=
11128:                  &Apache::lonhtmlcommon::confirm_success(
11129:                      &mt('No IDs found to determine correct answer'),1);
11130:             return $result;
11131:         }
11132:     }
11133:     if (length($env{'form.upfile'}) < 2) {
11134:         $result .=
11135:             &Apache::lonhtmlcommon::confirm_success(
11136:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
11137:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
11138:         return $result;
11139:     }
11140:     my $mimetype;
11141:     if ($env{'form.upfiletype'} eq 'iclicker') {
11142:         my $mm = new File::MMagic;
11143:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
11144:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
11145:             $result.= '<p>'.
11146:                 &Apache::lonhtmlcommon::confirm_success(
11147:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
11148:             return $result;
11149:         }
11150:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
11151:         $result .= '<p>'.
11152:             &Apache::lonhtmlcommon::confirm_success(
11153:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
11154:         return $result;
11155:     }
11156: 
11157: # Were able to get all the info needed, now analyze the file
11158: 
11159:     $result.=&Apache::loncommon::studentbrowser_javascript();
11160:     $symb = &Apache::lonenc::check_encrypt($symb);
11161:     $result.=&Apache::loncommon::start_data_table().
11162:              &Apache::loncommon::start_data_table_header_row().
11163:              '<th>'.&mt('Evaluate clicker file').'</th>'.
11164:              &Apache::loncommon::end_data_table_header_row().
11165:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
11166: <td>
11167: <form method="post" action="/adm/grades" name="clickeranalysis">
11168: <input type="hidden" name="symb" value="$symb" />
11169: <input type="hidden" name="command" value="assignclickergrades" />
11170: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
11171: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
11172: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
11173: ENDHEADER
11174:     if ($env{'form.gradingmechanism'} eq 'given') {
11175:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
11176:     } 
11177:     my %responses;
11178:     my @questiontitles;
11179:     my $errormsg='';
11180:     my $number=0;
11181:     if ($env{'form.upfiletype'} eq 'iclicker') {
11182:         if ($mimetype eq 'text/plain') {
11183:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
11184:         } elsif ($mimetype eq 'text/html') {
11185:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
11186:         }
11187:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
11188:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
11189:     } elsif ($env{'form.upfiletype'} eq 'turning') {
11190:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
11191:     }
11192:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
11193:              '<input type="hidden" name="number" value="'.$number.'" />'.
11194:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
11195:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
11196:              '<br />';
11197:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
11198:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
11199:        return $result;
11200:     } 
11201: # Remember Question Titles
11202: # FIXME: Possibly need delimiter other than ":"
11203:     for (my $i=0;$i<$number;$i++) {
11204:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
11205:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
11206:     }
11207:     my $correct_count=0;
11208:     my $student_count=0;
11209:     my $unknown_count=0;
11210: # Match answers with usernames
11211: # FIXME: Possibly need delimiter other than ":"
11212:     foreach my $id (keys(%responses)) {
11213:        if ($correct_ids{$id}) {
11214:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
11215:           $correct_count++;
11216:        } elsif ($clicker_ids{$id}) {
11217:           if ($clicker_ids{$id}=~/\,/) {
11218: # More than one user with the same clicker!
11219:              $result.="</td>".&Apache::loncommon::end_data_table_row().
11220:                            &Apache::loncommon::start_data_table_row()."<td>".
11221:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
11222:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11223:                            "<select name='multi".$id."'>";
11224:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
11225:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
11226:              }
11227:              $result.='</select>';
11228:              $unknown_count++;
11229:           } else {
11230: # Good: found one and only one user with the right clicker
11231:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
11232:              $student_count++;
11233:           }
11234:        } else {
11235:           $result.="</td>".&Apache::loncommon::end_data_table_row().
11236:                            &Apache::loncommon::start_data_table_row()."<td>".
11237:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
11238:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11239:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
11240:                    "\n".&mt("Domain").": ".
11241:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
11242:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
11243:           $unknown_count++;
11244:        }
11245:     }
11246:     $result.='<hr />'.
11247:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
11248:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
11249:        if ($correct_count==0) {
11250:           $errormsg.="Found no correct answers for grading!";
11251:        } elsif ($correct_count>1) {
11252:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
11253:        }
11254:     }
11255:     if ($number<1) {
11256:        $errormsg.="Found no questions.";
11257:     }
11258:     if ($errormsg) {
11259:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
11260:     } else {
11261:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
11262:     }
11263:     $result.='</form></td>'.
11264:              &Apache::loncommon::end_data_table_row().
11265:              &Apache::loncommon::end_data_table();
11266:     return $result;
11267: }
11268: 
11269: sub iclicker_eval {
11270:     my ($questiontitles,$responses)=@_;
11271:     my $number=0;
11272:     my $errormsg='';
11273:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11274:         my %components=&Apache::loncommon::record_sep($line);
11275:         my @entries=map {$components{$_}} (sort(keys(%components)));
11276: 	if ($entries[0] eq 'Question') {
11277: 	    for (my $i=3;$i<$#entries;$i+=6) {
11278: 		$$questiontitles[$number]=$entries[$i];
11279: 		$number++;
11280: 	    }
11281: 	}
11282: 	if ($entries[0]=~/^\#/) {
11283: 	    my $id=$entries[0];
11284: 	    my @idresponses;
11285: 	    $id=~s/^[\#0]+//;
11286: 	    for (my $i=0;$i<$number;$i++) {
11287: 		my $idx=3+$i*6;
11288:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11289: 		push(@idresponses,$entries[$idx]);
11290: 	    }
11291: 	    $$responses{$id}=join(',',@idresponses);
11292: 	}
11293:     }
11294:     return ($errormsg,$number);
11295: }
11296: 
11297: sub iclickerxml_eval {
11298:     my ($questiontitles,$responses)=@_;
11299:     my $number=0;
11300:     my $errormsg='';
11301:     my @state;
11302:     my %respbyid;
11303:     my $p = HTML::Parser->new
11304:     (
11305:         xml_mode => 1,
11306:         start_h =>
11307:             [sub {
11308:                  my ($tagname,$attr) = @_;
11309:                  push(@state,$tagname);
11310:                  if ("@state" eq "ssn p") {
11311:                      my $title = $attr->{qn};
11312:                      $title =~ s/(^\s+|\s+$)//g;
11313:                      $questiontitles->[$number]=$title;
11314:                  } elsif ("@state" eq "ssn p v") {
11315:                      my $id = $attr->{id};
11316:                      my $entry = $attr->{ans};
11317:                      $id=~s/^[\#0]+//;
11318:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11319:                      $respbyid{$id}[$number] = $entry;
11320:                  }
11321:             }, "tagname, attr"],
11322:          end_h =>
11323:                [sub {
11324:                    my ($tagname) = @_;
11325:                    if ("@state" eq "ssn p") {
11326:                        $number++;
11327:                    }
11328:                    pop(@state);
11329:                 }, "tagname"],
11330:     );
11331: 
11332:     $p->parse($env{'form.upfile'});
11333:     $p->eof;
11334:     foreach my $id (keys(%respbyid)) {
11335:         $responses->{$id}=join(',',@{$respbyid{$id}});
11336:     }
11337:     return ($errormsg,$number);
11338: }
11339: 
11340: sub interwrite_eval {
11341:     my ($questiontitles,$responses)=@_;
11342:     my $number=0;
11343:     my $errormsg='';
11344:     my $skipline=1;
11345:     my $questionnumber=0;
11346:     my %idresponses=();
11347:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11348:         my %components=&Apache::loncommon::record_sep($line);
11349:         my @entries=map {$components{$_}} (sort(keys(%components)));
11350:         if ($entries[1] eq 'Time') { $skipline=0; next; }
11351:         if ($entries[1] eq 'Response') { $skipline=1; }
11352:         next if $skipline;
11353:         if ($entries[0]!=$questionnumber) {
11354:            $questionnumber=$entries[0];
11355:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
11356:            $number++;
11357:         }
11358:         my $id=$entries[4];
11359:         $id=~s/^[\#0]+//;
11360:         $id=~s/^v\d*\://i;
11361:         $id=~s/[\-\:]//g;
11362:         $idresponses{$id}[$number]=$entries[6];
11363:     }
11364:     foreach my $id (keys(%idresponses)) {
11365:        $$responses{$id}=join(',',@{$idresponses{$id}});
11366:        $$responses{$id}=~s/^\s*\,//;
11367:     }
11368:     return ($errormsg,$number);
11369: }
11370: 
11371: sub turning_eval {
11372:     my ($questiontitles,$responses)=@_;
11373:     my $number=0;
11374:     my $errormsg='';
11375:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11376:         my %components=&Apache::loncommon::record_sep($line);
11377:         my @entries=map {$components{$_}} (sort(keys(%components)));
11378:         if ($#entries>$number) { $number=$#entries; }
11379:         my $id=$entries[0];
11380:         my @idresponses;
11381:         $id=~s/^[\#0]+//;
11382:         unless ($id) { next; }
11383:         for (my $idx=1;$idx<=$#entries;$idx++) {
11384:             $entries[$idx]=~s/\,/\;/g;
11385:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
11386:             push(@idresponses,$entries[$idx]);
11387:         }
11388:         $$responses{$id}=join(',',@idresponses);
11389:     }
11390:     for (my $i=1; $i<=$number; $i++) {
11391:         $$questiontitles[$i]=&mt('Question [_1]',$i);
11392:     }
11393:     return ($errormsg,$number);
11394: }
11395: 
11396: 
11397: sub assign_clicker_grades {
11398:     my ($r,$symb) = @_;
11399:     if (!$symb) {return '';}
11400: # See which part we are saving to
11401:     my $res_error;
11402:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
11403:     if ($res_error) {
11404:         return &navmap_errormsg();
11405:     }
11406: # FIXME: This should probably look for the first handgradeable part
11407:     my $part=$$partlist[0];
11408: # Start screen output
11409:     my $result = &Apache::loncommon::start_data_table().
11410:                  &Apache::loncommon::start_data_table_header_row().
11411:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11412:                  &Apache::loncommon::end_data_table_header_row().
11413:                  &Apache::loncommon::start_data_table_row().'<td>';
11414: # Get correct result
11415: # FIXME: Possibly need delimiter other than ":"
11416:     my @correct=();
11417:     my $gradingmechanism=$env{'form.gradingmechanism'};
11418:     my $number=$env{'form.number'};
11419:     if ($gradingmechanism ne 'attendance') {
11420:        foreach my $key (keys(%env)) {
11421:           if ($key=~/^form\.correct\:/) {
11422:              my @input=split(/\,/,$env{$key});
11423:              for (my $i=0;$i<=$#input;$i++) {
11424:                  if (($correct[$i]) && ($input[$i]) &&
11425:                      ($correct[$i] ne $input[$i])) {
11426:                     $result.='<br /><span class="LC_warning">'.
11427:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11428:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11429:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11430:                     $correct[$i]=$input[$i];
11431:                  }
11432:              }
11433:           }
11434:        }
11435:        for (my $i=0;$i<$number;$i++) {
11436:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11437:              $result.='<br /><span class="LC_error">'.
11438:                       &mt('No correct result given for question "[_1]"!',
11439:                           $env{'form.question:'.$i}).'</span>';
11440:           }
11441:        }
11442:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11443:     }
11444: # Start grading
11445:     my $pcorrect=$env{'form.pcorrect'};
11446:     my $pincorrect=$env{'form.pincorrect'};
11447:     my $storecount=0;
11448:     my %users=();
11449:     foreach my $key (keys(%env)) {
11450:        my $user='';
11451:        if ($key=~/^form\.student\:(.*)$/) {
11452:           $user=$1;
11453:        }
11454:        if ($key=~/^form\.unknown\:(.*)$/) {
11455:           my $id=$1;
11456:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11457:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11458:           } elsif ($env{'form.multi'.$id}) {
11459:              $user=$env{'form.multi'.$id};
11460:           }
11461:        }
11462:        if ($user) {
11463:           if ($users{$user}) {
11464:              $result.='<br /><span class="LC_warning">'.
11465:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11466:                       '</span><br />';
11467:           }
11468:           $users{$user}=1; 
11469:           my @answer=split(/\,/,$env{$key});
11470:           my $sum=0;
11471:           my $realnumber=$number;
11472:           for (my $i=0;$i<$number;$i++) {
11473:              if  ($correct[$i] eq '-') {
11474:                 $realnumber--;
11475:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11476:                 if ($gradingmechanism eq 'attendance') {
11477:                    $sum+=$pcorrect;
11478:                 } elsif ($correct[$i] eq '*') {
11479:                    $sum+=$pcorrect;
11480:                 } else {
11481: # We actually grade if correct or not
11482:                    my $increment=$pincorrect;
11483: # Special case: numerical answer "0"
11484:                    if ($correct[$i] eq '0') {
11485:                       if ($answer[$i]=~/^[0\.]+$/) {
11486:                          $increment=$pcorrect;
11487:                       }
11488: # General numerical answer, both evaluate to something non-zero
11489:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11490:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11491:                          $increment=$pcorrect;
11492:                       }
11493: # Must be just alphanumeric
11494:                    } elsif ($answer[$i] eq $correct[$i]) {
11495:                       $increment=$pcorrect;
11496:                    }
11497:                    $sum+=$increment;
11498:                 }
11499:              }
11500:           }
11501:           my $ave=$sum/(100*$realnumber);
11502: # Store
11503:           my ($username,$domain)=split(/\:/,$user);
11504:           my %grades=();
11505:           $grades{"resource.$part.solved"}='correct_by_override';
11506:           $grades{"resource.$part.awarded"}=$ave;
11507:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11508:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11509:                                                  $env{'request.course.id'},
11510:                                                  $domain,$username);
11511:           if ($returncode ne 'ok') {
11512:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11513:           } else {
11514:              $storecount++;
11515:           }
11516:        }
11517:     }
11518: # We are done
11519:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11520:              '</td>'.
11521:              &Apache::loncommon::end_data_table_row().
11522:              &Apache::loncommon::end_data_table();
11523:     return $result;
11524: }
11525: 
11526: sub navmap_errormsg {
11527:     return '<div class="LC_error">'.
11528:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11529:            &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>').
11530:            '</div>';
11531: }
11532: 
11533: sub startpage {
11534:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11535:     my %args;
11536:     if ($onload) {
11537:          my %loaditems = (
11538:                         'onload' => $onload,
11539:                       );
11540:          $args{'add_entries'} = \%loaditems;
11541:     }
11542:     if ($nomenu) {
11543:         $args{'only_body'} = 1; 
11544:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11545:     } else {
11546:         if ($env{'request.course.id'}) { 
11547:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11548:         }
11549:         $args{'bread_crumbs'} = $crumbs;
11550:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11551:         if ($env{'request.course.id'}) {
11552:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11553:         }
11554:     }
11555:     unless ($nodisplayflag) {
11556:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11557:     }
11558: }
11559: 
11560: sub select_problem {
11561:     my ($r)=@_;
11562:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11563:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11564:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11565:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11566: }
11567: 
11568: #----- display problem, answer, and submissions for a single student (no grading)
11569: 
11570: sub view_as_user {
11571:     my ($symb,$vuname,$vudom,$hasperm) = @_;
11572:     my $plainname = &Apache::loncommon::plainname($vuname,$vudom,'lastname');
11573:     my $displayname = &nameUserString('',$plainname,$vuname,$vudom);
11574:     my $output = &Apache::loncommon::get_student_view($symb,$vuname,$vudom,
11575:                                                       $env{'request.course.id'},
11576:                                                       undef,{'disable_submit' => 1}).
11577:                  "\n\n".
11578:                  '<div class="LC_grade_show_user">'.
11579:                  '<h2>'.$displayname.'</h2>'.
11580:                  "\n".
11581:                  &Apache::loncommon::track_student_link('View recent activity',
11582:                                                         $vuname,$vudom,'check').' '.
11583:                  "\n";
11584:     if (&Apache::lonnet::allowed('opa',$env{'request.course.id'}) ||
11585:         (($env{'request.course.sec'} ne '') &&
11586:          &Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
11587:         $output .= &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
11588:                                                $vuname,$vudom,$symb,'check');
11589:     }
11590:     $output .= "\n";
11591:     my $companswer = &Apache::loncommon::get_student_answers($symb,$vuname,$vudom,
11592:                                                              $env{'request.course.id'});
11593:     $companswer=~s|<form(.*?)>||g;
11594:     $companswer=~s|</form>||g;
11595:     $companswer=~s|name="submit"|name="would_have_been_submit"|g;
11596:     $output .= '<div class="LC_Box">'.
11597:                '<h3 class="LC_hcell">'.&mt('Correct answer for[_1]',$displayname).'</h3>'.
11598:                $companswer.
11599:                '</div>'."\n";
11600:     my $is_tool = ($symb =~ /ext\.tool$/);
11601:     my ($essayurl,%coursedesc_by_cid);
11602:     (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
11603:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$vudom,$vuname);
11604:     my $res_error;
11605:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
11606:         &response_type($symb,\$res_error);
11607:     my $fullname;
11608:     my $collabinfo;
11609:     if ($numessay) {
11610:         unless ($hasperm) {
11611:             &init_perm();
11612:         }
11613:         ($collabinfo,$fullname)=
11614:             &check_collaborators($symb,$vuname,$vudom,\%record,$handgrade,0);
11615:         unless ($hasperm) {
11616:             &reset_perm();
11617:         }
11618:     }
11619:     my $checkIcon = '<img alt="'.&mt('Check Mark').
11620:                     '" src="'.$Apache::lonnet::perlvar{'lonIconsURL'}.
11621:                     '/check.gif" height="16" border="0" />';
11622:     my ($lastsubonly,$partinfo) =
11623:         &show_last_submission($vuname,$vudom,$symb,$essayurl,$responseType,'datesub',
11624:                               '',$fullname,\%record,\%coursedesc_by_cid);
11625:     $output .= '<div class="LC_Box">'.
11626:                '<h3 class="LC_hcell">'.&mt('Submissions').'</h3>'."\n".$collabinfo."\n";
11627:     if (($numresp > $numessay) & !$is_tool) {
11628:         $output .='<p class="LC_info">'.
11629:                   &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon).
11630:                   "</p>\n";
11631:     }
11632:     $output .= $partinfo;
11633:     $output .= $lastsubonly;
11634:     $output .= &displaySubByDates($symb,\%record,$partlist,$responseType,$checkIcon,$vuname,$vudom);
11635:     $output .= '</div></div>'."\n";
11636:     return $output;
11637: }
11638: 
11639: sub handler {
11640:     my $request=$_[0];
11641:     &reset_caches();
11642:     if ($request->header_only) {
11643:         &Apache::loncommon::content_type($request,'text/html');
11644:         $request->send_http_header;
11645:         return OK;
11646:     }
11647:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11648: 
11649: # see what command we need to execute
11650: 
11651:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11652:     my $command=$commands[0];
11653: 
11654:     &init_perm();
11655:     if (!$env{'request.course.id'}) {
11656:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11657:                 ($command =~ /^scantronupload/)) {
11658:             # Not in a course.
11659:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11660:             return HTTP_NOT_ACCEPTABLE;
11661:         }
11662:     } elsif (!%perm) {
11663:         $request->internal_redirect('/adm/quickgrades');
11664:         return OK;
11665:     }
11666:     &Apache::loncommon::content_type($request,'text/html');
11667:     $request->send_http_header;
11668: 
11669:     if ($#commands > 0) {
11670: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11671:     }
11672: 
11673: # see what the symb is
11674: 
11675:     my $symb=$env{'form.symb'};
11676:     unless ($symb) {
11677:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11678:        $symb=&Apache::lonnet::symbread($url);
11679:     }
11680:     &Apache::lonenc::check_decrypt(\$symb);
11681: 
11682:     $ssi_error = 0;
11683:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11684: #
11685: # Not called from a resource, but inside a course
11686: #    
11687:         &startpage($request,undef,[],1,1);
11688:         &select_problem($request);
11689:     } else {
11690: 	if ($command eq 'submission' && $perm{'vgr'}) {
11691:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11692:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11693:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11694:                     &choose_task_version_form($symb,$env{'form.student'},
11695:                                               $env{'form.userdom'});
11696:             }
11697:             my $divforres;
11698:             if ($env{'form.student'} eq '') {
11699:                 $js .= &part_selector_js();
11700:                 $onload = "toggleParts('gradesub');";
11701:             } else {
11702:                 $divforres = 1;
11703:             }
11704:             my $head_extra = $js;
11705:             unless ($env{'form.vProb'} eq 'no') {
11706:                 my $csslinks = &Apache::loncommon::css_links($symb);
11707:                 if ($csslinks) {
11708:                     $head_extra .= "\n$csslinks";
11709:                 }
11710:             }
11711:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11712:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11713:             if ($versionform) {
11714:                 if ($divforres) {
11715:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11716:                 }
11717:                 $request->print($versionform);
11718:             }
11719: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11720:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11721:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11722:                 &choose_task_version_form($symb,$env{'form.student'},
11723:                                           $env{'form.userdom'},
11724:                                           $env{'form.inhibitmenu'});
11725:             my $head_extra = $js;
11726:             unless ($env{'form.vProb'} eq 'no') {
11727:                 my $csslinks = &Apache::loncommon::css_links($symb);
11728:                 if ($csslinks) {
11729:                     $head_extra .= "\n$csslinks";
11730:                 }
11731:             }
11732:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11733:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11734:             if ($versionform) {
11735:                 $request->print($versionform);
11736:             }
11737:             $request->print('<br clear="all" />');
11738:             $request->print(&show_previous_task_version($request,$symb));
11739: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11740:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11741:                                        {href=>'',text=>'Select student'}],1,1);
11742: 	    &pickStudentPage($request,$symb);
11743: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11744:             my $csslinks;
11745:             unless ($env{'form.vProb'} eq 'no') {
11746:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11747:             }
11748:             &startpage($request,$symb,
11749:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11750:                                        {href=>'',text=>'Select student'},
11751:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11752: 	    &displayPage($request,$symb);
11753: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11754:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11755:                                        {href=>'',text=>'Select student'},
11756:                                        {href=>'',text=>'Grade student'},
11757:                                        {href=>'',text=>'Store grades'}],1,1);
11758: 	    &updateGradeByPage($request,$symb);
11759: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11760:             my $csslinks;
11761:             unless ($env{'form.vProb'} eq 'no') {
11762:                 $csslinks = &Apache::loncommon::css_links($symb);
11763:             }
11764:             &startpage($request,$symb,[{href=>'',text=>'...'},
11765:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11766: 	    &processGroup($request,$symb);
11767: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11768:             &startpage($request,$symb);
11769: 	    $request->print(&grading_menu($request,$symb));
11770: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11771:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11772: 	    $request->print(&submit_options($request,$symb));
11773:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11774:             my $js = &part_selector_js();
11775:             my $onload = "toggleParts('gradesub');";
11776:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11777:                        undef,undef,undef,undef,undef,$js,$onload);
11778:             $request->print(&listStudents($request,$symb,'graded'));
11779:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11780:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11781:             $request->print(&submit_options_table($request,$symb));
11782:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11783:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11784:             $request->print(&submit_options_sequence($request,$symb));
11785: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11786:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11787: 	    $request->print(&viewgrades($request,$symb));
11788: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11789:             &startpage($request,$symb,[{href=>'',text=>'...'},
11790:                                        {href=>'',text=>'Store grades'}]);
11791: 	    $request->print(&processHandGrade($request,$symb));
11792: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11793:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11794:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11795:                                                                              text=>"Modify grades"},
11796:                                        {href=>'', text=>"Store grades"}]);
11797: 	    $request->print(&editgrades($request,$symb));
11798:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11799:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11800:             $request->print(&initialverifyreceipt($request,$symb));
11801: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11802:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11803:                                        {href=>'',text=>'Verification Result'}]);
11804: 	    $request->print(&verifyreceipt($request,$symb));
11805:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11806:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11807:             $request->print(&process_clicker($request,$symb));
11808:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11809:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11810:                                        {href=>'', text=>'Process clicker file'}]);
11811:             $request->print(&process_clicker_file($request,$symb));
11812:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11813:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11814:                                        {href=>'', text=>'Process clicker file'},
11815:                                        {href=>'', text=>'Store grades'}]);
11816:             $request->print(&assign_clicker_grades($request,$symb));
11817: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11818:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11819: 	    $request->print(&upcsvScores_form($request,$symb));
11820: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11821:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11822: 	    $request->print(&csvupload($request,$symb));
11823: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11824:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11825: 	    $request->print(&csvuploadmap($request,$symb));
11826: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11827: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11828:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11829: 		$request->print(&csvuploadoptions($request,$symb));
11830: 	    } else {
11831: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11832: 		    $env{'form.upfile_associate'} = 'reverse';
11833: 		} else {
11834: 		    $env{'form.upfile_associate'} = 'forward';
11835: 		}
11836:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11837: 		$request->print(&csvuploadmap($request,$symb));
11838: 	    }
11839: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11840:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11841: 	    $request->print(&csvuploadassign($request,$symb));
11842: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11843:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11844:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11845: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11846:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11847:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11848:  	    $request->print(&scantron_do_warning($request,$symb));
11849: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11850:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11851: 	    $request->print(&scantron_validate_file($request,$symb));
11852: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11853:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11854: 	    $request->print(&scantron_process_students($request,$symb));
11855:  	} elsif ($command eq 'scantronupload' && 
11856:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11857:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11858:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11859:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11860:  	} elsif ($command eq 'scantronupload_save' &&
11861:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11862:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11863:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11864:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11865:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11866:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11867:         } elsif ($command eq 'scantronupload_delete' &&
11868:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11869:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11870:             &scantron_upload_delete($request,$symb);
11871:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11872:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11873:             $request->print(&checkscantron_results($request,$symb));
11874:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11875:             my $js = &part_selector_js();
11876:             my $onload = "toggleParts('gradingMenu');";
11877:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11878:                        undef,undef,undef,undef,undef,$js,$onload);
11879:             $request->print(&submit_options_download($request,$symb));
11880:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11881:             &startpage($request,$symb,
11882:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11883:     {href=>'', text=>'Download submitted files'}],
11884:                undef,undef,undef,undef,undef,undef,undef,1);
11885:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11886:             &submit_download_link($request,$symb);
11887: 	} elsif ($command) {
11888:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11889: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11890: 	}
11891:     }
11892:     if ($ssi_error) {
11893: 	&ssi_print_error($request);
11894:     }
11895:     if ($env{'form.inhibitmenu'}) {
11896:         $request->print(&Apache::loncommon::end_page());
11897:     } elsif ($env{'request.course.id'}) {
11898:         &Apache::lonquickgrades::endGradeScreen($request);
11899:     }
11900:     &reset_caches();
11901:     return OK;
11902: }
11903: 
11904: 1;
11905: 
11906: __END__;
11907: 
11908: 
11909: =head1 NAME
11910: 
11911: Apache::grades
11912: 
11913: =head1 SYNOPSIS
11914: 
11915: Handles the viewing of grades.
11916: 
11917: This is part of the LearningOnline Network with CAPA project
11918: described at http://www.lon-capa.org.
11919: 
11920: =head1 OVERVIEW
11921: 
11922: Do an ssi with retries:
11923: While I'd love to factor out this with the version in lonprintout,
11924: 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
11925: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11926: 
11927: At least the logic that drives this has been pulled out into loncommon.
11928: 
11929: 
11930: 
11931: ssi_with_retries - Does the server side include of a resource.
11932:                      if the ssi call returns an error we'll retry it up to
11933:                      the number of times requested by the caller.
11934:                      If we still have a problem, no text is appended to the
11935:                      output and we set some global variables.
11936:                      to indicate to the caller an SSI error occurred.  
11937:                      All of this is supposed to deal with the issues described
11938:                      in LON-CAPA BZ 5631 see:
11939:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11940:                      by informing the user that this happened.
11941: 
11942: Parameters:
11943:   resource   - The resource to include.  This is passed directly, without
11944:                interpretation to lonnet::ssi.
11945:   form       - The form hash parameters that guide the interpretation of the resource
11946:                
11947:   retries    - Number of retries allowed before giving up completely.
11948: Returns:
11949:   On success, returns the rendered resource identified by the resource parameter.
11950: Side Effects:
11951:   The following global variables can be set:
11952:    ssi_error                - If an unrecoverable error occurred this becomes true.
11953:                               It is up to the caller to initialize this to false
11954:                               if desired.
11955:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11956:                               of the resource that could not be rendered by the ssi
11957:                               call.
11958:    ssi_error_message   - The error string fetched from the ssi response
11959:                               in the event of an error.
11960: 
11961: 
11962: =head1 HANDLER SUBROUTINE
11963: 
11964: ssi_with_retries()
11965: 
11966: =head1 SUBROUTINES
11967: 
11968: =over
11969: 
11970: =head1 Routines to display previous version of a Task for a specific student
11971: 
11972: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11973: can receive another opportunity. Access to tasks is slot-based. If a slot
11974: requires a proctor to check-in the student, a new version of the Task will
11975: be created when the student is checked in to the new opportunity.
11976: 
11977: If a particular student has tried two or more versions of a particular task,
11978: the submission screen provides a user with vgr privileges (e.g., a Course
11979: Coordinator) the ability to display a previous version worked on by the
11980: student.  By default, the current version is displayed. If a previous version
11981: has been selected for display, submission data are only shown that pertain
11982: to that particular version, and the interface to submit grades is not shown.
11983: 
11984: =over 4
11985: 
11986: =item show_previous_task_version()
11987: 
11988: Displays a specified version of a student's Task, as the student sees it.
11989: 
11990: Inputs: 2
11991:         request - request object
11992:         symb    - unique symb for current instance of resource
11993: 
11994: Output: None.
11995: 
11996: Side Effects: calls &show_problem() to print version of Task, with
11997:               version contained in form item: $env{'form.previousversion'}
11998: 
11999: =item choose_task_version_form()
12000: 
12001: Displays a web form used to select which version of a student's view of a
12002: Task should be displayed.  Either launches a pop-up window, or replaces
12003: content in existing pop-up, or replaces page in main window.
12004: 
12005: Inputs: 4
12006:         symb    - unique symb for current instance of resource
12007:         uname   - username of student
12008:         udom    - domain of student
12009:         nomenu  - 1 if display is in a pop-up window, and hence no menu
12010:                   breadcrumbs etc., are displayed
12011: 
12012: Output: 4
12013:         current   - student's current version
12014:         displayed - student's version being displayed
12015:         result    - scalar containing HTML for web form used to switch to
12016:                     a different version (or a link to close window, if pop-up).
12017:         js        - javascript for processing selection in versions web form
12018: 
12019: Side Effects: None.
12020: 
12021: =item previous_display_javascript()
12022: 
12023: Inputs: 2
12024:         nomenu  - 1 if display is in a pop-up window, and hence no menu
12025:                   breadcrumbs etc., are displayed.
12026:         current - student's current version number.
12027: 
12028: Output: 1
12029:         js      - javascript for processing selection in versions web form.
12030: 
12031: Side Effects: None.
12032: 
12033: =back
12034: 
12035: =head1 Routines to process bubblesheet data.
12036: 
12037: =over 4
12038: 
12039: =item scantron_get_correction() : 
12040: 
12041:    Builds the interface screen to interact with the operator to fix a
12042:    specific error condition in a specific scanline
12043: 
12044:  Arguments:
12045:     $r           - Apache request object
12046:     $i           - number of the current scanline
12047:     $scan_record - hash ref as returned from &scantron_parse_scanline()
12048:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
12049:     $line        - full contents of the current scanline
12050:     $error       - error condition, valid values are
12051:                    'incorrectCODE', 'duplicateCODE',
12052:                    'doublebubble', 'missingbubble',
12053:                    'duplicateID', 'incorrectID'
12054:     $arg         - extra information needed
12055:        For errors:
12056:          - duplicateID   - paper number that this studentID was seen before on
12057:          - duplicateCODE - array ref of the paper numbers this CODE was
12058:                            seen on before
12059:          - incorrectCODE - current incorrect CODE 
12060:          - doublebubble  - array ref of the bubble lines that have double
12061:                            bubble errors
12062:          - missingbubble - array ref of the bubble lines that have missing
12063:                            bubble errors
12064: 
12065:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
12066:    $randompick  - True if exam folder (or a sub-folder) has randompick set
12067:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
12068:                      for current line to question number used for same question
12069:                      in "Master Seqence" (as seen by Course Coordinator).
12070:    $startline   - Reference to hash where key is question number (0 is first)
12071:                   and value is number of first bubble line for current student
12072:                   or code-based randompick and/or randomorder.
12073: 
12074: 
12075: 
12076: =item  scantron_get_maxbubble() : 
12077: 
12078:    Arguments:
12079:        $nav_error  - Reference to scalar which is a flag to indicate a
12080:                       failure to retrieve a navmap object.
12081:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
12082:        calling routine should trap the error condition and display the warning
12083:        found in &navmap_errormsg().
12084: 
12085:        $scantron_config - Reference to bubblesheet format configuration hash.
12086: 
12087:    Returns the maximum number of bubble lines that are expected to
12088:    occur. Does this by walking the selected sequence rendering the
12089:    resource and then checking &Apache::lonxml::get_problem_counter()
12090:    for what the current value of the problem counter is.
12091: 
12092:    Caches the results to $env{'form.scantron_maxbubble'},
12093:    $env{'form.scantron.bubble_lines.n'}, 
12094:    $env{'form.scantron.first_bubble_line.n'} and
12095:    $env{"form.scantron.sub_bubblelines.n"}
12096:    which are the total number of bubble lines, the number of bubble
12097:    lines for response n and number of the first bubble line for response n,
12098:    and a comma separated list of numbers of bubble lines for sub-questions
12099:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
12100: 
12101: 
12102: =item  scantron_validate_missingbubbles() : 
12103: 
12104:    Validates all scanlines in the selected file to not have any
12105:     answers that don't have bubbles that have not been verified
12106:     to be bubble free.
12107: 
12108: =item  scantron_process_students() : 
12109: 
12110:    Routine that does the actual grading of the bubblesheet information.
12111: 
12112:    The parsed scanline hash is added to %env 
12113: 
12114:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
12115:    foreach resource , with the form data of
12116: 
12117: 	'submitted'     =>'scantron' 
12118: 	'grade_target'  =>'grade',
12119: 	'grade_username'=> username of student
12120: 	'grade_domain'  => domain of student
12121: 	'grade_courseid'=> of course
12122: 	'grade_symb'    => symb of resource to grade
12123: 
12124:     This triggers a grading pass. The problem grading code takes care
12125:     of converting the bubbled letter information (now in %env) into a
12126:     valid submission.
12127: 
12128: =item  scantron_upload_scantron_data() :
12129: 
12130:     Creates the screen for adding a new bubblesheet data file to a course.
12131: 
12132: =item  scantron_upload_scantron_data_save() : 
12133: 
12134:    Adds a provided bubble information data file to the course if user
12135:    has the correct privileges to do so.
12136: 
12137: = item scantron_upload_delete() :
12138: 
12139:    Deletes a previously uploaded bubble information data file, if user
12140:    was the one who uploaded the file, and has the privileges to do so.
12141: 
12142: =item  valid_file() :
12143: 
12144:    Validates that the requested bubble data file exists in the course.
12145: 
12146: =item  scantron_download_scantron_data() : 
12147: 
12148:    Shows a list of the three internal files (original, corrected,
12149:    skipped) for a specific bubblesheet data file that exists in the
12150:    course.
12151: 
12152: =item  scantron_validate_ID() : 
12153: 
12154:    Validates all scanlines in the selected file to not have any
12155:    invalid or underspecified student/employee IDs
12156: 
12157: =item navmap_errormsg() :
12158: 
12159:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
12160:    Should be called whenever the request to instantiate a navmap object fails.
12161: 
12162: =back
12163: 
12164: =back
12165: 
12166: =cut

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