File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.782: download - view: text, annotated - select for diffs
Sat Jan 23 20:24:53 2021 UTC (3 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Be wary of uninitialized package variables in perl modules under mod_perl.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.782 2021/01/23 20:24:53 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:         } else {
 1177:             @sections = &Apache::loncommon::get_env_multiple('form.section');
 1178:         }
 1179:         if (grep(/^all$/,@sections)) {
 1180:             $showmore = 1;
 1181:         } else {
 1182:             foreach my $sec (@sections) {
 1183:                 if (&canmodify($sec)) {
 1184:                     $showmore = 1;
 1185:                     last;
 1186:                 }
 1187:             }
 1188:         }
 1189:     }
 1190: 
 1191:     if ($showmore) {
 1192:         $gradeTable .=
 1193:                    &Apache::lonhtmlcommon::row_closure()
 1194:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1195:                   .'<span class="LC_nobreak">'
 1196:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1197:                   .&mt('No').('&nbsp;'x2).'</label>'
 1198:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1199:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1200:                   .&Apache::lonhtmlcommon::row_closure();
 1201: 
 1202:         $gradeTable .= 
 1203:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1204:                   .'<select name="increment">'
 1205:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1206:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1207:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1208:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1209:                   .'</select>';
 1210:     }
 1211:     $gradeTable .= 
 1212:         &build_section_inputs().
 1213: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1214: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1215: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1216:     if (exists($env{'form.Status'})) {
 1217: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1218:     } else {
 1219:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1220:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1221:                       .&Apache::lonhtmlcommon::StatusOptions(
 1222:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1223:     }
 1224:     if ($numessay) {
 1225:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1226:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1227:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1228:     }
 1229:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1230:                   .&Apache::lonhtmlcommon::end_pick_box();
 1231:     my $regrademsg;
 1232:     if ($is_tool) {
 1233:         $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.");
 1234:     } else {
 1235:         $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.");
 1236:     }
 1237:     $gradeTable .= '<p>'
 1238:                   .$regrademsg."\n"
 1239:                   .'<input type="hidden" name="command" value="processGroup" />'
 1240:                   .'</p>';
 1241: 
 1242: # checkall buttons
 1243:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1244:     $gradeTable.='<input type="button" '."\n".
 1245:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1246:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1247:     $gradeTable.=&check_buttons();
 1248:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1249:     $gradeTable.= &Apache::loncommon::start_data_table().
 1250: 	&Apache::loncommon::start_data_table_header_row();
 1251:     my $loop = 0;
 1252:     while ($loop < 2) {
 1253: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1254: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1255: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1256: 	    foreach my $part (sort(@$partlist)) {
 1257: 		my $display_part=
 1258: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1259: 		$gradeTable.=
 1260: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1261: 	    }
 1262: 	} elsif ($submitonly eq 'queued') {
 1263: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1264: 	}
 1265: 	$loop++;
 1266: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1267:     }
 1268:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1269: 
 1270:     my $ctr = 0;
 1271:     foreach my $student (sort 
 1272: 			 {
 1273: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1274: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1275: 			     }
 1276: 			     return $a cmp $b;
 1277: 			 }
 1278: 			 (keys(%$fullname))) {
 1279: 	my ($uname,$udom) = split(/:/,$student);
 1280: 
 1281: 	my %status = ();
 1282: 
 1283: 	if ($submitonly eq 'queued') {
 1284: 	    my %queue_status = 
 1285: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1286: 							$udom,$uname);
 1287: 	    next if (!defined($queue_status{'gradingqueue'}));
 1288: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1289: 	}
 1290: 
 1291: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1292: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1293: 	    my $submitted = 0;
 1294: 	    my $graded = 0;
 1295: 	    my $incorrect = 0;
 1296: 	    foreach (keys(%status)) {
 1297: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1298: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1299: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1300: 		
 1301: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1302: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1303: 		    $submitted = 0;
 1304: 		    my ($part)=split(/\./,$partid);
 1305: 		    $gradeTable.='<input type="hidden" name="'.
 1306: 			$student.':'.$part.':submitted_by" value="'.
 1307: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1308: 		}
 1309: 	    }
 1310: 	    
 1311: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1312: 				     $submitonly eq 'incorrect' ||
 1313: 				     $submitonly eq 'graded'));
 1314: 	    next if (!$graded && ($submitonly eq 'graded'));
 1315: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1316: 	}
 1317: 
 1318: 	$ctr++;
 1319: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1320:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1321: 	if ( $perm{'vgr'} eq 'F' ) {
 1322: 	    if ($ctr%2 ==1) {
 1323: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1324: 	    }
 1325: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1326:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1327:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1328: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1329: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1330: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1331: 
 1332: 	    if ($submitonly ne 'all') {
 1333: 		foreach (sort(keys(%status))) {
 1334: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1335: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1336: 		}
 1337: 	    }
 1338: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1339: 	    if ($ctr%2 ==0) {
 1340: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1341: 	    }
 1342: 	}
 1343:     }
 1344:     if ($ctr%2 ==1) {
 1345: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1346: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1347: 		foreach (@$partlist) {
 1348: 		    $gradeTable.='<td>&nbsp;</td>';
 1349: 		}
 1350: 	    } elsif ($submitonly eq 'queued') {
 1351: 		$gradeTable.='<td>&nbsp;</td>';
 1352: 	    }
 1353: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1354:     }
 1355: 
 1356:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1357:         '<input type="button" '.
 1358:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1359:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1360:     if ($ctr == 0) {
 1361: 	my $num_students=(scalar(keys(%$fullname)));
 1362: 	if ($num_students eq 0) {
 1363: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1364: 	} else {
 1365: 	    my $submissions='submissions';
 1366: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1367: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1368: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1369: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1370: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1371: 		    $num_students).
 1372: 		'</span><br />';
 1373: 	}
 1374:     } elsif ($ctr == 1) {
 1375: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1376:     }
 1377:     $request->print($gradeTable);
 1378:     return '';
 1379: }
 1380: 
 1381: #---- Called from the listStudents routine
 1382: 
 1383: sub check_script {
 1384:     my ($form,$type) = @_;
 1385:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1386:     function checkall() {
 1387:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1388:             ele = document.forms.'.$form.'.elements[i];
 1389:             if (ele.name == "'.$type.'") {
 1390:             document.forms.'.$form.'.elements[i].checked=true;
 1391:                                        }
 1392:         }
 1393:     }
 1394: 
 1395:     function checksec() {
 1396:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1397:             ele = document.forms.'.$form.'.elements[i];
 1398:            string = document.forms.'.$form.'.chksec.value;
 1399:            if
 1400:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1401:               document.forms.'.$form.'.elements[i].checked=true;
 1402:             }
 1403:         }
 1404:     }
 1405: 
 1406: 
 1407:     function uncheckall() {
 1408:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1409:             ele = document.forms.'.$form.'.elements[i];
 1410:             if (ele.name == "'.$type.'") {
 1411:             document.forms.'.$form.'.elements[i].checked=false;
 1412:                                        }
 1413:         }
 1414:     }
 1415: 
 1416: '."\n");
 1417:     return $chkallscript;
 1418: }
 1419: 
 1420: sub check_buttons {
 1421:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1422:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1423:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1424:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1425:     return $buttons;
 1426: }
 1427: 
 1428: #     Displays the submissions for one student or a group of students
 1429: sub processGroup {
 1430:     my ($request,$symb) = @_;
 1431:     my $ctr        = 0;
 1432:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1433:     my $total      = scalar(@stuchecked)-1;
 1434: 
 1435:     foreach my $student (@stuchecked) {
 1436: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1437: 	$env{'form.student'}        = $uname;
 1438: 	$env{'form.userdom'}        = $udom;
 1439: 	$env{'form.fullname'}       = $fullname;
 1440: 	&submission($request,$ctr,$total,$symb);
 1441: 	$ctr++;
 1442:     }
 1443:     return '';
 1444: }
 1445: 
 1446: #------------------------------------------------------------------------------------
 1447: #
 1448: #-------------------------- Next few routines handles grading by student, essentially
 1449: #                           handles essay response type problem/part
 1450: #
 1451: #--- Javascript to handle the submission page functionality ---
 1452: sub sub_page_js {
 1453:     my $request = shift;
 1454:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1455:     &js_escape(\$alertmsg);
 1456:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1457:     function updateRadio(formname,id,weight) {
 1458: 	var gradeBox = formname["GD_BOX"+id];
 1459: 	var radioButton = formname["RADVAL"+id];
 1460: 	var oldpts = formname["oldpts"+id].value;
 1461: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1462: 	gradeBox.value = pts;
 1463: 	var resetbox = false;
 1464: 	if (isNaN(pts) || pts < 0) {
 1465: 	    alert("$alertmsg"+pts);
 1466: 	    for (var i=0; i<radioButton.length; i++) {
 1467: 		if (radioButton[i].checked) {
 1468: 		    gradeBox.value = i;
 1469: 		    resetbox = true;
 1470: 		}
 1471: 	    }
 1472: 	    if (!resetbox) {
 1473: 		formtextbox.value = "";
 1474: 	    }
 1475: 	    return;
 1476: 	}
 1477: 
 1478: 	if (pts > weight) {
 1479: 	    var resp = confirm("You entered a value ("+pts+
 1480: 			       ") greater than the weight for the part. Accept?");
 1481: 	    if (resp == false) {
 1482: 		gradeBox.value = oldpts;
 1483: 		return;
 1484: 	    }
 1485: 	}
 1486: 
 1487: 	for (var i=0; i<radioButton.length; i++) {
 1488: 	    radioButton[i].checked=false;
 1489: 	    if (pts == i && pts != "") {
 1490: 		radioButton[i].checked=true;
 1491: 	    }
 1492: 	}
 1493: 	updateSelect(formname,id);
 1494: 	formname["stores"+id].value = "0";
 1495:     }
 1496: 
 1497:     function writeBox(formname,id,pts) {
 1498: 	var gradeBox = formname["GD_BOX"+id];
 1499: 	if (checkSolved(formname,id) == 'update') {
 1500: 	    gradeBox.value = pts;
 1501: 	} else {
 1502: 	    var oldpts = formname["oldpts"+id].value;
 1503: 	    gradeBox.value = oldpts;
 1504: 	    var radioButton = formname["RADVAL"+id];
 1505: 	    for (var i=0; i<radioButton.length; i++) {
 1506: 		radioButton[i].checked=false;
 1507: 		if (i == oldpts) {
 1508: 		    radioButton[i].checked=true;
 1509: 		}
 1510: 	    }
 1511: 	}
 1512: 	formname["stores"+id].value = "0";
 1513: 	updateSelect(formname,id);
 1514: 	return;
 1515:     }
 1516: 
 1517:     function clearRadBox(formname,id) {
 1518: 	if (checkSolved(formname,id) == 'noupdate') {
 1519: 	    updateSelect(formname,id);
 1520: 	    return;
 1521: 	}
 1522: 	gradeSelect = formname["GD_SEL"+id];
 1523: 	for (var i=0; i<gradeSelect.length; i++) {
 1524: 	    if (gradeSelect[i].selected) {
 1525: 		var selectx=i;
 1526: 	    }
 1527: 	}
 1528: 	var stores = formname["stores"+id];
 1529: 	if (selectx == stores.value) { return };
 1530: 	var gradeBox = formname["GD_BOX"+id];
 1531: 	gradeBox.value = "";
 1532: 	var radioButton = formname["RADVAL"+id];
 1533: 	for (var i=0; i<radioButton.length; i++) {
 1534: 	    radioButton[i].checked=false;
 1535: 	}
 1536: 	stores.value = selectx;
 1537:     }
 1538: 
 1539:     function checkSolved(formname,id) {
 1540: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1541: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1542: 	    if (!reply) {return "noupdate";}
 1543: 	    formname.overRideScore.value = 'yes';
 1544: 	}
 1545: 	return "update";
 1546:     }
 1547: 
 1548:     function updateSelect(formname,id) {
 1549: 	formname["GD_SEL"+id][0].selected = true;
 1550: 	return;
 1551:     }
 1552: 
 1553: //=========== Check that a point is assigned for all the parts  ============
 1554:     function checksubmit(formname,val,total,parttot) {
 1555: 	formname.gradeOpt.value = val;
 1556: 	if (val == "Save & Next") {
 1557: 	    for (i=0;i<=total;i++) {
 1558: 		for (j=0;j<parttot;j++) {
 1559: 		    var partid = formname["partid"+i+"_"+j].value;
 1560: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1561: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1562: 			if (points == "") {
 1563: 			    var name = formname["name"+i].value;
 1564: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1565: 			    var resp = confirm("You did not assign a score for "+studentID+
 1566: 					       ", part "+partid+". Continue?");
 1567: 			    if (resp == false) {
 1568: 				formname["GD_BOX"+i+"_"+partid].focus();
 1569: 				return false;
 1570: 			    }
 1571: 			}
 1572: 		    }
 1573: 		}
 1574: 	    }
 1575: 	}
 1576: 	formname.submit();
 1577:     }
 1578: 
 1579: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1580:     function checkSubmitPage(formname,total) {
 1581: 	noscore = new Array(100);
 1582: 	var ptr = 0;
 1583: 	for (i=1;i<total;i++) {
 1584: 	    var partid = formname["q_"+i].value;
 1585: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1586: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1587: 		var status = formname["solved"+i+"_"+partid].value;
 1588: 		if (points == "" && status != "correct_by_student") {
 1589: 		    noscore[ptr] = i;
 1590: 		    ptr++;
 1591: 		}
 1592: 	    }
 1593: 	}
 1594: 	if (ptr != 0) {
 1595: 	    var sense = ptr == 1 ? ": " : "s: ";
 1596: 	    var prolist = "";
 1597: 	    if (ptr == 1) {
 1598: 		prolist = noscore[0];
 1599: 	    } else {
 1600: 		var i = 0;
 1601: 		while (i < ptr-1) {
 1602: 		    prolist += noscore[i]+", ";
 1603: 		    i++;
 1604: 		}
 1605: 		prolist += "and "+noscore[i];
 1606: 	    }
 1607: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1608: 	    if (resp == false) {
 1609: 		return false;
 1610: 	    }
 1611: 	}
 1612: 
 1613: 	formname.submit();
 1614:     }
 1615: SUBJAVASCRIPT
 1616: }
 1617: 
 1618: #--- javascript for grading message center
 1619: sub sub_grademessage_js {
 1620:     my $request = shift;
 1621:     my $iconpath = $request->dir_config('lonIconsURL');
 1622:     &commonJSfunctions($request);
 1623: 
 1624:     my $inner_js_msg_central= (<<INNERJS);
 1625: <script type="text/javascript">
 1626:     function checkInput() {
 1627:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1628:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1629:       var usrctr = document.msgcenter.usrctr.value;
 1630:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1631:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1632: 
 1633:       var msgchk = "";
 1634:       if (document.msgcenter.subchk.checked) {
 1635:          msgchk = "msgsub,";
 1636:       }
 1637:       var includemsg = 0;
 1638:       for (var i=1; i<=nmsg; i++) {
 1639:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1640:           var frmmsg = document.msgcenter["msg"+i];
 1641:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1642:           var showflg = opener.document.SCORE["shownOnce"+i];
 1643:           showflg.value = "1";
 1644:           var chkbox = document.msgcenter["msgn"+i];
 1645:           if (chkbox.checked) {
 1646:              msgchk += "savemsg"+i+",";
 1647:              includemsg = 1;
 1648:           }
 1649:       }
 1650:       if (document.msgcenter.newmsgchk.checked) {
 1651:          msgchk += "newmsg"+usrctr;
 1652:          includemsg = 1;
 1653:       }
 1654:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1655:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1656:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1657:       includemsg.value = msgchk;
 1658: 
 1659:       self.close()
 1660: 
 1661:     }
 1662: </script>
 1663: INNERJS
 1664: 
 1665:     my $start_page_msg_central =
 1666:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1667: 				       {'js_ready'  => 1,
 1668: 					'only_body' => 1,
 1669: 					'bgcolor'   =>'#FFFFFF',});
 1670:     my $end_page_msg_central =
 1671: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1672: 
 1673:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1674:     $docopen=~s/^document\.//;
 1675: 
 1676:     my %html_js_lt = &Apache::lonlocal::texthash(
 1677:                 comp => 'Compose Message for: ',
 1678:                 incl => 'Include',
 1679:                 type => 'Type',
 1680:                 subj => 'Subject',
 1681:                 mesa => 'Message',
 1682:                 new  => 'New',
 1683:                 save => 'Save',
 1684:                 canc => 'Cancel',
 1685:              );
 1686:     &html_escape(\%html_js_lt);
 1687:     &js_escape(\%html_js_lt);
 1688:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1689: 
 1690: //===================== Script to view submitted by ==================
 1691:   function viewSubmitter(submitter) {
 1692:     document.SCORE.refresh.value = "on";
 1693:     document.SCORE.NCT.value = "1";
 1694:     document.SCORE.unamedom0.value = submitter;
 1695:     document.SCORE.submit();
 1696:     return;
 1697:   }
 1698: 
 1699: //====================== Script for composing message ==============
 1700:    // preload images
 1701:    img1 = new Image();
 1702:    img1.src = "$iconpath/mailbkgrd.gif";
 1703:    img2 = new Image();
 1704:    img2.src = "$iconpath/mailto.gif";
 1705: 
 1706:   function msgCenter(msgform,usrctr,fullname) {
 1707:     var Nmsg  = msgform.savemsgN.value;
 1708:     savedMsgHeader(Nmsg,usrctr,fullname);
 1709:     var subject = msgform.msgsub.value;
 1710:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1711:     re = /msgsub/;
 1712:     var shwsel = "";
 1713:     if (re.test(msgchk)) { shwsel = "checked" }
 1714:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1715:     displaySubject(checkEntities(subject),shwsel);
 1716:     for (var i=1; i<=Nmsg; i++) {
 1717: 	var testmsg = "savemsg"+i+",";
 1718: 	re = new RegExp(testmsg,"g");
 1719: 	shwsel = "";
 1720: 	if (re.test(msgchk)) { shwsel = "checked" }
 1721: 	var message = document.SCORE["savemsg"+i].value;
 1722: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1723: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1724: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1725:     }
 1726:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1727:     shwsel = "";
 1728:     re = /newmsg/;
 1729:     if (re.test(msgchk)) { shwsel = "checked" }
 1730:     newMsg(newmsg,shwsel);
 1731:     msgTail(); 
 1732:     return;
 1733:   }
 1734: 
 1735:   function checkEntities(strx) {
 1736:     if (strx.length == 0) return strx;
 1737:     var orgStr = ["&", "<", ">", '"']; 
 1738:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1739:     var counter = 0;
 1740:     while (counter < 4) {
 1741: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1742: 	counter++;
 1743:     }
 1744:     return strx;
 1745:   }
 1746: 
 1747:   function strReplace(strx, orgStr, newStr) {
 1748:     return strx.split(orgStr).join(newStr);
 1749:   }
 1750: 
 1751:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1752:     var height = 70*Nmsg+250;
 1753:     if (height > 600) {
 1754: 	height = 600;
 1755:     }
 1756:     var xpos = (screen.width-600)/2;
 1757:     xpos = (xpos < 0) ? '0' : xpos;
 1758:     var ypos = (screen.height-height)/2-30;
 1759:     ypos = (ypos < 0) ? '0' : ypos;
 1760: 
 1761:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1762:     pWin.focus();
 1763:     pDoc = pWin.document;
 1764:     pDoc.$docopen;
 1765:     pDoc.write('$start_page_msg_central');
 1766: 
 1767:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1768:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1769:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1770: 
 1771:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1772:     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>");
 1773: }
 1774:     function displaySubject(msg,shwsel) {
 1775:     pDoc = pWin.document;
 1776:     pDoc.write("<tr>");
 1777:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1778:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1779:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1780: }
 1781: 
 1782:   function displaySavedMsg(ctr,msg,shwsel) {
 1783:     pDoc = pWin.document;
 1784:     pDoc.write("<tr>");
 1785:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1786:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1787:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1788: }
 1789: 
 1790:   function newMsg(newmsg,shwsel) {
 1791:     pDoc = pWin.document;
 1792:     pDoc.write("<tr>");
 1793:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1794:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1795:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1796: }
 1797: 
 1798:   function msgTail() {
 1799:     pDoc = pWin.document;
 1800:     //pDoc.write("<\\/table>");
 1801:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1802:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1803:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1804:     pDoc.write("<\\/form>");
 1805:     pDoc.write('$end_page_msg_central');
 1806:     pDoc.close();
 1807: }
 1808: 
 1809: SUBJAVASCRIPT
 1810: }
 1811: 
 1812: #--- javascript for essay type problem --
 1813: sub sub_page_kw_js {
 1814:     my $request = shift;
 1815: 
 1816:     unless ($env{'form.compmsg'}) {
 1817:         &commonJSfunctions($request);
 1818:     }
 1819: 
 1820:     my $inner_js_highlight_central= (<<INNERJS);
 1821: <script type="text/javascript">
 1822:     function updateChoice(flag) {
 1823:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1824:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1825:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1826:       opener.document.SCORE.refresh.value = "on";
 1827:       if (opener.document.SCORE.keywords.value!=""){
 1828:          opener.document.SCORE.submit();
 1829:       }
 1830:       self.close()
 1831:     }
 1832: </script>
 1833: INNERJS
 1834: 
 1835:     my $start_page_highlight_central =
 1836:         &Apache::loncommon::start_page('Highlight Central',
 1837:                                        $inner_js_highlight_central,
 1838:                                        {'js_ready'  => 1,
 1839:                                         'only_body' => 1,
 1840:                                         'bgcolor'   =>'#FFFFFF',});
 1841:     my $end_page_highlight_central =
 1842:         &Apache::loncommon::end_page({'js_ready' => 1});
 1843: 
 1844:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1845:     $docopen=~s/^document\.//;
 1846: 
 1847:     my %js_lt = &Apache::lonlocal::texthash(
 1848:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1849:                 plse => 'Please select a word or group of words from document and then click this link.',
 1850:                 adds => 'Add selection to keyword list? Edit if desired.',
 1851:                 col1 => 'red',
 1852:                 col2 => 'green',
 1853:                 col3 => 'blue',
 1854:                 siz1 => 'normal',
 1855:                 siz2 => '+1',
 1856:                 siz3 => '+2',
 1857:                 sty1 => 'normal',
 1858:                 sty2 => 'italic',
 1859:                 sty3 => 'bold',
 1860:              );
 1861:     my %html_js_lt = &Apache::lonlocal::texthash(
 1862:                 save => 'Save',
 1863:                 canc => 'Cancel',
 1864:                 kehi => 'Keyword Highlight Options',
 1865:                 txtc => 'Text Color',
 1866:                 font => 'Font Size',
 1867:                 fnst => 'Font Style',
 1868:              );
 1869:     &js_escape(\%js_lt);
 1870:     &html_escape(\%html_js_lt);
 1871:     &js_escape(\%html_js_lt);
 1872:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1873: 
 1874: //===================== Show list of keywords ====================
 1875:   function keywords(formname) {
 1876:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1877:     if (nret==null) return;
 1878:     formname.keywords.value = nret;
 1879: 
 1880:     if (formname.keywords.value != "") {
 1881:         formname.refresh.value = "on";
 1882:         formname.submit();
 1883:     }
 1884:     return;
 1885:   }
 1886: 
 1887: //===================== Script to add keyword(s) ==================
 1888:   function getSel() {
 1889:     if (document.getSelection) txt = document.getSelection();
 1890:     else if (document.selection) txt = document.selection.createRange().text;
 1891:     else return;
 1892:     if (typeof(txt) != 'string') {
 1893:         txt = String(txt);
 1894:     }
 1895:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1896:     if (cleantxt=="") {
 1897:         alert("$js_lt{'plse'}");
 1898:         return;
 1899:     }
 1900:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1901:     if (nret==null) return;
 1902:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1903:     if (document.SCORE.keywords.value != "") {
 1904:         document.SCORE.refresh.value = "on";
 1905:         document.SCORE.submit();
 1906:     }
 1907:     return;
 1908:   }
 1909: 
 1910: //====================== Script for keyword highlight options ==============
 1911:   function kwhighlight() {
 1912:     var kwclr    = document.SCORE.kwclr.value;
 1913:     var kwsize   = document.SCORE.kwsize.value;
 1914:     var kwstyle  = document.SCORE.kwstyle.value;
 1915:     var redsel = "";
 1916:     var grnsel = "";
 1917:     var blusel = "";
 1918:     var txtcol1 = "$js_lt{'col1'}";
 1919:     var txtcol2 = "$js_lt{'col2'}";
 1920:     var txtcol3 = "$js_lt{'col3'}";
 1921:     var txtsiz1 = "$js_lt{'siz1'}";
 1922:     var txtsiz2 = "$js_lt{'siz2'}";
 1923:     var txtsiz3 = "$js_lt{'siz3'}";
 1924:     var txtsty1 = "$js_lt{'sty1'}";
 1925:     var txtsty2 = "$js_lt{'sty2'}";
 1926:     var txtsty3 = "$js_lt{'sty3'}";
 1927:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1928:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1929:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1930:     var sznsel = "";
 1931:     var sz1sel = "";
 1932:     var sz2sel = "";
 1933:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1934:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1935:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1936:     var synsel = "";
 1937:     var syisel = "";
 1938:     var sybsel = "";
 1939:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1940:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1941:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1942:     highlightCentral();
 1943:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1944:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1945:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1946:     highlightend();
 1947:     return;
 1948:   }
 1949: 
 1950:   function highlightCentral() {
 1951: //    if (window.hwdWin) window.hwdWin.close();
 1952:     var xpos = (screen.width-400)/2;
 1953:     xpos = (xpos < 0) ? '0' : xpos;
 1954:     var ypos = (screen.height-330)/2-30;
 1955:     ypos = (ypos < 0) ? '0' : ypos;
 1956: 
 1957:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1958:     hwdWin.focus();
 1959:     var hDoc = hwdWin.document;
 1960:     hDoc.$docopen;
 1961:     hDoc.write('$start_page_highlight_central');
 1962:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1963:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1964: 
 1965:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1966:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1967:   }
 1968: 
 1969:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1970:     var hDoc = hwdWin.document;
 1971:     hDoc.write("<tr>");
 1972:     hDoc.write("<td align=\\"left\\">");
 1973:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1974:     hDoc.write("<td align=\\"left\\">");
 1975:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1976:     hDoc.write("<td align=\\"left\\">");
 1977:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1978:     hDoc.write("<\\/tr>");
 1979:   }
 1980: 
 1981:   function highlightend() { 
 1982:     var hDoc = hwdWin.document;
 1983:     hDoc.write("<\\/table><br \\/>");
 1984:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1985:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1986:     hDoc.write("<\\/form>");
 1987:     hDoc.write('$end_page_highlight_central');
 1988:     hDoc.close();
 1989:   }
 1990: 
 1991: SUBJAVASCRIPT
 1992: }
 1993: 
 1994: sub get_increment {
 1995:     my $increment = $env{'form.increment'};
 1996:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1997:         $increment != .1) {
 1998:         $increment = 1;
 1999:     }
 2000:     return $increment;
 2001: }
 2002: 
 2003: sub gradeBox_start {
 2004:     return (
 2005:         &Apache::loncommon::start_data_table()
 2006:        .&Apache::loncommon::start_data_table_header_row()
 2007:        .'<th>'.&mt('Part').'</th>'
 2008:        .'<th>'.&mt('Points').'</th>'
 2009:        .'<th>&nbsp;</th>'
 2010:        .'<th>'.&mt('Assign Grade').'</th>'
 2011:        .'<th>'.&mt('Weight').'</th>'
 2012:        .'<th>'.&mt('Grade Status').'</th>'
 2013:        .&Apache::loncommon::end_data_table_header_row()
 2014:     );
 2015: }
 2016: 
 2017: sub gradeBox_end {
 2018:     return (
 2019:         &Apache::loncommon::end_data_table()
 2020:     );
 2021: }
 2022: #--- displays the grading box, used in essay type problem and grading by page/sequence
 2023: sub gradeBox {
 2024:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 2025:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2026: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2027:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2028:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2029:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2030:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2031:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2032: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2033:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2034:     my $display_part= &get_display_part($partid,$symb);
 2035:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2036: 				       [$partid]);
 2037:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2038:     if ($last_resets{$partid}) {
 2039:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2040:     }
 2041:     my $result=&Apache::loncommon::start_data_table_row();
 2042:     my $ctr = 0;
 2043:     my $thisweight = 0;
 2044:     my $increment = &get_increment();
 2045: 
 2046:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2047:     while ($thisweight<=$wgt) {
 2048: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2049:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2050: 	    $thisweight.')" value="'.$thisweight.'" '.
 2051: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2052: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2053:         $thisweight += $increment;
 2054: 	$ctr++;
 2055:     }
 2056:     $radio.='</tr></table>';
 2057: 
 2058:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2059: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2060: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2061: 	$wgt.')" /></td>'."\n";
 2062:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2063: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2064: 	' </td>'."\n";
 2065:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2066: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2067:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2068: 	$line.='<option></option>'.
 2069: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2070:     } else {
 2071: 	$line.='<option selected="selected"></option>'.
 2072: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2073:     }
 2074:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2075: 
 2076: 
 2077:     $result .= 
 2078: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2079:     $result.=&Apache::loncommon::end_data_table_row();
 2080:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2081:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2082: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2083: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2084: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2085:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2086:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2087:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2088:         $aggtries.'" />'."\n";
 2089:     my $res_error;
 2090:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2091:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2092:     if ($res_error) {
 2093:         return &navmap_errormsg();
 2094:     }
 2095:     return $result;
 2096: }
 2097: 
 2098: sub handback_box {
 2099:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2100:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2101:     return unless ($numessay);
 2102:     my (@respids);
 2103:     my @part_response_id = &flatten_responseType($responseType);
 2104:     foreach my $part_response_id (@part_response_id) {
 2105:     	my ($part,$resp) = @{ $part_response_id };
 2106:         if ($part eq $partid) {
 2107:             push(@respids,$resp);
 2108:         }
 2109:     }
 2110:     my $result;
 2111:     foreach my $respid (@respids) {
 2112: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2113: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2114: 	next if (!@$files);
 2115: 	my $file_counter = 0;
 2116: 	foreach my $file (@$files) {
 2117: 	    if ($file =~ /\/portfolio\//) {
 2118:                 $file_counter++;
 2119:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2120:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 2121:     	        $file_disp = "$name.$ext";
 2122:     	        $file = $file_path.$file_disp;
 2123:     	        $result.=&mt('Return commented version of [_1] to student.',
 2124:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2125:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2126:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2127: 	    }
 2128: 	}
 2129:         if ($file_counter) {
 2130:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2131:                        '<span class="LC_info">'.
 2132:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2133:         }
 2134:     }
 2135:     return $result;    
 2136: }
 2137: 
 2138: sub show_problem {
 2139:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2140:     my $rendered;
 2141:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2142:     &Apache::lonxml::remember_problem_counter();
 2143:     if ($mode eq 'both' or $mode eq 'text') {
 2144: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2145: 						       $env{'request.course.id'},
 2146: 						       undef,\%form);
 2147:     }
 2148:     if ($removeform) {
 2149: 	$rendered=~s|<form(.*?)>||g;
 2150: 	$rendered=~s|</form>||g;
 2151: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2152:     }
 2153:     my $companswer;
 2154:     if ($mode eq 'both' or $mode eq 'answer') {
 2155: 	&Apache::lonxml::restore_problem_counter();
 2156: 	$companswer=
 2157: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2158: 						    $env{'request.course.id'},
 2159: 						    %form);
 2160:     }
 2161:     if ($removeform) {
 2162: 	$companswer=~s|<form(.*?)>||g;
 2163: 	$companswer=~s|</form>||g;
 2164: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2165:     }
 2166:     my $renderheading = &mt('View of the problem');
 2167:     my $answerheading = &mt('Correct answer');
 2168:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2169:         my $stu_fullname = $env{'form.fullname'};
 2170:         if ($stu_fullname eq '') {
 2171:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2172:         }
 2173:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2174:         if ($forwhom ne '') {
 2175:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2176:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2177:         }
 2178:     }
 2179:     $rendered=
 2180:         '<div class="LC_Box">'
 2181:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2182:        .$rendered
 2183:        .'</div>';
 2184:     $companswer=
 2185:         '<div class="LC_Box">'
 2186:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2187:        .$companswer
 2188:        .'</div>';
 2189:     my $result;
 2190:     if ($mode eq 'both') {
 2191:         $result=$rendered.$companswer;
 2192:     } elsif ($mode eq 'text') {
 2193:         $result=$rendered;
 2194:     } elsif ($mode eq 'answer') {
 2195:         $result=$companswer;
 2196:     }
 2197:     return $result;
 2198: }
 2199: 
 2200: sub files_exist {
 2201:     my ($r, $symb) = @_;
 2202:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2203:     foreach my $student (@students) {
 2204:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2205:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2206: 					      $udom,$uname);
 2207:         my ($string,$timestamp)= &get_last_submission(\%record);
 2208:         foreach my $submission (@$string) {
 2209:             my ($partid,$respid) =
 2210: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2211:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2212: 					   \%record);
 2213:             return 1 if (@$files);
 2214:         }
 2215:     }
 2216:     return 0;
 2217: }
 2218: 
 2219: sub download_all_link {
 2220:     my ($r,$symb) = @_;
 2221:     unless (&files_exist($r, $symb)) {
 2222:         $r->print(&mt('There are currently no submitted documents.'));
 2223:         return;
 2224:     }
 2225:     my $all_students = 
 2226: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2227: 
 2228:     my $parts =
 2229: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2230: 
 2231:     my $identifier = &Apache::loncommon::get_cgi_id();
 2232:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2233:                              'cgi.'.$identifier.'.symb' => $symb,
 2234:                              'cgi.'.$identifier.'.parts' => $parts,});
 2235:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2236: 	      &mt('Download All Submitted Documents').'</a>');
 2237:     return;
 2238: }
 2239: 
 2240: sub submit_download_link {
 2241:     my ($request,$symb) = @_;
 2242:     if (!$symb) { return ''; }
 2243:     my $res_error;
 2244:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2245:         &response_type($symb,\$res_error);
 2246:     if ($res_error) {
 2247:         $request->print(&mt('An error occurred retrieving response types'));
 2248:         return;
 2249:     }
 2250:     unless ($numessay) {
 2251:         $request->print(&mt('No essayresponse items found'));
 2252:         return;
 2253:     }
 2254:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2255:     if (@chosenparts) {
 2256:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2257:                                           undef,undef,1));
 2258:     }
 2259:     if ($numessay) {
 2260:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2261:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2262:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2263:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2264:         if (ref($fullname) eq 'HASH') {
 2265:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2266:             if (@students) {
 2267:                 @{$env{'form.stuinfo'}} = @students;
 2268:                 if ($numdropbox) {
 2269:                     &download_all_link($request,$symb);
 2270:                 } else {
 2271:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2272:                 }
 2273: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2274: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2275:             } else {
 2276:                 $request->print(&mt('No students match the criteria you selected'));
 2277:             }
 2278:         } else {
 2279:             $request->print(&mt('Could not retrieve student information'));
 2280:         }
 2281:     } else {
 2282:         $request->print(&mt('No essayresponse items found'));
 2283:     }
 2284:     return;
 2285: }
 2286: 
 2287: sub build_section_inputs {
 2288:     my $section_inputs;
 2289:     if ($env{'form.section'} eq '') {
 2290:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2291:     } else {
 2292:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2293:         foreach my $section (@sections) {
 2294:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2295:         }
 2296:     }
 2297:     return $section_inputs;
 2298: }
 2299: 
 2300: # --------------------------- show submissions of a student, option to grade 
 2301: sub submission {
 2302:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2303:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2304:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2305:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2306:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2307: 
 2308:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2309:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2310:     my $is_tool = ($symb =~ /ext\.tool$/);
 2311:     my ($essayurl,%coursedesc_by_cid);
 2312: 
 2313:     if (!&canview($usec)) {
 2314:         $request->print(
 2315:             '<span class="LC_warning">'.
 2316:             &mt('Unable to view requested student.').
 2317:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2318:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2319:             '</span>');
 2320: 	return;
 2321:     }
 2322: 
 2323:     my $res_error;
 2324:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2325:         &response_type($symb,\$res_error);
 2326:     if ($res_error) {
 2327:         $request->print(&navmap_errormsg());
 2328:         return;
 2329:     }
 2330: 
 2331:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2332:     unless ($is_tool) { 
 2333:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2334:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2335:     }
 2336:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2337:         $env{'form.compmsg'} = 1;
 2338:     }
 2339:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2340:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2341: 	'" src="'.$request->dir_config('lonIconsURL').
 2342: 	'/check.gif" height="16" border="0" />';
 2343: 
 2344:     # header info
 2345:     if ($counter == 0) {
 2346:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2347:         if (@chosenparts) {
 2348:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2349:         } elsif ($divforres) {
 2350:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2351:         } else {
 2352:             $request->print('<br clear="all" />');
 2353:         }
 2354: 	&sub_page_js($request);
 2355:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2356: 	&sub_page_kw_js($request) if ($numessay);
 2357: 
 2358: 	# option to display problem, only once else it cause problems 
 2359:         # with the form later since the problem has a form.
 2360: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2361: 	    my $mode;
 2362: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2363: 		$mode='both';
 2364: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2365: 		$mode='text';
 2366: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2367: 		$mode='answer';
 2368: 	    }
 2369: 	    &Apache::lonxml::clear_problem_counter();
 2370: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2371: 	}
 2372: 
 2373: 	my %keyhash = ();
 2374: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2375: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2376: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2377: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2378: 	}
 2379: 	# kwclr is the only variable that is guaranteed not to be blank
 2380: 	# if this subroutine has been called once.
 2381: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2382: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2383: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2384: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2385: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2386: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2387: 	}
 2388: 	if ($env{'form.compmsg'}) {
 2389: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2390: 		$keyhash{$symb.'_subject'} : $probtitle;
 2391: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2392: 	}
 2393: 
 2394: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2395: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2396: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2397: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2398: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2399: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2400: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2401: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2402: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2403: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2404: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2405: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2406: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2407: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2408: 			&build_section_inputs().
 2409: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2410: 			'<input type="hidden" name="NCT"'.
 2411: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2412: 	if ($env{'form.compmsg'}) {
 2413: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2414: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2415: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2416: 	}
 2417: 	if ($numessay) {
 2418: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2419: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2420: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2421: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2422: 	}
 2423: 
 2424: 	my ($cts,$prnmsg) = (1,'');
 2425: 	while ($cts <= $env{'form.savemsgN'}) {
 2426: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2427: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2428: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2429: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2430: 		'" />'."\n".
 2431: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2432: 	    $cts++;
 2433: 	}
 2434: 	$request->print($prnmsg);
 2435: 
 2436: 	if ($numessay) {
 2437: 
 2438:             my %lt = &Apache::lonlocal::texthash(
 2439:                           keyh => 'Keyword Highlighting for Essays',
 2440:                           keyw => 'Keyword Options',
 2441:                           list => 'List',
 2442:                           past => 'Paste Selection to List',
 2443:                           high => 'Highlight Attribute',
 2444:                      );
 2445: #
 2446: # Print out the keyword options line
 2447: #
 2448: 	    $request->print(
 2449:                 '<div class="LC_columnSection">'
 2450:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2451:                .&Apache::lonhtmlcommon::funclist_from_array(
 2452:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2453:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2454:  class="page">'.$lt{'past'}.'</a>',
 2455:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2456:                     {legend => $lt{'keyw'}})
 2457:                .'</fieldset></div>'
 2458:             );
 2459: 
 2460: #
 2461: # Load the other essays for similarity check
 2462: #
 2463:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2464:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2465:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2466:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2467:                 if ($cdom ne '' && $cnum ne '') {
 2468:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2469:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2470:                         my $apath = $1.'_'.$id;
 2471:                         $apath=~s/\W/\_/gs;
 2472:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2473:                     }
 2474:                 }
 2475:             } else {
 2476: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2477: 	        $apath=&escape($apath);
 2478: 	        $apath=~s/\W/\_/gs;
 2479:                 &init_old_essays($symb,$apath,$adom,$aname);
 2480:             }
 2481:         }
 2482:     }
 2483: 
 2484: # This is where output for one specific student would start
 2485:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2486:     $request->print(
 2487:         "\n\n"
 2488:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2489:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2490:        ."\n"
 2491:     );
 2492: 
 2493:     # Show additional functions if allowed
 2494:     if ($perm{'vgr'}) {
 2495:         $request->print(
 2496:             &Apache::loncommon::track_student_link(
 2497:                 'View recent activity',
 2498:                 $uname,$udom,'check')
 2499:            .' '
 2500:         );
 2501:     }
 2502:     if ($perm{'opa'}) {
 2503:         $request->print(
 2504:             &Apache::loncommon::pprmlink(
 2505:                 &mt('Set/Change parameters'),
 2506:                 $uname,$udom,$symb,'check'));
 2507:     }
 2508: 
 2509:     # Show Problem
 2510:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2511: 	my $mode;
 2512: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2513: 	    $mode='both';
 2514: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2515: 	    $mode='text';
 2516: 	} elsif ($env{'form.vAns'} eq 'all') {
 2517: 	    $mode='answer';
 2518: 	}
 2519: 	&Apache::lonxml::clear_problem_counter();
 2520: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2521:     }
 2522: 
 2523:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2524: 
 2525:     # Display student info
 2526:     $request->print(($counter == 0 ? '' : '<br />'));
 2527: 
 2528:     my $boxtitle = &mt('Submissions');
 2529:     if ($is_tool) {
 2530:         $boxtitle = &mt('Transactions')
 2531:     }
 2532:     my $result='<div class="LC_Box">'
 2533:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2534:     $result.='<input type="hidden" name="name'.$counter.
 2535:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2536:     if (($numresp > $numessay) && !$is_tool) {
 2537:         $result.='<p class="LC_info">'
 2538:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2539:                 ."</p>\n";
 2540:     }
 2541: 
 2542:     # If any part of the problem is an essayresponse, then check for collaborators
 2543:     my $fullname;
 2544:     my $col_fullnames = [];
 2545:     if ($numessay) {
 2546: 	(my $sub_result,$fullname,$col_fullnames)=
 2547: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2548: 				 $counter);
 2549: 	$result.=$sub_result;
 2550:     }
 2551:     $request->print($result."\n");
 2552: 
 2553:     # print student answer/submission
 2554:     # Options are (1) Last submission only
 2555:     #             (2) Last submission (with detailed information for that submission)
 2556:     #             (3) All transactions (by date)
 2557:     #             (4) The whole record (with detailed information for all transactions)
 2558: 
 2559:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2560: 
 2561:     my $lastsubonly;
 2562: 
 2563:     if ($$timestamp eq '') {
 2564:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2565:     } elsif ($is_tool) {
 2566:         $lastsubonly =
 2567:             '<div class="LC_grade_submissions_body">'
 2568:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2569:     } else {
 2570:         $lastsubonly =
 2571:             '<div class="LC_grade_submissions_body">'
 2572:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2573: 
 2574: 	my %seenparts;
 2575: 	my @part_response_id = &flatten_responseType($responseType);
 2576: 	foreach my $part (@part_response_id) {
 2577: 	    my ($partid,$respid) = @{ $part };
 2578: 	    my $display_part=&get_display_part($partid,$symb);
 2579: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2580: 		if (exists($seenparts{$partid})) { next; }
 2581: 		$seenparts{$partid}=1;
 2582:                 $request->print(
 2583:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2584:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2585:                                '<a href="javascript:viewSubmitter(\''.
 2586:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2587:                                '\');" target="_self">'.
 2588:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2589:                     '<br />');
 2590: 		next;
 2591: 	    }
 2592: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2593: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2594:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2595:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2596:                     ' <span class="LC_internal_info">'.
 2597:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2598:                     '</span>&nbsp; &nbsp;'.
 2599: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2600: 		next;
 2601: 	    }
 2602: 	    foreach my $submission (@$string) {
 2603: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2604: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2605: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2606: 		# Similarity check
 2607:                 my $similar='';
 2608:                 my ($type,$trial,$rndseed);
 2609:                 if ($hide eq 'rand') {
 2610:                     $type = 'randomizetry';
 2611:                     $trial = $record{"resource.$partid.tries"};
 2612:                     $rndseed = $record{"resource.$partid.rndseed"};
 2613:                 }
 2614: 	        if ($env{'form.checkPlag'}) {
 2615: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2616: 		    &most_similar($uname,$udom,$symb,$subval);
 2617: 		    if ($osim) {
 2618: 			$osim=int($osim*100.0);
 2619:                         if ($hide eq 'anon') {
 2620:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2621:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2622:                         } else {
 2623: 			    $similar='<hr />';
 2624:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2625:                                 $similar .= '<h3><span class="LC_warning">'.
 2626:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2627:                                                 $osim,
 2628:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2629:                                             '</span></h3>';
 2630:                             } else {
 2631:                                 my %old_course_desc;
 2632:                                 if ($ocrsid ne '') {
 2633:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2634:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2635:                                     } else {
 2636:                                         my $args;
 2637:                                         if ($ocrsid ne $env{'request.course.id'}) {
 2638:                                             $args = {'one_time' => 1};
 2639:                                         }
 2640:                                         %old_course_desc =
 2641:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
 2642:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2643:                                     }
 2644:                                     $similar .=
 2645:                                         '<h3><span class="LC_warning">'.
 2646:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2647:                                             $osim,
 2648:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2649:                                             $old_course_desc{'description'},
 2650:                                             $old_course_desc{'num'},
 2651:                                             $old_course_desc{'domain'}).
 2652:                                         '</span></h3>';
 2653:                                 } else {
 2654:                                     $similar .=
 2655:                                         '<h3><span class="LC_warning">'.
 2656:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2657:                                             $osim,
 2658:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2659:                                         '</span></h3>';
 2660:                                 }
 2661:                             }
 2662:                             $similar .= '<blockquote><i>'.
 2663:                                         &keywords_highlight($oessay).
 2664:                                         '</i></blockquote><hr />';
 2665:                         }
 2666: 	            }
 2667: 		}
 2668: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2669:                                      undef,$type,$trial,$rndseed);
 2670:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2671:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2672:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2673: 		    my $display_part=&get_display_part($partid,$symb);
 2674:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2675:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2676:                         ' <span class="LC_internal_info">'.
 2677:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2678:                         '</span>&nbsp; &nbsp;';
 2679: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2680: 		    if (@$files) {
 2681:                         if ($hide eq 'anon') {
 2682:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2683:                         } else {
 2684:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2685:                                         .'<br /><span class="LC_warning">';
 2686:                             if(@$files == 1) {
 2687:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2688:                             } else {
 2689:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2690:                             }
 2691:                             $lastsubonly .= '</span>';
 2692:                             foreach my $file (@$files) {
 2693:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2694:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2695:                             }
 2696:                         }
 2697: 			$lastsubonly.='<br />';
 2698:                     }
 2699:                     if ($hide eq 'anon') {
 2700:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2701:                     } else {
 2702:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2703:                         if ($draft) {
 2704:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2705:                         }
 2706:                         $subval =
 2707: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2708: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2709:                         if ($responsetype eq 'essay') {
 2710:                             $subval =~ s{\n}{<br />}g;
 2711:                         }
 2712:                         $lastsubonly.=$subval."\n";
 2713:                     }
 2714:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2715: 		    $lastsubonly.='</div>';
 2716: 		}
 2717:             }
 2718: 	}
 2719: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2720:     }
 2721:     $request->print($lastsubonly);
 2722:     if ($env{'form.lastSub'} eq 'datesub') {
 2723:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2724: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2725:     }
 2726:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2727:         my $identifier = (&canmodify($usec)? $counter : '');
 2728:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2729: 								 $env{'request.course.id'},
 2730: 								 $last,'.submission',
 2731: 								 'Apache::grades::keywords_highlight',
 2732:                                                                  $usec,$identifier));
 2733:     }
 2734:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2735: 	.$udom.'" />'."\n");
 2736:     # return if view submission with no grading option
 2737:     if (!&canmodify($usec)) {
 2738: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2739: 	return;
 2740:     } else {
 2741: 	$request->print('</div>'."\n");
 2742:     }
 2743: 
 2744:     # grading message center
 2745: 
 2746:     if ($env{'form.compmsg'}) {
 2747:         my $result='<div class="LC_Box">'.
 2748:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2749:                    '<div class="LC_grade_message_center_body">';
 2750:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2751:         my $msgfor = $givenn.' '.$lastname;
 2752:         if (scalar(@$col_fullnames) > 0) {
 2753:             my $lastone = pop(@$col_fullnames);
 2754:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2755:         }
 2756:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2757:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2758:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2759:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2760:                  ',\''.$msgfor.'\');" target="_self">'.
 2761:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2762:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2763:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2764:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2765:                  '<br />&nbsp;('.
 2766:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2767:                  '</div></div>';
 2768:         $request->print($result);
 2769:     }
 2770: 
 2771:     my %seen = ();
 2772:     my @partlist;
 2773:     my @gradePartRespid;
 2774:     my @part_response_id;
 2775:     if ($is_tool) {
 2776:         @part_response_id = ([0,'']);
 2777:     } else {
 2778:         @part_response_id = &flatten_responseType($responseType);
 2779:     }
 2780:     $request->print(
 2781:         '<div class="LC_Box">'
 2782:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2783:     );
 2784:     $request->print(&gradeBox_start());
 2785:     foreach my $part_response_id (@part_response_id) {
 2786:     	my ($partid,$respid) = @{ $part_response_id };
 2787: 	my $part_resp = join('_',@{ $part_response_id });
 2788: 	next if ($seen{$partid} > 0);
 2789: 	$seen{$partid}++;
 2790: 	push(@partlist,$partid);
 2791: 	push(@gradePartRespid,$partid.'.'.$respid);
 2792: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2793:     }
 2794:     $request->print(&gradeBox_end()); # </div>
 2795:     $request->print('</div>');
 2796: 
 2797:     $request->print('<div class="LC_grade_info_links">');
 2798:     $request->print('</div>');
 2799: 
 2800:     $result='<input type="hidden" name="partlist'.$counter.
 2801: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2802:     $result.='<input type="hidden" name="gradePartRespid'.
 2803: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2804:     my $ctr = 0;
 2805:     while ($ctr < scalar(@partlist)) {
 2806: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2807: 	    $partlist[$ctr].'" />'."\n";
 2808: 	$ctr++;
 2809:     }
 2810:     $request->print($result.''."\n");
 2811: 
 2812: # Done with printing info for one student
 2813: 
 2814:     $request->print('</div>');#LC_grade_show_user
 2815: 
 2816: 
 2817:     # print end of form
 2818:     if ($counter == $total) {
 2819:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2820: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2821: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2822: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2823: 	my $ntstu ='<select name="NTSTU">'.
 2824: 	    '<option>1</option><option>2</option>'.
 2825: 	    '<option>3</option><option>5</option>'.
 2826: 	    '<option>7</option><option>10</option></select>'."\n";
 2827: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2828: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2829:         $endform.=&mt('[_1]student(s)',$ntstu);
 2830: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2831: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2832: 	    '<input type="button" value="'.&mt('Next').'" '.
 2833: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2834:         $endform.='<span class="LC_warning">'.
 2835:                   &mt('(Next and Previous (student) do not save the scores.)').
 2836:                   '</span>'."\n" ;
 2837:         $endform.="<input type='hidden' value='".&get_increment().
 2838:             "' name='increment' />";
 2839: 	$endform.='</td></tr></table></form>';
 2840: 	$request->print($endform);
 2841:     }
 2842:     return '';
 2843: }
 2844: 
 2845: sub check_collaborators {
 2846:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2847:     my ($result,@col_fullnames);
 2848:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2849:     foreach my $part (keys(%$handgrade)) {
 2850: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2851: 					'.maxcollaborators',
 2852: 					$symb,$udom,$uname);
 2853: 	next if ($ncol <= 0);
 2854: 	$part =~ s/\_/\./g;
 2855: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2856: 	my (@good_collaborators, @bad_collaborators);
 2857: 	foreach my $possible_collaborator
 2858: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2859: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2860: 	    next if ($possible_collaborator eq '');
 2861: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2862: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2863: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2864: 	    # Doing this grep allows 'fuzzy' specification
 2865: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2866: 			       keys(%$classlist));
 2867: 	    if (! scalar(@matches)) {
 2868: 		push(@bad_collaborators, $possible_collaborator);
 2869: 	    } else {
 2870: 		push(@good_collaborators, @matches);
 2871: 	    }
 2872: 	}
 2873: 	if (scalar(@good_collaborators) != 0) {
 2874: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2875: 	    foreach my $name (@good_collaborators) {
 2876: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2877: 		push(@col_fullnames, $givenn.' '.$lastname);
 2878: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2879: 	    }
 2880: 	    $result.='</ol><br />'."\n";
 2881: 	    my ($part)=split(/\./,$part);
 2882: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2883: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2884: 		"\n";
 2885: 	}
 2886: 	if (scalar(@bad_collaborators) > 0) {
 2887: 	    $result.='<div class="LC_warning">';
 2888: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2889: 	    $result .= '</div>';
 2890: 	}         
 2891: 	if (scalar(@bad_collaborators > $ncol)) {
 2892: 	    $result .= '<div class="LC_warning">';
 2893: 	    $result .= &mt('This student has submitted too many '.
 2894: 		'collaborators.  Maximum is [_1].',$ncol);
 2895: 	    $result .= '</div>';
 2896: 	}
 2897:     }
 2898:     return ($result,$fullname,\@col_fullnames);
 2899: }
 2900: 
 2901: #--- Retrieve the last submission for all the parts
 2902: sub get_last_submission {
 2903:     my ($returnhash,$is_tool)=@_;
 2904:     my (@string,$timestamp,%lasthidden);
 2905:     if ($$returnhash{'version'}) {
 2906: 	my %lasthash=();
 2907: 	my ($version);
 2908: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2909: 	    foreach my $key (sort(split(/\:/,
 2910: 					$$returnhash{$version.':keys'}))) {
 2911: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2912: 		$timestamp = 
 2913: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2914: 	    }
 2915: 	}
 2916:         my (%typeparts,%randombytry);
 2917:         my $showsurv = 
 2918:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2919:         foreach my $key (sort(keys(%lasthash))) {
 2920:             if ($key =~ /\.type$/) {
 2921:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2922:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2923:                     ($lasthash{$key} eq 'randomizetry')) {
 2924:                     my ($ign,@parts) = split(/\./,$key);
 2925:                     pop(@parts);
 2926:                     my $id = join('.',@parts);
 2927:                     if ($lasthash{$key} eq 'randomizetry') {
 2928:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2929:                     } else {
 2930:                         unless ($showsurv) {
 2931:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2932:                         }
 2933:                     }
 2934:                     delete($lasthash{$key});
 2935:                 }
 2936:             }
 2937:         }
 2938:         my @hidden = keys(%typeparts);
 2939:         my @randomize = keys(%randombytry);
 2940: 	foreach my $key (keys(%lasthash)) {
 2941: 	    next if ($key !~ /\.submission$/);
 2942:             my $hide;
 2943:             if (@hidden) {
 2944:                 foreach my $id (@hidden) {
 2945:                     if ($key =~ /^\Q$id\E/) {
 2946:                         $hide = 'anon';
 2947:                         last;
 2948:                     }
 2949:                 }
 2950:             }
 2951:             unless ($hide) {
 2952:                 if (@randomize) {
 2953:                     foreach my $id (@randomize) {
 2954:                         if ($key =~ /^\Q$id\E/) {
 2955:                             $hide = 'rand';
 2956:                             last;
 2957:                         }
 2958:                     }
 2959:                 }
 2960:             }
 2961: 	    my ($partid,$foo) = split(/submission$/,$key);
 2962: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2963:             push(@string, join(':', $key, $hide, $draft, (
 2964:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2965:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2966: 	}
 2967:     }
 2968:     if (!@string) {
 2969:         my $msg;
 2970:         if ($is_tool) {
 2971:             $msg = &mt('No grade passed back.');
 2972:         } else {
 2973:             $msg = &mt('Nothing submitted - no attempts.');
 2974:         }
 2975: 	$string[0] =
 2976: 	    '<span class="LC_warning">'.$msg.'</span>';
 2977:     }
 2978:     return (\@string,\$timestamp);
 2979: }
 2980: 
 2981: #--- High light keywords, with style choosen by user.
 2982: sub keywords_highlight {
 2983:     my $string    = shift;
 2984:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2985:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2986:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2987:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2988:     foreach my $keyword (@keylist) {
 2989: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2990:     }
 2991:     return $string;
 2992: }
 2993: 
 2994: # For Tasks provide a mechanism to display previous version for one specific student
 2995: 
 2996: sub show_previous_task_version {
 2997:     my ($request,$symb) = @_;
 2998:     if ($symb eq '') {
 2999:         $request->print(
 3000:             '<span class="LC_error">'.
 3001:             &mt('Unable to handle ambiguous references.').
 3002:             '</span>');
 3003:         return '';
 3004:     }
 3005:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 3006:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 3007:     if (!&canview($usec)) {
 3008:         $request->print(
 3009:             '<span class="LC_warning">'.
 3010:             &mt('Unable to view previous version for requested student.').
 3011:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 3012:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 3013:             '</span>');
 3014:         return;
 3015:     }
 3016:     my $mode = 'both';
 3017:     my $isTask = ($symb =~/\.task$/);
 3018:     if ($isTask) {
 3019:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 3020:             if ($env{'form.fullname'} eq '') {
 3021:                 $env{'form.fullname'} =
 3022:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 3023:             }
 3024:             my $probtitle=&Apache::lonnet::gettitle($symb);
 3025:             $request->print("\n\n".
 3026:                             '<div class="LC_grade_show_user">'.
 3027:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3028:                             '</h2>'."\n");
 3029:             &Apache::lonxml::clear_problem_counter();
 3030:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 3031:                             {'previousversion' => $env{'form.previousversion'} }));
 3032:             $request->print("\n</div>");
 3033:         }
 3034:     }
 3035:     return;
 3036: }
 3037: 
 3038: sub choose_task_version_form {
 3039:     my ($symb,$uname,$udom,$nomenu) = @_;
 3040:     my $isTask = ($symb =~/\.task$/);
 3041:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3042:     if ($isTask) {
 3043:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3044:                                               $udom,$uname);
 3045:         if (($record{'resource.0.version'} eq '') ||
 3046:             ($record{'resource.0.version'} < 2)) {
 3047:             return ($record{'resource.0.version'},
 3048:                     $record{'resource.0.version'},$result,$js);
 3049:         } else {
 3050:             $current = $record{'resource.0.version'};
 3051:         }
 3052:         if ($env{'form.previousversion'}) {
 3053:             $displayed = $env{'form.previousversion'};
 3054:             $rowtitle = &mt('Choose another version:')
 3055:         } else {
 3056:             $displayed = $current;
 3057:             $rowtitle = &mt('Show earlier version:');
 3058:         }
 3059:         $result = '<div class="LC_left_float">';
 3060:         my $list;
 3061:         my $numversions = 0;
 3062:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3063:             if ($i == $current) {
 3064:                 if (!$env{'form.previousversion'} || $nomenu) {
 3065:                     next;
 3066:                 } else {
 3067:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3068:                     $numversions ++;
 3069:                 }
 3070:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3071:                 unless ($i == $env{'form.previousversion'}) {
 3072:                     $numversions ++;
 3073:                 }
 3074:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3075:             }
 3076:         }
 3077:         if ($numversions) {
 3078:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3079:             $result .=
 3080:                 '<form name="getprev" method="post" action=""'.
 3081:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3082:                 &Apache::loncommon::start_data_table().
 3083:                 &Apache::loncommon::start_data_table_row().
 3084:                 '<th align="left">'.$rowtitle.'</th>'.
 3085:                 '<td><select name="version">'.
 3086:                 '<option>'.&mt('Select').'</option>'.
 3087:                 $list.
 3088:                 '</select></td>'.
 3089:                 &Apache::loncommon::end_data_table_row();
 3090:             unless ($nomenu) {
 3091:                 $result .= &Apache::loncommon::start_data_table_row().
 3092:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3093:                 '<td><span class="LC_nobreak">'.
 3094:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3095:                 &mt('Yes').'</label>'.
 3096:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3097:                 '</span></td>'.
 3098:                 &Apache::loncommon::end_data_table_row();
 3099:             }
 3100:             $result .=
 3101:                 &Apache::loncommon::start_data_table_row().
 3102:                 '<th align="left">&nbsp;</th>'.
 3103:                 '<td>'.
 3104:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3105:                 '</td>'.
 3106:                 &Apache::loncommon::end_data_table_row().
 3107:                 &Apache::loncommon::end_data_table().
 3108:                 '</form>';
 3109:             $js = &previous_display_javascript($nomenu,$current);
 3110:         } elsif ($displayed && $nomenu) {
 3111:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3112:         } else {
 3113:             $result .= &mt('No previous versions to show for this student');
 3114:         }
 3115:         $result .= '</div>';
 3116:     }
 3117:     return ($current,$displayed,$result,$js);
 3118: }
 3119: 
 3120: sub previous_display_javascript {
 3121:     my ($nomenu,$current) = @_;
 3122:     my $js = <<"JSONE";
 3123: <script type="text/javascript">
 3124: // <![CDATA[
 3125: function previousVersion(uname,udom,symb) {
 3126:     var current = '$current';
 3127:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3128:     var prevstr = new RegExp("^\\\\d+\$");
 3129:     if (!prevstr.test(version)) {
 3130:         return false;
 3131:     }
 3132:     var url = '';
 3133:     if (version == current) {
 3134:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3135:     } else {
 3136:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3137:     }
 3138: JSONE
 3139:     if ($nomenu) {
 3140:         $js .= <<"JSTWO";
 3141:     document.location.href = url;
 3142: JSTWO
 3143:     } else {
 3144:         $js .= <<"JSTHREE";
 3145:     var newwin = 0;
 3146:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3147:         if (document.getprev.prevwin[i].checked == true) {
 3148:             newwin = document.getprev.prevwin[i].value;
 3149:         }
 3150:     }
 3151:     if (newwin == 1) {
 3152:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3153:         url = url+'&inhibitmenu=yes';
 3154:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3155:             previousWin = window.open(url,'',options,1);
 3156:         } else {
 3157:             previousWin.location.href = url;
 3158:         }
 3159:         previousWin.focus();
 3160:         return false;
 3161:     } else {
 3162:         document.location.href = url;
 3163:         return false;
 3164:     }
 3165: JSTHREE
 3166:     }
 3167:     $js .= <<"ENDJS";
 3168:     return false;
 3169: }
 3170: // ]]>
 3171: </script>
 3172: ENDJS
 3173: 
 3174: }
 3175: 
 3176: #--- Called from submission routine
 3177: sub processHandGrade {
 3178:     my ($request,$symb) = @_;
 3179:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3180:     my $button = $env{'form.gradeOpt'};
 3181:     my $ngrade = $env{'form.NCT'};
 3182:     my $ntstu  = $env{'form.NTSTU'};
 3183:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3184:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3185: 
 3186:     if ($button eq 'Save & Next') {
 3187: 	my $ctr = 0;
 3188: 	while ($ctr < $ngrade) {
 3189: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3190: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3191:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 3192: 	    if ($errorflag eq 'no_score') {
 3193: 		$ctr++;
 3194: 		next;
 3195: 	    }
 3196: 	    if ($errorflag eq 'not_allowed') {
 3197: 		$request->print(
 3198:                     '<span class="LC_error">'
 3199:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3200:                    .'</span>');
 3201: 		$ctr++;
 3202: 		next;
 3203: 	    }
 3204:             if ($numhidden) {
 3205:                 $request->print(
 3206:                     '<span class="LC_info">'
 3207:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3208:                    .'</span><br />');
 3209:             }
 3210: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3211: 	    my ($subject,$message,$msgstatus) = ('','','');
 3212: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3213:             my ($feedurl,$showsymb) =
 3214: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3215: 	    my $messagetail;
 3216: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3217: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3218: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3219: 		$subject.=' ['.$restitle.']';
 3220: 		my (@msgnum) = split(/,/,$includemsg);
 3221: 		foreach (@msgnum) {
 3222: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3223: 		}
 3224: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3225: 		if ($env{'form.withgrades'.$ctr}) {
 3226: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3227: 		    $messagetail = " for <a href=\"".
 3228: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3229: 		}
 3230: 		$msgstatus = 
 3231:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3232: 						     $message.$messagetail,
 3233:                                                      undef,$feedurl,undef,
 3234:                                                      undef,undef,$showsymb,
 3235:                                                      $restitle);
 3236: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3237: 				$msgstatus.'<br />');
 3238: 	    }
 3239: 	    if ($env{'form.collaborator'.$ctr}) {
 3240: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3241: 		foreach my $collabstr (@collabstrs) {
 3242: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3243: 		    foreach my $collaborator (@collaborators) {
 3244: 			my ($errorflag,$pts,$wgt) = 
 3245: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3246: 					   $env{'form.unamedom'.$ctr},$part);
 3247: 			if ($errorflag eq 'not_allowed') {
 3248: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3249: 			    next;
 3250: 			} elsif ($message ne '') {
 3251: 			    my ($baseurl,$showsymb) = 
 3252: 				&get_feedurl_and_symb($symb,$collaborator,
 3253: 						      $udom);
 3254: 			    if ($env{'form.withgrades'.$ctr}) {
 3255: 				$messagetail = " for <a href=\"".
 3256:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3257: 			    }
 3258: 			    $msgstatus = 
 3259: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3260: 			}
 3261: 		    }
 3262: 		}
 3263: 	    }
 3264: 	    $ctr++;
 3265: 	}
 3266:     }
 3267: 
 3268:     my $res_error;
 3269:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3270:     if ($res_error) {
 3271:         $request->print(&navmap_errormsg());
 3272:         return;
 3273:     }
 3274: 
 3275:     my %keyhash = ();
 3276:     if ($numessay) {
 3277: 	# Keywords sorted in alphabatical order
 3278: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3279: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3280: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3281: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3282: 	$env{'form.keywords'} = join(' ',@keywords);
 3283: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3284: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3285: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3286: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3287: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3288:     }
 3289: 
 3290:     if ($env{'form.compmsg'}) {
 3291: 	# message center - Order of message gets changed. Blank line is eliminated.
 3292: 	# New messages are saved in env for the next student.
 3293: 	# All messages are saved in nohist_handgrade.db
 3294: 	my ($ctr,$idx) = (1,1);
 3295: 	while ($ctr <= $env{'form.savemsgN'}) {
 3296: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3297: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3298: 		$idx++;
 3299: 	    }
 3300: 	    $ctr++;
 3301: 	}
 3302: 	$ctr = 0;
 3303: 	while ($ctr < $ngrade) {
 3304: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3305: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3306: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3307: 	        $idx++;
 3308: 	    }
 3309: 	    $ctr++;
 3310: 	}
 3311: 	$env{'form.savemsgN'} = --$idx;
 3312: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3313:     }
 3314:     if (($numessay) || ($env{'form.compmsg'})) {
 3315:         my $putresult = &Apache::lonnet::put
 3316:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3317:     }
 3318: 
 3319:     # Called by Save & Refresh from Highlight Attribute Window
 3320:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3321:     if ($env{'form.refresh'} eq 'on') {
 3322: 	my ($ctr,$total) = (0,0);
 3323: 	while ($ctr < $ngrade) {
 3324: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3325: 	    $ctr++;
 3326: 	}
 3327: 	$env{'form.NTSTU'}=$ngrade;
 3328: 	$ctr = 0;
 3329: 	while ($ctr < $total) {
 3330: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3331: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3332: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3333: 	    &submission($request,$ctr,$total-1,$symb);
 3334: 	    $ctr++;
 3335: 	}
 3336: 	return '';
 3337:     }
 3338: 
 3339:     # Get the next/previous one or group of students
 3340:     my $firststu = $env{'form.unamedom0'};
 3341:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3342:     my $ctr = 2;
 3343:     while ($laststu eq '') {
 3344: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3345: 	$ctr++;
 3346: 	$laststu = $firststu if ($ctr > $ngrade);
 3347:     }
 3348: 
 3349:     my (@parsedlist,@nextlist);
 3350:     my ($nextflg) = 0;
 3351:     foreach my $item (sort 
 3352: 	     {
 3353: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3354: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3355: 		 }
 3356: 		 return $a cmp $b;
 3357: 	     } (keys(%$fullname))) {
 3358: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3359: 	    push(@parsedlist,$item);
 3360: 	}
 3361: 	$nextflg = 1 if ($item eq $laststu);
 3362: 	if ($button eq 'Previous') {
 3363: 	    last if ($item eq $firststu);
 3364: 	    push(@parsedlist,$item);
 3365: 	}
 3366:     }
 3367:     $ctr = 0;
 3368:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3369:     foreach my $student (@parsedlist) {
 3370: 	my $submitonly=$env{'form.submitonly'};
 3371: 	my ($uname,$udom) = split(/:/,$student);
 3372: 	
 3373: 	if ($submitonly eq 'queued') {
 3374: 	    my %queue_status = 
 3375: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3376: 							$udom,$uname);
 3377: 	    next if (!defined($queue_status{'gradingqueue'}));
 3378: 	}
 3379: 
 3380: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3381: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3382: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3383: 	    my $submitted = 0;
 3384: 	    my $ungraded = 0;
 3385: 	    my $incorrect = 0;
 3386: 	    foreach my $item (keys(%status)) {
 3387: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3388: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3389: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3390: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3391: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3392: 		    $submitted = 0;
 3393: 		}
 3394: 	    }
 3395: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3396: 				     $submitonly eq 'incorrect' ||
 3397: 				     $submitonly eq 'graded'));
 3398: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3399: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3400: 	}
 3401: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3402: 	last if ($ctr == $ntstu);
 3403: 	$ctr++;
 3404:     }
 3405: 
 3406:     $ctr = 0;
 3407:     my $total = scalar(@nextlist)-1;
 3408: 
 3409:     foreach (sort(@nextlist)) {
 3410: 	my ($uname,$udom,$submitter) = split(/:/);
 3411: 	$env{'form.student'}  = $uname;
 3412: 	$env{'form.userdom'}  = $udom;
 3413: 	$env{'form.fullname'} = $$fullname{$_};
 3414: 	&submission($request,$ctr,$total,$symb);
 3415: 	$ctr++;
 3416:     }
 3417:     if ($total < 0) {
 3418: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3419: 	$request->print($the_end);
 3420:     }
 3421:     return '';
 3422: }
 3423: 
 3424: #---- Save the score and award for each student, if changed
 3425: sub saveHandGrade {
 3426:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3427:     my @version_parts;
 3428:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3429: 					   $env{'request.course.id'});
 3430:     if (!&canmodify($usec)) { return('not_allowed'); }
 3431:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3432:     my @parts_graded;
 3433:     my %newrecord  = ();
 3434:     my ($pts,$wgt,$totchg) = ('','',0);
 3435:     my %aggregate = ();
 3436:     my $aggregateflag = 0;
 3437:     if ($env{'form.HIDE'.$newflg}) {
 3438:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3439:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3440:         $totchg += $numchgs;
 3441:     }
 3442:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3443:     foreach my $new_part (@parts) {
 3444: 	#collaborator ($submi may vary for different parts
 3445: 	if ($submitter && $new_part ne $part) { next; }
 3446: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3447: 	if ($dropMenu eq 'excused') {
 3448: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3449: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3450: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3451: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3452: 		}
 3453: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3454: 	    }
 3455: 	} elsif ($dropMenu eq 'reset status'
 3456: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3457: 	    foreach my $key (keys(%record)) {
 3458: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3459: 	    }
 3460: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3461: 		"$env{'user.name'}:$env{'user.domain'}";
 3462:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3463: 
 3464:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3465: 					       [$new_part]);
 3466:             my $aggtries =$totaltries;
 3467:             if ($last_resets{$new_part}) {
 3468:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3469: 					   $new_part);
 3470:             }
 3471: 
 3472:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3473:             if ($aggtries > 0) {
 3474:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3475:                 $aggregateflag = 1;
 3476:             }
 3477: 	} elsif ($dropMenu eq '') {
 3478: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3479: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3480: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3481: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3482: 		next;
 3483: 	    }
 3484: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3485: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3486: 	    my $partial= $pts/$wgt;
 3487: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3488: 		#do not update score for part if not changed.
 3489:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3490: 		next;
 3491: 	    } else {
 3492: 	        push(@parts_graded,$new_part);
 3493: 	    }
 3494: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3495: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3496: 	    }
 3497: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3498: 	    if ($partial == 0) {
 3499: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3500: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3501: 		}
 3502: 	    } else {
 3503: 		if ($record{$reckey} ne 'correct_by_override') {
 3504: 		    $newrecord{$reckey} = 'correct_by_override';
 3505: 		}
 3506: 	    }	    
 3507: 	    if ($submitter && 
 3508: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3509: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3510: 	    }
 3511: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3512: 		"$env{'user.name'}:$env{'user.domain'}";
 3513: 	}
 3514: 	# unless problem has been graded, set flag to version the submitted files
 3515: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3516: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3517: 	        $dropMenu eq 'reset status')
 3518: 	   {
 3519: 	    push(@version_parts,$new_part);
 3520: 	}
 3521:     }
 3522:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3523:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3524: 
 3525:     if (%newrecord) {
 3526:         if (@version_parts) {
 3527:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3528:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3529: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3530: 	    foreach my $new_part (@version_parts) {
 3531: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3532: 				$new_part,\%newrecord);
 3533: 	    }
 3534:         }
 3535: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3536: 				$env{'request.course.id'},$domain,$stuname);
 3537: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3538: 				     $cdom,$cnum,$domain,$stuname);
 3539:     }
 3540:     if ($aggregateflag) {
 3541:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3542: 			      $cdom,$cnum);
 3543:     }
 3544:     return ('',$pts,$wgt,$totchg);
 3545: }
 3546: 
 3547: sub makehidden {
 3548:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3549:     return unless (ref($record) eq 'HASH');
 3550:     my %modified;
 3551:     my $numchanged = 0;
 3552:     if (exists($record->{$version.':keys'})) {
 3553:         my $partsregexp = $parts;
 3554:         $partsregexp =~ s/,/|/g;
 3555:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3556:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3557:                  my $item = $1;
 3558:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3559:                      $modified{$key} = $record->{$version.':'.$key};
 3560:                  }
 3561:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3562:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3563:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3564:                 $modified{$key} = $record->{$version.':'.$key};
 3565:             }
 3566:         }
 3567:         if (keys(%modified)) {
 3568:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3569:                                           $domain,$stuname,$tolog) eq 'ok') {
 3570:                 $numchanged ++;
 3571:             }
 3572:         }
 3573:     }
 3574:     return $numchanged;
 3575: }
 3576: 
 3577: sub check_and_remove_from_queue {
 3578:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3579:     my @ungraded_parts;
 3580:     foreach my $part (@{$parts}) {
 3581: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3582: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3583: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3584: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3585: 		) {
 3586: 	    push(@ungraded_parts, $part);
 3587: 	}
 3588:     }
 3589:     if ( !@ungraded_parts ) {
 3590: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3591: 					       $cnum,$domain,$stuname);
 3592:     }
 3593: }
 3594: 
 3595: sub handback_files {
 3596:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3597:     my $portfolio_root = '/userfiles/portfolio';
 3598:     my $res_error;
 3599:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3600:     if ($res_error) {
 3601:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3602:         return;
 3603:     }
 3604:     my @handedback;
 3605:     my $file_msg;
 3606:     my @part_response_id = &flatten_responseType($responseType);
 3607:     foreach my $part_response_id (@part_response_id) {
 3608:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3609: 	my $part_resp = join('_',@{ $part_response_id });
 3610:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3611:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3612:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3613:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3614:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3615:                     my ($directory,$answer_file) = 
 3616:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3617:                     my ($answer_name,$answer_ver,$answer_ext) =
 3618: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3619: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3620:                     my $getpropath = 1;
 3621:                     my ($dir_list,$listerror) =
 3622:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3623:                                                  $domain,$stuname,$getpropath);
 3624: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3625:                     # fix filename
 3626:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3627:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3628:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3629:             	                                $save_file_name);
 3630:                     if ($result !~ m|^/uploaded/|) {
 3631:                         $request->print('<br /><span class="LC_error">'.
 3632:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3633:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3634:                                         '</span>');
 3635:                     } else {
 3636:                         # mark the file as read only
 3637:                         push(@handedback,$save_file_name);
 3638: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3639: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3640: 			}
 3641:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3642: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3643:                     }
 3644:                     $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>'));
 3645:                 }
 3646:             }
 3647:         }
 3648:     }
 3649:     if (@handedback > 0) {
 3650:         $request->print('<br />');
 3651:         my @what = ($symb,$env{'request.course.id'},'handback');
 3652:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3653:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3654:         my ($subject,$message);
 3655:         if (scalar(@handedback) == 1) {
 3656:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3657:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3658:         } else {
 3659:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3660:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3661:         }
 3662:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3663:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3664:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3665:         my ($feedurl,$showsymb) =
 3666:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3667:         my $restitle = &Apache::lonnet::gettitle($symb);
 3668:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3669:         my $msgstatus =
 3670:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3671:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3672:                  $restitle);
 3673:         if ($msgstatus) {
 3674:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3675:         }
 3676:     }
 3677:     return;
 3678: }
 3679: 
 3680: sub get_feedurl_and_symb {
 3681:     my ($symb,$uname,$udom) = @_;
 3682:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3683:     $url = &Apache::lonnet::clutter($url);
 3684:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3685: 					$symb,$udom,$uname);
 3686:     if ($encrypturl =~ /^yes$/i) {
 3687: 	&Apache::lonenc::encrypted(\$url,1);
 3688: 	&Apache::lonenc::encrypted(\$symb,1);
 3689:     }
 3690:     return ($url,$symb);
 3691: }
 3692: 
 3693: sub get_submitted_files {
 3694:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3695:     my @files;
 3696:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3697:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3698:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3699:     	    push(@files,$file_url.$file);
 3700:         }
 3701:     }
 3702:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3703:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3704:     }
 3705:     return (\@files);
 3706: }
 3707: 
 3708: # ----------- Provides number of tries since last reset.
 3709: sub get_num_tries {
 3710:     my ($record,$last_reset,$part) = @_;
 3711:     my $timestamp = '';
 3712:     my $num_tries = 0;
 3713:     if ($$record{'version'}) {
 3714:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3715:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3716:                 $timestamp = $$record{$version.':timestamp'};
 3717:                 if ($timestamp > $last_reset) {
 3718:                     $num_tries ++;
 3719:                 } else {
 3720:                     last;
 3721:                 }
 3722:             }
 3723:         }
 3724:     }
 3725:     return $num_tries;
 3726: }
 3727: 
 3728: # ----------- Determine decrements required in aggregate totals 
 3729: sub decrement_aggs {
 3730:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3731:     my %decrement = (
 3732:                         attempts => 0,
 3733:                         users => 0,
 3734:                         correct => 0
 3735:                     );
 3736:     $decrement{'attempts'} = $aggtries;
 3737:     if ($solvedstatus =~ /^correct/) {
 3738:         $decrement{'correct'} = 1;
 3739:     }
 3740:     if ($aggtries == $totaltries) {
 3741:         $decrement{'users'} = 1;
 3742:     }
 3743:     foreach my $type (keys(%decrement)) {
 3744:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3745:     }
 3746:     return;
 3747: }
 3748: 
 3749: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3750: sub get_last_resets {
 3751:     my ($symb,$courseid,$partids) =@_;
 3752:     my %last_resets;
 3753:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3754:     my $cname = $env{'course.'.$courseid.'.num'};
 3755:     my @keys;
 3756:     foreach my $part (@{$partids}) {
 3757: 	push(@keys,"$symb\0$part\0resettime");
 3758:     }
 3759:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3760: 				     $cdom,$cname);
 3761:     foreach my $part (@{$partids}) {
 3762: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3763:     }
 3764:     return %last_resets;
 3765: }
 3766: 
 3767: # ----------- Handles creating versions for portfolio files as answers
 3768: sub version_portfiles {
 3769:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3770:     my $version_parts = join('|',@$v_flag);
 3771:     my @returned_keys;
 3772:     my $parts = join('|', @$parts_graded);
 3773:     foreach my $key (keys(%$record)) {
 3774:         my $new_portfiles;
 3775:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3776:             my @versioned_portfiles;
 3777:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3778:             if (@portfiles) {
 3779:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3780:                                                       \@versioned_portfiles);
 3781:             }
 3782:             $$record{$key} = join(',',@versioned_portfiles);
 3783:             push(@returned_keys,$key);
 3784:         }
 3785:     } 
 3786:     return (@returned_keys);   
 3787: }
 3788: 
 3789: #--------------------------------------------------------------------------------------
 3790: #
 3791: #-------------------------- Next few routines handles grading by section or whole class
 3792: #
 3793: #--- Javascript to handle grading by section or whole class
 3794: sub viewgrades_js {
 3795:     my ($request) = shift;
 3796: 
 3797:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3798:     &js_escape(\$alertmsg);
 3799:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3800:    function writePoint(partid,weight,point) {
 3801: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3802: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3803: 	if (point == "textval") {
 3804: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3805: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3806: 		alert("$alertmsg"+parseFloat(point));
 3807: 		var resetbox = false;
 3808: 		for (var i=0; i<radioButton.length; i++) {
 3809: 		    if (radioButton[i].checked) {
 3810: 			textbox.value = i;
 3811: 			resetbox = true;
 3812: 		    }
 3813: 		}
 3814: 		if (!resetbox) {
 3815: 		    textbox.value = "";
 3816: 		}
 3817: 		return;
 3818: 	    }
 3819: 	    if (parseFloat(point) > parseFloat(weight)) {
 3820: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3821: 				   ") greater than the weight for the part. Accept?");
 3822: 		if (resp == false) {
 3823: 		    textbox.value = "";
 3824: 		    return;
 3825: 		}
 3826: 	    }
 3827: 	    for (var i=0; i<radioButton.length; i++) {
 3828: 		radioButton[i].checked=false;
 3829: 		if (parseFloat(point) == i) {
 3830: 		    radioButton[i].checked=true;
 3831: 		}
 3832: 	    }
 3833: 
 3834: 	} else {
 3835: 	    textbox.value = parseFloat(point);
 3836: 	}
 3837: 	for (i=0;i<document.classgrade.total.value;i++) {
 3838: 	    var user = document.classgrade["ctr"+i].value;
 3839: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3840: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3841: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3842: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3843: 	    if (saveval != "correct") {
 3844: 		scorename.value = point;
 3845: 		if (selname[0].selected != true) {
 3846: 		    selname[0].selected = true;
 3847: 		}
 3848: 	    }
 3849: 	}
 3850: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3851:     }
 3852: 
 3853:     function writeRadText(partid,weight) {
 3854: 	var selval   = document.classgrade["SELVAL_"+partid];
 3855: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3856:         var override = document.classgrade["FORCE_"+partid].checked;
 3857: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3858: 	if (selval[1].selected || selval[2].selected) {
 3859: 	    for (var i=0; i<radioButton.length; i++) {
 3860: 		radioButton[i].checked=false;
 3861: 
 3862: 	    }
 3863: 	    textbox.value = "";
 3864: 
 3865: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3866: 		var user = document.classgrade["ctr"+i].value;
 3867: 		user = user.replace(new RegExp(':', 'g'),"_");
 3868: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3869: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3870: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3871: 		if ((saveval != "correct") || override) {
 3872: 		    scorename.value = "";
 3873: 		    if (selval[1].selected) {
 3874: 			selname[1].selected = true;
 3875: 		    } else {
 3876: 			selname[2].selected = true;
 3877: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3878: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3879: 		    }
 3880: 		}
 3881: 	    }
 3882: 	} else {
 3883: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3884: 		var user = document.classgrade["ctr"+i].value;
 3885: 		user = user.replace(new RegExp(':', 'g'),"_");
 3886: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3887: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3888: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3889: 		if ((saveval != "correct") || override) {
 3890: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3891: 		    selname[0].selected = true;
 3892: 		}
 3893: 	    }
 3894: 	}	    
 3895:     }
 3896: 
 3897:     function changeSelect(partid,user) {
 3898: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3899: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3900: 	var point  = textbox.value;
 3901: 	var weight = document.classgrade["weight_"+partid].value;
 3902: 
 3903: 	if (isNaN(point) || parseFloat(point) < 0) {
 3904: 	    alert("$alertmsg"+parseFloat(point));
 3905: 	    textbox.value = "";
 3906: 	    return;
 3907: 	}
 3908: 	if (parseFloat(point) > parseFloat(weight)) {
 3909: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3910: 			       ") greater than the weight of the part. Accept?");
 3911: 	    if (resp == false) {
 3912: 		textbox.value = "";
 3913: 		return;
 3914: 	    }
 3915: 	}
 3916: 	selval[0].selected = true;
 3917:     }
 3918: 
 3919:     function changeOneScore(partid,user) {
 3920: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3921: 	if (selval[1].selected || selval[2].selected) {
 3922: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3923: 	    if (selval[2].selected) {
 3924: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3925: 	    }
 3926:         }
 3927:     }
 3928: 
 3929:     function resetEntry(numpart) {
 3930: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3931: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3932: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3933: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3934: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3935: 	    for (var i=0; i<radioButton.length; i++) {
 3936: 		radioButton[i].checked=false;
 3937: 
 3938: 	    }
 3939: 	    textbox.value = "";
 3940: 	    selval[0].selected = true;
 3941: 
 3942: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3943: 		var user = document.classgrade["ctr"+i].value;
 3944: 		user = user.replace(new RegExp(':', 'g'),"_");
 3945: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3946: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3947: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3948: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3949: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3950: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3951: 		if (saveselval == "excused") {
 3952: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3953: 		} else {
 3954: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3955: 		}
 3956: 	    }
 3957: 	}
 3958:     }
 3959: 
 3960: VIEWJAVASCRIPT
 3961: }
 3962: 
 3963: #--- show scores for a section or whole class w/ option to change/update a score
 3964: sub viewgrades {
 3965:     my ($request,$symb) = @_;
 3966:     my ($is_tool,$toolsymb);
 3967:     if ($symb =~ /ext\.tool$/) {
 3968:         $is_tool = 1;
 3969:         $toolsymb = $symb;
 3970:     }
 3971:     &viewgrades_js($request);
 3972: 
 3973:     #need to make sure we have the correct data for later EXT calls, 
 3974:     #thus invalidate the cache
 3975:     &Apache::lonnet::devalidatecourseresdata(
 3976:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3977:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3978:     &Apache::lonnet::clear_EXT_cache_status();
 3979: 
 3980:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3981: 
 3982:     #view individual student submission form - called using Javascript viewOneStudent
 3983:     $result.=&jscriptNform($symb);
 3984: 
 3985:     #beginning of class grading form
 3986:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3987:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3988: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3989: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3990: 	&build_section_inputs().
 3991: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3992: 
 3993:     #retrieve selected groups
 3994:     my (@groups,$group_display);
 3995:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3996:     if (grep(/^all$/,@groups)) {
 3997:         @groups = ('all');
 3998:     } elsif (grep(/^none$/,@groups)) {
 3999:         @groups = ('none');
 4000:     } elsif (@groups > 0) {
 4001:         $group_display = join(', ',@groups);
 4002:     }
 4003: 
 4004:     my ($common_header,$specific_header,@sections,$section_display);
 4005:     if ($env{'request.course.sec'} ne '') {
 4006:         @sections = ($env{'request.course.sec'});
 4007:     } else {
 4008:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4009:     }
 4010: 
 4011: # Check if Save button should be usable
 4012:     my $disabled = ' disabled="disabled"';
 4013:     if ($perm{'mgr'}) {
 4014:         if (grep(/^all$/,@sections)) {
 4015:             undef($disabled);
 4016:         } else {
 4017:             foreach my $sec (@sections) {
 4018:                 if (&canmodify($sec)) {
 4019:                     undef($disabled);
 4020:                     last;
 4021:                 }
 4022:             }
 4023:         }
 4024:     }
 4025:     if (grep(/^all$/,@sections)) {
 4026:         @sections = ('all');
 4027:         if ($group_display) {
 4028:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4029:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4030:         } elsif (grep(/^none$/,@groups)) {
 4031:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4032:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4033:         } else {
 4034: 	    $common_header = &mt('Assign Common Grade to Class');
 4035:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4036:         }
 4037:     } elsif (grep(/^none$/,@sections)) {
 4038:         @sections = ('none');
 4039:         if ($group_display) {
 4040:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4041:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4042:         } elsif (grep(/^none$/,@groups)) {
 4043:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4044:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4045:         } else {
 4046:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4047: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4048:         }
 4049:     } else {
 4050:         $section_display = join (", ",@sections);
 4051:         if ($group_display) {
 4052:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4053:                                  $section_display,$group_display);
 4054:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4055:                                    $section_display,$group_display);
 4056:         } elsif (grep(/^none$/,@groups)) {
 4057:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4058:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4059:         } else {
 4060:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4061: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4062:         }
 4063:     }
 4064:     my %submit_types = &substatus_options();
 4065:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4066: 
 4067:     if ($env{'form.submitonly'} eq 'all') {
 4068:         $result.= '<h3>'.$common_header.'</h3>';
 4069:     } else {
 4070:         my $text;
 4071:         if ($is_tool) {
 4072:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4073:         } else {
 4074:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4075:         }
 4076:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 4077:     }
 4078:     $result .= &Apache::loncommon::start_data_table();
 4079:     #radio buttons/text box for assigning points for a section or class.
 4080:     #handles different parts of a problem
 4081:     my $res_error;
 4082:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4083:     if ($res_error) {
 4084:         return &navmap_errormsg();
 4085:     }
 4086:     my %weight = ();
 4087:     my $ctsparts = 0;
 4088:     my %seen = ();
 4089:     my @part_response_id;
 4090:     if ($is_tool) {
 4091:         @part_response_id = ([0,'']);
 4092:     } else {
 4093:         @part_response_id = &flatten_responseType($responseType);
 4094:     }
 4095:     foreach my $part_response_id (@part_response_id) {
 4096:     	my ($partid,$respid) = @{ $part_response_id };
 4097: 	my $part_resp = join('_',@{ $part_response_id });
 4098: 	next if $seen{$partid};
 4099: 	$seen{$partid}++;
 4100: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4101: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4102: 
 4103: 	my $display_part=&get_display_part($partid,$symb);
 4104: 	my $radio.='<table border="0"><tr>';  
 4105: 	my $ctr = 0;
 4106: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4107: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4108: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4109: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4110: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4111: 	    $ctr++;
 4112: 	}
 4113: 	$radio.='</tr></table>';
 4114: 	my $line = '<input type="text" name="TEXTVAL_'.
 4115: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4116: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4117: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4118:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4119:             '<select name="SELVAL_'.$partid.'" '.
 4120:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 4121:                 $weight{$partid}.')"> '.
 4122: 	    '<option selected="selected"> </option>'.
 4123: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4124: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4125: 	    '</select></td>'.
 4126:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4127: 	$line.='<input type="hidden" name="partid_'.
 4128: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4129: 	$line.='<input type="hidden" name="weight_'.
 4130: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4131: 
 4132: 	$result.=
 4133: 	    &Apache::loncommon::start_data_table_row()."\n".
 4134: 	    '<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>'.
 4135: 	    &Apache::loncommon::end_data_table_row()."\n";
 4136: 	$ctsparts++;
 4137:     }
 4138:     $result.=&Apache::loncommon::end_data_table()."\n".
 4139: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4140:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4141: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4142: 
 4143:     #table listing all the students in a section/class
 4144:     #header of table
 4145:     if ($env{'form.submitonly'} eq 'all') {
 4146:         $result.= '<h3>'.$specific_header.'</h3>';
 4147:     } else {
 4148:         my $text;
 4149:         if ($is_tool) {
 4150:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 4151:         } else {
 4152:             $text = &mt('(submission status: "[_1]")',$submission_status);
 4153:         }
 4154:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 4155:     }
 4156:     $result.= &Apache::loncommon::start_data_table().
 4157: 	      &Apache::loncommon::start_data_table_header_row().
 4158: 	      '<th>'.&mt('No.').'</th>'.
 4159: 	      '<th>'.&nameUserString('header')."</th>\n";
 4160:     my $partserror;
 4161:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4162:     if ($partserror) {
 4163:         return &navmap_errormsg();
 4164:     }
 4165:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4166:     my @partids = ();
 4167:     foreach my $part (@parts) {
 4168: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4169:         my $narrowtext = &mt('Tries');
 4170: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4171: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 4172: 	my ($partid) = &split_part_type($part);
 4173:         push(@partids,$partid);
 4174: #
 4175: # FIXME: Looks like $display looks at English text
 4176: #
 4177: 	my $display_part=&get_display_part($partid,$symb);
 4178: 	if ($display =~ /^Partial Credit Factor/) {
 4179: 	    $result.='<th>'.
 4180: 		&mt('Score Part: [_1][_2](weight = [_3])',
 4181: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4182: 	    next;
 4183: 	    
 4184: 	} else {
 4185: 	    if ($display =~ /Problem Status/) {
 4186: 		my $grade_status_mt = &mt('Grade Status');
 4187: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4188: 	    }
 4189: 	    my $part_mt = &mt('Part:');
 4190: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4191: 	}
 4192: 
 4193: 	$result.='<th>'.$display.'</th>'."\n";
 4194:     }
 4195:     $result.=&Apache::loncommon::end_data_table_header_row();
 4196: 
 4197:     my %last_resets = 
 4198: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4199: 
 4200:     #get info for each student
 4201:     #list all the students - with points and grade status
 4202:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4203:     my $ctr = 0;
 4204:     foreach (sort 
 4205: 	     {
 4206: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4207: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4208: 		 }
 4209: 		 return $a cmp $b;
 4210: 	     } (keys(%$fullname))) {
 4211: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4212: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 4213:     }
 4214:     $result.=&Apache::loncommon::end_data_table();
 4215:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4216:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4217: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4218:     if ($ctr == 0) {
 4219:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4220:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4221:                 '<span class="LC_warning">';
 4222:         if ($env{'form.submitonly'} eq 'all') {
 4223:             if (grep(/^all$/,@sections)) {
 4224:                 if (grep(/^all$/,@groups)) {
 4225:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4226:                                    $stu_status);
 4227:                 } elsif (grep(/^none$/,@groups)) {
 4228:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4229:                                    $stu_status); 
 4230:                 } else {
 4231:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4232:                                    $group_display,$stu_status);
 4233:                 }
 4234:             } elsif (grep(/^none$/,@sections)) {
 4235:                 if (grep(/^all$/,@groups)) {
 4236:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4237:                                    $stu_status);
 4238:                 } elsif (grep(/^none$/,@groups)) {
 4239:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4240:                                    $stu_status);
 4241:                 } else {
 4242:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4243:                                    $group_display,$stu_status);
 4244:                 }
 4245:             } else {
 4246:                 if (grep(/^all$/,@groups)) {
 4247:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4248:                                    $section_display,$stu_status);
 4249:                 } elsif (grep(/^none$/,@groups)) {
 4250:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4251:                                    $section_display,$stu_status);
 4252:                 } else {
 4253:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4254:                                    $section_display,$group_display,$stu_status);
 4255:                 }
 4256:             }
 4257:         } else {
 4258:             if (grep(/^all$/,@sections)) {
 4259:                 if (grep(/^all$/,@groups)) {
 4260:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4261:                                    $stu_status,$submission_status);
 4262:                 } elsif (grep(/^none$/,@groups)) {
 4263:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4264:                                    $stu_status,$submission_status);
 4265:                 } else {
 4266:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4267:                                    $group_display,$stu_status,$submission_status);
 4268:                 }
 4269:             } elsif (grep(/^none$/,@sections)) {
 4270:                 if (grep(/^all$/,@groups)) {
 4271:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4272:                                    $stu_status,$submission_status);
 4273:                 } elsif (grep(/^none$/,@groups)) {
 4274:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4275:                                    $stu_status,$submission_status);
 4276:                 } else {
 4277:                     $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.',
 4278:                                    $group_display,$stu_status,$submission_status);
 4279:                 }
 4280:             } else {
 4281:                 if (grep(/^all$/,@groups)) {
 4282: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4283: 	                           $section_display,$stu_status,$submission_status);
 4284:                 } elsif (grep(/^none$/,@groups)) {
 4285:                     $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.',
 4286:                                    $section_display,$stu_status,$submission_status);
 4287:                 } else {
 4288:                     $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.',
 4289:                                    $section_display,$group_display,$stu_status,$submission_status);
 4290:                 }
 4291:             }
 4292:         }
 4293: 	$result .= '</span><br />';
 4294:     }
 4295:     return $result;
 4296: }
 4297: 
 4298: #--- call by previous routine to display each student who satisfies submission filter. 
 4299: sub viewstudentgrade {
 4300:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4301:     my ($uname,$udom) = split(/:/,$student);
 4302:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4303:     my $submitonly = $env{'form.submitonly'};
 4304:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4305:         my %partstatus = ();
 4306:         if (ref($parts) eq 'ARRAY') {
 4307:             foreach my $apart (@{$parts}) {
 4308:                 my ($part,$type) = &split_part_type($apart);
 4309:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4310:                 $status = 'nothing' if ($status eq '');
 4311:                 $partstatus{$part}      = $status;
 4312:                 my $subkey = "resource.$part.submitted_by";
 4313:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4314:             }
 4315:             my $submitted = 0;
 4316:             my $graded = 0;
 4317:             my $incorrect = 0;
 4318:             foreach my $key (keys(%partstatus)) {
 4319:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4320:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4321:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4322: 
 4323:                 my $partid = (split(/\./,$key))[1];
 4324:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4325:                     $submitted = 0;
 4326:                 }
 4327:             }
 4328:             return if (!$submitted && ($submitonly eq 'yes' ||
 4329:                                        $submitonly eq 'incorrect' ||
 4330:                                        $submitonly eq 'graded'));
 4331:             return if (!$graded && ($submitonly eq 'graded'));
 4332:             return if (!$incorrect && $submitonly eq 'incorrect');
 4333:         }
 4334:     }
 4335:     if ($submitonly eq 'queued') {
 4336:         my ($cdom,$cnum) = split(/_/,$courseid);
 4337:         my %queue_status =
 4338:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4339:                                                     $udom,$uname);
 4340:         return if (!defined($queue_status{'gradingqueue'}));
 4341:     }
 4342:     $$ctr++;
 4343:     my %aggregates = ();
 4344:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4345: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4346: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4347: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4348: 	'\');" target="_self">'.$fullname.'</a> '.
 4349: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4350:     $student=~s/:/_/; # colon doen't work in javascript for names
 4351:     foreach my $apart (@$parts) {
 4352: 	my ($part,$type) = &split_part_type($apart);
 4353: 	my $score=$record{"resource.$part.$type"};
 4354:         $result.='<td align="center">';
 4355:         my ($aggtries,$totaltries);
 4356:         unless (exists($aggregates{$part})) {
 4357: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4358: 	    $aggtries = $totaltries;
 4359:             if ($$last_resets{$part}) {  
 4360:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4361: 					   $part);
 4362:             }
 4363:             $result.='<input type="hidden" name="'.
 4364:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4365:             $result.='<input type="hidden" name="'.
 4366:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4367:             $aggregates{$part} = 1;
 4368:         }
 4369: 	if ($type eq 'awarded') {
 4370: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4371: 	    $result.='<input type="hidden" name="'.
 4372: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4373: 	    $result.='<input type="text" name="'.
 4374: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4375:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4376: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4377: 	} elsif ($type eq 'solved') {
 4378: 	    my ($status,$foo)=split(/_/,$score,2);
 4379: 	    $status = 'nothing' if ($status eq '');
 4380: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4381: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4382: 	    $result.='&nbsp;<select name="'.
 4383: 		'GD_'.$student.'_'.$part.'_solved" '.
 4384:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4385: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4386: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4387: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4388: 	    $result.="</select>&nbsp;</td>\n";
 4389: 	} else {
 4390: 	    $result.='<input type="hidden" name="'.
 4391: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4392: 		    "\n";
 4393: 	    $result.='<input type="text" name="'.
 4394: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4395: 		'value="'.$score.'" size="4" /></td>'."\n";
 4396: 	}
 4397:     }
 4398:     $result.=&Apache::loncommon::end_data_table_row();
 4399:     return $result;
 4400: }
 4401: 
 4402: #--- change scores for all the students in a section/class
 4403: #    record does not get update if unchanged
 4404: sub editgrades {
 4405:     my ($request,$symb) = @_;
 4406:     my $toolsymb;
 4407:     if ($symb =~ /ext\.tool$/) {
 4408:         $toolsymb = $symb;
 4409:     }
 4410: 
 4411:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4412:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4413:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4414: 
 4415:     my $result= &Apache::loncommon::start_data_table().
 4416: 	&Apache::loncommon::start_data_table_header_row().
 4417: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4418: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4419:     my %scoreptr = (
 4420: 		    'correct'  =>'correct_by_override',
 4421: 		    'incorrect'=>'incorrect_by_override',
 4422: 		    'excused'  =>'excused',
 4423: 		    'ungraded' =>'ungraded_attempted',
 4424:                     'credited' =>'credit_attempted',
 4425: 		    'nothing'  => '',
 4426: 		    );
 4427:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4428: 
 4429:     my (@partid);
 4430:     my %weight = ();
 4431:     my %columns = ();
 4432:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4433: 
 4434:     my $partserror;
 4435:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4436:     if ($partserror) {
 4437:         return &navmap_errormsg();
 4438:     }
 4439:     my $header;
 4440:     while ($ctr < $env{'form.totalparts'}) {
 4441: 	my $partid = $env{'form.partid_'.$ctr};
 4442: 	push(@partid,$partid);
 4443: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4444: 	$ctr++;
 4445:     }
 4446:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4447:     my $totcolspan = 0;
 4448:     foreach my $partid (@partid) {
 4449: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4450: 	    '<th align="center">'.&mt('New Score').'</th>';
 4451: 	$columns{$partid}=2;
 4452: 	foreach my $stores (@parts) {
 4453: 	    my ($part,$type) = &split_part_type($stores);
 4454: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4455: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4456: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4457: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4458:             my $narrowtext = &mt('Tries');
 4459: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4460: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4461: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4462: 	    $columns{$partid}+=2;
 4463: 	}
 4464:         $totcolspan += $columns{$partid};
 4465:     }
 4466:     foreach my $partid (@partid) {
 4467: 	my $display_part=&get_display_part($partid,$symb);
 4468: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4469: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4470: 	    '</th>';
 4471: 
 4472:     }
 4473:     $result .= &Apache::loncommon::end_data_table_header_row().
 4474: 	&Apache::loncommon::start_data_table_header_row().
 4475: 	$header.
 4476: 	&Apache::loncommon::end_data_table_header_row();
 4477:     my @noupdate;
 4478:     my ($updateCtr,$noupdateCtr) = (1,1);
 4479:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4480: 	my $user = $env{'form.ctr'.$i};
 4481: 	my ($uname,$udom)=split(/:/,$user);
 4482: 	my %newrecord;
 4483: 	my $updateflag = 0;
 4484: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4485: 	my $canmodify = &canmodify($usec);
 4486: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4487: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4488: 	if (!$canmodify) {
 4489: 	    push(@noupdate,
 4490: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4491: 		 &mt('Not allowed to modify student')."</span></td>");
 4492: 	    next;
 4493: 	}
 4494:         my %aggregate = ();
 4495:         my $aggregateflag = 0;
 4496: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4497: 	foreach (@partid) {
 4498: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4499: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4500: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4501: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4502: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4503: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4504: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4505: 	    my $score;
 4506: 	    if ($partial eq '') {
 4507: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4508: 	    } elsif ($partial > 0) {
 4509: 		$score = 'correct_by_override';
 4510: 	    } elsif ($partial == 0) {
 4511: 		$score = 'incorrect_by_override';
 4512: 	    }
 4513: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4514: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4515: 
 4516: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4517: 		"$env{'user.name'}:$env{'user.domain'}";
 4518: 	    if ($dropMenu eq 'reset status' &&
 4519: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4520: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4521: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4522: 		$newrecord{'resource.'.$_.'.award'} = '';
 4523: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4524: 		$updateflag = 1;
 4525:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4526:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4527:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4528:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4529:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4530:                     $aggregateflag = 1;
 4531:                 }
 4532: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4533: 		$updateflag = 1;
 4534: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4535: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4536: 		$rec_update++;
 4537: 	    }
 4538: 
 4539: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4540: 		'<td align="center">'.$awarded.
 4541: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4542: 
 4543: 
 4544: 	    my $partid=$_;
 4545: 	    foreach my $stores (@parts) {
 4546: 		my ($part,$type) = &split_part_type($stores);
 4547: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4548: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4549: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4550: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4551: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4552: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4553: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4554: 		    $updateflag=1;
 4555: 		}
 4556: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4557: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4558: 	    }
 4559: 	}
 4560: 	$line.="\n";
 4561: 
 4562: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4563: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4564: 
 4565: 	if ($updateflag) {
 4566: 	    $count++;
 4567: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4568: 				    $udom,$uname);
 4569: 
 4570: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4571: 					      $cnum,$udom,$uname)) {
 4572: 		# need to figure out if should be in queue.
 4573: 		my %record =  
 4574: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4575: 					     $udom,$uname);
 4576: 		my $all_graded = 1;
 4577: 		my $none_graded = 1;
 4578: 		foreach my $part (@parts) {
 4579: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4580: 			$all_graded = 0;
 4581: 		    } else {
 4582: 			$none_graded = 0;
 4583: 		    }
 4584: 		}
 4585: 
 4586: 		if ($all_graded || $none_graded) {
 4587: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4588: 							   $symb,$cdom,$cnum,
 4589: 							   $udom,$uname);
 4590: 		}
 4591: 	    }
 4592: 
 4593: 	    $result.=&Apache::loncommon::start_data_table_row().
 4594: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4595: 		&Apache::loncommon::end_data_table_row();
 4596: 	    $updateCtr++;
 4597: 	} else {
 4598: 	    push(@noupdate,
 4599: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4600: 	    $noupdateCtr++;
 4601: 	}
 4602:         if ($aggregateflag) {
 4603:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4604: 				  $cdom,$cnum);
 4605:         }
 4606:     }
 4607:     if (@noupdate) {
 4608:         my $numcols=$totcolspan+2;
 4609: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4610: 	    '<td align="center" colspan="'.$numcols.'">'.
 4611: 	    &mt('No Changes Occurred For the Students Below').
 4612: 	    '</td>'.
 4613: 	    &Apache::loncommon::end_data_table_row();
 4614: 	foreach my $line (@noupdate) {
 4615: 	    $result.=
 4616: 		&Apache::loncommon::start_data_table_row().
 4617: 		$line.
 4618: 		&Apache::loncommon::end_data_table_row();
 4619: 	}
 4620:     }
 4621:     $result .= &Apache::loncommon::end_data_table();
 4622:     my $msg = '<p><b>'.
 4623: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4624: 	    $rec_update,$count).'</b><br />'.
 4625: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4626: 	'</b></p>';
 4627:     return $title.$msg.$result;
 4628: }
 4629: 
 4630: sub split_part_type {
 4631:     my ($partstr) = @_;
 4632:     my ($temp,@allparts)=split(/_/,$partstr);
 4633:     my $type=pop(@allparts);
 4634:     my $part=join('_',@allparts);
 4635:     return ($part,$type);
 4636: }
 4637: 
 4638: #------------- end of section for handling grading by section/class ---------
 4639: #
 4640: #----------------------------------------------------------------------------
 4641: 
 4642: 
 4643: #----------------------------------------------------------------------------
 4644: #
 4645: #-------------------------- Next few routines handles grading by csv upload
 4646: #
 4647: #--- Javascript to handle csv upload
 4648: sub csvupload_javascript_reverse_associate {
 4649:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4650:     my $error2=&mt('You need to specify at least one grading field');
 4651:   &js_escape(\$error1);
 4652:   &js_escape(\$error2);
 4653:   return(<<ENDPICK);
 4654:   function verify(vf) {
 4655:     var foundsomething=0;
 4656:     var founduname=0;
 4657:     var foundID=0;
 4658:     var foundclicker=0;
 4659:     for (i=0;i<=vf.nfields.value;i++) {
 4660:       tw=eval('vf.f'+i+'.selectedIndex');
 4661:       if (i==0 && tw!=0) { foundID=1; }
 4662:       if (i==1 && tw!=0) { founduname=1; }
 4663:       if (i==2 && tw!=0) { foundclicker=1; }
 4664:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4665:     }
 4666:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4667: 	alert('$error1');
 4668: 	return;
 4669:     }
 4670:     if (foundsomething==0) {
 4671: 	alert('$error2');
 4672: 	return;
 4673:     }
 4674:     vf.submit();
 4675:   }
 4676:   function flip(vf,tf) {
 4677:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4678:     var i;
 4679:     for (i=0;i<=vf.nfields.value;i++) {
 4680:       //can not pick the same destination field for both name and domain
 4681:       if (((i ==0)||(i ==1)) && 
 4682:           ((tf==0)||(tf==1)) && 
 4683:           (i!=tf) &&
 4684:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4685:         eval('vf.f'+i+'.selectedIndex=0;')
 4686:       }
 4687:     }
 4688:   }
 4689: ENDPICK
 4690: }
 4691: 
 4692: sub csvupload_javascript_forward_associate {
 4693:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4694:     my $error2=&mt('You need to specify at least one grading field');
 4695:   &js_escape(\$error1);
 4696:   &js_escape(\$error2);
 4697:   return(<<ENDPICK);
 4698:   function verify(vf) {
 4699:     var foundsomething=0;
 4700:     var founduname=0;
 4701:     var foundID=0;
 4702:     var foundclicker=0;
 4703:     for (i=0;i<=vf.nfields.value;i++) {
 4704:       tw=eval('vf.f'+i+'.selectedIndex');
 4705:       if (tw==1) { foundID=1; }
 4706:       if (tw==2) { founduname=1; }
 4707:       if (tw==3) { foundclicker=1; }
 4708:       if (tw>4) { foundsomething=1; }
 4709:     }
 4710:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4711: 	alert('$error1');
 4712: 	return;
 4713:     }
 4714:     if (foundsomething==0) {
 4715: 	alert('$error2');
 4716: 	return;
 4717:     }
 4718:     vf.submit();
 4719:   }
 4720:   function flip(vf,tf) {
 4721:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4722:     var i;
 4723:     //can not pick the same destination field twice
 4724:     for (i=0;i<=vf.nfields.value;i++) {
 4725:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4726:         eval('vf.f'+i+'.selectedIndex=0;')
 4727:       }
 4728:     }
 4729:   }
 4730: ENDPICK
 4731: }
 4732: 
 4733: sub csvuploadmap_header {
 4734:     my ($request,$symb,$datatoken,$distotal)= @_;
 4735:     my $javascript;
 4736:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4737: 	$javascript=&csvupload_javascript_reverse_associate();
 4738:     } else {
 4739: 	$javascript=&csvupload_javascript_forward_associate();
 4740:     }
 4741: 
 4742:     $symb = &Apache::lonenc::check_encrypt($symb);
 4743:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4744:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4745:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4746:     my $reverse=&mt("Reverse Association");
 4747:     $request->print(<<ENDPICK);
 4748: <br />
 4749: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4750: <input type="hidden" name="associate"  value="" />
 4751: <input type="hidden" name="phase"      value="three" />
 4752: <input type="hidden" name="datatoken"  value="$datatoken" />
 4753: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4754: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4755: <input type="hidden" name="upfile_associate" 
 4756:                                        value="$env{'form.upfile_associate'}" />
 4757: <input type="hidden" name="symb"       value="$symb" />
 4758: <input type="hidden" name="command"    value="csvuploadoptions" />
 4759: <hr />
 4760: ENDPICK
 4761:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4762:     return '';
 4763: 
 4764: }
 4765: 
 4766: sub csvupload_fields {
 4767:     my ($symb,$errorref) = @_;
 4768:     my $toolsymb;
 4769:     if ($symb =~ /ext\.tool$/) {
 4770:         $toolsymb = $symb;
 4771:     }
 4772:     my (@parts) = &getpartlist($symb,$errorref);
 4773:     if (ref($errorref)) {
 4774:         if ($$errorref) {
 4775:             return;
 4776:         }
 4777:     }
 4778: 
 4779:     my @fields=(['ID','Student/Employee ID'],
 4780: 		['username','Student Username'],
 4781: 		['clicker','Clicker ID'],
 4782: 		['domain','Student Domain']);
 4783:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4784:     foreach my $part (sort(@parts)) {
 4785: 	my @datum;
 4786: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4787: 	my $name=$part;
 4788: 	if (!$display) { $display = $name; }
 4789: 	@datum=($name,$display);
 4790: 	if ($name=~/^stores_(.*)_awarded/) {
 4791: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4792: 	}
 4793: 	push(@fields,\@datum);
 4794:     }
 4795:     return (@fields);
 4796: }
 4797: 
 4798: sub csvuploadmap_footer {
 4799:     my ($request,$i,$keyfields) =@_;
 4800:     my $buttontext = &mt('Assign Grades');
 4801:     $request->print(<<ENDPICK);
 4802: </table>
 4803: <input type="hidden" name="nfields" value="$i" />
 4804: <input type="hidden" name="keyfields" value="$keyfields" />
 4805: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4806: </form>
 4807: ENDPICK
 4808: }
 4809: 
 4810: sub checkforfile_js {
 4811:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4812:     &js_escape(\$alertmsg);
 4813:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4814:     function checkUpload(formname) {
 4815: 	if (formname.upfile.value == "") {
 4816: 	    alert("$alertmsg");
 4817: 	    return false;
 4818: 	}
 4819: 	formname.submit();
 4820:     }
 4821: CSVFORMJS
 4822:     return $result;
 4823: }
 4824: 
 4825: sub upcsvScores_form {
 4826:     my ($request,$symb) = @_;
 4827:     if (!$symb) {return '';}
 4828:     my $result=&checkforfile_js();
 4829:     $result.=&Apache::loncommon::start_data_table().
 4830:              &Apache::loncommon::start_data_table_header_row().
 4831:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4832:              &Apache::loncommon::end_data_table_header_row().
 4833:              &Apache::loncommon::start_data_table_row().'<td>';
 4834:     my $upload=&mt("Upload Scores");
 4835:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4836:     my $ignore=&mt('Ignore First Line');
 4837:     $symb = &Apache::lonenc::check_encrypt($symb);
 4838:     $result.=<<ENDUPFORM;
 4839: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4840: <input type="hidden" name="symb" value="$symb" />
 4841: <input type="hidden" name="command" value="csvuploadmap" />
 4842: $upfile_select
 4843: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4844: </form>
 4845: ENDUPFORM
 4846:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4847:                            &mt("How do I create a CSV file from a spreadsheet")).
 4848:              '</td>'.
 4849:             &Apache::loncommon::end_data_table_row().
 4850:             &Apache::loncommon::end_data_table();
 4851:     return $result;
 4852: }
 4853: 
 4854: 
 4855: sub csvuploadmap {
 4856:     my ($request,$symb) = @_;
 4857:     if (!$symb) {return '';}
 4858: 
 4859:     my $datatoken;
 4860:     if (!$env{'form.datatoken'}) {
 4861: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4862:     } else {
 4863: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4864:         if ($datatoken ne '') {
 4865: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4866:         }
 4867:     }
 4868:     my @records=&Apache::loncommon::upfile_record_sep();
 4869:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4870:     my ($i,$keyfields);
 4871:     if (@records) {
 4872:         my $fieldserror;
 4873: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4874:         if ($fieldserror) {
 4875:             $request->print(&navmap_errormsg());
 4876:             return;
 4877:         }
 4878: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4879: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4880: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4881: 							  \@fields);
 4882: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4883: 	    chop($keyfields);
 4884: 	} else {
 4885: 	    unshift(@fields,['none','']);
 4886: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4887: 							    \@fields);
 4888:             foreach my $rec (@records) {
 4889:                 my %temp = &Apache::loncommon::record_sep($rec);
 4890:                 if (%temp) {
 4891:                     $keyfields=join(',',sort(keys(%temp)));
 4892:                     last;
 4893:                 }
 4894:             }
 4895: 	}
 4896:     }
 4897:     &csvuploadmap_footer($request,$i,$keyfields);
 4898: 
 4899:     return '';
 4900: }
 4901: 
 4902: sub csvuploadoptions {
 4903:     my ($request,$symb)= @_;
 4904:     my $overwrite=&mt('Overwrite any existing score');
 4905:     $request->print(<<ENDPICK);
 4906: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4907: <input type="hidden" name="command"    value="csvuploadassign" />
 4908: <p>
 4909: <label>
 4910:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4911:    $overwrite
 4912: </label>
 4913: </p>
 4914: ENDPICK
 4915:     my %fields=&get_fields();
 4916:     if (!defined($fields{'domain'})) {
 4917: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4918: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4919:     }
 4920:     foreach my $key (sort(keys(%env))) {
 4921: 	if ($key !~ /^form\.(.*)$/) { next; }
 4922: 	my $cleankey=$1;
 4923: 	if ($cleankey eq 'command') { next; }
 4924: 	$request->print('<input type="hidden" name="'.$cleankey.
 4925: 			'"  value="'.$env{$key}.'" />'."\n");
 4926:     }
 4927:     # FIXME do a check for any duplicated user ids...
 4928:     # FIXME do a check for any invalid user ids?...
 4929:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4930: <hr /></form>'."\n");
 4931:     return '';
 4932: }
 4933: 
 4934: sub get_fields {
 4935:     my %fields;
 4936:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4937:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4938: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4939: 	    if ($env{'form.f'.$i} ne 'none') {
 4940: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4941: 	    }
 4942: 	} else {
 4943: 	    if ($env{'form.f'.$i} ne 'none') {
 4944: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4945: 	    }
 4946: 	}
 4947:     }
 4948:     return %fields;
 4949: }
 4950: 
 4951: sub csvuploadassign {
 4952:     my ($request,$symb) = @_;
 4953:     if (!$symb) {return '';}
 4954:     my $error_msg = '';
 4955:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4956:     if ($datatoken ne '') { 
 4957:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4958:     }
 4959:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4960:     my %fields=&get_fields();
 4961:     my $courseid=$env{'request.course.id'};
 4962:     my ($classlist) = &getclasslist('all',0);
 4963:     my @notallowed;
 4964:     my @skipped;
 4965:     my @warnings;
 4966:     my $countdone=0;
 4967:     foreach my $grade (@gradedata) {
 4968: 	my %entries=&Apache::loncommon::record_sep($grade);
 4969: 	my $domain;
 4970: 	if ($entries{$fields{'domain'}}) {
 4971: 	    $domain=$entries{$fields{'domain'}};
 4972: 	} else {
 4973: 	    $domain=$env{'form.default_domain'};
 4974: 	}
 4975: 	$domain=~s/\s//g;
 4976: 	my $username=$entries{$fields{'username'}};
 4977: 	$username=~s/\s//g;
 4978: 	if (!$username) {
 4979: 	    my $id=$entries{$fields{'ID'}};
 4980: 	    $id=~s/\s//g;
 4981:             if ($id ne '') {
 4982: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4983: 	        $username=$ids{$id};
 4984:             } else {
 4985:                 if ($entries{$fields{'clicker'}}) {
 4986:                     my $clicker = $entries{$fields{'clicker'}};
 4987:                     $clicker=~s/\s//g;
 4988:                     if ($clicker ne '') {
 4989:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4990:                         if ($clickers{$clicker} ne '') {  
 4991:                             my $match = 0;
 4992:                             my @inclass;
 4993:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4994:                                 if (exists($$classlist{"$poss:$domain"})) {
 4995:                                     $username = $poss;
 4996:                                     push(@inclass,$poss);
 4997:                                     $match ++;
 4998:                                     
 4999:                                 }
 5000:                             }
 5001:                             if ($match > 1) {
 5002:                                 undef($username); 
 5003:                                 $request->print('<p class="LC_warning">'.
 5004:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 5005:                                                 $clicker,join(', ',@inclass)).'</p>');
 5006:                             }
 5007:                         }
 5008:                     }
 5009:                 }
 5010:             }
 5011: 	}
 5012: 	if (!exists($$classlist{"$username:$domain"})) {
 5013: 	    my $id=$entries{$fields{'ID'}};
 5014: 	    $id=~s/\s//g;
 5015:             my $clicker = $entries{$fields{'clicker'}};
 5016:             $clicker=~s/\s//g;
 5017:             if ($clicker) {
 5018:                 push(@skipped,"$clicker:$domain");
 5019: 	    } elsif ($id) {
 5020: 		push(@skipped,"$id:$domain");
 5021: 	    } else {
 5022: 		push(@skipped,"$username:$domain");
 5023: 	    }
 5024: 	    next;
 5025: 	}
 5026: 	my $usec=$classlist->{"$username:$domain"}[5];
 5027: 	if (!&canmodify($usec)) {
 5028: 	    push(@notallowed,"$username:$domain");
 5029: 	    next;
 5030: 	}
 5031: 	my %points;
 5032: 	my %grades;
 5033: 	foreach my $dest (keys(%fields)) {
 5034: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5035: 		$dest eq 'domain') { next; }
 5036: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5037: 	    if ($dest=~/stores_(.*)_points/) {
 5038: 		my $part=$1;
 5039: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5040: 					      $symb,$domain,$username);
 5041:                 if ($wgt) {
 5042:                     $entries{$fields{$dest}}=~s/\s//g;
 5043:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5044:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5045:                                           : 'correct_by_override';
 5046:                     if ($pcr>1) {
 5047:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5048:                     }
 5049:                     $grades{"resource.$part.awarded"}=$pcr;
 5050:                     $grades{"resource.$part.solved"}=$award;
 5051:                     $points{$part}=1;
 5052:                 } else {
 5053:                     $error_msg = "<br />" .
 5054:                         &mt("Some point values were assigned"
 5055:                             ." for problems with a weight "
 5056:                             ."of zero. These values were "
 5057:                             ."ignored.");
 5058:                 }
 5059: 	    } else {
 5060: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5061: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5062: 		my $store_key=$dest;
 5063: 		$store_key=~s/^stores/resource/;
 5064: 		$store_key=~s/_/\./g;
 5065: 		$grades{$store_key}=$entries{$fields{$dest}};
 5066: 	    }
 5067: 	}
 5068: 	if (! %grades) {
 5069:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5070:         } else {
 5071: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5072: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5073: 					   $env{'request.course.id'},
 5074: 					   $domain,$username);
 5075: 	   if ($result eq 'ok') {
 5076: # Successfully stored
 5077: 	      $request->print('.');
 5078: # Remove from grading queue
 5079:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5080:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5081:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5082:                                              $domain,$username);
 5083:               $countdone++;
 5084:            } else {
 5085: 	      $request->print("<p><span class=\"LC_error\">".
 5086:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5087:                                   "$username:$domain",$result)."</span></p>");
 5088: 	   }
 5089: 	   $request->rflush();
 5090:         }
 5091:     }
 5092:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5093:     if (@warnings) {
 5094:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5095:         $request->print(join(', ',@warnings));
 5096:     }
 5097:     if (@skipped) {
 5098: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5099:         $request->print(join(', ',@skipped));
 5100:     }
 5101:     if (@notallowed) {
 5102: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5103: 	$request->print(join(', ',@notallowed));
 5104:     }
 5105:     $request->print("<br />\n");
 5106:     return $error_msg;
 5107: }
 5108: #------------- end of section for handling csv file upload ---------
 5109: #
 5110: #-------------------------------------------------------------------
 5111: #
 5112: #-------------- Next few routines handle grading by page/sequence
 5113: #
 5114: #--- Select a page/sequence and a student to grade
 5115: sub pickStudentPage {
 5116:     my ($request,$symb) = @_;
 5117: 
 5118:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5119:     &js_escape(\$alertmsg);
 5120:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5121: 
 5122: function checkPickOne(formname) {
 5123:     if (radioSelection(formname.student) == null) {
 5124: 	alert("$alertmsg");
 5125: 	return;
 5126:     }
 5127:     ptr = pullDownSelection(formname.selectpage);
 5128:     formname.page.value = formname["page"+ptr].value;
 5129:     formname.title.value = formname["title"+ptr].value;
 5130:     formname.submit();
 5131: }
 5132: 
 5133: LISTJAVASCRIPT
 5134:     &commonJSfunctions($request);
 5135: 
 5136:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5137:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5138:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5139:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5140: 
 5141:     my $result='<h3><span class="LC_info">&nbsp;'.
 5142: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5143: 
 5144:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5145:     my $map_error;
 5146:     my ($titles,$symbx) = &getSymbMap($map_error);
 5147:     if ($map_error) {
 5148:         $request->print(&navmap_errormsg());
 5149:         return; 
 5150:     }
 5151:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5152: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5153: #    my $type=($curpage =~ /\.(page|sequence)/);
 5154: 
 5155:     # Collection of hidden fields
 5156:     my $ctr=0;
 5157:     foreach (@$titles) {
 5158:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5159:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5160:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5161:         $ctr++;
 5162:     }
 5163:     $result.='<input type="hidden" name="page" />'."\n".
 5164:         '<input type="hidden" name="title" />'."\n";
 5165: 
 5166:     $result.=&build_section_inputs();
 5167:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5168:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5169: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 5170: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5171: 
 5172:     # Show grading options
 5173:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5174:     my $select = '<select name="selectpage">'."\n";
 5175:     $ctr=0;
 5176:     foreach (@$titles) {
 5177: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5178: 	$select.='<option value="'.$ctr.'"'.
 5179: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5180: 	    '>'.$showtitle.'</option>'."\n";
 5181: 	$ctr++;
 5182:     }
 5183:     $select.= '</select>';
 5184: 
 5185:     $result.=
 5186:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5187:        .$select
 5188:        .&Apache::lonhtmlcommon::row_closure();
 5189: 
 5190:     $result.=
 5191:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5192:        .'<label><input type="radio" name="vProb" value="no"'
 5193:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5194:        .'<label><input type="radio" name="vProb" value="yes" />'
 5195:            .&mt('yes').'</label>'."\n"
 5196:        .&Apache::lonhtmlcommon::row_closure();
 5197: 
 5198:     $result.=
 5199:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5200:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5201:            .&mt('none').' </label>'."\n"
 5202:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5203:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5204:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5205:            .&mt('all submissions with details').' </label>'
 5206:        .&Apache::lonhtmlcommon::row_closure();
 5207:     
 5208:     $result.=
 5209:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5210:        .'<input type="text" name="CODE" value="" />'
 5211:        .&Apache::lonhtmlcommon::row_closure(1)
 5212:        .&Apache::lonhtmlcommon::end_pick_box();
 5213: 
 5214:     # Show list of students to select for grading
 5215:     $result.='<br /><input type="button" '.
 5216:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5217: 
 5218:     $request->print($result);
 5219: 
 5220:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5221: 	&Apache::loncommon::start_data_table().
 5222: 	&Apache::loncommon::start_data_table_header_row().
 5223: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5224: 	'<th>'.&nameUserString('header').'</th>'.
 5225: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5226: 	'<th>'.&nameUserString('header').'</th>'.
 5227: 	&Apache::loncommon::end_data_table_header_row();
 5228:  
 5229:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5230:     my $ptr = 1;
 5231:     foreach my $student (sort 
 5232: 			 {
 5233: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5234: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5235: 			     }
 5236: 			     return $a cmp $b;
 5237: 			 } (keys(%$fullname))) {
 5238: 	my ($uname,$udom) = split(/:/,$student);
 5239: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5240:                                   : '</td>');
 5241: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5242: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5243: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5244: 	$studentTable.=
 5245: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5246:                          : '');
 5247: 	$ptr++;
 5248:     }
 5249:     if ($ptr%2 == 0) {
 5250: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5251: 	    &Apache::loncommon::end_data_table_row();
 5252:     }
 5253:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5254:     $studentTable.='<input type="button" '.
 5255:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5256: 
 5257:     $request->print($studentTable);
 5258: 
 5259:     return '';
 5260: }
 5261: 
 5262: sub getSymbMap {
 5263:     my ($map_error) = @_;
 5264:     my $navmap = Apache::lonnavmaps::navmap->new();
 5265:     unless (ref($navmap)) {
 5266:         if (ref($map_error)) {
 5267:             $$map_error = 'navmap';
 5268:         }
 5269:         return;
 5270:     }
 5271:     my %symbx = ();
 5272:     my @titles = ();
 5273:     my $minder = 0;
 5274: 
 5275:     # Gather every sequence that has problems.
 5276:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5277: 					       1,0,1);
 5278:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5279: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5280: 	    my $title = $minder.'.'.
 5281: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5282: 	    push(@titles, $title); # minder in case two titles are identical
 5283: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5284: 	    $minder++;
 5285: 	}
 5286:     }
 5287:     return \@titles,\%symbx;
 5288: }
 5289: 
 5290: #
 5291: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5292: sub displayPage {
 5293:     my ($request,$symb) = @_;
 5294:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5295:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5296:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5297:     my $pageTitle = $env{'form.page'};
 5298:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5299:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5300:     my $usec=$classlist->{$env{'form.student'}}[5];
 5301: 
 5302:     #need to make sure we have the correct data for later EXT calls, 
 5303:     #thus invalidate the cache
 5304:     &Apache::lonnet::devalidatecourseresdata(
 5305:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5306:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5307:     &Apache::lonnet::clear_EXT_cache_status();
 5308: 
 5309:     if (!&canview($usec)) {
 5310:         $request->print(
 5311:             '<span class="LC_warning">'.
 5312:             &mt('Unable to view requested student. ([_1])',
 5313:                     $env{'form.student'}).
 5314:             '</span>');
 5315:         return;
 5316:     }
 5317:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5318:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5319: 	'</h3>'."\n";
 5320:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5321:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5322: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5323:     } else {
 5324: 	delete($env{'form.CODE'});
 5325:     }
 5326:     &sub_page_js($request);
 5327:     $request->print($result);
 5328: 
 5329:     my $navmap = Apache::lonnavmaps::navmap->new();
 5330:     unless (ref($navmap)) {
 5331:         $request->print(&navmap_errormsg());
 5332:         return;
 5333:     }
 5334:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5335:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5336:     if (!$map) {
 5337: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5338: 	return; 
 5339:     }
 5340:     my $iterator = $navmap->getIterator($map->map_start(),
 5341: 					$map->map_finish());
 5342: 
 5343:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5344: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5345: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5346: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5347: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5348: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5349: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5350: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5351: 
 5352:     if (defined($env{'form.CODE'})) {
 5353: 	$studentTable.=
 5354: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5355:     }
 5356:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5357: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5358: 
 5359:     $studentTable.='&nbsp;<span class="LC_info">'.
 5360:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5361:         '</span>'."\n".
 5362: 	&Apache::loncommon::start_data_table().
 5363: 	&Apache::loncommon::start_data_table_header_row().
 5364: 	'<th>'.&mt('Prob.').'</th>'.
 5365: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5366: 	&Apache::loncommon::end_data_table_header_row();
 5367: 
 5368:     &Apache::lonxml::clear_problem_counter();
 5369:     my ($depth,$question,$prob) = (1,1,1);
 5370:     $iterator->next(); # skip the first BEGIN_MAP
 5371:     my $curRes = $iterator->next(); # for "current resource"
 5372:     while ($depth > 0) {
 5373:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5374:         if($curRes == $iterator->END_MAP) { $depth--; }
 5375: 
 5376:         if (ref($curRes) && $curRes->is_gradable()) {
 5377: 	    my $parts = $curRes->parts();
 5378:             my $title = $curRes->compTitle();
 5379: 	    my $symbx = $curRes->symb();
 5380:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5381: 	    $studentTable.=
 5382: 		&Apache::loncommon::start_data_table_row().
 5383: 		'<td align="center" valign="top" >'.$prob.
 5384: 		(scalar(@{$parts}) == 1 ? '' 
 5385: 		                        : '<br />('.&mt('[_1]parts',
 5386: 							scalar(@{$parts}).'&nbsp;').')'
 5387: 		 ).
 5388: 		 '</td>';
 5389: 	    $studentTable.='<td valign="top">';
 5390: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5391:             if ($is_tool) {
 5392:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5393:             } else {
 5394: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5395: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5396: 					         undef,'both',\%form);
 5397: 	        } else {
 5398: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5399: 		    $companswer =~ s|<form(.*?)>||g;
 5400: 		    $companswer =~ s|</form>||g;
 5401: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5402: #		        $companswer =~ s/$1/ /ms;
 5403: #		        $request->print('match='.$1."<br />\n");
 5404: #		    }
 5405: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5406: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5407: 		}
 5408: 	    }
 5409: 
 5410: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5411: 
 5412: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5413: 		if ($record{'version'} eq '') {
 5414:                     my $msg = &mt('No recorded submission for this problem.');
 5415:                     if ($is_tool) {
 5416:                         $msg = &mt('No recorded transactions for this external tool');
 5417:                     }
 5418: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5419: 		} else {
 5420: 		    my %responseType = ();
 5421: 		    foreach my $partid (@{$parts}) {
 5422: 			my @responseIds =$curRes->responseIds($partid);
 5423: 			my @responseType =$curRes->responseType($partid);
 5424: 			my %responseIds;
 5425: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5426: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5427: 			}
 5428: 			$responseType{$partid} = \%responseIds;
 5429: 		    }
 5430: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5431: 		}
 5432: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5433: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5434:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5435: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5436: 									$env{'request.course.id'},
 5437: 									'','.submission',undef,
 5438:                                                                         $usec,$identifier);
 5439:  
 5440: 	    }
 5441: 	    if (&canmodify($usec)) {
 5442:             $studentTable.=&gradeBox_start();
 5443: 		foreach my $partid (@{$parts}) {
 5444: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5445: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5446: 		    $question++;
 5447: 		}
 5448:             $studentTable.=&gradeBox_end();
 5449: 		$prob++;
 5450: 	    }
 5451: 	    $studentTable.='</td></tr>';
 5452: 
 5453: 	}
 5454:         $curRes = $iterator->next();
 5455:     }
 5456:     my $disabled;
 5457:     unless (&canmodify($usec)) {
 5458:         $disabled = ' disabled="disabled"';
 5459:     }
 5460: 
 5461:     $studentTable.=
 5462:         '</table>'."\n".
 5463:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5464:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5465:         '</form>'."\n";
 5466:     $request->print($studentTable);
 5467: 
 5468:     return '';
 5469: }
 5470: 
 5471: sub displaySubByDates {
 5472:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5473:     my $isCODE=0;
 5474:     my $isTask = ($symb =~/\.task$/);
 5475:     my $is_tool = ($symb =~/\.tool$/);
 5476:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5477:     my $studentTable=&Apache::loncommon::start_data_table().
 5478: 	&Apache::loncommon::start_data_table_header_row().
 5479: 	'<th>'.&mt('Date/Time').'</th>'.
 5480: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5481:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5482: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5483: 	'<th>'.&mt('Status').'</th>'.
 5484: 	&Apache::loncommon::end_data_table_header_row();
 5485:     my ($version);
 5486:     my %mark;
 5487:     my %orders;
 5488:     $mark{'correct_by_student'} = $checkIcon;
 5489:     if (!exists($$record{'1:timestamp'})) {
 5490:         if ($is_tool) {
 5491:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5492:         } else {
 5493:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5494:         }
 5495:     }
 5496: 
 5497:     my $interaction;
 5498:     my $no_increment = 1;
 5499:     my (%lastrndseed,%lasttype);
 5500:     for ($version=1;$version<=$$record{'version'};$version++) {
 5501: 	my $timestamp = 
 5502: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5503: 	if (exists($$record{$version.':resource.0.version'})) {
 5504: 	    $interaction = $$record{$version.':resource.0.version'};
 5505: 	}
 5506:         if ($isTask && $env{'form.previousversion'}) {
 5507:             next unless ($interaction == $env{'form.previousversion'});
 5508:         }
 5509: 	my $where = ($isTask ? "$version:resource.$interaction"
 5510: 		             : "$version:resource");
 5511: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5512: 	    '<td>'.$timestamp.'</td>';
 5513: 	if ($isCODE) {
 5514: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5515: 	}
 5516:         if ($isTask) {
 5517:             $studentTable.='<td>'.$interaction.'</td>';
 5518:         }
 5519: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5520: 	my @displaySub = ();
 5521: 	foreach my $partid (@{$parts}) {
 5522:             my ($hidden,$type);
 5523:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5524:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5525:                 $hidden = 1;
 5526:             }
 5527:             my @matchKey;
 5528:             if ($isTask) {
 5529:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5530:             } elsif ($is_tool) {
 5531:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
 5532:             } else {
 5533:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5534:             }
 5535: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5536: 	    my $display_part=&get_display_part($partid,$symb);
 5537: 	    foreach my $matchKey (@matchKey) {
 5538: 		if (exists($$record{$version.':'.$matchKey}) &&
 5539: 		    $$record{$version.':'.$matchKey} ne '') {
 5540:                     if ($is_tool) {
 5541:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5542:                     } else {
 5543: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5544: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5545:                         $displaySub[0].='<span class="LC_nobreak">';
 5546:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5547:                                        .' <span class="LC_internal_info">'
 5548:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5549:                                        .'</span>'
 5550:                                        .' <b>';
 5551:                         if ($hidden) {
 5552:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5553:                         } else {
 5554:                             my ($trial,$rndseed,$newvariation);
 5555:                             if ($type eq 'randomizetry') {
 5556:                                 $trial = $$record{"$where.$partid.tries"};
 5557:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5558:                             }
 5559: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5560: 			        $displaySub[0].=&mt('Trial not counted');
 5561: 		            } else {
 5562: 			        $displaySub[0].=&mt('Trial: [_1]',
 5563: 					        $$record{"$where.$partid.tries"});
 5564:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5565:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5566:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5567:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5568:                                     }
 5569:                                 }
 5570:                                 $lastrndseed{$partid} = $rndseed;
 5571:                                 $lasttype{$partid} = $type;
 5572: 		            }
 5573: 		            my $responseType=($isTask ? 'Task'
 5574:                                               : $responseType->{$partid}->{$responseId});
 5575: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5576: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5577: 			        $orders{$partid}->{$responseId}=
 5578: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5579:                                                $no_increment,$type,$trial,$rndseed);
 5580: 		            }
 5581: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5582: 		            $displaySub[0].='&nbsp; '.
 5583: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5584:                         }
 5585:                     }
 5586: 		}
 5587: 	    }
 5588: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5589: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5590: 				    $$record{"$where.$partid.checkedin"},
 5591: 				    $$record{"$where.$partid.checkedin.slot"}).
 5592: 					'<br />';
 5593: 	    }
 5594: 	    if (exists $$record{"$where.$partid.award"}) {
 5595: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5596: 		    lc($$record{"$where.$partid.award"}).' '.
 5597: 		    $mark{$$record{"$where.$partid.solved"}}.
 5598: 		    '<br />';
 5599: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5600: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5601: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5602: 		}
 5603: 	    }
 5604: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5605: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5606: 		unless ($is_tool) {
 5607: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5608: 		}
 5609: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5610: 		$displaySub[2].=
 5611: 		    $$record{"$version:resource.$partid.regrader"};
 5612:                 unless ($is_tool) {
 5613: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5614:                 }
 5615: 	    }
 5616: 	}
 5617: 	# needed because old essay regrader has not parts info
 5618: 	if (exists $$record{"$version:resource.regrader"}) {
 5619: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5620: 	}
 5621: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5622: 	if ($displaySub[2]) {
 5623: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5624: 	}
 5625: 	$studentTable.='&nbsp;</td>'.
 5626: 	    &Apache::loncommon::end_data_table_row();
 5627:     }
 5628:     $studentTable.=&Apache::loncommon::end_data_table();
 5629:     return $studentTable;
 5630: }
 5631: 
 5632: sub updateGradeByPage {
 5633:     my ($request,$symb) = @_;
 5634: 
 5635:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5636:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5637:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5638:     my $pageTitle = $env{'form.page'};
 5639:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5640:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5641:     my $usec=$classlist->{$env{'form.student'}}[5];
 5642:     if (!&canmodify($usec)) {
 5643: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5644: 	return;
 5645:     }
 5646:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5647:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5648: 	'</h3>'."\n";
 5649: 
 5650:     $request->print($result);
 5651: 
 5652: 
 5653:     my $navmap = Apache::lonnavmaps::navmap->new();
 5654:     unless (ref($navmap)) {
 5655:         $request->print(&navmap_errormsg());
 5656:         return;
 5657:     }
 5658:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5659:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5660:     if (!$map) {
 5661: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5662: 	return; 
 5663:     }
 5664:     my $iterator = $navmap->getIterator($map->map_start(),
 5665: 					$map->map_finish());
 5666: 
 5667:     my $studentTable=
 5668: 	&Apache::loncommon::start_data_table().
 5669: 	&Apache::loncommon::start_data_table_header_row().
 5670: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5671: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5672: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5673: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5674: 	&Apache::loncommon::end_data_table_header_row();
 5675: 
 5676:     $iterator->next(); # skip the first BEGIN_MAP
 5677:     my $curRes = $iterator->next(); # for "current resource"
 5678:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5679:     while ($depth > 0) {
 5680:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5681:         if($curRes == $iterator->END_MAP) { $depth--; }
 5682: 
 5683:         if (ref($curRes) && $curRes->is_problem()) {
 5684: 	    my $parts = $curRes->parts();
 5685:             my $title = $curRes->compTitle();
 5686: 	    my $symbx = $curRes->symb();
 5687: 	    $studentTable.=
 5688: 		&Apache::loncommon::start_data_table_row().
 5689: 		'<td align="center" valign="top" >'.$prob.
 5690: 		(scalar(@{$parts}) == 1 ? '' 
 5691:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5692: 		.')').'</td>';
 5693: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5694: 
 5695: 	    my %newrecord=();
 5696: 	    my @displayPts=();
 5697:             my %aggregate = ();
 5698:             my $aggregateflag = 0;
 5699:             if ($env{'form.HIDE'.$prob}) {
 5700:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5701:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5702:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5703:                 $hideflag += $numchgs;
 5704:             }
 5705: 	    foreach my $partid (@{$parts}) {
 5706: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5707: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5708: 
 5709: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5710: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5711: 		my $partial = $newpts/$wgt;
 5712: 		my $score;
 5713: 		if ($partial > 0) {
 5714: 		    $score = 'correct_by_override';
 5715: 		} elsif ($newpts ne '') { #empty is taken as 0
 5716: 		    $score = 'incorrect_by_override';
 5717: 		}
 5718: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5719: 		if ($dropMenu eq 'excused') {
 5720: 		    $partial = '';
 5721: 		    $score = 'excused';
 5722: 		} elsif ($dropMenu eq 'reset status'
 5723: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5724: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5725: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5726: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5727: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5728: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5729: 		    $changeflag++;
 5730: 		    $newpts = '';
 5731:                     
 5732:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5733:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5734:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5735:                     if ($aggtries > 0) {
 5736:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5737:                         $aggregateflag = 1;
 5738:                     }
 5739: 		}
 5740: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5741: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5742: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5743: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5744: 		    '&nbsp;<br />';
 5745: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5746: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5747: 		    '&nbsp;<br />';
 5748: 		$question++;
 5749: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5750: 
 5751: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5752: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5753: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5754: 		    if (scalar(keys(%newrecord)) > 0);
 5755: 
 5756: 		$changeflag++;
 5757: 	    }
 5758: 	    if (scalar(keys(%newrecord)) > 0) {
 5759: 		my %record = 
 5760: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5761: 					     $udom,$uname);
 5762: 
 5763: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5764: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5765: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5766: 		    $newrecord{'resource.CODE'} = '';
 5767: 		}
 5768: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5769: 					$udom,$uname);
 5770: 		%record = &Apache::lonnet::restore($symbx,
 5771: 						   $env{'request.course.id'},
 5772: 						   $udom,$uname);
 5773: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5774: 					     $cdom,$cnum,$udom,$uname);
 5775: 	    }
 5776: 	    
 5777:             if ($aggregateflag) {
 5778:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5779:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5780:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5781:             }
 5782: 
 5783: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5784: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5785: 		&Apache::loncommon::end_data_table_row();
 5786: 
 5787: 	    $prob++;
 5788: 	}
 5789:         $curRes = $iterator->next();
 5790:     }
 5791: 
 5792:     $studentTable.=&Apache::loncommon::end_data_table();
 5793:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5794: 		  &mt('The scores were changed for [quant,_1,problem].',
 5795: 		  $changeflag).'<br />');
 5796:     my $hidemsg=($hideflag == 0 ? '' :
 5797:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5798:                      $hideflag).'<br />');
 5799:     $request->print($hidemsg.$grademsg.$studentTable);
 5800: 
 5801:     return '';
 5802: }
 5803: 
 5804: #-------- end of section for handling grading by page/sequence ---------
 5805: #
 5806: #-------------------------------------------------------------------
 5807: 
 5808: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5809: #
 5810: #------ start of section for handling grading by page/sequence ---------
 5811: 
 5812: =pod
 5813: 
 5814: =head1 Bubble sheet grading routines
 5815: 
 5816:   For this documentation:
 5817: 
 5818:    'scanline' refers to the full line of characters
 5819:    from the file that we are parsing that represents one entire sheet
 5820: 
 5821:    'bubble line' refers to the data
 5822:    representing the line of bubbles that are on the physical bubblesheet
 5823: 
 5824: 
 5825: The overall process is that a scanned in bubblesheet data is uploaded
 5826: into a course. When a user wants to grade, they select a
 5827: sequence/folder of resources, a file of bubblesheet info, and pick
 5828: one of the predefined configurations for what each scanline looks
 5829: like.
 5830: 
 5831: Next each scanline is checked for any errors of either 'missing
 5832: bubbles' (it's an error because it may have been mis-scanned
 5833: because too light bubbling), 'double bubble' (each bubble line should
 5834: have no more than one letter picked), invalid or duplicated CODE,
 5835: invalid student/employee ID
 5836: 
 5837: If the CODE option is used that determines the randomization of the
 5838: homework problems, either way the student/employee ID is looked up into a
 5839: username:domain.
 5840: 
 5841: During the validation phase the instructor can choose to skip scanlines. 
 5842: 
 5843: After the validation phase, there are now 3 bubblesheet files
 5844: 
 5845:   scantron_original_filename (unmodified original file)
 5846:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5847:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5848: 
 5849: Also there is a separate hash nohist_scantrondata that contains extra
 5850: correction information that isn't representable in the bubblesheet
 5851: file (see &scantron_getfile() for more information)
 5852: 
 5853: After all scanlines are either valid, marked as valid or skipped, then
 5854: foreach line foreach problem in the picked sequence, an ssi request is
 5855: made that simulates a user submitting their selected letter(s) against
 5856: the homework problem.
 5857: 
 5858: =over 4
 5859: 
 5860: 
 5861: 
 5862: =item defaultFormData
 5863: 
 5864:   Returns html hidden inputs used to hold context/default values.
 5865: 
 5866:  Arguments:
 5867:   $symb - $symb of the current resource 
 5868: 
 5869: =cut
 5870: 
 5871: sub defaultFormData {
 5872:     my ($symb)=@_;
 5873:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5874: }
 5875: 
 5876: 
 5877: =pod 
 5878: 
 5879: =item getSequenceDropDown
 5880: 
 5881:    Return html dropdown of possible sequences to grade
 5882:  
 5883:  Arguments:
 5884:    $symb - $symb of the current resource
 5885:    $map_error - ref to scalar which will container error if
 5886:                 $navmap object is unavailable in &getSymbMap().
 5887: 
 5888: =cut
 5889: 
 5890: sub getSequenceDropDown {
 5891:     my ($symb,$map_error)=@_;
 5892:     my $result='<select name="selectpage">'."\n";
 5893:     my ($titles,$symbx) = &getSymbMap($map_error);
 5894:     if (ref($map_error)) {
 5895:         return if ($$map_error);
 5896:     }
 5897:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5898:     my $ctr=0;
 5899:     foreach (@$titles) {
 5900: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5901: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5902: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5903: 	    '>'.$showtitle.'</option>'."\n";
 5904: 	$ctr++;
 5905:     }
 5906:     $result.= '</select>';
 5907:     return $result;
 5908: }
 5909: 
 5910: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5911:                                    # key is zero-based index - 0, 1, 2 ...
 5912: 
 5913: my %first_bubble_line;             # First bubble line no. for each bubble.
 5914: 
 5915: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5916:                                    # matchresponse or rankresponse, where 
 5917:                                    # an individual response can have multiple 
 5918:                                    # lines
 5919: 
 5920: my %responsetype_per_response;     # responsetype for each response
 5921: 
 5922: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5923:                                    # numbered response. Needed when randomorder
 5924:                                    # or randompick are in use. Key is ID, value 
 5925:                                    # is response number.
 5926: 
 5927: # Save and restore the bubble lines array to the form env.
 5928: 
 5929: 
 5930: sub save_bubble_lines {
 5931:     foreach my $line (keys(%bubble_lines_per_response)) {
 5932: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5933: 	$env{"form.scantron.first_bubble_line.$line"} =
 5934: 	    $first_bubble_line{$line};
 5935:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5936:             $subdivided_bubble_lines{$line};
 5937:         $env{"form.scantron.responsetype.$line"} =
 5938:             $responsetype_per_response{$line};
 5939:     }
 5940:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5941:         my $line = $masterseq_id_responsenum{$resid};
 5942:         $env{"form.scantron.residpart.$line"} = $resid;
 5943:     }
 5944: }
 5945: 
 5946: 
 5947: sub restore_bubble_lines {
 5948:     my $line = 0;
 5949:     %bubble_lines_per_response = ();
 5950:     %masterseq_id_responsenum = ();
 5951:     while ($env{"form.scantron.bubblelines.$line"}) {
 5952: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5953: 	$bubble_lines_per_response{$line} = $value;
 5954: 	$first_bubble_line{$line}  =
 5955: 	    $env{"form.scantron.first_bubble_line.$line"};
 5956:         $subdivided_bubble_lines{$line} =
 5957:             $env{"form.scantron.sub_bubblelines.$line"};
 5958:         $responsetype_per_response{$line} =
 5959:             $env{"form.scantron.responsetype.$line"};
 5960:         my $id = $env{"form.scantron.residpart.$line"};
 5961:         $masterseq_id_responsenum{$id} = $line;
 5962: 	$line++;
 5963:     }
 5964: }
 5965: 
 5966: =pod 
 5967: 
 5968: =item scantron_filenames
 5969: 
 5970:    Returns a list of the scantron files in the current course 
 5971: 
 5972: =cut
 5973: 
 5974: sub scantron_filenames {
 5975:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5976:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5977:     my $getpropath = 1;
 5978:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5979:                                                         $cname,$getpropath);
 5980:     my @possiblenames;
 5981:     if (ref($dirlist) eq 'ARRAY') {
 5982:         foreach my $filename (sort(@{$dirlist})) {
 5983: 	    ($filename)=split(/&/,$filename);
 5984: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5985: 	    $filename=~s/^scantron_orig_//;
 5986: 	    push(@possiblenames,$filename);
 5987:         }
 5988:     }
 5989:     return @possiblenames;
 5990: }
 5991: 
 5992: =pod 
 5993: 
 5994: =item scantron_uploads
 5995: 
 5996:    Returns  html drop-down list of scantron files in current course.
 5997: 
 5998:  Arguments:
 5999:    $file2grade - filename to set as selected in the dropdown
 6000: 
 6001: =cut
 6002: 
 6003: sub scantron_uploads {
 6004:     my ($file2grade) = @_;
 6005:     my $result=	'<select name="scantron_selectfile">';
 6006:     $result.="<option></option>";
 6007:     foreach my $filename (sort(&scantron_filenames())) {
 6008: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 6009:     }
 6010:     $result.="</select>";
 6011:     return $result;
 6012: }
 6013: 
 6014: =pod 
 6015: 
 6016: =item scantron_scantab
 6017: 
 6018:   Returns html drop down of the scantron formats in the scantronformat.tab
 6019:   file.
 6020: 
 6021: =cut
 6022: 
 6023: sub scantron_scantab {
 6024:     my $result='<select name="scantron_format">'."\n";
 6025:     $result.='<option></option>'."\n";
 6026:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6027:     if (@lines > 0) {
 6028:         foreach my $line (@lines) {
 6029:             next if (($line =~ /^\#/) || ($line eq ''));
 6030: 	    my ($name,$descrip)=split(/:/,$line);
 6031: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6032:         }
 6033:     }
 6034:     $result.='</select>'."\n";
 6035:     return $result;
 6036: }
 6037: 
 6038: =pod 
 6039: 
 6040: =item scantron_CODElist
 6041: 
 6042:   Returns html drop down of the saved CODE lists from current course,
 6043:   generated from earlier printings.
 6044: 
 6045: =cut
 6046: 
 6047: sub scantron_CODElist {
 6048:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6049:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6050:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6051:     my $namechoice='<option></option>';
 6052:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6053: 	if ($name =~ /^error: 2 /) { next; }
 6054: 	if ($name =~ /^type\0/) { next; }
 6055: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6056:     }
 6057:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6058:     return $namechoice;
 6059: }
 6060: 
 6061: =pod 
 6062: 
 6063: =item scantron_CODEunique
 6064: 
 6065:   Returns the html for "Each CODE to be used once" radio.
 6066: 
 6067: =cut
 6068: 
 6069: sub scantron_CODEunique {
 6070:     my $result='<span class="LC_nobreak">
 6071:                  <label><input type="radio" name="scantron_CODEunique"
 6072:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6073:                 </span>
 6074:                 <span class="LC_nobreak">
 6075:                  <label><input type="radio" name="scantron_CODEunique"
 6076:                         value="no" />'.&mt('No').' </label>
 6077:                 </span>';
 6078:     return $result;
 6079: }
 6080: 
 6081: =pod 
 6082: 
 6083: =item scantron_selectphase
 6084: 
 6085:   Generates the initial screen to start the bubblesheet process.
 6086:   Allows for - starting a grading run.
 6087:              - downloading existing scan data (original, corrected
 6088:                                                 or skipped info)
 6089: 
 6090:              - uploading new scan data
 6091: 
 6092:  Arguments:
 6093:   $r          - The Apache request object
 6094:   $file2grade - name of the file that contain the scanned data to score
 6095: 
 6096: =cut
 6097: 
 6098: sub scantron_selectphase {
 6099:     my ($r,$file2grade,$symb) = @_;
 6100:     if (!$symb) {return '';}
 6101:     my $map_error;
 6102:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6103:     if ($map_error) {
 6104:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6105:         return;
 6106:     }
 6107:     my $default_form_data=&defaultFormData($symb);
 6108:     my $file_selector=&scantron_uploads($file2grade);
 6109:     my $format_selector=&scantron_scantab();
 6110:     my $CODE_selector=&scantron_CODElist();
 6111:     my $CODE_unique=&scantron_CODEunique();
 6112:     my $result;
 6113: 
 6114:     $ssi_error = 0;
 6115: 
 6116:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
 6117: 
 6118: 	# Chunk of form to prompt for a scantron file upload.
 6119: 
 6120:         $r->print('
 6121:     <br />');
 6122:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6123:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6124:     my $csec= $env{'request.course.sec'};
 6125:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6126:     &js_escape(\$alertmsg);
 6127:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6128:     $r->print(&Apache::lonhtmlcommon::scripttag('
 6129:     function checkUpload(formname) {
 6130: 	if (formname.upfile.value == "") {
 6131: 	    alert("'.$alertmsg.'");
 6132: 	    return false;
 6133: 	}
 6134: 	formname.submit();
 6135:     }'."\n".$formatjs));
 6136:     $r->print('
 6137:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6138:                 '.$default_form_data.'
 6139:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6140:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
 6141:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6142:                 <input name="command" value="scantronupload_save" type="hidden" />
 6143:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6144:               '.&Apache::loncommon::start_data_table_header_row().'
 6145:                 <th>
 6146:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6147:                 </th>
 6148:               '.&Apache::loncommon::end_data_table_header_row().'
 6149:               '.&Apache::loncommon::start_data_table_row().'
 6150:             <td>
 6151:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6152:     if ($formatoptions) {
 6153:         $r->print('</td>
 6154:                  '.&Apache::loncommon::end_data_table_row().'
 6155:                  '.&Apache::loncommon::start_data_table_row().'
 6156:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6157:                  </td>
 6158:                  '.&Apache::loncommon::end_data_table_row().'
 6159:                  '.&Apache::loncommon::start_data_table_row().'
 6160:                  <td>'
 6161:         );
 6162:     } else {
 6163:         $r->print(' <br />');
 6164:     }
 6165:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6166:               </td>
 6167:              '.&Apache::loncommon::end_data_table_row().'
 6168:              '.&Apache::loncommon::end_data_table().'
 6169:              </form>'
 6170:     );
 6171: 
 6172:     }
 6173: 
 6174:     # Chunk of form to prompt for a file to grade and how:
 6175: 
 6176:     $result.= '
 6177:     <br />
 6178:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6179:     <input type="hidden" name="command" value="scantron_warning" />
 6180:     '.$default_form_data.'
 6181:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6182:        '.&Apache::loncommon::start_data_table_header_row().'
 6183:             <th colspan="2">
 6184:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6185:             </th>
 6186:        '.&Apache::loncommon::end_data_table_header_row().'
 6187:        '.&Apache::loncommon::start_data_table_row().'
 6188:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6189:        '.&Apache::loncommon::end_data_table_row().'
 6190:        '.&Apache::loncommon::start_data_table_row().'
 6191:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6192:        '.&Apache::loncommon::end_data_table_row().'
 6193:        '.&Apache::loncommon::start_data_table_row().'
 6194:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6195:        '.&Apache::loncommon::end_data_table_row().'
 6196:        '.&Apache::loncommon::start_data_table_row().'
 6197:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6198:        '.&Apache::loncommon::end_data_table_row().'
 6199:        '.&Apache::loncommon::start_data_table_row().'
 6200:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6201:        '.&Apache::loncommon::end_data_table_row().'
 6202:        '.&Apache::loncommon::start_data_table_row().'
 6203: 	    <td> '.&mt('Options:').' </td>
 6204:             <td>
 6205: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6206:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6207:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6208: 	    </td>
 6209:        '.&Apache::loncommon::end_data_table_row().'
 6210:        '.&Apache::loncommon::start_data_table_row().'
 6211:             <td colspan="2">
 6212:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6213:             </td>
 6214:        '.&Apache::loncommon::end_data_table_row().'
 6215:     '.&Apache::loncommon::end_data_table().'
 6216:     </form>
 6217: ';
 6218:    
 6219:     $r->print($result);
 6220: 
 6221:     # Chunk of the form that prompts to view a scoring office file,
 6222:     # corrected file, skipped records in a file.
 6223: 
 6224:     $r->print('
 6225:    <br />
 6226:    <form action="/adm/grades" name="scantron_download">
 6227:      '.$default_form_data.'
 6228:      <input type="hidden" name="command" value="scantron_download" />
 6229:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6230:        '.&Apache::loncommon::start_data_table_header_row().'
 6231:               <th>
 6232:                 &nbsp;'.&mt('Download a scoring office file').'
 6233:               </th>
 6234:        '.&Apache::loncommon::end_data_table_header_row().'
 6235:        '.&Apache::loncommon::start_data_table_row().'
 6236:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6237:                 <br />
 6238:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6239:        '.&Apache::loncommon::end_data_table_row().'
 6240:      '.&Apache::loncommon::end_data_table().'
 6241:    </form>
 6242:    <br />
 6243: ');
 6244: 
 6245:     &Apache::lonpickcode::code_list($r,2);
 6246: 
 6247:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6248:              $default_form_data."\n".
 6249:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6250:              &Apache::loncommon::start_data_table_header_row()."\n".
 6251:              '<th colspan="2">
 6252:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6253:              '</th>'."\n".
 6254:               &Apache::loncommon::end_data_table_header_row()."\n".
 6255:               &Apache::loncommon::start_data_table_row()."\n".
 6256:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6257:               '<td> '.$sequence_selector.' </td>'.
 6258:               &Apache::loncommon::end_data_table_row()."\n".
 6259:               &Apache::loncommon::start_data_table_row()."\n".
 6260:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6261:               '<td> '.$file_selector.' </td>'."\n".
 6262:               &Apache::loncommon::end_data_table_row()."\n".
 6263:               &Apache::loncommon::start_data_table_row()."\n".
 6264:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6265:               '<td> '.$format_selector.' </td>'."\n".
 6266:               &Apache::loncommon::end_data_table_row()."\n".
 6267:               &Apache::loncommon::start_data_table_row()."\n".
 6268:               '<td> '.&mt('Options').' </td>'."\n".
 6269:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6270:               &Apache::loncommon::end_data_table_row()."\n".
 6271:               &Apache::loncommon::start_data_table_row()."\n".
 6272:               '<td colspan="2">'."\n".
 6273:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6274:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6275:               '</td>'."\n".
 6276:               &Apache::loncommon::end_data_table_row()."\n".
 6277:               &Apache::loncommon::end_data_table()."\n".
 6278:               '</form><br />');
 6279:     return;
 6280: }
 6281: 
 6282: =pod 
 6283: 
 6284: =item username_to_idmap
 6285: 
 6286:     creates a hash keyed by student/employee ID with values of the corresponding
 6287:     student username:domain. If a single ID occurs for more than one student,
 6288:     the status of the student is checked, and if Active, the value in the hash
 6289:     will be set to the Active student.
 6290: 
 6291:   Arguments:
 6292: 
 6293:     $classlist - reference to the class list hash. This is a hash
 6294:                  keyed by student name:domain  whose elements are references
 6295:                  to arrays containing various chunks of information
 6296:                  about the student. (See loncoursedata for more info).
 6297: 
 6298:   Returns
 6299:     %idmap - the constructed hash
 6300: 
 6301: =cut
 6302: 
 6303: sub username_to_idmap {
 6304:     my ($classlist)= @_;
 6305:     my %idmap;
 6306:     foreach my $student (keys(%$classlist)) {
 6307:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6308:         unless ($id eq '') {
 6309:             if (!exists($idmap{$id})) {
 6310:                 $idmap{$id} = $student;
 6311:             } else {
 6312:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6313:                 if ($status eq 'Active') {
 6314:                     $idmap{$id} = $student;
 6315:                 }
 6316:             }
 6317:         }
 6318:     }
 6319:     return %idmap;
 6320: }
 6321: 
 6322: =pod
 6323: 
 6324: =item scantron_fixup_scanline
 6325: 
 6326:    Process a requested correction to a scanline.
 6327: 
 6328:   Arguments:
 6329:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6330:     $scan_data         - hash of correction information 
 6331:                           (see &scantron_getfile())
 6332:     $line              - existing scanline
 6333:     $whichline         - line number of the passed in scanline
 6334:     $field             - type of change to process 
 6335:                          (either 
 6336:                           'ID'     -> correct the student/employee ID
 6337:                           'CODE'   -> correct the CODE
 6338:                           'answer' -> fixup the submitted answers)
 6339:     
 6340:    $args               - hash of additional info,
 6341:                           - 'ID' 
 6342:                                'newid' -> studentID to use in replacement
 6343:                                           of existing one
 6344:                           - 'CODE' 
 6345:                                'CODE_ignore_dup' - set to true if duplicates
 6346:                                                    should be ignored.
 6347: 	                       'CODE' - is new code or 'use_unfound'
 6348:                                         if the existing unfound code should
 6349:                                         be used as is
 6350:                           - 'answer'
 6351:                                'response' - new answer or 'none' if blank
 6352:                                'question' - the bubble line to change
 6353:                                'questionnum' - the question identifier,
 6354:                                                may include subquestion. 
 6355: 
 6356:   Returns:
 6357:     $line - the modified scanline
 6358: 
 6359:   Side effects: 
 6360:     $scan_data - may be updated
 6361: 
 6362: =cut
 6363: 
 6364: 
 6365: sub scantron_fixup_scanline {
 6366:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6367:     if ($field eq 'ID') {
 6368: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6369: 	    return ($line,1,'New value too large');
 6370: 	}
 6371: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6372: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6373: 				     $args->{'newid'});
 6374: 	}
 6375: 	substr($line,$$scantron_config{'IDstart'}-1,
 6376: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6377: 	if ($args->{'newid'}=~/^\s*$/) {
 6378: 	    &scan_data($scan_data,"$whichline.user",
 6379: 		       $args->{'username'}.':'.$args->{'domain'});
 6380: 	}
 6381:     } elsif ($field eq 'CODE') {
 6382: 	if ($args->{'CODE_ignore_dup'}) {
 6383: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6384: 	}
 6385: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6386: 	if ($args->{'CODE'} ne 'use_unfound') {
 6387: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6388: 		return ($line,1,'New CODE value too large');
 6389: 	    }
 6390: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6391: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6392: 	    }
 6393: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6394: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6395: 	}
 6396:     } elsif ($field eq 'answer') {
 6397: 	my $length=$scantron_config->{'Qlength'};
 6398: 	my $off=$scantron_config->{'Qoff'};
 6399: 	my $on=$scantron_config->{'Qon'};
 6400: 	my $answer=${off}x$length;
 6401: 	if ($args->{'response'} eq 'none') {
 6402: 	    &scan_data($scan_data,
 6403: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6404: 	} else {
 6405: 	    if ($on eq 'letter') {
 6406: 		my @alphabet=('A'..'Z');
 6407: 		$answer=$alphabet[$args->{'response'}];
 6408: 	    } elsif ($on eq 'number') {
 6409: 		$answer=$args->{'response'}+1;
 6410: 		if ($answer == 10) { $answer = '0'; }
 6411: 	    } else {
 6412: 		substr($answer,$args->{'response'},1)=$on;
 6413: 	    }
 6414: 	    &scan_data($scan_data,
 6415: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6416: 	}
 6417: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6418: 	substr($line,$where-1,$length)=$answer;
 6419:     }
 6420:     return $line;
 6421: }
 6422: 
 6423: =pod
 6424: 
 6425: =item scan_data
 6426: 
 6427:     Edit or look up  an item in the scan_data hash.
 6428: 
 6429:   Arguments:
 6430:     $scan_data  - The hash (see scantron_getfile)
 6431:     $key        - shorthand of the key to edit (actual key is
 6432:                   scantronfilename_key).
 6433:     $data        - New value of the hash entry.
 6434:     $delete      - If true, the entry is removed from the hash.
 6435: 
 6436:   Returns:
 6437:     The new value of the hash table field (undefined if deleted).
 6438: 
 6439: =cut
 6440: 
 6441: 
 6442: sub scan_data {
 6443:     my ($scan_data,$key,$value,$delete)=@_;
 6444:     my $filename=$env{'form.scantron_selectfile'};
 6445:     if (defined($value)) {
 6446: 	$scan_data->{$filename.'_'.$key} = $value;
 6447:     }
 6448:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6449:     return $scan_data->{$filename.'_'.$key};
 6450: }
 6451: 
 6452: # ----- These first few routines are general use routines.----
 6453: 
 6454: # Return the number of occurences of a pattern in a string.
 6455: 
 6456: sub occurence_count {
 6457:     my ($string, $pattern) = @_;
 6458: 
 6459:     my @matches = ($string =~ /$pattern/g);
 6460: 
 6461:     return scalar(@matches);
 6462: }
 6463: 
 6464: 
 6465: # Take a string known to have digits and convert all the
 6466: # digits into letters in the range J,A..I.
 6467: 
 6468: sub digits_to_letters {
 6469:     my ($input) = @_;
 6470: 
 6471:     my @alphabet = ('J', 'A'..'I');
 6472: 
 6473:     my @input    = split(//, $input);
 6474:     my $output ='';
 6475:     for (my $i = 0; $i < scalar(@input); $i++) {
 6476: 	if ($input[$i] =~ /\d/) {
 6477: 	    $output .= $alphabet[$input[$i]];
 6478: 	} else {
 6479: 	    $output .= $input[$i];
 6480: 	}
 6481:     }
 6482:     return $output;
 6483: }
 6484: 
 6485: =pod 
 6486: 
 6487: =item scantron_parse_scanline
 6488: 
 6489:   Decodes a scanline from the selected bubblesheet file
 6490: 
 6491:  Arguments:
 6492:     line             - The text of the bubblesheet file line to process
 6493:     whichline        - Line number
 6494:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6495:     scan_data        - Hash of extra information about the scanline
 6496:                        (see scantron_getfile for more information)
 6497:     just_header      - True if should not process question answers but only
 6498:                        the stuff to the left of the answers.
 6499:     randomorder      - True if randomorder in use
 6500:     randompick       - True if randompick in use
 6501:     sequence         - Exam folder URL
 6502:     master_seq       - Ref to array containing symbs in exam folder
 6503:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6504:                        (corresponding values are resource objects)
 6505:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6506:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6507:                        are refs to an array of resource objects, ordered
 6508:                        according to order used for CODE, when randomorder
 6509:                        and or randompick are in use.
 6510:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6511:                        for current line to question number used for same question
 6512:                         in "Master Sequence" (as seen by Course Coordinator).
 6513:     startline        - Ref to hash where key is question number (0 is first)
 6514:                        and value is number of first bubble line for current 
 6515:                        student or code-based randompick and/or randomorder.
 6516:     totalref         - Ref of scalar used to score total number of bubble
 6517:                        lines needed for responses in a scan line (used when
 6518:                        randompick in use. 
 6519:     
 6520:  Returns:
 6521:    Hash containing the result of parsing the scanline
 6522: 
 6523:    Keys are all proceeded by the string 'scantron.'
 6524: 
 6525:        CODE    - the CODE in use for this scanline
 6526:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6527:                  by the operator
 6528:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6529:                             CODEs were selected, but the usage has been
 6530:                             forced by the operator
 6531:        ID  - student/employee ID
 6532:        PaperID - if used, the ID number printed on the sheet when the 
 6533:                  paper was scanned
 6534:        FirstName - first name from the sheet
 6535:        LastName  - last name from the sheet
 6536: 
 6537:      if just_header was not true these key may also exist
 6538: 
 6539:        missingerror - a list of bubble ranges that are considered to be answers
 6540:                       to a single question that don't have any bubbles filled in.
 6541:                       Of the form questionnumber:firstbubblenumber:count.
 6542:        doubleerror  - a list of bubble ranges that are considered to be answers
 6543:                       to a single question that have more than one bubble filled in.
 6544:                       Of the form questionnumber::firstbubblenumber:count
 6545:    
 6546:                 In the above, count is the number of bubble responses in the
 6547:                 input line needed to represent the possible answers to the question.
 6548:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6549:                 per line would have count = 2.
 6550: 
 6551:        maxquest     - the number of the last bubble line that was parsed
 6552: 
 6553:        (<number> starts at 1)
 6554:        <number>.answer - zero or more letters representing the selected
 6555:                          letters from the scanline for the bubble line 
 6556:                          <number>.
 6557:                          if blank there was either no bubble or there where
 6558:                          multiple bubbles, (consult the keys missingerror and
 6559:                          doubleerror if this is an error condition)
 6560: 
 6561: =cut
 6562: 
 6563: sub scantron_parse_scanline {
 6564:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6565:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6566:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6567: 
 6568:     my %record;
 6569:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6570:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6571: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6572: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6573: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6574: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6575: 	    $record{'scantron.CODE'}=substr($data,
 6576: 					    $$scantron_config{'CODEstart'}-1,
 6577: 					    $$scantron_config{'CODElength'});
 6578: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6579: 		$record{'scantron.useCODE'}=1;
 6580: 	    }
 6581: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6582: 		$record{'scantron.CODE_ignore_dup'}=1;
 6583: 	    }
 6584: 	} else {
 6585: 	    #FIXME interpret first N questions
 6586: 	}
 6587:     }
 6588:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6589: 				  $$scantron_config{'IDlength'});
 6590:     $record{'scantron.PaperID'}=
 6591: 	substr($data,$$scantron_config{'PaperID'}-1,
 6592: 	       $$scantron_config{'PaperIDlength'});
 6593:     $record{'scantron.FirstName'}=
 6594: 	substr($data,$$scantron_config{'FirstName'}-1,
 6595: 	       $$scantron_config{'FirstNamelength'});
 6596:     $record{'scantron.LastName'}=
 6597: 	substr($data,$$scantron_config{'LastName'}-1,
 6598: 	       $$scantron_config{'LastNamelength'});
 6599:     if ($just_header) { return \%record; }
 6600: 
 6601:     my @alphabet=('A'..'Z');
 6602:     my $questnum=0;
 6603:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6604: 
 6605:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6606:     if ($randompick || $randomorder) {
 6607:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6608:                                          $master_seq,$symb_to_resource,
 6609:                                          $partids_by_symb,$orderedforcode,
 6610:                                          $respnumlookup,$startline);
 6611:         if ($total) {
 6612:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6613:         }
 6614:         if (ref($totalref)) {
 6615:             $$totalref = $total;
 6616:         }
 6617:     }
 6618:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6619:     chomp($questions);		# Get rid of any trailing \n.
 6620:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6621:     while (length($questions)) {
 6622:         my $answers_needed;
 6623:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6624:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6625:         } else {
 6626: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6627:         }
 6628:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6629:                              || 1;
 6630:         $questnum++;
 6631:         my $quest_id = $questnum;
 6632:         my $currentquest = substr($questions,0,$answer_length);
 6633:         $questions       = substr($questions,$answer_length);
 6634:         if (length($currentquest) < $answer_length) { next; }
 6635: 
 6636:         my $subdivided;
 6637:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6638:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6639:         } else {
 6640:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6641:         }
 6642:         if ($subdivided =~ /,/) {
 6643:             my $subquestnum = 1;
 6644:             my $subquestions = $currentquest;
 6645:             my @subanswers_needed = split(/,/,$subdivided);
 6646:             foreach my $subans (@subanswers_needed) {
 6647:                 my $subans_length =
 6648:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6649:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6650:                 $subquestions   = substr($subquestions,$subans_length);
 6651:                 $quest_id = "$questnum.$subquestnum";
 6652:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6653:                     ($$scantron_config{'Qon'} eq 'number')) {
 6654:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6655:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6656:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6657:                         $randomorder,$randompick,$respnumlookup);
 6658:                 } else {
 6659:                     $ansnum = &scantron_validator_positional($ansnum,
 6660:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6661:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6662:                         $randomorder,$randompick,$respnumlookup);
 6663:                 }
 6664:                 $subquestnum ++;
 6665:             }
 6666:         } else {
 6667:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6668:                 ($$scantron_config{'Qon'} eq 'number')) {
 6669:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6670:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6671:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6672:                     $randomorder,$randompick,$respnumlookup);
 6673:             } else {
 6674:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6675:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6676:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6677:                     $randomorder,$randompick,$respnumlookup);
 6678:             }
 6679:         }
 6680:     }
 6681:     $record{'scantron.maxquest'}=$questnum;
 6682:     return \%record;
 6683: }
 6684: 
 6685: sub get_master_seq {
 6686:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6687:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6688:                    (ref($symb_to_resource) eq 'HASH'));
 6689:     my $resource_error;
 6690:     foreach my $resource (@{$resources}) {
 6691:         my $ressymb;
 6692:         if (ref($resource)) {
 6693:             $ressymb = $resource->symb();
 6694:             push(@{$master_seq},$ressymb);
 6695:             $symb_to_resource->{$ressymb} = $resource;
 6696:         } else {
 6697:             $resource_error = 1;
 6698:             last;
 6699:         }
 6700:     }
 6701:     return $resource_error;
 6702: }
 6703: 
 6704: sub get_respnum_lookups {
 6705:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6706:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6707:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6708:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6709:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6710:                    (ref($startline) eq 'HASH'));
 6711:     my ($user,$scancode);
 6712:     if ((exists($record->{'scantron.CODE'})) &&
 6713:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6714:         $scancode = $record->{'scantron.CODE'};
 6715:     } else {
 6716:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6717:     }
 6718:     my @mapresources =
 6719:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6720:                      $orderedforcode);
 6721:     my $total = 0;
 6722:     my $count = 0;
 6723:     foreach my $resource (@mapresources) {
 6724:         my $id = $resource->id();
 6725:         my $symb = $resource->symb();
 6726:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6727:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6728:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6729:                 if ($respnum ne '') {
 6730:                     $respnumlookup->{$count} = $respnum;
 6731:                     $startline->{$count} = $total;
 6732:                     $total += $bubble_lines_per_response{$respnum};
 6733:                     $count ++;
 6734:                 }
 6735:             }
 6736:         }
 6737:     }
 6738:     return $total;
 6739: }
 6740: 
 6741: sub scantron_validator_lettnum {
 6742:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6743:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6744:         $randompick,$respnumlookup) = @_;
 6745: 
 6746:     # Qon 'letter' implies for each slot in currquest we have:
 6747:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6748:     #    about anything else (esp. a value of Qoff) for missing
 6749:     #    bubbles.
 6750:     #
 6751:     # Qon 'number' implies each slot gives a digit that indexes the
 6752:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6753:     #    and * or ? for double bubbles on a single line.
 6754:     #
 6755: 
 6756:     my $matchon;
 6757:     if ($$scantron_config{'Qon'} eq 'letter') {
 6758:         $matchon = '[A-Z]';
 6759:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6760:         $matchon = '\d';
 6761:     }
 6762:     my $occurrences = 0;
 6763:     my $responsenum = $questnum-1;
 6764:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6765:        $responsenum = $respnumlookup->{$questnum-1} 
 6766:     }
 6767:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6768:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6769:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6770:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6771:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6772:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6773:         my @singlelines = split('',$currquest);
 6774:         foreach my $entry (@singlelines) {
 6775:             $occurrences = &occurence_count($entry,$matchon);
 6776:             if ($occurrences > 1) {
 6777:                 last;
 6778:             }
 6779:         }
 6780:     } else {
 6781:         $occurrences = &occurence_count($currquest,$matchon); 
 6782:     }
 6783:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6784:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6785:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6786:             my $bubble = substr($currquest,$ans,1);
 6787:             if ($bubble =~ /$matchon/ ) {
 6788:                 if ($$scantron_config{'Qon'} eq 'number') {
 6789:                     if ($bubble == 0) {
 6790:                         $bubble = 10; 
 6791:                     }
 6792:                     $record->{"scantron.$ansnum.answer"} = 
 6793:                         $alphabet->[$bubble-1];
 6794:                 } else {
 6795:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6796:                 }
 6797:             } else {
 6798:                 $record->{"scantron.$ansnum.answer"}='';
 6799:             }
 6800:             $ansnum++;
 6801:         }
 6802:     } elsif (!defined($currquest)
 6803:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6804:             || (&occurence_count($currquest,$matchon) == 0)) {
 6805:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6806:             $record->{"scantron.$ansnum.answer"}='';
 6807:             $ansnum++;
 6808:         }
 6809:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6810:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6811:         }
 6812:     } else {
 6813:         if ($$scantron_config{'Qon'} eq 'number') {
 6814:             $currquest = &digits_to_letters($currquest);            
 6815:         }
 6816:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6817:             my $bubble = substr($currquest,$ans,1);
 6818:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6819:             $ansnum++;
 6820:         }
 6821:     }
 6822:     return $ansnum;
 6823: }
 6824: 
 6825: sub scantron_validator_positional {
 6826:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6827:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6828:         $randomorder,$randompick,$respnumlookup) = @_;
 6829: 
 6830:     # Otherwise there's a positional notation;
 6831:     # each bubble line requires Qlength items, and there are filled in
 6832:     # bubbles for each case where there 'Qon' characters.
 6833:     #
 6834: 
 6835:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6836: 
 6837:     # If the split only gives us one element.. the full length of the
 6838:     # answer string, no bubbles are filled in:
 6839: 
 6840:     if ($answers_needed eq '') {
 6841:         return;
 6842:     }
 6843: 
 6844:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6845:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6846:             $record->{"scantron.$ansnum.answer"}='';
 6847:             $ansnum++;
 6848:         }
 6849:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6850:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6851:         }
 6852:     } elsif (scalar(@array) == 2) {
 6853:         my $location = length($array[0]);
 6854:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6855:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6856:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6857:             if ($ans eq $line_num) {
 6858:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6859:             } else {
 6860:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6861:             }
 6862:             $ansnum++;
 6863:          }
 6864:     } else {
 6865:         #  If there's more than one instance of a bubble character
 6866:         #  That's a double bubble; with positional notation we can
 6867:         #  record all the bubbles filled in as well as the
 6868:         #  fact this response consists of multiple bubbles.
 6869:         #
 6870:         my $responsenum = $questnum-1;
 6871:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6872:             $responsenum = $respnumlookup->{$questnum-1}
 6873:         }
 6874:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6875:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6876:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6877:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6878:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6879:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6880:             my $doubleerror = 0;
 6881:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6882:                    (!$doubleerror)) {
 6883:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6884:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6885:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6886:                if (length(@currarray) > 2) {
 6887:                    $doubleerror = 1;
 6888:                } 
 6889:             }
 6890:             if ($doubleerror) {
 6891:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6892:             }
 6893:         } else {
 6894:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6895:         }
 6896:         my $item = $ansnum;
 6897:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6898:             $record->{"scantron.$item.answer"} = '';
 6899:             $item ++;
 6900:         }
 6901: 
 6902:         my @ans=@array;
 6903:         my $i=0;
 6904:         my $increment = 0;
 6905:         while ($#ans) {
 6906:             $i+=length($ans[0]) + $increment;
 6907:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6908:             my $bubble = $i%$$scantron_config{'Qlength'};
 6909:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6910:             shift(@ans);
 6911:             $increment = 1;
 6912:         }
 6913:         $ansnum += $answers_needed;
 6914:     }
 6915:     return $ansnum;
 6916: }
 6917: 
 6918: =pod
 6919: 
 6920: =item scantron_add_delay
 6921: 
 6922:    Adds an error message that occurred during the grading phase to a
 6923:    queue of messages to be shown after grading pass is complete
 6924: 
 6925:  Arguments:
 6926:    $delayqueue  - arrary ref of hash ref of error messages
 6927:    $scanline    - the scanline that caused the error
 6928:    $errormesage - the error message
 6929:    $errorcode   - a numeric code for the error
 6930: 
 6931:  Side Effects:
 6932:    updates the $delayqueue to have a new hash ref of the error
 6933: 
 6934: =cut
 6935: 
 6936: sub scantron_add_delay {
 6937:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6938:     push(@$delayqueue,
 6939: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6940: 	  'ecode' => $errorcode }
 6941: 	 );
 6942: }
 6943: 
 6944: =pod
 6945: 
 6946: =item scantron_find_student
 6947: 
 6948:    Finds the username for the current scanline
 6949: 
 6950:   Arguments:
 6951:    $scantron_record - hash result from scantron_parse_scanline
 6952:    $scan_data       - hash of correction information 
 6953:                       (see &scantron_getfile() form more information)
 6954:    $idmap           - hash from &username_to_idmap()
 6955:    $line            - number of current scanline
 6956:  
 6957:   Returns:
 6958:    Either 'username:domain' or undef if unknown
 6959: 
 6960: =cut
 6961: 
 6962: sub scantron_find_student {
 6963:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6964:     my $scanID=$$scantron_record{'scantron.ID'};
 6965:     if ($scanID =~ /^\s*$/) {
 6966:  	return &scan_data($scan_data,"$line.user");
 6967:     }
 6968:     foreach my $id (keys(%$idmap)) {
 6969:  	if (lc($id) eq lc($scanID)) {
 6970:  	    return $$idmap{$id};
 6971:  	}
 6972:     }
 6973:     return undef;
 6974: }
 6975: 
 6976: =pod
 6977: 
 6978: =item scantron_filter
 6979: 
 6980:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6981:    hidden resources was selected
 6982: 
 6983: =cut
 6984: 
 6985: sub scantron_filter {
 6986:     my ($curres)=@_;
 6987: 
 6988:     if (ref($curres) && $curres->is_problem()) {
 6989: 	# if the user has asked to not have either hidden
 6990: 	# or 'randomout' controlled resources to be graded
 6991: 	# don't include them
 6992: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6993: 	    && $curres->randomout) {
 6994: 	    return 0;
 6995: 	}
 6996: 	return 1;
 6997:     }
 6998:     return 0;
 6999: }
 7000: 
 7001: =pod
 7002: 
 7003: =item scantron_process_corrections
 7004: 
 7005:    Gets correction information out of submitted form data and corrects
 7006:    the scanline
 7007: 
 7008: =cut
 7009: 
 7010: sub scantron_process_corrections {
 7011:     my ($r) = @_;
 7012:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7013:     my ($scanlines,$scan_data)=&scantron_getfile();
 7014:     my $classlist=&Apache::loncoursedata::get_classlist();
 7015:     my $which=$env{'form.scantron_line'};
 7016:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7017:     my ($skip,$err,$errmsg);
 7018:     if ($env{'form.scantron_skip_record'}) {
 7019: 	$skip=1;
 7020:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7021: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7022: 	    $env{'form.scantron_domain'};
 7023: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7024: 	($line,$err,$errmsg)=
 7025: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7026: 				     'ID',{'newid'=>$newid,
 7027: 				    'username'=>$env{'form.scantron_username'},
 7028: 				    'domain'=>$env{'form.scantron_domain'}});
 7029:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7030: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7031: 	my $newCODE;
 7032: 	my %args;
 7033: 	if      ($resolution eq 'use_unfound') {
 7034: 	    $newCODE='use_unfound';
 7035: 	} elsif ($resolution eq 'use_found') {
 7036: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7037: 	} elsif ($resolution eq 'use_typed') {
 7038: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7039: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7040: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7041: 	}
 7042: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7043: 	    $args{'CODE_ignore_dup'}=1;
 7044: 	}
 7045: 	$args{'CODE'}=$newCODE;
 7046: 	($line,$err,$errmsg)=
 7047: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7048: 				     'CODE',\%args);
 7049:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7050: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7051: 	    ($line,$err,$errmsg)=
 7052: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7053: 					 $which,'answer',
 7054: 					 { 'question'=>$question,
 7055: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7056:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7057: 	    if ($err) { last; }
 7058: 	}
 7059:     }
 7060:     if ($err) {
 7061:         $r->print(
 7062:             '<p class="LC_error">'
 7063:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7064:                 $errmsg)
 7065:            .'</p>');
 7066:     } else {
 7067: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7068: 	&scantron_putfile($scanlines,$scan_data);
 7069:     }
 7070: }
 7071: 
 7072: =pod
 7073: 
 7074: =item reset_skipping_status
 7075: 
 7076:    Forgets the current set of remember skipped scanlines (and thus
 7077:    reverts back to considering all lines in the
 7078:    scantron_skipped_<filename> file)
 7079: 
 7080: =cut
 7081: 
 7082: sub reset_skipping_status {
 7083:     my ($scanlines,$scan_data)=&scantron_getfile();
 7084:     &scan_data($scan_data,'remember_skipping',undef,1);
 7085:     &scantron_putfile(undef,$scan_data);
 7086: }
 7087: 
 7088: =pod
 7089: 
 7090: =item start_skipping
 7091: 
 7092:    Marks a scanline to be skipped. 
 7093: 
 7094: =cut
 7095: 
 7096: sub start_skipping {
 7097:     my ($scan_data,$i)=@_;
 7098:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7099:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7100: 	$remembered{$i}=2;
 7101:     } else {
 7102: 	$remembered{$i}=1;
 7103:     }
 7104:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7105: }
 7106: 
 7107: =pod
 7108: 
 7109: =item should_be_skipped
 7110: 
 7111:    Checks whether a scanline should be skipped.
 7112: 
 7113: =cut
 7114: 
 7115: sub should_be_skipped {
 7116:     my ($scanlines,$scan_data,$i)=@_;
 7117:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7118: 	# not redoing old skips
 7119: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7120: 	return 0;
 7121:     }
 7122:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7123: 
 7124:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7125: 	return 0;
 7126:     }
 7127:     return 1;
 7128: }
 7129: 
 7130: =pod
 7131: 
 7132: =item remember_current_skipped
 7133: 
 7134:    Discovers what scanlines are in the scantron_skipped_<filename>
 7135:    file and remembers them into scan_data for later use.
 7136: 
 7137: =cut
 7138: 
 7139: sub remember_current_skipped {
 7140:     my ($scanlines,$scan_data)=&scantron_getfile();
 7141:     my %to_remember;
 7142:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7143: 	if ($scanlines->{'skipped'}[$i]) {
 7144: 	    $to_remember{$i}=1;
 7145: 	}
 7146:     }
 7147: 
 7148:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7149:     &scantron_putfile(undef,$scan_data);
 7150: }
 7151: 
 7152: =pod
 7153: 
 7154: =item check_for_error
 7155: 
 7156:     Checks if there was an error when attempting to remove a specific
 7157:     scantron_.. bubblesheet data file. Prints out an error if
 7158:     something went wrong.
 7159: 
 7160: =cut
 7161: 
 7162: sub check_for_error {
 7163:     my ($r,$result)=@_;
 7164:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7165: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7166:     }
 7167: }
 7168: 
 7169: =pod
 7170: 
 7171: =item scantron_warning_screen
 7172: 
 7173:    Interstitial screen to make sure the operator has selected the
 7174:    correct options before we start the validation phase.
 7175: 
 7176: =cut
 7177: 
 7178: sub scantron_warning_screen {
 7179:     my ($button_text,$symb)=@_;
 7180:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7181:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7182:     my $CODElist;
 7183:     if ($scantron_config{'CODElocation'} &&
 7184: 	$scantron_config{'CODEstart'} &&
 7185: 	$scantron_config{'CODElength'}) {
 7186: 	$CODElist=$env{'form.scantron_CODElist'};
 7187: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7188: 	$CODElist=
 7189: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7190: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7191:     }
 7192:     my $lastbubblepoints;
 7193:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7194:         $lastbubblepoints =
 7195:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7196:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7197:     }
 7198:     return '
 7199: <p>
 7200: <span class="LC_warning">
 7201: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7202: </p>
 7203: <table>
 7204: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7205: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7206: '.$CODElist.$lastbubblepoints.'
 7207: </table>
 7208: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7209: '.&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>
 7210: ';
 7211: }
 7212: 
 7213: =pod
 7214: 
 7215: =item scantron_do_warning
 7216: 
 7217:    Check if the operator has picked something for all required
 7218:    fields. Error out if something is missing.
 7219: 
 7220: =cut
 7221: 
 7222: sub scantron_do_warning {
 7223:     my ($r,$symb)=@_;
 7224:     if (!$symb) {return '';}
 7225:     my $default_form_data=&defaultFormData($symb);
 7226:     $r->print(&scantron_form_start().$default_form_data);
 7227:     if ( $env{'form.selectpage'} eq '' ||
 7228: 	 $env{'form.scantron_selectfile'} eq '' ||
 7229: 	 $env{'form.scantron_format'} eq '' ) {
 7230: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7231: 	if ( $env{'form.selectpage'} eq '') {
 7232: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7233: 	} 
 7234: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7235: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7236: 	}
 7237: 	if ( $env{'form.scantron_format'} eq '') {
 7238: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7239: 	}
 7240:     } else {
 7241: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7242:         my ($checksec,@possibles) = &gradable_sections();
 7243:         my $gradesections;
 7244:         if ($checksec) {
 7245:             my $file=$env{'form.scantron_selectfile'};
 7246:             if (&valid_file($file)) {
 7247:                 my %bysec = &scantron_get_sections();
 7248:                 my $table;
 7249:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
 7250:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
 7251:                     $table = &Apache::loncommon::start_data_table()."\n".
 7252:                              &Apache::loncommon::start_data_table_header_row().
 7253:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
 7254:                               &Apache::loncommon::end_data_table_header_row()."\n";
 7255:                     if ($bysec{'none'}) {
 7256:                         $table .= &Apache::loncommon::start_data_table_row().
 7257:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
 7258:                                   &Apache::loncommon::end_data_table_row()."\n";
 7259:                     }
 7260:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
 7261:                         next if ($sec eq 'none');
 7262:                         $table .= &Apache::loncommon::start_data_table_row().
 7263:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
 7264:                                   &Apache::loncommon::end_data_table_row()."\n";
 7265:                     }
 7266:                     $table .= &Apache::loncommon::end_data_table()."\n";
 7267:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
 7268:                                       '<p>'.$table.'</p>';
 7269:                     if (@possibles) {
 7270:                         $gradesections .= '<p>'.
 7271:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
 7272:                                               scalar(@possibles)).'<br />'.
 7273:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
 7274:                                               '<i>'.$checksec.'</i>').' ';
 7275:                         foreach my $sec (sort {$a <=> $b } @possibles) {
 7276:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
 7277:                         }
 7278:                         $gradesections .= '</p>';
 7279:                     }
 7280:                 }
 7281:             } else {
 7282:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
 7283:             }
 7284:         }
 7285:         my $bubbledbyhand=&hand_bubble_option();
 7286: 	$r->print('
 7287: '.$warning.$gradesections.$bubbledbyhand.'
 7288: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7289: <input type="hidden" name="command" value="scantron_validate" />
 7290: ');
 7291:     }
 7292:     $r->print("</form><br />");
 7293:     return '';
 7294: }
 7295: 
 7296: =pod
 7297: 
 7298: =item scantron_form_start
 7299: 
 7300:     html hidden input for remembering all selected grading options
 7301: 
 7302: =cut
 7303: 
 7304: sub scantron_form_start {
 7305:     my ($max_bubble)=@_;
 7306:     my $result= <<SCANTRONFORM;
 7307: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7308:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7309:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7310:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7311:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7312:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7313:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7314:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7315:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7316:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7317: SCANTRONFORM
 7318: 
 7319:   my $line = 0;
 7320:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7321:        my $chunk =
 7322: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7323:        $chunk .=
 7324: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7325:        $chunk .= 
 7326:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7327:        $chunk .=
 7328:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7329:        $chunk .=
 7330:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7331:        $result .= $chunk;
 7332:        $line++;
 7333:     }
 7334:     return $result;
 7335: }
 7336: 
 7337: =pod
 7338: 
 7339: =item scantron_validate_file
 7340: 
 7341:     Dispatch routine for doing validation of a bubblesheet data file.
 7342: 
 7343:     Also processes any necessary information resets that need to
 7344:     occur before validation begins (ignore previous corrections,
 7345:     restarting the skipped records processing)
 7346: 
 7347: =cut
 7348: 
 7349: sub scantron_validate_file {
 7350:     my ($r,$symb) = @_;
 7351:     if (!$symb) {return '';}
 7352:     my $default_form_data=&defaultFormData($symb);
 7353:     
 7354:     # do the detection of only doing skipped records first before we delete
 7355:     # them when doing the corrections reset
 7356:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7357: 	&reset_skipping_status();
 7358:     }
 7359:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7360: 	&remember_current_skipped();
 7361: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7362:     }
 7363: 
 7364:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7365: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7366: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7367: 	&check_for_error($r,&scantron_remove_scan_data());
 7368: 	$env{'form.scantron_options_ignore'}='done';
 7369:     }
 7370: 
 7371:     if ($env{'form.scantron_corrections'}) {
 7372: 	&scantron_process_corrections($r);
 7373:     }
 7374: 
 7375:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
 7376:     my ($checksec,@gradable);
 7377:     if ($env{'request.course.sec'}) {
 7378:         ($checksec,my @possibles) = &gradable_sections();
 7379:         if ($checksec) {
 7380:             if (@possibles) {
 7381:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
 7382:                 if (@chosensecs) {
 7383:                     foreach my $sec (@chosensecs) {
 7384:                         if (grep(/^\Q$sec\E$/,@possibles)) {
 7385:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
 7386:                                 push(@gradable,$sec);
 7387:                             }
 7388:                         }
 7389:                     }
 7390:                 }
 7391:             }
 7392:             $r->print('<p><table>');
 7393:             if (@gradable) {
 7394:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
 7395:                 $r->print(
 7396:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
 7397:             } else {
 7398:                 $r->print(
 7399:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
 7400:             }
 7401:             $r->print('</table></p>');
 7402:         }
 7403:     }
 7404:     $r->rflush();
 7405: 
 7406:     #get the student pick code ready
 7407:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7408:     my $nav_error;
 7409:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7410:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7411:     if ($nav_error) {
 7412:         $r->print(&navmap_errormsg());
 7413:         return '';
 7414:     }
 7415:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7416:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7417:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7418:     }
 7419:     $r->print($result);
 7420:     
 7421:     my @validate_phases=( 'sequence',
 7422: 			  'ID',
 7423: 			  'CODE',
 7424: 			  'doublebubble',
 7425: 			  'missingbubbles');
 7426:     if (!$env{'form.validatepass'}) {
 7427: 	$env{'form.validatepass'} = 0;
 7428:     }
 7429:     my $currentphase=$env{'form.validatepass'};
 7430:     my %skipbysec=();
 7431: 
 7432:     my $stop=0;
 7433:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7434: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7435: 	$r->rflush();
 7436:      
 7437: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7438: 	{
 7439: 	    no strict 'refs';
 7440:             my @extras=();
 7441:             if ($validate_phases[$currentphase] eq 'ID') {
 7442:                 @extras = (\%skipbysec,$checksec,@gradable);
 7443:             }
 7444: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
 7445: 	}
 7446:     }
 7447:     if (!$stop) {
 7448: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7449:         my $secinfo;
 7450:         if (keys(%skipbysec) > 0) {
 7451:             my $seclist = '<ul>';
 7452:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
 7453:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
 7454:             }
 7455:             $seclist .= '</ul>';
 7456:             $secinfo = '<p class="LC_info">'.
 7457:                        &mt('Numbers of records for students in sections not being graded [_1]',
 7458:                            $seclist).
 7459:                        '</p>';
 7460:         }
 7461: 	$r->print(&mt('Validation process complete.').'<br />'.
 7462:                   $secinfo.$warning.
 7463:                   &mt('Perform verification for each student after storage of submissions?').
 7464:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7465:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7466:                   ('&nbsp;'x3).'<label>'.
 7467:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7468:                   '</label></span><br />'.
 7469:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7470:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7471:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7472:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7473:     } else {
 7474: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7475: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7476:     }
 7477:     if ($stop) {
 7478: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7479: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7480: 	    $r->print(' '.&mt('this error').' <br />');
 7481: 
 7482: 	    $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>');
 7483: 	} else {
 7484:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7485: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7486:             } else {
 7487:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7488:             }
 7489: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7490: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7491: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7492: 	}
 7493:     }
 7494:     $r->print(" </form><br />");
 7495:     return '';
 7496: }
 7497: 
 7498: 
 7499: =pod
 7500: 
 7501: =item scantron_remove_file
 7502: 
 7503:    Removes the requested bubblesheet data file, makes sure that
 7504:    scantron_original_<filename> is never removed
 7505: 
 7506: 
 7507: =cut
 7508: 
 7509: sub scantron_remove_file {
 7510:     my ($which)=@_;
 7511:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7512:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7513:     my $file='scantron_';
 7514:     if ($which eq 'corrected' || $which eq 'skipped') {
 7515: 	$file.=$which.'_';
 7516:     } else {
 7517: 	return 'refused';
 7518:     }
 7519:     $file.=$env{'form.scantron_selectfile'};
 7520:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7521: }
 7522: 
 7523: 
 7524: =pod
 7525: 
 7526: =item scantron_remove_scan_data
 7527: 
 7528:    Removes all scan_data correction for the requested bubblesheet
 7529:    data file.  (In the case that both the are doing skipped records we need
 7530:    to remember the old skipped lines for the time being so that element
 7531:    persists for a while.)
 7532: 
 7533: =cut
 7534: 
 7535: sub scantron_remove_scan_data {
 7536:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7537:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7538:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7539:     my @todelete;
 7540:     my $filename=$env{'form.scantron_selectfile'};
 7541:     foreach my $key (@keys) {
 7542: 	if ($key=~/^\Q$filename\E_/) {
 7543: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7544: 		$key=~/remember_skipping/) {
 7545: 		next;
 7546: 	    }
 7547: 	    push(@todelete,$key);
 7548: 	}
 7549:     }
 7550:     my $result;
 7551:     if (@todelete) {
 7552: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7553: 				       \@todelete,$cdom,$cname);
 7554:     } else {
 7555: 	$result = 'ok';
 7556:     }
 7557:     return $result;
 7558: }
 7559: 
 7560: 
 7561: =pod
 7562: 
 7563: =item scantron_getfile
 7564: 
 7565:     Fetches the requested bubblesheet data file (all 3 versions), and
 7566:     the scan_data hash
 7567:   
 7568:   Arguments:
 7569:     None
 7570: 
 7571:   Returns:
 7572:     2 hash references
 7573: 
 7574:      - first one has 
 7575:          orig      -
 7576:          corrected -
 7577:          skipped   -  each of which points to an array ref of the specified
 7578:                       file broken up into individual lines
 7579:          count     - number of scanlines
 7580:  
 7581:      - second is the scan_data hash possible keys are
 7582:        ($number refers to scanline numbered $number and thus the key affects
 7583:         only that scanline
 7584:         $bubline refers to the specific bubble line element and the aspects
 7585:         refers to that specific bubble line element)
 7586: 
 7587:        $number.user - username:domain to use
 7588:        $number.CODE_ignore_dup 
 7589:                     - ignore the duplicate CODE error 
 7590:        $number.useCODE
 7591:                     - use the CODE in the scanline as is
 7592:        $number.no_bubble.$bubline
 7593:                     - it is valid that there is no bubbled in bubble
 7594:                       at $number $bubline
 7595:        remember_skipping
 7596:                     - a frozen hash containing keys of $number and values
 7597:                       of either 
 7598:                         1 - we are on a 'do skipped records pass' and plan
 7599:                             on processing this line
 7600:                         2 - we are on a 'do skipped records pass' and this
 7601:                             scanline has been marked to skip yet again
 7602: 
 7603: =cut
 7604: 
 7605: sub scantron_getfile {
 7606:     #FIXME really would prefer a scantron directory
 7607:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7608:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7609:     my $lines;
 7610:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7611: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7612:     my %scanlines;
 7613:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7614:     my $temp=$scanlines{'orig'};
 7615:     $scanlines{'count'}=$#$temp;
 7616: 
 7617:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7618: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7619:     if ($lines eq '-1') {
 7620: 	$scanlines{'corrected'}=[];
 7621:     } else {
 7622: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7623:     }
 7624:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7625: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7626:     if ($lines eq '-1') {
 7627: 	$scanlines{'skipped'}=[];
 7628:     } else {
 7629: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7630:     }
 7631:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7632:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7633:     my %scan_data = @tmp;
 7634:     return (\%scanlines,\%scan_data);
 7635: }
 7636: 
 7637: =pod
 7638: 
 7639: =item lonnet_putfile
 7640: 
 7641:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7642: 
 7643:  Arguments:
 7644:    $contents - data to store
 7645:    $filename - filename to store $contents into
 7646: 
 7647:  Returns:
 7648:    result value from &Apache::lonnet::finishuserfileupload
 7649: 
 7650: =cut
 7651: 
 7652: sub lonnet_putfile {
 7653:     my ($contents,$filename)=@_;
 7654:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7655:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7656:     $env{'form.sillywaytopassafilearound'}=$contents;
 7657:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7658: 
 7659: }
 7660: 
 7661: =pod
 7662: 
 7663: =item scantron_putfile
 7664: 
 7665:     Stores the current version of the bubblesheet data files, and the
 7666:     scan_data hash. (Does not modify the original version only the
 7667:     corrected and skipped versions.
 7668: 
 7669:  Arguments:
 7670:     $scanlines - hash ref that looks like the first return value from
 7671:                  &scantron_getfile()
 7672:     $scan_data - hash ref that looks like the second return value from
 7673:                  &scantron_getfile()
 7674: 
 7675: =cut
 7676: 
 7677: sub scantron_putfile {
 7678:     my ($scanlines,$scan_data) = @_;
 7679:     #FIXME really would prefer a scantron directory
 7680:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7681:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7682:     if ($scanlines) {
 7683: 	my $prefix='scantron_';
 7684: # no need to update orig, shouldn't change
 7685: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7686: #		    $env{'form.scantron_selectfile'});
 7687: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7688: 			$prefix.'corrected_'.
 7689: 			$env{'form.scantron_selectfile'});
 7690: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7691: 			$prefix.'skipped_'.
 7692: 			$env{'form.scantron_selectfile'});
 7693:     }
 7694:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7695: }
 7696: 
 7697: =pod
 7698: 
 7699: =item scantron_get_line
 7700: 
 7701:    Returns the correct version of the scanline
 7702: 
 7703:  Arguments:
 7704:     $scanlines - hash ref that looks like the first return value from
 7705:                  &scantron_getfile()
 7706:     $scan_data - hash ref that looks like the second return value from
 7707:                  &scantron_getfile()
 7708:     $i         - number of the requested line (starts at 0)
 7709: 
 7710:  Returns:
 7711:    A scanline, (either the original or the corrected one if it
 7712:    exists), or undef if the requested scanline should be
 7713:    skipped. (Either because it's an skipped scanline, or it's an
 7714:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7715:    pass.
 7716: 
 7717: =cut
 7718: 
 7719: sub scantron_get_line {
 7720:     my ($scanlines,$scan_data,$i)=@_;
 7721:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7722:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7723:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7724:     return $scanlines->{'orig'}[$i]; 
 7725: }
 7726: 
 7727: =pod
 7728: 
 7729: =item scantron_todo_count
 7730: 
 7731:     Counts the number of scanlines that need processing.
 7732: 
 7733:  Arguments:
 7734:     $scanlines - hash ref that looks like the first return value from
 7735:                  &scantron_getfile()
 7736:     $scan_data - hash ref that looks like the second return value from
 7737:                  &scantron_getfile()
 7738: 
 7739:  Returns:
 7740:     $count - number of scanlines to process
 7741: 
 7742: =cut
 7743: 
 7744: sub get_todo_count {
 7745:     my ($scanlines,$scan_data)=@_;
 7746:     my $count=0;
 7747:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7748: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7749: 	if ($line=~/^[\s\cz]*$/) { next; }
 7750: 	$count++;
 7751:     }
 7752:     return $count;
 7753: }
 7754: 
 7755: =pod
 7756: 
 7757: =item scantron_put_line
 7758: 
 7759:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7760:     data file.
 7761: 
 7762:  Arguments:
 7763:     $scanlines - hash ref that looks like the first return value from
 7764:                  &scantron_getfile()
 7765:     $scan_data - hash ref that looks like the second return value from
 7766:                  &scantron_getfile()
 7767:     $i         - line number to update
 7768:     $newline   - contents of the updated scanline
 7769:     $skip      - if true make the line for skipping and update the
 7770:                  'skipped' file
 7771: 
 7772: =cut
 7773: 
 7774: sub scantron_put_line {
 7775:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7776:     if ($skip) {
 7777: 	$scanlines->{'skipped'}[$i]=$newline;
 7778: 	&start_skipping($scan_data,$i);
 7779: 	return;
 7780:     }
 7781:     $scanlines->{'corrected'}[$i]=$newline;
 7782: }
 7783: 
 7784: =pod
 7785: 
 7786: =item scantron_clear_skip
 7787: 
 7788:    Remove a line from the 'skipped' file
 7789: 
 7790:  Arguments:
 7791:     $scanlines - hash ref that looks like the first return value from
 7792:                  &scantron_getfile()
 7793:     $scan_data - hash ref that looks like the second return value from
 7794:                  &scantron_getfile()
 7795:     $i         - line number to update
 7796: 
 7797: =cut
 7798: 
 7799: sub scantron_clear_skip {
 7800:     my ($scanlines,$scan_data,$i)=@_;
 7801:     if (exists($scanlines->{'skipped'}[$i])) {
 7802: 	undef($scanlines->{'skipped'}[$i]);
 7803: 	return 1;
 7804:     }
 7805:     return 0;
 7806: }
 7807: 
 7808: =pod
 7809: 
 7810: =item scantron_filter_not_exam
 7811: 
 7812:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7813:    filter out resources that are not marked as 'exam' mode
 7814: 
 7815: =cut
 7816: 
 7817: sub scantron_filter_not_exam {
 7818:     my ($curres)=@_;
 7819:     
 7820:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7821: 	# if the user has asked to not have either hidden
 7822: 	# or 'randomout' controlled resources to be graded
 7823: 	# don't include them
 7824: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7825: 	    && $curres->randomout) {
 7826: 	    return 0;
 7827: 	}
 7828: 	return 1;
 7829:     }
 7830:     return 0;
 7831: }
 7832: 
 7833: =pod
 7834: 
 7835: =item scantron_validate_sequence
 7836: 
 7837:     Validates the selected sequence, checking for resource that are
 7838:     not set to exam mode.
 7839: 
 7840: =cut
 7841: 
 7842: sub scantron_validate_sequence {
 7843:     my ($r,$currentphase) = @_;
 7844: 
 7845:     my $navmap=Apache::lonnavmaps::navmap->new();
 7846:     unless (ref($navmap)) {
 7847:         $r->print(&navmap_errormsg());
 7848:         return (1,$currentphase);
 7849:     }
 7850:     my (undef,undef,$sequence)=
 7851: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7852: 
 7853:     my $map=$navmap->getResourceByUrl($sequence);
 7854: 
 7855:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7856:                                     value="ignore" />');
 7857:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7858: 	my @resources=
 7859: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7860: 	if (@resources) {
 7861: 	    $r->print(
 7862:                 '<p class="LC_warning">'
 7863:                .&mt('Some resources in the sequence currently are not set to'
 7864:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7865:                    .' work correctly.')
 7866:                .'</p>'
 7867:             );
 7868: 	    return (1,$currentphase);
 7869: 	}
 7870:     }
 7871: 
 7872:     return (0,$currentphase+1);
 7873: }
 7874: 
 7875: 
 7876: 
 7877: sub scantron_validate_ID {
 7878:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
 7879:     
 7880:     #get student info
 7881:     my $classlist=&Apache::loncoursedata::get_classlist();
 7882:     my %idmap=&username_to_idmap($classlist);
 7883:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 7884: 
 7885:     #get scantron line setup
 7886:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7887:     my ($scanlines,$scan_data)=&scantron_getfile();
 7888: 
 7889:     my $nav_error;
 7890:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7891:     if ($nav_error) {
 7892:         $r->print(&navmap_errormsg());
 7893:         return(1,$currentphase);
 7894:     }
 7895: 
 7896:     my %found=('ids'=>{},'usernames'=>{});
 7897:     my $unsavedskips = 0;
 7898:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7899: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7900: 	if ($line=~/^[\s\cz]*$/) { next; }
 7901: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7902: 						 $scan_data);
 7903: 	my $id=$$scan_record{'scantron.ID'};
 7904: 	my $found;
 7905: 	foreach my $checkid (keys(%idmap)) {
 7906: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7907: 	}
 7908: 	if ($found) {
 7909: 	    my $username=$idmap{$found};
 7910:             if ($checksec) {
 7911:                 if (ref($classlist->{$username}) eq 'ARRAY') {
 7912:                     my $stusec = $classlist->{$username}->[$secidx];
 7913:                     if ($stusec ne $checksec) {
 7914:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7915:                             my $skip=1;
 7916:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7917:                             if (ref($skipbysec) eq 'HASH') {
 7918:                                 if ($stusec eq '') {
 7919:                                     $skipbysec->{'none'} ++;
 7920:                                 } else {
 7921:                                     $skipbysec->{$stusec} ++;
 7922:                                 }
 7923:                             }
 7924:                             $unsavedskips ++;
 7925:                             next;
 7926:                         }
 7927:                     }
 7928:                 }
 7929:             }
 7930: 	    if ($found{'ids'}{$found}) {
 7931: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7932: 					 $line,'duplicateID',$found);
 7933:                 if ($unsavedskips) {
 7934:                     &scantron_putfile($scanlines,$scan_data);
 7935:                     $unsavedskips = 0;
 7936:                 }
 7937: 		return(1,$currentphase);
 7938: 	    } elsif ($found{'usernames'}{$username}) {
 7939: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7940: 					 $line,'duplicateID',$username);
 7941:                 if ($unsavedskips) {
 7942:                     &scantron_putfile($scanlines,$scan_data);
 7943:                     $unsavedskips = 0;
 7944:                 }
 7945: 		return(1,$currentphase);
 7946: 	    }
 7947: 	    #FIXME store away line we previously saw the ID on to use above
 7948: 	    $found{'ids'}{$found}++;
 7949: 	    $found{'usernames'}{$username}++;
 7950: 	} else {
 7951: 	    if ($id =~ /^\s*$/) {
 7952: 		my $username=&scan_data($scan_data,"$i.user");
 7953:                 if (($checksec && $username ne '')) {
 7954:                     if (ref($classlist->{$username}) eq 'ARRAY') {
 7955:                         my $stusec = $classlist->{$username}->[$secidx];
 7956:                         if ($stusec ne $checksec) {
 7957:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
 7958:                                 my $skip=1;
 7959:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
 7960:                                 if (ref($skipbysec) eq 'HASH') {
 7961:                                     if ($stusec eq '') {
 7962:                                         $skipbysec->{'none'} ++;
 7963:                                     } else {
 7964:                                         $skipbysec->{$stusec} ++;
 7965:                                     }
 7966:                                 }
 7967:                                 $unsavedskips ++;
 7968:                                 next;
 7969:                             }
 7970:                         }
 7971:                     }
 7972: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
 7973: 		    &scantron_get_correction($r,$i,$scan_record,
 7974: 					     \%scantron_config,
 7975: 					     $line,'duplicateID',$username);
 7976:                     if ($unsavedskips) {
 7977:                         &scantron_putfile($scanlines,$scan_data);
 7978:                         $unsavedskips = 0;
 7979:                     }
 7980: 		    return(1,$currentphase);
 7981: 		} elsif (!defined($username)) {
 7982: 		    &scantron_get_correction($r,$i,$scan_record,
 7983: 					     \%scantron_config,
 7984: 					     $line,'incorrectID');
 7985:                     if ($unsavedskips) {
 7986:                         &scantron_putfile($scanlines,$scan_data);
 7987:                         $unsavedskips = 0;
 7988:                     }
 7989: 		    return(1,$currentphase);
 7990: 		}
 7991: 		$found{'usernames'}{$username}++;
 7992: 	    } else {
 7993: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7994: 					 $line,'incorrectID');
 7995:                 if ($unsavedskips) {
 7996:                     &scantron_putfile($scanlines,$scan_data);
 7997:                     $unsavedskips = 0;
 7998:                 }
 7999: 		return(1,$currentphase);
 8000: 	    }
 8001: 	}
 8002:     }
 8003:     if ($unsavedskips) {
 8004:         &scantron_putfile($scanlines,$scan_data);
 8005:         $unsavedskips = 0;
 8006:     }
 8007:     return (0,$currentphase+1);
 8008: }
 8009: 
 8010: sub scantron_get_sections {
 8011:     my %bysec;
 8012:     if ($env{'form.scantron_format'} ne '') {
 8013:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8014:         my ($scanlines,$scan_data)=&scantron_getfile();
 8015:         my $classlist=&Apache::loncoursedata::get_classlist();
 8016:         my %idmap=&username_to_idmap($classlist);
 8017:         foreach my $key (keys(%idmap)) {
 8018:             my $lckey = lc($key);
 8019:             $idmap{$lckey} = $idmap{$key};
 8020:         }
 8021:         my $secidx = &Apache::loncoursedata::CL_SECTION();
 8022:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8023:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8024:             if ($line=~/^[\s\cz]*$/) { next; }
 8025:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8026:                                                      $scan_data);
 8027:             my $id=lc($$scan_record{'scantron.ID'});
 8028:             if (exists($idmap{$id})) {
 8029:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 8030:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 8031:                     if ($stusec eq '') {
 8032:                         $bysec{'none'} ++;
 8033:                     } else {
 8034:                         $bysec{$stusec} ++;
 8035:                     }
 8036:                 }
 8037:             }
 8038:         }
 8039:     }
 8040:     return %bysec;
 8041: }
 8042: 
 8043: sub scantron_get_correction {
 8044:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 8045:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 8046: #FIXME in the case of a duplicated ID the previous line, probably need
 8047: #to show both the current line and the previous one and allow skipping
 8048: #the previous one or the current one
 8049: 
 8050:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 8051:         $r->print(
 8052:             '<p class="LC_warning">'
 8053:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 8054:                 "<b>$error</b>",
 8055:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 8056:            ."</p> \n");
 8057:     } else {
 8058:         $r->print(
 8059:             '<p class="LC_warning">'
 8060:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 8061:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 8062:            ."</p> \n");
 8063:     }
 8064:     my $message =
 8065:         '<p>'
 8066:        .&mt('The ID on the form is [_1]',
 8067:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 8068:        .'<br />'
 8069:        .&mt('The name on the paper is [_1], [_2]',
 8070:             $$scan_record{'scantron.LastName'},
 8071:             $$scan_record{'scantron.FirstName'})
 8072:        .'</p>';
 8073: 
 8074:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 8075:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 8076:                            # Array populated for doublebubble or
 8077:     my @lines_to_correct;  # missingbubble errors to build javascript
 8078:                            # to validate radio button checking   
 8079: 
 8080:     if ($error =~ /ID$/) {
 8081: 	if ($error eq 'incorrectID') {
 8082:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 8083: 		      "</p>\n");
 8084: 	} elsif ($error eq 'duplicateID') {
 8085:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 8086: 	}
 8087: 	$r->print($message);
 8088: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 8089: 	$r->print("\n<ul><li> ");
 8090: 	#FIXME it would be nice if this sent back the user ID and
 8091: 	#could do partial userID matches
 8092: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 8093: 				       'scantron_username','scantron_domain'));
 8094: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 8095: 	$r->print("\n:\n".
 8096: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 8097: 
 8098: 	$r->print('</li>');
 8099:     } elsif ($error =~ /CODE$/) {
 8100: 	if ($error eq 'incorrectCODE') {
 8101: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 8102: 	} elsif ($error eq 'duplicateCODE') {
 8103: 	    $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");
 8104: 	}
 8105: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 8106: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 8107:                  ."</p>\n");
 8108: 	$r->print($message);
 8109: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 8110: 	$r->print("\n<br /> ");
 8111: 	my $i=0;
 8112: 	if ($error eq 'incorrectCODE' 
 8113: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 8114: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 8115: 	    if ($closest > 0) {
 8116: 		foreach my $testcode (@{$closest}) {
 8117: 		    my $checked='';
 8118: 		    if (!$i) { $checked=' checked="checked"'; }
 8119: 		    $r->print("
 8120:    <label>
 8121:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 8122:        ".&mt("Use the similar CODE [_1] instead.",
 8123: 	    "<b><tt>".$testcode."</tt></b>")."
 8124:     </label>
 8125:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 8126: 		    $r->print("\n<br />");
 8127: 		    $i++;
 8128: 		}
 8129: 	    }
 8130: 	}
 8131: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 8132: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 8133: 	    $r->print("
 8134:     <label>
 8135:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 8136:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 8137: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 8138:     </label>");
 8139: 	    $r->print("\n<br />");
 8140: 	}
 8141: 
 8142: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 8143: function change_radio(field) {
 8144:     var slct=document.scantronupload.scantron_CODE_resolution;
 8145:     var i;
 8146:     for (i=0;i<slct.length;i++) {
 8147:         if (slct[i].value==field) { slct[i].checked=true; }
 8148:     }
 8149: }
 8150: ENDSCRIPT
 8151: 	my $href="/adm/pickcode?".
 8152: 	   "form=".&escape("scantronupload").
 8153: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8154: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8155: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8156: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8157: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8158: 	    $r->print("
 8159:     <label>
 8160:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8161:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8162: 	     "<a target='_blank' href='$href'>","</a>")."
 8163:     </label> 
 8164:     ".&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\')" />'));
 8165: 	    $r->print("\n<br />");
 8166: 	}
 8167: 	$r->print("
 8168:     <label>
 8169:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8170:        ".&mt("Use [_1] as the CODE.",
 8171: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8172: 	$r->print("\n<br /><br />");
 8173:     } elsif ($error eq 'doublebubble') {
 8174: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8175: 
 8176: 	# The form field scantron_questions is acutally a list of line numbers.
 8177: 	# represented by this form so:
 8178: 
 8179: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8180:                                                 $respnumlookup,$startline);
 8181: 
 8182: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8183: 		  $line_list.'" />');
 8184: 	$r->print($message);
 8185: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8186: 	foreach my $question (@{$arg}) {
 8187: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8188:                                                    $scan_record, $error,
 8189:                                                    $randomorder,$randompick,
 8190:                                                    $respnumlookup,$startline);
 8191:             push(@lines_to_correct,@linenums);
 8192: 	}
 8193:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8194:     } elsif ($error eq 'missingbubble') {
 8195: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8196: 	$r->print($message);
 8197: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8198: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8199: 
 8200: 	# The form field scantron_questions is actually a list of line numbers not
 8201: 	# a list of question numbers. Therefore:
 8202: 	#
 8203: 
 8204: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8205:                                                 $respnumlookup,$startline);
 8206: 
 8207: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8208: 		  $line_list.'" />');
 8209: 	foreach my $question (@{$arg}) {
 8210: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8211:                                                    $scan_record, $error,
 8212:                                                    $randomorder,$randompick,
 8213:                                                    $respnumlookup,$startline);
 8214:             push(@lines_to_correct,@linenums);
 8215: 	}
 8216:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8217:     } else {
 8218: 	$r->print("\n<ul>");
 8219:     }
 8220:     $r->print("\n</li></ul>");
 8221: }
 8222: 
 8223: sub verify_bubbles_checked {
 8224:     my (@ansnums) = @_;
 8225:     my $ansnumstr = join('","',@ansnums);
 8226:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8227:     &js_escape(\$warning);
 8228:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8229: function verify_bubble_radio(form) {
 8230:     var ansnumArray = new Array ("$ansnumstr");
 8231:     var need_bubble_count = 0;
 8232:     for (var i=0; i<ansnumArray.length; i++) {
 8233:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8234:             var bubble_picked = 0; 
 8235:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8236:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8237:                     bubble_picked = 1;
 8238:                 }
 8239:             }
 8240:             if (bubble_picked == 0) {
 8241:                 need_bubble_count ++;
 8242:             }
 8243:         }
 8244:     }
 8245:     if (need_bubble_count) {
 8246:         alert("$warning");
 8247:         return;
 8248:     }
 8249:     form.submit(); 
 8250: }
 8251: ENDSCRIPT
 8252:     return $output;
 8253: }
 8254: 
 8255: =pod
 8256: 
 8257: =item  questions_to_line_list
 8258: 
 8259: Converts a list of questions into a string of comma separated
 8260: line numbers in the answer sheet used by the questions.  This is
 8261: used to fill in the scantron_questions form field.
 8262: 
 8263:   Arguments:
 8264:      questions    - Reference to an array of questions.
 8265:      randomorder  - True if randomorder in use.
 8266:      randompick   - True if randompick in use.
 8267:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8268:                      for current line to question number used for same question
 8269:                      in "Master Seqence" (as seen by Course Coordinator).
 8270:      startline    - Reference to hash where key is question number (0 is first)
 8271:                     and key is number of first bubble line for current student
 8272:                     or code-based randompick and/or randomorder.
 8273: 
 8274: =cut
 8275: 
 8276: 
 8277: sub questions_to_line_list {
 8278:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8279:     my @lines;
 8280: 
 8281:     foreach my $item (@{$questions}) {
 8282:         my $question = $item;
 8283:         my ($first,$count,$last);
 8284:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8285:             $question = $1;
 8286:             my $subquestion = $2;
 8287:             my $responsenum = $question-1;
 8288:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8289:                 $responsenum = $respnumlookup->{$question-1};
 8290:                 if (ref($startline) eq 'HASH') {
 8291:                     $first = $startline->{$question-1} + 1;
 8292:                 }
 8293:             } else {
 8294:                 $first = $first_bubble_line{$responsenum} + 1;
 8295:             }
 8296:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8297:             my $subcount = 1;
 8298:             while ($subcount<$subquestion) {
 8299:                 $first += $subans[$subcount-1];
 8300:                 $subcount ++;
 8301:             }
 8302:             $count = $subans[$subquestion-1];
 8303:         } else {
 8304:             my $responsenum = $question-1;
 8305:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8306:                 $responsenum = $respnumlookup->{$question-1};
 8307:                 if (ref($startline) eq 'HASH') {
 8308:                     $first = $startline->{$question-1} + 1;
 8309:                 }
 8310:             } else {
 8311:                 $first = $first_bubble_line{$responsenum} + 1;
 8312:             }
 8313: 	    $count   = $bubble_lines_per_response{$responsenum};
 8314:         }
 8315:         $last = $first+$count-1;
 8316:         push(@lines, ($first..$last));
 8317:     }
 8318:     return join(',', @lines);
 8319: }
 8320: 
 8321: =pod 
 8322: 
 8323: =item prompt_for_corrections
 8324: 
 8325: Prompts for a potentially multiline correction to the
 8326: user's bubbling (factors out common code from scantron_get_correction
 8327: for multi and missing bubble cases).
 8328: 
 8329:  Arguments:
 8330:    $r           - Apache request object.
 8331:    $question    - The question number to prompt for.
 8332:    $scan_config - The scantron file configuration hash.
 8333:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8334:    $error       - Type of error
 8335:    $randomorder - True if randomorder in use.
 8336:    $randompick  - True if randompick in use.
 8337:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8338:                     for current line to question number used for same question
 8339:                     in "Master Seqence" (as seen by Course Coordinator).
 8340:    $startline   - Reference to hash where key is question number (0 is first)
 8341:                   and value is number of first bubble line for current student
 8342:                   or code-based randompick and/or randomorder.
 8343: 
 8344: 
 8345:  Implicit inputs:
 8346:    %bubble_lines_per_response   - Starting line numbers for each question.
 8347:                                   Numbered from 0 (but question numbers are from
 8348:                                   1.
 8349:    %first_bubble_line           - Starting bubble line for each question.
 8350:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8351:                                   type problems render as separate sub-questions, 
 8352:                                   in exam mode. This hash contains a 
 8353:                                   comma-separated list of the lines per 
 8354:                                   sub-question.
 8355:    %responsetype_per_response   - essayresponse, formularesponse,
 8356:                                   stringresponse, imageresponse, reactionresponse,
 8357:                                   and organicresponse type problem parts can have
 8358:                                   multiple lines per response if the weight
 8359:                                   assigned exceeds 10.  In this case, only
 8360:                                   one bubble per line is permitted, but more 
 8361:                                   than one line might contain bubbles, e.g.
 8362:                                   bubbling of: line 1 - J, line 2 - J, 
 8363:                                   line 3 - B would assign 22 points.  
 8364: 
 8365: =cut
 8366: 
 8367: sub prompt_for_corrections {
 8368:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8369:         $randompick, $respnumlookup, $startline) = @_;
 8370:     my ($current_line,$lines);
 8371:     my @linenums;
 8372:     my $questionnum = $question;
 8373:     my ($first,$responsenum);
 8374:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8375:         $question = $1;
 8376:         my $subquestion = $2;
 8377:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8378:             $responsenum = $respnumlookup->{$question-1};
 8379:             if (ref($startline) eq 'HASH') {
 8380:                 $first = $startline->{$question-1};
 8381:             }
 8382:         } else {
 8383:             $responsenum = $question-1;
 8384:             $first = $first_bubble_line{$responsenum};
 8385:         }
 8386:         $current_line = $first + 1 ;
 8387:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8388:         my $subcount = 1;
 8389:         while ($subcount<$subquestion) {
 8390:             $current_line += $subans[$subcount-1];
 8391:             $subcount ++;
 8392:         }
 8393:         $lines = $subans[$subquestion-1];
 8394:     } else {
 8395:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8396:             $responsenum = $respnumlookup->{$question-1};
 8397:             if (ref($startline) eq 'HASH') { 
 8398:                 $first = $startline->{$question-1};
 8399:             }
 8400:         } else {
 8401:             $responsenum = $question-1;
 8402:             $first = $first_bubble_line{$responsenum};
 8403:         }
 8404:         $current_line = $first + 1;
 8405:         $lines        = $bubble_lines_per_response{$responsenum};
 8406:     }
 8407:     if ($lines > 1) {
 8408:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8409:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8410:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8411:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8412:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8413:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8414:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8415:             $r->print(
 8416:                 &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)
 8417:                .'<br /><br />'
 8418:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8419:                .'<br />'
 8420:                .&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.')
 8421:                .'<br />'
 8422:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8423:                .'<br /><br />'
 8424:             );
 8425:         } else {
 8426:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8427:         }
 8428:     }
 8429:     for (my $i =0; $i < $lines; $i++) {
 8430:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8431: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8432: 	        		  $questionnum,$error,split('', $selected));
 8433:         push(@linenums,$current_line);
 8434: 	$current_line++;
 8435:     }
 8436:     if ($lines > 1) {
 8437: 	$r->print("<hr /><br />");
 8438:     }
 8439:     return @linenums;
 8440: }
 8441: 
 8442: =pod
 8443: 
 8444: =item scantron_bubble_selector
 8445:   
 8446:    Generates the html radiobuttons to correct a single bubble line
 8447:    possibly showing the existing the selected bubbles if known
 8448: 
 8449:  Arguments:
 8450:     $r           - Apache request object
 8451:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8452:     $line        - Number of the line being displayed.
 8453:     $questionnum - Question number (may include subquestion)
 8454:     $error       - Type of error.
 8455:     @selected    - Array of bubbles picked on this line.
 8456: 
 8457: =cut
 8458: 
 8459: sub scantron_bubble_selector {
 8460:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8461:     my $max=$$scan_config{'Qlength'};
 8462: 
 8463:     my $scmode=$$scan_config{'Qon'};
 8464:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8465:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8466:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8467:             $max=$$scan_config{'BubblesPerRow'};
 8468:             if (($scmode eq 'number') && ($max > 10)) {
 8469:                 $max = 10;
 8470:             } elsif (($scmode eq 'letter') && $max > 26) {
 8471:                 $max = 26;
 8472:             }
 8473:         } else {
 8474:             $max = 10;
 8475:         }
 8476:     }
 8477: 
 8478:     my @alphabet=('A'..'Z');
 8479:     $r->print(&Apache::loncommon::start_data_table().
 8480:               &Apache::loncommon::start_data_table_row());
 8481:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8482:     for (my $i=0;$i<$max+1;$i++) {
 8483: 	$r->print("\n".'<td align="center">');
 8484: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8485: 	else { $r->print('&nbsp;'); }
 8486: 	$r->print('</td>');
 8487:     }
 8488:     $r->print(&Apache::loncommon::end_data_table_row().
 8489:               &Apache::loncommon::start_data_table_row());
 8490:     for (my $i=0;$i<$max;$i++) {
 8491: 	$r->print("\n".
 8492: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8493: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8494:     }
 8495:     my $nobub_checked = ' ';
 8496:     if ($error eq 'missingbubble') {
 8497:         $nobub_checked = ' checked = "checked" ';
 8498:     }
 8499:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8500: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8501:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8502:               $line.'" value="'.$questionnum.'" /></td>');
 8503:     $r->print(&Apache::loncommon::end_data_table_row().
 8504:               &Apache::loncommon::end_data_table());
 8505: }
 8506: 
 8507: =pod
 8508: 
 8509: =item num_matches
 8510: 
 8511:    Counts the number of characters that are the same between the two arguments.
 8512: 
 8513:  Arguments:
 8514:    $orig - CODE from the scanline
 8515:    $code - CODE to match against
 8516: 
 8517:  Returns:
 8518:    $count - integer count of the number of same characters between the
 8519:             two arguments
 8520: 
 8521: =cut
 8522: 
 8523: sub num_matches {
 8524:     my ($orig,$code) = @_;
 8525:     my @code=split(//,$code);
 8526:     my @orig=split(//,$orig);
 8527:     my $same=0;
 8528:     for (my $i=0;$i<scalar(@code);$i++) {
 8529: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8530:     }
 8531:     return $same;
 8532: }
 8533: 
 8534: =pod
 8535: 
 8536: =item scantron_get_closely_matching_CODEs
 8537: 
 8538:    Cycles through all CODEs and finds the set that has the greatest
 8539:    number of same characters as the provided CODE
 8540: 
 8541:  Arguments:
 8542:    $allcodes - hash ref returned by &get_codes()
 8543:    $CODE     - CODE from the current scanline
 8544: 
 8545:  Returns:
 8546:    2 element list
 8547:     - first elements is number of how closely matching the best fit is 
 8548:       (5 means best set has 5 matching characters)
 8549:     - second element is an arrary ref containing the set of valid CODEs
 8550:       that best fit the passed in CODE
 8551: 
 8552: =cut
 8553: 
 8554: sub scantron_get_closely_matching_CODEs {
 8555:     my ($allcodes,$CODE)=@_;
 8556:     my @CODEs;
 8557:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8558: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8559:     }
 8560: 
 8561:     return ($#CODEs,$CODEs[-1]);
 8562: }
 8563: 
 8564: =pod
 8565: 
 8566: =item get_codes
 8567: 
 8568:    Builds a hash which has keys of all of the valid CODEs from the selected
 8569:    set of remembered CODEs.
 8570: 
 8571:  Arguments:
 8572:   $old_name - name of the set of remembered CODEs
 8573:   $cdom     - domain of the course
 8574:   $cnum     - internal course name
 8575: 
 8576:  Returns:
 8577:   %allcodes - keys are the valid CODEs, values are all 1
 8578: 
 8579: =cut
 8580: 
 8581: sub get_codes {
 8582:     my ($old_name, $cdom, $cnum) = @_;
 8583:     if (!$old_name) {
 8584: 	$old_name=$env{'form.scantron_CODElist'};
 8585:     }
 8586:     if (!$cdom) {
 8587: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8588:     }
 8589:     if (!$cnum) {
 8590: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8591:     }
 8592:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8593: 				    $cdom,$cnum);
 8594:     my %allcodes;
 8595:     if ($result{"type\0$old_name"} eq 'number') {
 8596: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8597:     } else {
 8598: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8599:     }
 8600:     return %allcodes;
 8601: }
 8602: 
 8603: =pod
 8604: 
 8605: =item scantron_validate_CODE
 8606: 
 8607:    Validates all scanlines in the selected file to not have any
 8608:    invalid or underspecified CODEs and that none of the codes are
 8609:    duplicated if this was requested.
 8610: 
 8611: =cut
 8612: 
 8613: sub scantron_validate_CODE {
 8614:     my ($r,$currentphase) = @_;
 8615:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8616:     if ($scantron_config{'CODElocation'} &&
 8617: 	$scantron_config{'CODEstart'} &&
 8618: 	$scantron_config{'CODElength'}) {
 8619: 	if (!defined($env{'form.scantron_CODElist'})) {
 8620: 	    &FIXME_blow_up()
 8621: 	}
 8622:     } else {
 8623: 	return (0,$currentphase+1);
 8624:     }
 8625:     
 8626:     my %usedCODEs;
 8627: 
 8628:     my %allcodes=&get_codes();
 8629: 
 8630:     my $nav_error;
 8631:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8632:     if ($nav_error) {
 8633:         $r->print(&navmap_errormsg());
 8634:         return(1,$currentphase);
 8635:     }
 8636: 
 8637:     my ($scanlines,$scan_data)=&scantron_getfile();
 8638:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8639: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8640: 	if ($line=~/^[\s\cz]*$/) { next; }
 8641: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8642: 						 $scan_data);
 8643: 	my $CODE=$$scan_record{'scantron.CODE'};
 8644: 	my $error=0;
 8645: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8646: 	    &scantron_get_correction($r,$i,$scan_record,
 8647: 				     \%scantron_config,
 8648: 				     $line,'incorrectCODE',\%allcodes);
 8649: 	    return(1,$currentphase);
 8650: 	}
 8651: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8652: 	    && !$$scan_record{'scantron.useCODE'}) {
 8653: 	    &scantron_get_correction($r,$i,$scan_record,
 8654: 				     \%scantron_config,
 8655: 				     $line,'incorrectCODE',\%allcodes);
 8656: 	    return(1,$currentphase);
 8657: 	}
 8658: 	if (exists($usedCODEs{$CODE}) 
 8659: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8660: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8661: 	    &scantron_get_correction($r,$i,$scan_record,
 8662: 				     \%scantron_config,
 8663: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8664: 	    return(1,$currentphase);
 8665: 	}
 8666: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8667:     }
 8668:     return (0,$currentphase+1);
 8669: }
 8670: 
 8671: =pod
 8672: 
 8673: =item scantron_validate_doublebubble
 8674: 
 8675:    Validates all scanlines in the selected file to not have any
 8676:    bubble lines with multiple bubbles marked.
 8677: 
 8678: =cut
 8679: 
 8680: sub scantron_validate_doublebubble {
 8681:     my ($r,$currentphase) = @_;
 8682:     #get student info
 8683:     my $classlist=&Apache::loncoursedata::get_classlist();
 8684:     my %idmap=&username_to_idmap($classlist);
 8685:     my (undef,undef,$sequence)=
 8686:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8687: 
 8688:     #get scantron line setup
 8689:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8690:     my ($scanlines,$scan_data)=&scantron_getfile();
 8691: 
 8692:     my $navmap = Apache::lonnavmaps::navmap->new();
 8693:     unless (ref($navmap)) {
 8694:         $r->print(&navmap_errormsg());
 8695:         return(1,$currentphase);
 8696:     }
 8697:     my $map=$navmap->getResourceByUrl($sequence);
 8698:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8699:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8700:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8701:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8702: 
 8703:     my $nav_error;
 8704:     if (ref($map)) {
 8705:         $randomorder = $map->randomorder();
 8706:         $randompick = $map->randompick();
 8707:         if ($randomorder || $randompick) {
 8708:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8709:             if ($nav_error) {
 8710:                 $r->print(&navmap_errormsg());
 8711:                 return(1,$currentphase);
 8712:             }
 8713:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8714:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8715:         }
 8716:     } else {
 8717:         $r->print(&navmap_errormsg());
 8718:         return(1,$currentphase);
 8719:     }
 8720: 
 8721:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8722:     if ($nav_error) {
 8723:         $r->print(&navmap_errormsg());
 8724:         return(1,$currentphase);
 8725:     }
 8726: 
 8727:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8728: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8729: 	if ($line=~/^[\s\cz]*$/) { next; }
 8730: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8731: 						 $scan_data,undef,\%idmap,$randomorder,
 8732:                                                  $randompick,$sequence,\@master_seq,
 8733:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8734:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8735: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8736: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8737: 				 'doublebubble',
 8738: 				 $$scan_record{'scantron.doubleerror'},
 8739:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8740:     	return (1,$currentphase);
 8741:     }
 8742:     return (0,$currentphase+1);
 8743: }
 8744: 
 8745: 
 8746: sub scantron_get_maxbubble {
 8747:     my ($nav_error,$scantron_config) = @_;
 8748:     if (defined($env{'form.scantron_maxbubble'}) &&
 8749: 	$env{'form.scantron_maxbubble'}) {
 8750: 	&restore_bubble_lines();
 8751: 	return $env{'form.scantron_maxbubble'};
 8752:     }
 8753: 
 8754:     my (undef, undef, $sequence) =
 8755: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8756: 
 8757:     my $navmap=Apache::lonnavmaps::navmap->new();
 8758:     unless (ref($navmap)) {
 8759:         if (ref($nav_error)) {
 8760:             $$nav_error = 1;
 8761:         }
 8762:         return;
 8763:     }
 8764:     my $map=$navmap->getResourceByUrl($sequence);
 8765:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8766:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8767: 
 8768:     &Apache::lonxml::clear_problem_counter();
 8769: 
 8770:     my $uname       = $env{'user.name'};
 8771:     my $udom        = $env{'user.domain'};
 8772:     my $cid         = $env{'request.course.id'};
 8773:     my $total_lines = 0;
 8774:     %bubble_lines_per_response = ();
 8775:     %first_bubble_line         = ();
 8776:     %subdivided_bubble_lines   = ();
 8777:     %responsetype_per_response = ();
 8778:     %masterseq_id_responsenum  = ();
 8779: 
 8780:     my $response_number = 0;
 8781:     my $bubble_line     = 0;
 8782:     foreach my $resource (@resources) {
 8783:         my $resid = $resource->id(); 
 8784:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8785:                                                           $udom,undef,$bubbles_per_row);
 8786:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8787: 	    foreach my $part_id (@{$parts}) {
 8788:                 my $lines;
 8789: 
 8790: 	        # TODO - make this a persistent hash not an array.
 8791: 
 8792:                 # optionresponse, matchresponse and rankresponse type items 
 8793:                 # render as separate sub-questions in exam mode.
 8794:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8795:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8796:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8797:                     my ($numbub,$numshown);
 8798:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8799:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8800:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8801:                         }
 8802:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8803:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8804:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8805:                         }
 8806:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8807:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8808:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8809:                         }
 8810:                     }
 8811:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8812:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8813:                     }
 8814:                     my $bubbles_per_row =
 8815:                         &bubblesheet_bubbles_per_row($scantron_config);
 8816:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8817:                     if (($numbub % $bubbles_per_row) != 0) {
 8818:                         $inner_bubble_lines++;
 8819:                     }
 8820:                     for (my $i=0; $i<$numshown; $i++) {
 8821:                         $subdivided_bubble_lines{$response_number} .= 
 8822:                             $inner_bubble_lines.',';
 8823:                     }
 8824:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8825:                     $lines = $numshown * $inner_bubble_lines;
 8826:                 } else {
 8827:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8828:                 }
 8829: 
 8830:                 $first_bubble_line{$response_number} = $bubble_line;
 8831: 	        $bubble_lines_per_response{$response_number} = $lines;
 8832:                 $responsetype_per_response{$response_number} = 
 8833:                     $analysis->{$part_id.'.type'};
 8834:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8835: 	        $response_number++;
 8836: 
 8837: 	        $bubble_line +=  $lines;
 8838: 	        $total_lines +=  $lines;
 8839: 	    }
 8840:         }
 8841:     }
 8842:     &Apache::lonnet::delenv('scantron.');
 8843: 
 8844:     &save_bubble_lines();
 8845:     $env{'form.scantron_maxbubble'} =
 8846: 	$total_lines;
 8847:     return $env{'form.scantron_maxbubble'};
 8848: }
 8849: 
 8850: sub bubblesheet_bubbles_per_row {
 8851:     my ($scantron_config) = @_;
 8852:     my $bubbles_per_row;
 8853:     if (ref($scantron_config) eq 'HASH') {
 8854:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8855:     }
 8856:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8857:         $bubbles_per_row = 10;
 8858:     }
 8859:     return $bubbles_per_row;
 8860: }
 8861: 
 8862: sub scantron_validate_missingbubbles {
 8863:     my ($r,$currentphase) = @_;
 8864:     #get student info
 8865:     my $classlist=&Apache::loncoursedata::get_classlist();
 8866:     my %idmap=&username_to_idmap($classlist);
 8867:     my (undef,undef,$sequence)=
 8868:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8869: 
 8870:     #get scantron line setup
 8871:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8872:     my ($scanlines,$scan_data)=&scantron_getfile();
 8873: 
 8874:     my $navmap = Apache::lonnavmaps::navmap->new();
 8875:     unless (ref($navmap)) {
 8876:         $r->print(&navmap_errormsg());
 8877:         return(1,$currentphase);
 8878:     }
 8879: 
 8880:     my $map=$navmap->getResourceByUrl($sequence);
 8881:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8882:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8883:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8884:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8885: 
 8886:     my $nav_error;
 8887:     if (ref($map)) {
 8888:         $randomorder = $map->randomorder();
 8889:         $randompick = $map->randompick();
 8890:         if ($randomorder || $randompick) {
 8891:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8892:             if ($nav_error) {
 8893:                 $r->print(&navmap_errormsg());
 8894:                 return(1,$currentphase);
 8895:             }
 8896:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8897:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8898:         }
 8899:     } else {
 8900:         $r->print(&navmap_errormsg());
 8901:         return(1,$currentphase);
 8902:     }
 8903: 
 8904: 
 8905:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8906:     if ($nav_error) {
 8907:         $r->print(&navmap_errormsg());
 8908:         return(1,$currentphase);
 8909:     }
 8910: 
 8911:     if (!$max_bubble) { $max_bubble=2**31; }
 8912:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8913: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8914: 	if ($line=~/^[\s\cz]*$/) { next; }
 8915: 	my $scan_record =
 8916:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8917: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8918:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8919:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8920: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8921: 	my @to_correct;
 8922: 	
 8923: 	# Probably here's where the error is...
 8924: 
 8925: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8926:             my $lastbubble;
 8927:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8928:                my $question = $1;
 8929:                my $subquestion = $2;
 8930:                my ($first,$responsenum);
 8931:                if ($randomorder || $randompick) {
 8932:                    $responsenum = $respnumlookup{$question-1};
 8933:                    $first = $startline{$question-1};
 8934:                } else {
 8935:                    $responsenum = $question-1; 
 8936:                    $first = $first_bubble_line{$responsenum};
 8937:                }
 8938:                if (!defined($first)) { next; }
 8939:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8940:                my $subcount = 1;
 8941:                while ($subcount<$subquestion) {
 8942:                    $first += $subans[$subcount-1];
 8943:                    $subcount ++;
 8944:                }
 8945:                my $count = $subans[$subquestion-1];
 8946:                $lastbubble = $first + $count;
 8947:             } else {
 8948:                my ($first,$responsenum);
 8949:                if ($randomorder || $randompick) {
 8950:                    $responsenum = $respnumlookup{$missing-1};
 8951:                    $first = $startline{$missing-1};
 8952:                } else {
 8953:                    $responsenum = $missing-1;
 8954:                    $first = $first_bubble_line{$responsenum};
 8955:                }
 8956:                if (!defined($first)) { next; }
 8957:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8958:             }
 8959:             if ($lastbubble > $max_bubble) { next; }
 8960: 	    push(@to_correct,$missing);
 8961: 	}
 8962: 	if (@to_correct) {
 8963: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8964: 				     $line,'missingbubble',\@to_correct,
 8965:                                      $randomorder,$randompick,\%respnumlookup,
 8966:                                      \%startline);
 8967: 	    return (1,$currentphase);
 8968: 	}
 8969: 
 8970:     }
 8971:     return (0,$currentphase+1);
 8972: }
 8973: 
 8974: sub hand_bubble_option {
 8975:     my (undef, undef, $sequence) =
 8976:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8977:     return if ($sequence eq '');
 8978:     my $navmap = Apache::lonnavmaps::navmap->new();
 8979:     unless (ref($navmap)) {
 8980:         return;
 8981:     }
 8982:     my $needs_hand_bubbles;
 8983:     my $map=$navmap->getResourceByUrl($sequence);
 8984:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8985:     foreach my $res (@resources) {
 8986:         if (ref($res)) {
 8987:             if ($res->is_problem()) {
 8988:                 my $partlist = $res->parts();
 8989:                 foreach my $part (@{ $partlist }) {
 8990:                     my @types = $res->responseType($part);
 8991:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8992:                         $needs_hand_bubbles = 1;
 8993:                         last;
 8994:                     }
 8995:                 }
 8996:             }
 8997:         }
 8998:     }
 8999:     if ($needs_hand_bubbles) {
 9000:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9001:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9002:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 9003:                &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 />').
 9004:                '<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;'.
 9005:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 9006:     }
 9007:     return;
 9008: }
 9009: 
 9010: sub scantron_process_students {
 9011:     my ($r,$symb) = @_;
 9012: 
 9013:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 9014:     if (!$symb) {
 9015: 	return '';
 9016:     }
 9017:     my $default_form_data=&defaultFormData($symb);
 9018: 
 9019:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9020:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 9021:     my ($scanlines,$scan_data)=&scantron_getfile();
 9022:     my $classlist=&Apache::loncoursedata::get_classlist();
 9023:     my %idmap=&username_to_idmap($classlist);
 9024:     my $navmap=Apache::lonnavmaps::navmap->new();
 9025:     unless (ref($navmap)) {
 9026:         $r->print(&navmap_errormsg());
 9027:         return '';
 9028:     }
 9029:     my $map=$navmap->getResourceByUrl($sequence);
 9030:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9031:         %grader_randomlists_by_symb);
 9032:     if (ref($map)) {
 9033:         $randomorder = $map->randomorder();
 9034:         $randompick = $map->randompick();
 9035:     } else {
 9036:         $r->print(&navmap_errormsg());
 9037:         return '';
 9038:     }
 9039:     my $nav_error;
 9040:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9041:     if ($randomorder || $randompick) {
 9042:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9043:         if ($nav_error) {
 9044:             $r->print(&navmap_errormsg());
 9045:             return '';
 9046:         }
 9047:     }
 9048:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9049:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9050: 
 9051:     my ($uname,$udom);
 9052:     my $result= <<SCANTRONFORM;
 9053: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 9054:   <input type="hidden" name="command" value="scantron_configphase" />
 9055:   $default_form_data
 9056: SCANTRONFORM
 9057:     $r->print($result);
 9058: 
 9059:     my ($checksec,@possibles)=&gradable_sections();
 9060:     my @delayqueue;
 9061:     my (%completedstudents,%scandata);
 9062: 
 9063:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 9064:     my $count=&get_todo_count($scanlines,$scan_data);
 9065:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9066:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9067:     $r->print('<br />');
 9068:     my $start=&Time::HiRes::time();
 9069:     my $i=-1;
 9070:     my $started;
 9071: 
 9072:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9073:     if ($nav_error) {
 9074:         $r->print(&navmap_errormsg());
 9075:         return '';
 9076:     }
 9077: 
 9078:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 9079:     # the user and return.
 9080: 
 9081:     if ($ssi_error) {
 9082: 	$r->print("</form>");
 9083: 	&ssi_print_error($r);
 9084:         &Apache::lonnet::remove_lock($lock);
 9085: 	return '';		# Dunno why the other returns return '' rather than just returning.
 9086:     }
 9087: 
 9088:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9089:     my $numletts = scalar(keys(%lettdig));
 9090:     my %orderedforcode;
 9091: 
 9092:     while ($i<$scanlines->{'count'}) {
 9093:  	($uname,$udom)=('','');
 9094:  	$i++;
 9095:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 9096:  	if ($line=~/^[\s\cz]*$/) { next; }
 9097: 	if ($started) {
 9098: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9099: 	}
 9100: 	$started=1;
 9101:         my %respnumlookup = ();
 9102:         my %startline = ();
 9103:         my $total;
 9104:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 9105:                                                  $scan_data,undef,\%idmap,$randomorder,
 9106:                                                  $randompick,$sequence,\@master_seq,
 9107:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 9108:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 9109:                                                  \$total);
 9110:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9111:  					      \%idmap,$i)) {
 9112:   	    &scantron_add_delay(\@delayqueue,$line,
 9113:  				'Unable to find a student that matches',1);
 9114:  	    next;
 9115:   	}
 9116:  	if (exists $completedstudents{$uname}) {
 9117:  	    &scantron_add_delay(\@delayqueue,$line,
 9118:  				'Student '.$uname.' has multiple sheets',2);
 9119:  	    next;
 9120:  	}
 9121:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9122:         if (($checksec ne '') && ($checksec ne $usec)) {
 9123:             unless (grep(/^\Q$usec\E$/,@possibles)) {
 9124:                 &scantron_add_delay(\@delayqueue,$line,
 9125:                                     "No role with manage grades privilege in student's section ($usec)",3);
 9126:                 next;
 9127:             }
 9128:         }
 9129:         my $user = $uname.':'.$usec;
 9130:   	($uname,$udom)=split(/:/,$uname);
 9131: 
 9132:         my $scancode;
 9133:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9134:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9135:             $scancode = $scan_record->{'scantron.CODE'};
 9136:         } else {
 9137:             $scancode = '';
 9138:         }
 9139: 
 9140:         my @mapresources = @resources;
 9141:         if ($randomorder || $randompick) {
 9142:             @mapresources = 
 9143:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9144:                              \%orderedforcode);
 9145:         }
 9146:         my (%partids_by_symb,$res_error);
 9147:         foreach my $resource (@mapresources) {
 9148:             my $ressymb;
 9149:             if (ref($resource)) {
 9150:                 $ressymb = $resource->symb();
 9151:             } else {
 9152:                 $res_error = 1;
 9153:                 last;
 9154:             }
 9155:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9156:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9157:                 my $currcode;
 9158:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9159:                     $currcode = $scancode;
 9160:                 }
 9161:                 my ($analysis,$parts) =
 9162:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9163:                                               $uname,$udom,undef,$bubbles_per_row,
 9164:                                               $currcode);
 9165:                 $partids_by_symb{$ressymb} = $parts;
 9166:             } else {
 9167:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9168:             }
 9169:         }
 9170: 
 9171:         if ($res_error) {
 9172:             &scantron_add_delay(\@delayqueue,$line,
 9173:                                 'An error occurred while grading student '.$uname,2);
 9174:             next;
 9175:         }
 9176: 
 9177: 	&Apache::lonxml::clear_problem_counter();
 9178:   	&Apache::lonnet::appenv($scan_record);
 9179: 
 9180: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9181: 	    &scantron_putfile($scanlines,$scan_data);
 9182: 	}
 9183: 	
 9184:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9185:                                    \@mapresources,\%partids_by_symb,
 9186:                                    $bubbles_per_row,$randomorder,$randompick,
 9187:                                    \%respnumlookup,\%startline) 
 9188:             eq 'ssi_error') {
 9189:             $ssi_error = 0; # So end of handler error message does not trigger.
 9190:             $r->print("</form>");
 9191:             &ssi_print_error($r);
 9192:             &Apache::lonnet::remove_lock($lock);
 9193:             return '';      # Why return ''?  Beats me.
 9194:         }
 9195: 
 9196:         if (($scancode) && ($randomorder || $randompick)) {
 9197:             my $parmresult =
 9198:                 &Apache::lonparmset::storeparm_by_symb($symb,
 9199:                                                        '0_examcode',2,$scancode,
 9200:                                                        'string_examcode',$uname,
 9201:                                                        $udom);
 9202:         }
 9203: 	$completedstudents{$uname}={'line'=>$line};
 9204:         if ($env{'form.verifyrecord'}) {
 9205:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9206:             if ($randompick) {
 9207:                 if ($total) {
 9208:                     $lastpos = $total*$scantron_config{'Qlength'};
 9209:                 }
 9210:             }
 9211: 
 9212:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9213:             chomp($studentdata);
 9214:             $studentdata =~ s/\r$//;
 9215:             my $studentrecord = '';
 9216:             my $counter = -1;
 9217:             foreach my $resource (@mapresources) {
 9218:                 my $ressymb = $resource->symb();
 9219:                 ($counter,my $recording) =
 9220:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9221:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9222:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9223:                                              $randompick,\%respnumlookup,\%startline);
 9224:                 $studentrecord .= $recording;
 9225:             }
 9226:             if ($studentrecord ne $studentdata) {
 9227:                 &Apache::lonxml::clear_problem_counter();
 9228:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9229:                                            \@mapresources,\%partids_by_symb,
 9230:                                            $bubbles_per_row,$randomorder,$randompick,
 9231:                                            \%respnumlookup,\%startline) 
 9232:                     eq 'ssi_error') {
 9233:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9234:                     $r->print("</form>");
 9235:                     &ssi_print_error($r);
 9236:                     &Apache::lonnet::remove_lock($lock);
 9237:                     delete($completedstudents{$uname});
 9238:                     return '';
 9239:                 }
 9240:                 $counter = -1;
 9241:                 $studentrecord = '';
 9242:                 foreach my $resource (@mapresources) {
 9243:                     my $ressymb = $resource->symb();
 9244:                     ($counter,my $recording) =
 9245:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9246:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9247:                                                  \%scantron_config,\%lettdig,$numletts,
 9248:                                                  $randomorder,$randompick,\%respnumlookup,
 9249:                                                  \%startline);
 9250:                     $studentrecord .= $recording;
 9251:                 }
 9252:                 if ($studentrecord ne $studentdata) {
 9253:                     $r->print('<p><span class="LC_warning">');
 9254:                     if ($scancode eq '') {
 9255:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9256:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9257:                     } else {
 9258:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9259:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9260:                     }
 9261:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9262:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9263:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9264:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9265:                               &Apache::loncommon::start_data_table_row().
 9266:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9267:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9268:                               &Apache::loncommon::end_data_table_row().
 9269:                               &Apache::loncommon::start_data_table_row().
 9270:                               '<td>'.&mt('Stored submissions').'</td>'.
 9271:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9272:                               &Apache::loncommon::end_data_table_row().
 9273:                               &Apache::loncommon::end_data_table().'</p>');
 9274:                 } else {
 9275:                     $r->print('<br /><span class="LC_warning">'.
 9276:                              &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 />'.
 9277:                              &mt("As a consequence, this user's submission history records two tries.").
 9278:                                  '</span><br />');
 9279:                 }
 9280:             }
 9281:         }
 9282:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9283:     } continue {
 9284: 	&Apache::lonxml::clear_problem_counter();
 9285: 	&Apache::lonnet::delenv('scantron.');
 9286:     }
 9287:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9288:     &Apache::lonnet::remove_lock($lock);
 9289: #    my $lasttime = &Time::HiRes::time()-$start;
 9290: #    $r->print("<p>took $lasttime</p>");
 9291: 
 9292:     $r->print("</form>");
 9293:     return '';
 9294: }
 9295: 
 9296: sub graders_resources_pass {
 9297:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9298:         $bubbles_per_row) = @_;
 9299:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9300:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9301:         foreach my $resource (@{$resources}) {
 9302:             my $ressymb = $resource->symb();
 9303:             my ($analysis,$parts) =
 9304:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9305:                                           $env{'user.name'},$env{'user.domain'},
 9306:                                           1,$bubbles_per_row);
 9307:             $grader_partids_by_symb->{$ressymb} = $parts;
 9308:             if (ref($analysis) eq 'HASH') {
 9309:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9310:                     $grader_randomlists_by_symb->{$ressymb} =
 9311:                         $analysis->{'parts_withrandomlist'};
 9312:                 }
 9313:             }
 9314:         }
 9315:     }
 9316:     return;
 9317: }
 9318: 
 9319: =pod
 9320: 
 9321: =item users_order
 9322: 
 9323:   Returns array of resources in current map, ordered based on either CODE,
 9324:   if this is a CODEd exam, or based on student's identity if this is a 
 9325:   "NAMEd" exam.
 9326: 
 9327:   Should be used when randomorder and/or randompick applied when the 
 9328:   corresponding exam was printed, prior to students completing bubblesheets 
 9329:   for the version of the exam the student received.
 9330: 
 9331: =cut
 9332: 
 9333: sub users_order  {
 9334:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9335:     my @mapresources;
 9336:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9337:         return @mapresources;
 9338:     }
 9339:     if ($scancode) {
 9340:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9341:             @mapresources = @{$orderedforcode->{$scancode}};
 9342:         } else {
 9343:             $env{'form.CODE'} = $scancode;
 9344:             my $actual_seq =
 9345:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9346:                                                                $master_seq,
 9347:                                                                $user,$scancode,1);
 9348:             if (ref($actual_seq) eq 'ARRAY') {
 9349:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9350:                 if (ref($orderedforcode) eq 'HASH') {
 9351:                     if (@mapresources > 0) { 
 9352:                         $orderedforcode->{$scancode} = \@mapresources;
 9353:                     }
 9354:                 }
 9355:             }
 9356:             delete($env{'form.CODE'});
 9357:         }
 9358:     } else {
 9359:         my $actual_seq =
 9360:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9361:                                                            $master_seq,
 9362:                                                            $user,undef,1);
 9363:         if (ref($actual_seq) eq 'ARRAY') {
 9364:             @mapresources = 
 9365:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9366:         }
 9367:     }
 9368:     return @mapresources;
 9369: }
 9370: 
 9371: sub grade_student_bubbles {
 9372:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9373:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9374:     my $uselookup = 0;
 9375:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9376:         (ref($startline) eq 'HASH')) {
 9377:         $uselookup = 1;
 9378:     }
 9379: 
 9380:     if (ref($resources) eq 'ARRAY') {
 9381:         my $count = 0;
 9382:         foreach my $resource (@{$resources}) {
 9383:             my $ressymb = $resource->symb();
 9384:             my %form = ('submitted'      => 'scantron',
 9385:                         'grade_target'   => 'grade',
 9386:                         'grade_username' => $uname,
 9387:                         'grade_domain'   => $udom,
 9388:                         'grade_courseid' => $env{'request.course.id'},
 9389:                         'grade_symb'     => $ressymb,
 9390:                         'CODE'           => $scancode
 9391:                        );
 9392:             if ($bubbles_per_row ne '') {
 9393:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9394:             }
 9395:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9396:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9397:             }
 9398:             if (ref($parts) eq 'HASH') {
 9399:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9400:                     foreach my $part (@{$parts->{$ressymb}}) {
 9401:                         if ($uselookup) {
 9402:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9403:                         } else {
 9404:                             $form{'scantron_questnum_start.'.$part} =
 9405:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9406:                         }
 9407:                         $count++;
 9408:                     }
 9409:                 }
 9410:             }
 9411:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9412:             return 'ssi_error' if ($ssi_error);
 9413:             last if (&Apache::loncommon::connection_aborted($r));
 9414:         }
 9415:     }
 9416:     return;
 9417: }
 9418: 
 9419: sub scantron_upload_scantron_data {
 9420:     my ($r,$symb) = @_;
 9421:     my $dom = $env{'request.role.domain'};
 9422:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9423:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9424:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9425:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9426: 							  'domainid',
 9427: 							  'coursename',$dom);
 9428:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9429:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9430:     my $default_form_data=&defaultFormData($symb);
 9431:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9432:     &js_escape(\$nofile_alert);
 9433:     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.");
 9434:     &js_escape(\$nocourseid_alert);
 9435:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9436:     function checkUpload(formname) {
 9437: 	if (formname.upfile.value == "") {
 9438: 	    alert("'.$nofile_alert.'");
 9439: 	    return false;
 9440: 	}
 9441:         if (formname.courseid.value == "") {
 9442:             alert("'.$nocourseid_alert.'");
 9443:             return false;
 9444:         }
 9445: 	formname.submit();
 9446:     }
 9447: 
 9448:     function ToSyllabus() {
 9449:         var cdom = '."'$dom'".';
 9450:         var cnum = document.rules.courseid.value;
 9451:         if (cdom == "" || cdom == null) {
 9452:             return;
 9453:         }
 9454:         if (cnum == "" || cnum == null) {
 9455:            return;
 9456:         }
 9457:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9458:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9459:         return;
 9460:     }
 9461: 
 9462:     '.$formatjs.'
 9463: '));
 9464:     $r->print('
 9465: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9466: 
 9467: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9468: '.$default_form_data.
 9469:   &Apache::lonhtmlcommon::start_pick_box().
 9470:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9471:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9472:   &Apache::lonhtmlcommon::row_closure().
 9473:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9474:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9475:   &Apache::lonhtmlcommon::row_closure().
 9476:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9477:   '<input name="domainid" type="hidden" />'.$domdesc.
 9478:   &Apache::lonhtmlcommon::row_closure());
 9479:     if ($formatoptions) {
 9480:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9481:                   &Apache::lonhtmlcommon::row_closure());
 9482:     }
 9483:     $r->print(
 9484:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9485:   '<input type="file" name="upfile" size="50" />'.
 9486:   &Apache::lonhtmlcommon::row_closure(1).
 9487:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9488: 
 9489: <input name="command" value="scantronupload_save" type="hidden" />
 9490: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9491: </form>
 9492: ');
 9493:     return '';
 9494: }
 9495: 
 9496: sub scantron_upload_dataformat {
 9497:     my ($dom) = @_;
 9498:     my ($formatoptions,$formattitle,$formatjs);
 9499:     $formatjs = <<'END';
 9500: function toggleScantab(form) {
 9501:    return;
 9502: }
 9503: END
 9504:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9505:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9506:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9507:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9508:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9509:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9510:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
 9511:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9512:                             my ($onclick,$formatextra,$singleline);
 9513:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9514:                             my $count = 0;
 9515:                             foreach my $line (@lines) {
 9516:                                 next if ($line =~ /^#/);
 9517:                                 $singleline = $line;
 9518:                                 $count ++;
 9519:                             }
 9520:                             if ($count > 1) {
 9521:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9522:                                                '<span class="LC_nobreak">'.
 9523:                                                &mt('Bubblesheet type').':&nbsp;'.
 9524:                                                &scantron_scantab().'</span></div>';
 9525:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9526:                                 $formatjs = <<"END";
 9527: function toggleScantab(form) {
 9528:     var divid = 'bubbletype';
 9529:     if (document.getElementById(divid)) {
 9530:         var radioname = 'fileformat';
 9531:         var num = form.elements[radioname].length;
 9532:         if (num) {
 9533:             for (var i=0; i<num; i++) {
 9534:                 if (form.elements[radioname][i].checked) {
 9535:                     var chosen = form.elements[radioname][i].value;
 9536:                     if (chosen == 'dat') {
 9537:                         document.getElementById(divid).style.display = 'none';
 9538:                     } else if (chosen == 'csv') {
 9539:                         document.getElementById(divid).style.display = 'block';
 9540:                     }
 9541:                 }
 9542:             }
 9543:         }
 9544:     }
 9545:     return;
 9546: }
 9547: 
 9548: END
 9549:                             } elsif ($count == 1) {
 9550:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9551:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9552:                             }
 9553:                             $formattitle = &mt('File format');
 9554:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9555:                                              &mt('Plain Text (no delimiters)').
 9556:                                              '</label>'.('&nbsp;'x2).
 9557:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9558:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9559:                         }
 9560:                     }
 9561:                 }
 9562:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9563:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9564:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9565:                         $formattitle = &mt('Bubblesheet type');
 9566:                         $formatoptions = &scantron_scantab();
 9567:                     }
 9568:                 }
 9569:             }
 9570:         }
 9571:     }
 9572:     return ($formatoptions,$formattitle,$formatjs);
 9573: }
 9574: 
 9575: sub scantron_upload_scantron_data_save {
 9576:     my ($r,$symb) = @_;
 9577:     my $doanotherupload=
 9578: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9579: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9580: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9581: 	'</form>'."\n";
 9582:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9583: 	!&Apache::lonnet::allowed('usc',
 9584: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
 9585:         !&Apache::lonnet::allowed('usc',
 9586:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9587: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9588: 	unless ($symb) {
 9589: 	    $r->print($doanotherupload);
 9590: 	}
 9591: 	return '';
 9592:     }
 9593:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9594:     my $uploadedfile;
 9595:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9596:     if (length($env{'form.upfile'}) < 2) {
 9597:         $r->print(
 9598:             &Apache::lonhtmlcommon::confirm_success(
 9599:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9600:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9601:     } else {
 9602:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9603:         my $parser;
 9604:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9605:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9606:                 my $is_csv;
 9607:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9608:                 if (@possibles > 1) {
 9609:                     if ($env{'form.fileformat'} eq 'csv') {
 9610:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9611:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9612:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9613:                                     $is_csv = 1;
 9614:                                 }
 9615:                             }
 9616:                         }
 9617:                     }
 9618:                 } elsif (@possibles == 1) {
 9619:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9620:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9621:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9622:                                 $is_csv = 1;
 9623:                             }
 9624:                         }
 9625:                     }
 9626:                 }
 9627:                 if ($is_csv) {
 9628:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9629:                 }
 9630:             }
 9631:         }
 9632:         my $result =
 9633:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9634:                                             $env{'form.courseid'},$env{'form.domainid'});
 9635:         if ($result =~ m{^/uploaded/}) {
 9636:             $r->print(
 9637:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9638:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9639:                         (length($env{'form.upfile'})-1),
 9640:                         '<span class="LC_filename">'.$result.'</span>'));
 9641:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9642:             if ($uploadedfile =~ /^scantron_orig_/) {
 9643:                 my $logname = $uploadedfile;
 9644:                 $logname =~ s/^scantron_orig_//;
 9645:                 if ($logname ne '') {
 9646:                     my $now = time;
 9647:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
 9648:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9649:                 }
 9650:             }
 9651:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9652:                                                        $env{'form.courseid'},$symb,$uploadedfile));
 9653:         } else {
 9654:             $r->print(
 9655:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9656:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9657:                           $result,
 9658: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9659: 	}
 9660:     }
 9661:     if ($symb) {
 9662: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9663:     } else {
 9664: 	$r->print($doanotherupload);
 9665:     }
 9666:     return '';
 9667: }
 9668: 
 9669: sub validate_uploaded_scantron_file {
 9670:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
 9671: 
 9672:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9673:     my @lines;
 9674:     if ($scanlines ne '-1') {
 9675:         @lines=split("\n",$scanlines,-1);
 9676:     }
 9677:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
 9678:     $secidx = &Apache::loncoursedata::CL_SECTION();
 9679:     if ($context eq 'download') {
 9680:         $priv = 'mgr';
 9681:     } else {
 9682:         $priv = 'usc';
 9683:     }
 9684:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
 9685:             (($env{'request.course.id'}) &&
 9686:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
 9687:         if ($env{'request.course.sec'} ne '') {
 9688:             unless (&Apache::lonnet::allowed($priv,
 9689:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
 9690:                 unless ($context eq 'download') {
 9691:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
 9692:                 }
 9693:                 return $output;
 9694:             }
 9695:             ($checksec,@possibles)=&gradable_sections();
 9696:         }
 9697:     }
 9698:     if (@lines) {
 9699:         my (%counts,$max_match_format);
 9700:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9701:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9702:         my %idmap = &username_to_idmap($classlist);
 9703:         foreach my $key (keys(%idmap)) {
 9704:             my $lckey = lc($key);
 9705:             $idmap{$lckey} = $idmap{$key};
 9706:         }
 9707:         my %unique_formats;
 9708:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9709:         foreach my $line (@formatlines) {
 9710:             chomp($line);
 9711:             my @config = split(/:/,$line);
 9712:             my $idstart = $config[5];
 9713:             my $idlength = $config[6];
 9714:             if (($idstart ne '') && ($idlength > 0)) {
 9715:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9716:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9717:                 } else {
 9718:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9719:                 }
 9720:             }
 9721:         }
 9722:         foreach my $key (keys(%unique_formats)) {
 9723:             my ($idstart,$idlength) = split(':',$key);
 9724:             %{$counts{$key}} = (
 9725:                                'found'   => 0,
 9726:                                'total'   => 0,
 9727:                                'totalanysec' => 0,
 9728:                                'othersec' => 0,
 9729:                               );
 9730:             foreach my $line (@lines) {
 9731:                 next if ($line =~ /^#/);
 9732:                 next if ($line =~ /^[\s\cz]*$/);
 9733:                 my $id = substr($line,$idstart-1,$idlength);
 9734:                 $id = lc($id);
 9735:                 if (exists($idmap{$id})) {
 9736:                     if ($checksec ne '') {
 9737:                         $counts{$key}{'totalanysec'} ++;
 9738:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
 9739:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
 9740:                             if ($stusec ne $checksec) {
 9741:                                 if (@possibles) {
 9742:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
 9743:                                         $counts{$key}{'othersec'} ++;
 9744:                                         next;
 9745:                                     }
 9746:                                 } else {
 9747:                                     $counts{$key}{'othersec'} ++;
 9748:                                     next;
 9749:                                 }
 9750:                             }
 9751:                         }
 9752:                     }
 9753:                     $counts{$key}{'found'} ++;
 9754:                 }
 9755:                 $counts{$key}{'total'} ++;
 9756:             }
 9757:             if ($counts{$key}{'total'}) {
 9758:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9759:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9760:                     $max_match_pct = $percent_match;
 9761:                     $max_match_format = $key;
 9762:                     $found_match_count = $counts{$key}{'found'};
 9763:                     $max_match_count = $counts{$key}{'total'};
 9764:                 }
 9765:             }
 9766:         }
 9767:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
 9768:             my $format_descs;
 9769:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9770:             for (my $i=0; $i<$numwithformat; $i++) {
 9771:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9772:                 if ($i<$numwithformat-2) {
 9773:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9774:                 } elsif ($i==$numwithformat-2) {
 9775:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9776:                 } elsif ($i==$numwithformat-1) {
 9777:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9778:                 }
 9779:             }
 9780:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9781:             $output .= '<br />';
 9782:             if ($found_match_count == $max_match_count) {
 9783:                 # 100% matching entries
 9784:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9785:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9786:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9787:                 &mt('Comparison of student IDs in the uploaded file with'.
 9788:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9789:                     ' in the file (for the format defined for [_3]).',
 9790:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9791:             } else {
 9792:                 # Not all entries matching? -> Show warning and additional info
 9793:                 $output .=
 9794:                     &Apache::lonhtmlcommon::confirm_success(
 9795:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9796:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9797:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9798:                     &mt('Comparison of student IDs in the uploaded file with'.
 9799:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9800:                         ' in the file (for the format defined for [_3]).',
 9801:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9802:                     '<p class="LC_info">'.
 9803:                     &mt('A low percentage of matches results from one of the following:').
 9804:                     '</p><ul>'.
 9805:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9806:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9807:                                '<i>'.$cdom.'</i>').'</li>'.
 9808:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9809:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9810:                     '</ul>';
 9811:             }
 9812:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9813:                 if ($counts{$max_match_format}{'othersec'}) {
 9814:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
 9815:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
 9816:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
 9817:                     &js_escape(\$confirmdel);
 9818:                     $output .= '<p class="LC_warning">'.
 9819:                                &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',
 9820:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
 9821:                                '<br />'.
 9822:                                &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>').
 9823:                                '</p><p>'.
 9824:                                &mt('If you prefer to delete the file now, use: [_1]').
 9825:                                '<form method="post" name="delupload" action="/adm/grades">'.
 9826:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
 9827:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
 9828:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
 9829:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
 9830:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
 9831:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
 9832:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
 9833:                                '</form></p>';
 9834:                 }
 9835:             }
 9836:         }
 9837:         if (($context eq 'download') && ($checksec ne '')) {
 9838:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
 9839:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
 9840:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
 9841:             }
 9842:         } 
 9843:     } elsif ($context ne 'download') {
 9844:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9845:     }
 9846:     return $output;
 9847: }
 9848: 
 9849: sub gradable_sections {
 9850:     my $checksec = $env{'request.course.sec'};
 9851:     my @oksecs;
 9852:     if ($checksec) {
 9853:         my %availablesecs = &sections_grade_privs();
 9854:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
 9855:             foreach my $sec (@{$availablesecs{'mgr'}}) {
 9856:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
 9857:                     push(@oksecs,$sec);
 9858:                 }
 9859:             }
 9860:             if (grep(/^all$/,@oksecs)) {
 9861:                 undef($checksec);
 9862:             }
 9863:         }
 9864:     }
 9865:     return($checksec,@oksecs);
 9866: }
 9867: 
 9868: sub sections_grade_privs {
 9869:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9870:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9871:     my %availablesecs = (
 9872:                           mgr => [],
 9873:                           vgr => [],
 9874:                           usc => [],
 9875:                         );
 9876:     my $ccrole = 'cc';
 9877:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
 9878:         $ccrole = 'co';
 9879:     }
 9880:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
 9881:                                                      'userroles',['active'],
 9882:                                                      [$ccrole,'in','cr'],$cdom,1);
 9883:     my $crsid = $cnum.':'.$cdom;
 9884:     foreach my $item (keys(%crsroleshash)) {
 9885:         next unless ($item =~ /^$crsid\:/);
 9886:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
 9887:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
 9888:         if ($sec ne '') {
 9889:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
 9890:         }
 9891:         if (($role eq $ccrole) || ($role eq 'in')) {
 9892:             foreach my $priv ('mgr','vgr','usc') { 
 9893:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9894:                     if ($sec eq '') {
 9895:                         $availablesecs{$priv} = ['all'];
 9896:                     } elsif ($sec ne $env{'request.course.sec'}) {
 9897:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9898:                             push(@{$availablesecs{$priv}},$sec);
 9899:                         }
 9900:                     }
 9901:                 }
 9902:             }
 9903:         } elsif ($role =~ m{^cr/}) {
 9904:             foreach my $priv ('mgr','vgr','usc') {
 9905:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
 9906:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
 9907:                         if ($sec eq '') {
 9908:                             $availablesecs{$priv} = ['all'];
 9909:                         } elsif ($sec ne $env{'request.course.sec'}) {
 9910:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
 9911:                                 push(@{$availablesecs{$priv}},$sec);
 9912:                             }
 9913:                         }
 9914:                     }
 9915:                 }
 9916:             }
 9917:         }
 9918:     }
 9919:     return %availablesecs;
 9920: }
 9921: 
 9922: sub scantron_upload_delete {
 9923:     my ($r,$symb) = @_;
 9924:     my $filename = $env{'form.uploadedfile'};
 9925:     if ($filename =~ /^scantron_orig_/) {
 9926:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
 9927:             &Apache::lonnet::allowed('usc',
 9928:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
 9929:             &Apache::lonnet::allowed('usc',
 9930:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
 9931:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
 9932:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
 9933:             if ($retrieval eq '-1') {
 9934:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9935:                           &mt('File requested for deletion not found.'));
 9936:             } else {
 9937:                 $filename =~ s/^scantron_orig_//;
 9938:                 if ($filename ne '') {
 9939:                     my ($is_valid,$numleft);
 9940:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9941:                     if (keys(%info)) {
 9942:                         if (ref($info{$filename}) eq 'HASH') {
 9943:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
 9944:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 9945:                                     $is_valid = 1;
 9946:                                     delete($info{$filename}{$timestamp}); 
 9947:                                 }
 9948:                             }
 9949:                             $numleft = scalar(keys(%{$info{$filename}}));
 9950:                         }
 9951:                     }
 9952:                     if ($is_valid) {
 9953:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
 9954:                         if ($result eq 'ok') {
 9955:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
 9956:                             if ($numleft) {
 9957:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
 9958:                             } else {
 9959:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
 9960:                             }
 9961:                         } else {
 9962:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9963:                                       &mt('Result was [_1]',$result));
 9964:                         }
 9965:                     } else {
 9966:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9967:                                   &mt('File requested for deletion was uploaded by a different user.'));
 9968:                     }
 9969:                 } else {
 9970:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9971:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9972:                 }
 9973:             }
 9974:         } else {
 9975:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
 9976:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
 9977:         }
 9978:     } else {
 9979:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
 9980:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
 9981:     }
 9982:     return;
 9983: }
 9984: 
 9985: sub valid_file {
 9986:     my ($requested_file)=@_;
 9987:     foreach my $filename (sort(&scantron_filenames())) {
 9988: 	if ($requested_file eq $filename) { return 1; }
 9989:     }
 9990:     return 0;
 9991: }
 9992: 
 9993: sub scantron_download_scantron_data {
 9994:     my ($r,$symb) = @_;
 9995:     my $default_form_data=&defaultFormData($symb);
 9996:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9997:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9998:     my $file=$env{'form.scantron_selectfile'};
 9999:     if (! &valid_file($file)) {
10000: 	$r->print('
10001: 	<p>
10002: 	    '.&mt('The requested filename was invalid.').'
10003:         </p>
10004: ');
10005: 	return;
10006:     }
10007:     my (%uploader,$is_owner,%counts,$percent);
10008:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
10009:     if (ref($uploader{$file}) eq 'HASH') {
10010:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
10011:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
10012:                 $is_owner = 1;
10013:                 last;
10014:             }
10015:         }
10016:     }
10017:     unless ($is_owner) {
10018:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
10019:         if ($counts{'totalanysec'}) {
10020:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
10021:             if ($percent_othersec >= 10) {
10022:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
10023:                 $r->print('<p class="LC_warning">'.
10024:                           &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).
10025:                           '</p>');
10026:                 return;
10027:             }
10028:         }
10029:     }
10030:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
10031:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
10032:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
10033:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
10034:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
10035:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
10036:     $r->print('
10037:     <p>
10038: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
10039: 	      '<a href="'.$orig.'">','</a>').'
10040:     </p>
10041:     <p>
10042: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
10043: 	      '<a href="'.$corrected.'">','</a>').'
10044:     </p>
10045:     <p>
10046: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
10047: 	      '<a href="'.$skipped.'">','</a>').'
10048:     </p>
10049: ');
10050:     return '';
10051: }
10052: 
10053: sub checkscantron_results {
10054:     my ($r,$symb) = @_;
10055:     if (!$symb) {return '';}
10056:     my $cid = $env{'request.course.id'};
10057:     my %lettdig = &Apache::lonnet::letter_to_digits();
10058:     my $numletts = scalar(keys(%lettdig));
10059:     my $cnum = $env{'course.'.$cid.'.num'};
10060:     my $cdom = $env{'course.'.$cid.'.domain'};
10061:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
10062:     my %record;
10063:     my %scantron_config =
10064:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
10065:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
10066:     my ($scanlines,$scan_data)=&scantron_getfile();
10067:     my $classlist=&Apache::loncoursedata::get_classlist();
10068:     my %idmap=&Apache::grades::username_to_idmap($classlist);
10069:     my $navmap=Apache::lonnavmaps::navmap->new();
10070:     unless (ref($navmap)) {
10071:         $r->print(&navmap_errormsg());
10072:         return '';
10073:     }
10074:     my $map=$navmap->getResourceByUrl($sequence);
10075:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
10076:         %grader_randomlists_by_symb,%orderedforcode);
10077:     if (ref($map)) { 
10078:         $randomorder=$map->randomorder();
10079:         $randompick=$map->randompick();
10080:     }
10081:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
10082:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
10083:     if ($nav_error) {
10084:         $r->print(&navmap_errormsg());
10085:         return '';
10086:     }
10087:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
10088:                             \%grader_randomlists_by_symb,$bubbles_per_row);
10089:     my ($uname,$udom);
10090:     my (%scandata,%lastname,%bylast);
10091:     $r->print('
10092: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
10093: 
10094:     my @delayqueue;
10095:     my %completedstudents;
10096: 
10097:     my $count=&get_todo_count($scanlines,$scan_data);
10098:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
10099:     my ($username,$domain,$started);
10100:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
10101:     if ($nav_error) {
10102:         $r->print(&navmap_errormsg());
10103:         return '';
10104:     }
10105: 
10106:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
10107:     my $start=&Time::HiRes::time();
10108:     my $i=-1;
10109: 
10110:     while ($i<$scanlines->{'count'}) {
10111:         ($username,$domain,$uname)=('','','');
10112:         $i++;
10113:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
10114:         if ($line=~/^[\s\cz]*$/) { next; }
10115:         if ($started) {
10116:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
10117:         }
10118:         $started=1;
10119:         my $scan_record=
10120:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
10121:                                                      $scan_data);
10122:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
10123:                                               \%idmap,$i)) {
10124:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10125:                                 'Unable to find a student that matches',1);
10126:             next;
10127:         }
10128:         if (exists $completedstudents{$uname}) {
10129:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
10130:                                 'Student '.$uname.' has multiple sheets',2);
10131:             next;
10132:         }
10133:         my $pid = $scan_record->{'scantron.ID'};
10134:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
10135:         push(@{$bylast{$lastname{$pid}}},$pid);
10136:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
10137:         my $user = $uname.':'.$usec;
10138:         ($username,$domain)=split(/:/,$uname);
10139: 
10140:         my $scancode;
10141:         if ((exists($scan_record->{'scantron.CODE'})) &&
10142:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
10143:             $scancode = $scan_record->{'scantron.CODE'};
10144:         } else {
10145:             $scancode = '';
10146:         }
10147: 
10148:         my @mapresources = @resources;
10149:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
10150:         my %respnumlookup=();
10151:         my %startline=();
10152:         if ($randomorder || $randompick) {
10153:             @mapresources =
10154:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
10155:                              \%orderedforcode);
10156:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
10157:                                              $scan_record,\@master_seq,\%symb_to_resource,
10158:                                              \%grader_partids_by_symb,\%orderedforcode,
10159:                                              \%respnumlookup,\%startline);
10160:             if ($randompick && $total) {
10161:                 $lastpos = $total*$scantron_config{'Qlength'};
10162:             }
10163:         }
10164:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
10165:         chomp($scandata{$pid});
10166:         $scandata{$pid} =~ s/\r$//;
10167: 
10168:         my $counter = -1;
10169:         foreach my $resource (@mapresources) {
10170:             my $parts;
10171:             my $ressymb = $resource->symb();
10172:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
10173:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
10174:                 my $currcode;
10175:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
10176:                     $currcode = $scancode;
10177:                 }
10178:                 (my $analysis,$parts) =
10179:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
10180:                                               $username,$domain,undef,
10181:                                               $bubbles_per_row,$currcode);
10182:             } else {
10183:                 $parts = $grader_partids_by_symb{$ressymb};
10184:             }
10185:             ($counter,my $recording) =
10186:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
10187:                                          $scandata{$pid},$parts,
10188:                                          \%scantron_config,\%lettdig,$numletts,
10189:                                          $randomorder,$randompick,
10190:                                          \%respnumlookup,\%startline);
10191:             $record{$pid} .= $recording;
10192:         }
10193:     }
10194:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
10195:     $r->print('<br />');
10196:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
10197:     $passed = 0;
10198:     $failed = 0;
10199:     $numstudents = 0;
10200:     foreach my $last (sort(keys(%bylast))) {
10201:         if (ref($bylast{$last}) eq 'ARRAY') {
10202:             foreach my $pid (sort(@{$bylast{$last}})) {
10203:                 my $showscandata = $scandata{$pid};
10204:                 my $showrecord = $record{$pid};
10205:                 $showscandata =~ s/\s/&nbsp;/g;
10206:                 $showrecord =~ s/\s/&nbsp;/g;
10207:                 if ($scandata{$pid} eq $record{$pid}) {
10208:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
10209:                     $okstudents .= '<tr class="'.$css_class.'">'.
10210: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
10211: '</tr>'."\n".
10212: '<tr class="'.$css_class.'">'."\n".
10213: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
10214:                     $passed ++;
10215:                 } else {
10216:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
10217:                     $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".
10218: '</tr>'."\n".
10219: '<tr class="'.$css_class.'">'."\n".
10220: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
10221: '</tr>'."\n";
10222:                     $failed ++;
10223:                 }
10224:                 $numstudents ++;
10225:             }
10226:         }
10227:     }
10228:     $r->print(
10229:         '<p>'
10230:        .&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).',
10231:             '<b>',
10232:             $numstudents,
10233:             '</b>',
10234:             $env{'form.scantron_maxbubble'})
10235:        .'</p>'
10236:     );
10237:     $r->print('<p>'
10238:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
10239:              .'<br />'
10240:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
10241:              .'</p>'
10242:     );
10243:     if ($passed) {
10244:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
10245:         $r->print(&Apache::loncommon::start_data_table()."\n".
10246:                  &Apache::loncommon::start_data_table_header_row()."\n".
10247:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10248:                  &Apache::loncommon::end_data_table_header_row()."\n".
10249:                  $okstudents."\n".
10250:                  &Apache::loncommon::end_data_table().'<br />');
10251:     }
10252:     if ($failed) {
10253:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
10254:         $r->print(&Apache::loncommon::start_data_table()."\n".
10255:                  &Apache::loncommon::start_data_table_header_row()."\n".
10256:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
10257:                  &Apache::loncommon::end_data_table_header_row()."\n".
10258:                  $badstudents."\n".
10259:                  &Apache::loncommon::end_data_table()).'<br />'.
10260:                  &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.');  
10261:     }
10262:     $r->print('</form><br />');
10263:     return;
10264: }
10265: 
10266: sub verify_scantron_grading {
10267:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
10268:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
10269:         $respnumlookup,$startline) = @_;
10270:     my ($record,%expected,%startpos);
10271:     return ($counter,$record) if (!ref($resource));
10272:     return ($counter,$record) if (!$resource->is_problem());
10273:     my $symb = $resource->symb();
10274:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
10275:     foreach my $part_id (@{$partids}) {
10276:         $counter ++;
10277:         $expected{$part_id} = 0;
10278:         my $respnum = $counter;
10279:         if ($randomorder || $randompick) {
10280:             $respnum = $respnumlookup->{$counter};
10281:             $startpos{$part_id} = $startline->{$counter} + 1;
10282:         } else {
10283:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
10284:         }
10285:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
10286:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
10287:             foreach my $item (@sub_lines) {
10288:                 $expected{$part_id} += $item;
10289:             }
10290:         } else {
10291:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
10292:         }
10293:     }
10294:     if ($symb) {
10295:         my %recorded;
10296:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
10297:         if ($returnhash{'version'}) {
10298:             my %lasthash=();
10299:             my $version;
10300:             for ($version=1;$version<=$returnhash{'version'};$version++) {
10301:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
10302:                     $lasthash{$key}=$returnhash{$version.':'.$key};
10303:                 }
10304:             }
10305:             foreach my $key (keys(%lasthash)) {
10306:                 if ($key =~ /\.scantron$/) {
10307:                     my $value = &unescape($lasthash{$key});
10308:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
10309:                     if ($value eq '') {
10310:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
10311:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
10312:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
10313:                             }
10314:                         }
10315:                     } else {
10316:                         my @tocheck;
10317:                         my @items = split(//,$value);
10318:                         if (($scantron_config->{'Qon'} eq 'letter') ||
10319:                             ($scantron_config->{'Qon'} eq 'number')) {
10320:                             if (@items < $expected{$part_id}) {
10321:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
10322:                                 my @singles = split(//,$fragment);
10323:                                 foreach my $pos (@singles) {
10324:                                     if ($pos eq ' ') {
10325:                                         push(@tocheck,$pos);
10326:                                     } else {
10327:                                         my $next = shift(@items);
10328:                                         push(@tocheck,$next);
10329:                                     }
10330:                                 }
10331:                             } else {
10332:                                 @tocheck = @items;
10333:                             }
10334:                             foreach my $letter (@tocheck) {
10335:                                 if ($scantron_config->{'Qon'} eq 'letter') {
10336:                                     if ($letter !~ /^[A-J]$/) {
10337:                                         $letter = $scantron_config->{'Qoff'};
10338:                                     }
10339:                                     $recorded{$part_id} .= $letter;
10340:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
10341:                                     my $digit;
10342:                                     if ($letter !~ /^[A-J]$/) {
10343:                                         $digit = $scantron_config->{'Qoff'};
10344:                                     } else {
10345:                                         $digit = $lettdig->{$letter};
10346:                                     }
10347:                                     $recorded{$part_id} .= $digit;
10348:                                 }
10349:                             }
10350:                         } else {
10351:                             @tocheck = @items;
10352:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10353:                                 my $curr_sub = shift(@tocheck);
10354:                                 my $digit;
10355:                                 if ($curr_sub =~ /^[A-J]$/) {
10356:                                     $digit = $lettdig->{$curr_sub}-1;
10357:                                 }
10358:                                 if ($curr_sub eq 'J') {
10359:                                     $digit += scalar($numletts);
10360:                                 }
10361:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10362:                                     if ($j == $digit) {
10363:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10364:                                     } else {
10365:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10366:                                     }
10367:                                 }
10368:                             }
10369:                         }
10370:                     }
10371:                 }
10372:             }
10373:         }
10374:         foreach my $part_id (@{$partids}) {
10375:             if ($recorded{$part_id} eq '') {
10376:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10377:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10378:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10379:                     }
10380:                 }
10381:             }
10382:             $record .= $recorded{$part_id};
10383:         }
10384:     }
10385:     return ($counter,$record);
10386: }
10387: 
10388: #-------- end of section for handling grading scantron forms -------
10389: #
10390: #-------------------------------------------------------------------
10391: 
10392: #-------------------------- Menu interface -------------------------
10393: #
10394: #--- Href with symb and command ---
10395: 
10396: sub href_symb_cmd {
10397:     my ($symb,$cmd)=@_;
10398:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10399: }
10400: 
10401: sub grading_menu {
10402:     my ($request,$symb) = @_;
10403:     if (!$symb) {return '';}
10404: 
10405:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10406:                   'command'=>'individual');
10407:     
10408:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10409: 
10410:     $fields{'command'}='ungraded';
10411:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10412: 
10413:     $fields{'command'}='table';
10414:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10415: 
10416:     $fields{'command'}='all_for_one';
10417:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10418: 
10419:     $fields{'command'}='downloadfilesselect';
10420:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10421: 
10422:     $fields{'command'} = 'csvform';
10423:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10424:     
10425:     $fields{'command'} = 'processclicker';
10426:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10427:     
10428:     $fields{'command'} = 'scantron_selectphase';
10429:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10430: 
10431:     $fields{'command'} = 'initialverifyreceipt';
10432:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10433: 
10434:     my %permissions;
10435:     if ($perm{'mgr'}) {
10436:         $permissions{'either'} = 'F';
10437:         $permissions{'mgr'} = 'F';
10438:     }
10439:     if ($perm{'vgr'}) {
10440:         $permissions{'either'} = 'F';
10441:         $permissions{'vgr'} = 'F';
10442:     }
10443: 
10444:     my @menu = ({	categorytitle=>'Hand Grading',
10445:             items =>[
10446:                         {	linktext => 'Select individual students to grade',
10447:                     		url => $url1a,
10448:                     		permission => $permissions{'either'},
10449:                     		icon => 'grade_students.png',
10450:                     		linktitle => 'Grade current resource for a selection of students.'
10451:                         }, 
10452:                         {       linktext => 'Grade ungraded submissions',
10453:                                 url => $url1b,
10454:                                 permission => $permissions{'either'},
10455:                                 icon => 'ungrade_sub.png',
10456:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10457:                         },
10458: 
10459:                         {       linktext => 'Grading table',
10460:                                 url => $url1c,
10461:                                 permission => $permissions{'either'},
10462:                                 icon => 'grading_table.png',
10463:                                 linktitle => 'Grade current resource for all students.'
10464:                         },
10465:                         {       linktext => 'Grade page/folder for one student',
10466:                                 url => $url1d,
10467:                                 permission => $permissions{'either'},
10468:                                 icon => 'grade_PageFolder.png',
10469:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10470:                         },
10471:                         {       linktext => 'Download submissions',
10472:                                 url => $url1e,
10473:                                 permission => $permissions{'either'},
10474:                                 icon => 'download_sub.png',
10475:                                 linktitle => 'Download all students submissions.'
10476:                         }]},
10477:                          { categorytitle=>'Automated Grading',
10478:                items =>[
10479: 
10480:                 	    {	linktext => 'Upload Scores',
10481:                     		url => $url2,
10482:                     		permission => $permissions{'mgr'},
10483:                     		icon => 'uploadscores.png',
10484:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10485:                 	    },
10486:                 	    {	linktext => 'Process Clicker',
10487:                     		url => $url3,
10488:                     		permission => $permissions{'mgr'},
10489:                     		icon => 'addClickerInfoFile.png',
10490:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10491:                 	    },
10492:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10493:                     		url => $url4,
10494:                     		permission => $permissions{'mgr'},
10495:                     		icon => 'bubblesheet.png',
10496:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10497:                 	    },
10498:                             {   linktext => 'Verify Receipt Number',
10499:                                 url => $url5,
10500:                                 permission => $permissions{'either'},
10501:                                 icon => 'receipt_number.png',
10502:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10503:                             }
10504: 
10505:                     ]
10506:             });
10507: 
10508:     # Create the menu
10509:     my $Str;
10510:     $Str .= '<form method="post" action="" name="gradingMenu">';
10511:     $Str .= '<input type="hidden" name="command" value="" />'.
10512:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10513: 
10514:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10515:     return $Str;    
10516: }
10517: 
10518: sub ungraded {
10519:     my ($request)=@_;
10520:     &submit_options($request);
10521: }
10522: 
10523: sub submit_options_sequence {
10524:     my ($request,$symb) = @_;
10525:     if (!$symb) {return '';}
10526:     &commonJSfunctions($request);
10527:     my $result;
10528: 
10529:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10530:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10531:     $result.=&selectfield(0).
10532:             '<input type="hidden" name="command" value="pickStudentPage" />
10533:             <div>
10534:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10535:             </div>
10536:         </div>
10537:   </form>';
10538:     return $result;
10539: }
10540: 
10541: sub submit_options_table {
10542:     my ($request,$symb) = @_;
10543:     if (!$symb) {return '';}
10544:     &commonJSfunctions($request);
10545:     my $is_tool = ($symb =~ /ext\.tool$/);
10546:     my $result;
10547: 
10548:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10549:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10550: 
10551:     $result.=&selectfield(1,$is_tool).
10552:             '<input type="hidden" name="command" value="viewgrades" />
10553:             <div>
10554:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10555:             </div>
10556:         </div>
10557:   </form>';
10558:     return $result;
10559: }
10560: 
10561: sub submit_options_download {
10562:     my ($request,$symb) = @_;
10563:     if (!$symb) {return '';}
10564: 
10565:     my $res_error;
10566:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10567:         &response_type($symb,\$res_error);
10568:     if ($res_error) {
10569:         $request->print(&mt('An error occurred retrieving response types'));
10570:         return;
10571:     }
10572:     unless ($numessay) {
10573:         $request->print(&mt('No essayresponse items found'));
10574:         return;
10575:     }
10576:     my $table;
10577:     if (ref($partlist) eq 'ARRAY') {
10578:         if (scalar(@$partlist) > 1 ) {
10579:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10580:         }
10581:     }
10582: 
10583:     my $is_tool = ($symb =~ /ext\.tool$/);
10584:     &commonJSfunctions($request);
10585: 
10586:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10587:                $table."\n".
10588:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10589:     $result.='
10590: <h2>
10591:   '.&mt('Select Students for whom to Download Submissions').'
10592: </h2>'.&selectfield(1,$is_tool).'
10593:                 <input type="hidden" name="command" value="downloadfileslink" /> 
10594:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10595:             </div>
10596:           </div>
10597: 
10598: 
10599:   </form>';
10600:     return $result;
10601: }
10602: 
10603: #--- Displays the submissions first page -------
10604: sub submit_options {
10605:     my ($request,$symb) = @_;
10606:     if (!$symb) {return '';}
10607: 
10608:     my $is_tool = ($symb =~ /ext\.tool$/);
10609:     &commonJSfunctions($request);
10610:     my $result;
10611: 
10612:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10613: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10614:     $result.=&selectfield(1,$is_tool).'
10615:                 <input type="hidden" name="command" value="submission" /> 
10616: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
10617:             </div>
10618:           </div>
10619:   </form>';
10620:     return $result;
10621: }
10622: 
10623: sub selectfield {
10624:    my ($full,$is_tool)=@_;
10625:    my %options;
10626:    if ($is_tool) {
10627:        %options =
10628:            (&transtatus_options,
10629:             'select_form_order' => ['yes','incorrect','all']);
10630:    } else {
10631:        %options = 
10632:            (&substatus_options,
10633:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
10634:    }
10635: 
10636:   #
10637:   # PrepareClasslist() needs to be called to avoid getting a sections list
10638:   # for a different course from the @Sections global in lonstatistics.pm, 
10639:   # populated by an earlier request.
10640:   #
10641:    &Apache::lonstatistics::PrepareClasslist();
10642: 
10643:    my $result='<div class="LC_columnSection">
10644:   
10645:     <fieldset>
10646:       <legend>
10647:        '.&mt('Sections').'
10648:       </legend>
10649:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10650:     </fieldset>
10651:   
10652:     <fieldset>
10653:       <legend>
10654:         '.&mt('Groups').'
10655:       </legend>
10656:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10657:     </fieldset>
10658:   
10659:     <fieldset>
10660:       <legend>
10661:         '.&mt('Access Status').'
10662:       </legend>
10663:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10664:     </fieldset>';
10665:     if ($full) {
10666:         my $heading = &mt('Submission Status');
10667:         if ($is_tool) {
10668:             $heading = &mt('Transaction Status');
10669:         }
10670:         $result.='
10671:     <fieldset>
10672:       <legend>
10673:         '.$heading.'
10674:       </legend>'.
10675:        &Apache::loncommon::select_form('all','submitonly',\%options).
10676:    '</fieldset>';
10677:     }
10678:     $result.='</div><br />';
10679:     return $result;
10680: }
10681: 
10682: sub substatus_options {
10683:     return &Apache::lonlocal::texthash(
10684:                                       'yes'       => 'with submissions',
10685:                                       'queued'    => 'in grading queue',
10686:                                       'graded'    => 'with ungraded submissions',
10687:                                       'incorrect' => 'with incorrect submissions',
10688:                                       'all'       => 'with any status',
10689:                                       );
10690: }
10691: 
10692: sub transtatus_options {
10693:     return &Apache::lonlocal::texthash(
10694:                                        'yes'       => 'with score transactions',
10695:                                        'incorrect' => 'with less than full credit',
10696:                                        'all'       => 'with any status',
10697:                                       );
10698: }
10699: 
10700: sub reset_perm {
10701:     undef(%perm);
10702: }
10703: 
10704: sub init_perm {
10705:     &reset_perm();
10706:     foreach my $test_perm ('vgr','mgr','opa','usc') {
10707: 
10708: 	my $scope = $env{'request.course.id'};
10709: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10710: 
10711: 	    $scope .= '/'.$env{'request.course.sec'};
10712: 	    if ( $perm{$test_perm}=
10713: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10714: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10715: 	    } else {
10716: 		delete($perm{$test_perm});
10717: 	    }
10718: 	}
10719:     }
10720: }
10721: 
10722: sub init_old_essays {
10723:     my ($symb,$apath,$adom,$aname) = @_;
10724:     if ($symb ne '') {
10725:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10726:         if (keys(%essays) > 0) {
10727:             $old_essays{$symb} = \%essays;
10728:         }
10729:     }
10730:     return;
10731: }
10732: 
10733: sub reset_old_essays {
10734:     undef(%old_essays);
10735: }
10736: 
10737: sub gather_clicker_ids {
10738:     my %clicker_ids;
10739: 
10740:     my $classlist = &Apache::loncoursedata::get_classlist();
10741: 
10742:     # Set up a couple variables.
10743:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10744:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10745:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10746: 
10747:     foreach my $student (keys(%$classlist)) {
10748:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10749:         my $username = $classlist->{$student}->[$username_idx];
10750:         my $domain   = $classlist->{$student}->[$domain_idx];
10751:         my $clickers =
10752: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10753:         foreach my $id (split(/\,/,$clickers)) {
10754:             $id=~s/^[\#0]+//;
10755:             $id=~s/[\-\:]//g;
10756:             if (exists($clicker_ids{$id})) {
10757: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10758:             } else {
10759: 		$clicker_ids{$id}=$username.':'.$domain;
10760:             }
10761:         }
10762:     }
10763:     return %clicker_ids;
10764: }
10765: 
10766: sub gather_adv_clicker_ids {
10767:     my %clicker_ids;
10768:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10769:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10770:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10771:     foreach my $element (sort(keys(%coursepersonnel))) {
10772:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10773:             my ($puname,$pudom)=split(/\:/,$person);
10774:             my $clickers =
10775: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10776:             foreach my $id (split(/\,/,$clickers)) {
10777: 		$id=~s/^[\#0]+//;
10778:                 $id=~s/[\-\:]//g;
10779: 		if (exists($clicker_ids{$id})) {
10780: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10781: 		} else {
10782: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10783: 		}
10784:             }
10785:         }
10786:     }
10787:     return %clicker_ids;
10788: }
10789: 
10790: sub clicker_grading_parameters {
10791:     return ('gradingmechanism' => 'scalar',
10792:             'upfiletype' => 'scalar',
10793:             'specificid' => 'scalar',
10794:             'pcorrect' => 'scalar',
10795:             'pincorrect' => 'scalar');
10796: }
10797: 
10798: sub process_clicker {
10799:     my ($r,$symb)=@_;
10800:     if (!$symb) {return '';}
10801:     my $result=&checkforfile_js();
10802:     $result.=&Apache::loncommon::start_data_table().
10803:              &Apache::loncommon::start_data_table_header_row().
10804:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10805:              &Apache::loncommon::end_data_table_header_row().
10806:              &Apache::loncommon::start_data_table_row()."<td>\n";
10807: # Attempt to restore parameters from last session, set defaults if not present
10808:     my %Saveable_Parameters=&clicker_grading_parameters();
10809:     &Apache::loncommon::restore_course_settings('grades_clicker',
10810:                                                  \%Saveable_Parameters);
10811:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10812:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10813:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10814:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10815: 
10816:     my %checked;
10817:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10818:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10819:           $checked{$gradingmechanism}=' checked="checked"';
10820:        }
10821:     }
10822: 
10823:     my $upload=&mt("Evaluate File");
10824:     my $type=&mt("Type");
10825:     my $attendance=&mt("Award points just for participation");
10826:     my $personnel=&mt("Correctness determined from response by course personnel");
10827:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10828:     my $given=&mt("Correctness determined from given list of answers").' '.
10829:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10830:     my $pcorrect=&mt("Percentage points for correct solution");
10831:     my $pincorrect=&mt("Percentage points for incorrect solution");
10832:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10833: 						   {'iclicker' => 'i>clicker',
10834:                                                     'interwrite' => 'interwrite PRS',
10835:                                                     'turning' => 'Turning Technologies'});
10836:     $symb = &Apache::lonenc::check_encrypt($symb);
10837:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10838: function sanitycheck() {
10839: // Accept only integer percentages
10840:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10841:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10842: // Find out grading choice
10843:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10844:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10845:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10846:       }
10847:    }
10848: // By default, new choice equals user selection
10849:    newgradingchoice=gradingchoice;
10850: // Not good to give more points for false answers than correct ones
10851:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10852:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10853:    }
10854: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10855:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10856:       document.forms.gradesupload.pcorrect.value=100;
10857:       document.forms.gradesupload.pincorrect.value=100;
10858:    }
10859: // If the values are different, cannot be attendance only
10860:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10861:        (gradingchoice=='attendance')) {
10862:        newgradingchoice='personnel';
10863:    }
10864: // Change grading choice to new one
10865:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10866:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10867:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10868:       } else {
10869:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10870:       }
10871:    }
10872: // Remember the old state
10873:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10874: }
10875: ENDUPFORM
10876:     $result.= <<ENDUPFORM;
10877: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10878: <input type="hidden" name="symb" value="$symb" />
10879: <input type="hidden" name="command" value="processclickerfile" />
10880: <input type="file" name="upfile" size="50" />
10881: <br /><label>$type: $selectform</label>
10882: ENDUPFORM
10883:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10884:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10885:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10886: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10887: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10888: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10889: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10890: <br />&nbsp;&nbsp;&nbsp;
10891: <input type="text" name="givenanswer" size="50" />
10892: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10893: ENDGRADINGFORM
10894:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10895:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10896:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10897: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10898: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10899: </form>
10900: ENDPERCFORM
10901:     $result.='</td>'.
10902:              &Apache::loncommon::end_data_table_row().
10903:              &Apache::loncommon::end_data_table();
10904:     return $result;
10905: }
10906: 
10907: sub process_clicker_file {
10908:     my ($r,$symb) = @_;
10909:     if (!$symb) {return '';}
10910: 
10911:     my %Saveable_Parameters=&clicker_grading_parameters();
10912:     &Apache::loncommon::store_course_settings('grades_clicker',
10913:                                               \%Saveable_Parameters);
10914:     my $result='';
10915:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10916: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10917: 	return $result;
10918:     }
10919:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10920:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10921:         return $result;
10922:     }
10923:     my $foundgiven=0;
10924:     if ($env{'form.gradingmechanism'} eq 'given') {
10925:         $env{'form.givenanswer'}=~s/^\s*//gs;
10926:         $env{'form.givenanswer'}=~s/\s*$//gs;
10927:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10928:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10929:         my @answers=split(/\,/,$env{'form.givenanswer'});
10930:         $foundgiven=$#answers+1;
10931:     }
10932:     my %clicker_ids=&gather_clicker_ids();
10933:     my %correct_ids;
10934:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10935: 	%correct_ids=&gather_adv_clicker_ids();
10936:     }
10937:     if ($env{'form.gradingmechanism'} eq 'specific') {
10938: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10939: 	   $correct_id=~tr/a-z/A-Z/;
10940: 	   $correct_id=~s/\s//gs;
10941: 	   $correct_id=~s/^[\#0]+//;
10942:            $correct_id=~s/[\-\:]//g;
10943:            if ($correct_id) {
10944: 	      $correct_ids{$correct_id}='specified';
10945:            }
10946:         }
10947:     }
10948:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10949: 	$result.=&mt('Score based on attendance only');
10950:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10951:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10952:     } else {
10953: 	my $number=0;
10954: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10955: 	foreach my $id (sort(keys(%correct_ids))) {
10956: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10957: 	    if ($correct_ids{$id} eq 'specified') {
10958: 		$result.=&mt('specified');
10959: 	    } else {
10960: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10961: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10962: 	    }
10963: 	    $number++;
10964: 	}
10965:         $result.="</p>\n";
10966:         if ($number==0) {
10967:             $result .=
10968:                  &Apache::lonhtmlcommon::confirm_success(
10969:                      &mt('No IDs found to determine correct answer'),1);
10970:             return $result;
10971:         }
10972:     }
10973:     if (length($env{'form.upfile'}) < 2) {
10974:         $result .=
10975:             &Apache::lonhtmlcommon::confirm_success(
10976:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10977:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10978:         return $result;
10979:     }
10980:     my $mimetype;
10981:     if ($env{'form.upfiletype'} eq 'iclicker') {
10982:         my $mm = new File::MMagic;
10983:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10984:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10985:             $result.= '<p>'.
10986:                 &Apache::lonhtmlcommon::confirm_success(
10987:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10988:             return $result;
10989:         }
10990:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10991:         $result .= '<p>'.
10992:             &Apache::lonhtmlcommon::confirm_success(
10993:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10994:         return $result;
10995:     }
10996: 
10997: # Were able to get all the info needed, now analyze the file
10998: 
10999:     $result.=&Apache::loncommon::studentbrowser_javascript();
11000:     $symb = &Apache::lonenc::check_encrypt($symb);
11001:     $result.=&Apache::loncommon::start_data_table().
11002:              &Apache::loncommon::start_data_table_header_row().
11003:              '<th>'.&mt('Evaluate clicker file').'</th>'.
11004:              &Apache::loncommon::end_data_table_header_row().
11005:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
11006: <td>
11007: <form method="post" action="/adm/grades" name="clickeranalysis">
11008: <input type="hidden" name="symb" value="$symb" />
11009: <input type="hidden" name="command" value="assignclickergrades" />
11010: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
11011: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
11012: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
11013: ENDHEADER
11014:     if ($env{'form.gradingmechanism'} eq 'given') {
11015:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
11016:     } 
11017:     my %responses;
11018:     my @questiontitles;
11019:     my $errormsg='';
11020:     my $number=0;
11021:     if ($env{'form.upfiletype'} eq 'iclicker') {
11022:         if ($mimetype eq 'text/plain') {
11023:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
11024:         } elsif ($mimetype eq 'text/html') {
11025:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
11026:         }
11027:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
11028:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
11029:     } elsif ($env{'form.upfiletype'} eq 'turning') {
11030:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
11031:     }
11032:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
11033:              '<input type="hidden" name="number" value="'.$number.'" />'.
11034:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
11035:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
11036:              '<br />';
11037:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
11038:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
11039:        return $result;
11040:     } 
11041: # Remember Question Titles
11042: # FIXME: Possibly need delimiter other than ":"
11043:     for (my $i=0;$i<$number;$i++) {
11044:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
11045:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
11046:     }
11047:     my $correct_count=0;
11048:     my $student_count=0;
11049:     my $unknown_count=0;
11050: # Match answers with usernames
11051: # FIXME: Possibly need delimiter other than ":"
11052:     foreach my $id (keys(%responses)) {
11053:        if ($correct_ids{$id}) {
11054:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
11055:           $correct_count++;
11056:        } elsif ($clicker_ids{$id}) {
11057:           if ($clicker_ids{$id}=~/\,/) {
11058: # More than one user with the same clicker!
11059:              $result.="</td>".&Apache::loncommon::end_data_table_row().
11060:                            &Apache::loncommon::start_data_table_row()."<td>".
11061:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
11062:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11063:                            "<select name='multi".$id."'>";
11064:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
11065:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
11066:              }
11067:              $result.='</select>';
11068:              $unknown_count++;
11069:           } else {
11070: # Good: found one and only one user with the right clicker
11071:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
11072:              $student_count++;
11073:           }
11074:        } else {
11075:           $result.="</td>".&Apache::loncommon::end_data_table_row().
11076:                            &Apache::loncommon::start_data_table_row()."<td>".
11077:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
11078:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
11079:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
11080:                    "\n".&mt("Domain").": ".
11081:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
11082:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
11083:           $unknown_count++;
11084:        }
11085:     }
11086:     $result.='<hr />'.
11087:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
11088:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
11089:        if ($correct_count==0) {
11090:           $errormsg.="Found no correct answers for grading!";
11091:        } elsif ($correct_count>1) {
11092:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
11093:        }
11094:     }
11095:     if ($number<1) {
11096:        $errormsg.="Found no questions.";
11097:     }
11098:     if ($errormsg) {
11099:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
11100:     } else {
11101:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
11102:     }
11103:     $result.='</form></td>'.
11104:              &Apache::loncommon::end_data_table_row().
11105:              &Apache::loncommon::end_data_table();
11106:     return $result;
11107: }
11108: 
11109: sub iclicker_eval {
11110:     my ($questiontitles,$responses)=@_;
11111:     my $number=0;
11112:     my $errormsg='';
11113:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11114:         my %components=&Apache::loncommon::record_sep($line);
11115:         my @entries=map {$components{$_}} (sort(keys(%components)));
11116: 	if ($entries[0] eq 'Question') {
11117: 	    for (my $i=3;$i<$#entries;$i+=6) {
11118: 		$$questiontitles[$number]=$entries[$i];
11119: 		$number++;
11120: 	    }
11121: 	}
11122: 	if ($entries[0]=~/^\#/) {
11123: 	    my $id=$entries[0];
11124: 	    my @idresponses;
11125: 	    $id=~s/^[\#0]+//;
11126: 	    for (my $i=0;$i<$number;$i++) {
11127: 		my $idx=3+$i*6;
11128:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11129: 		push(@idresponses,$entries[$idx]);
11130: 	    }
11131: 	    $$responses{$id}=join(',',@idresponses);
11132: 	}
11133:     }
11134:     return ($errormsg,$number);
11135: }
11136: 
11137: sub iclickerxml_eval {
11138:     my ($questiontitles,$responses)=@_;
11139:     my $number=0;
11140:     my $errormsg='';
11141:     my @state;
11142:     my %respbyid;
11143:     my $p = HTML::Parser->new
11144:     (
11145:         xml_mode => 1,
11146:         start_h =>
11147:             [sub {
11148:                  my ($tagname,$attr) = @_;
11149:                  push(@state,$tagname);
11150:                  if ("@state" eq "ssn p") {
11151:                      my $title = $attr->{qn};
11152:                      $title =~ s/(^\s+|\s+$)//g;
11153:                      $questiontitles->[$number]=$title;
11154:                  } elsif ("@state" eq "ssn p v") {
11155:                      my $id = $attr->{id};
11156:                      my $entry = $attr->{ans};
11157:                      $id=~s/^[\#0]+//;
11158:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
11159:                      $respbyid{$id}[$number] = $entry;
11160:                  }
11161:             }, "tagname, attr"],
11162:          end_h =>
11163:                [sub {
11164:                    my ($tagname) = @_;
11165:                    if ("@state" eq "ssn p") {
11166:                        $number++;
11167:                    }
11168:                    pop(@state);
11169:                 }, "tagname"],
11170:     );
11171: 
11172:     $p->parse($env{'form.upfile'});
11173:     $p->eof;
11174:     foreach my $id (keys(%respbyid)) {
11175:         $responses->{$id}=join(',',@{$respbyid{$id}});
11176:     }
11177:     return ($errormsg,$number);
11178: }
11179: 
11180: sub interwrite_eval {
11181:     my ($questiontitles,$responses)=@_;
11182:     my $number=0;
11183:     my $errormsg='';
11184:     my $skipline=1;
11185:     my $questionnumber=0;
11186:     my %idresponses=();
11187:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11188:         my %components=&Apache::loncommon::record_sep($line);
11189:         my @entries=map {$components{$_}} (sort(keys(%components)));
11190:         if ($entries[1] eq 'Time') { $skipline=0; next; }
11191:         if ($entries[1] eq 'Response') { $skipline=1; }
11192:         next if $skipline;
11193:         if ($entries[0]!=$questionnumber) {
11194:            $questionnumber=$entries[0];
11195:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
11196:            $number++;
11197:         }
11198:         my $id=$entries[4];
11199:         $id=~s/^[\#0]+//;
11200:         $id=~s/^v\d*\://i;
11201:         $id=~s/[\-\:]//g;
11202:         $idresponses{$id}[$number]=$entries[6];
11203:     }
11204:     foreach my $id (keys(%idresponses)) {
11205:        $$responses{$id}=join(',',@{$idresponses{$id}});
11206:        $$responses{$id}=~s/^\s*\,//;
11207:     }
11208:     return ($errormsg,$number);
11209: }
11210: 
11211: sub turning_eval {
11212:     my ($questiontitles,$responses)=@_;
11213:     my $number=0;
11214:     my $errormsg='';
11215:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
11216:         my %components=&Apache::loncommon::record_sep($line);
11217:         my @entries=map {$components{$_}} (sort(keys(%components)));
11218:         if ($#entries>$number) { $number=$#entries; }
11219:         my $id=$entries[0];
11220:         my @idresponses;
11221:         $id=~s/^[\#0]+//;
11222:         unless ($id) { next; }
11223:         for (my $idx=1;$idx<=$#entries;$idx++) {
11224:             $entries[$idx]=~s/\,/\;/g;
11225:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
11226:             push(@idresponses,$entries[$idx]);
11227:         }
11228:         $$responses{$id}=join(',',@idresponses);
11229:     }
11230:     for (my $i=1; $i<=$number; $i++) {
11231:         $$questiontitles[$i]=&mt('Question [_1]',$i);
11232:     }
11233:     return ($errormsg,$number);
11234: }
11235: 
11236: 
11237: sub assign_clicker_grades {
11238:     my ($r,$symb) = @_;
11239:     if (!$symb) {return '';}
11240: # See which part we are saving to
11241:     my $res_error;
11242:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
11243:     if ($res_error) {
11244:         return &navmap_errormsg();
11245:     }
11246: # FIXME: This should probably look for the first handgradeable part
11247:     my $part=$$partlist[0];
11248: # Start screen output
11249:     my $result = &Apache::loncommon::start_data_table().
11250:                  &Apache::loncommon::start_data_table_header_row().
11251:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
11252:                  &Apache::loncommon::end_data_table_header_row().
11253:                  &Apache::loncommon::start_data_table_row().'<td>';
11254: # Get correct result
11255: # FIXME: Possibly need delimiter other than ":"
11256:     my @correct=();
11257:     my $gradingmechanism=$env{'form.gradingmechanism'};
11258:     my $number=$env{'form.number'};
11259:     if ($gradingmechanism ne 'attendance') {
11260:        foreach my $key (keys(%env)) {
11261:           if ($key=~/^form\.correct\:/) {
11262:              my @input=split(/\,/,$env{$key});
11263:              for (my $i=0;$i<=$#input;$i++) {
11264:                  if (($correct[$i]) && ($input[$i]) &&
11265:                      ($correct[$i] ne $input[$i])) {
11266:                     $result.='<br /><span class="LC_warning">'.
11267:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
11268:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
11269:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
11270:                     $correct[$i]=$input[$i];
11271:                  }
11272:              }
11273:           }
11274:        }
11275:        for (my $i=0;$i<$number;$i++) {
11276:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
11277:              $result.='<br /><span class="LC_error">'.
11278:                       &mt('No correct result given for question "[_1]"!',
11279:                           $env{'form.question:'.$i}).'</span>';
11280:           }
11281:        }
11282:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
11283:     }
11284: # Start grading
11285:     my $pcorrect=$env{'form.pcorrect'};
11286:     my $pincorrect=$env{'form.pincorrect'};
11287:     my $storecount=0;
11288:     my %users=();
11289:     foreach my $key (keys(%env)) {
11290:        my $user='';
11291:        if ($key=~/^form\.student\:(.*)$/) {
11292:           $user=$1;
11293:        }
11294:        if ($key=~/^form\.unknown\:(.*)$/) {
11295:           my $id=$1;
11296:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
11297:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
11298:           } elsif ($env{'form.multi'.$id}) {
11299:              $user=$env{'form.multi'.$id};
11300:           }
11301:        }
11302:        if ($user) {
11303:           if ($users{$user}) {
11304:              $result.='<br /><span class="LC_warning">'.
11305:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
11306:                       '</span><br />';
11307:           }
11308:           $users{$user}=1; 
11309:           my @answer=split(/\,/,$env{$key});
11310:           my $sum=0;
11311:           my $realnumber=$number;
11312:           for (my $i=0;$i<$number;$i++) {
11313:              if  ($correct[$i] eq '-') {
11314:                 $realnumber--;
11315:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
11316:                 if ($gradingmechanism eq 'attendance') {
11317:                    $sum+=$pcorrect;
11318:                 } elsif ($correct[$i] eq '*') {
11319:                    $sum+=$pcorrect;
11320:                 } else {
11321: # We actually grade if correct or not
11322:                    my $increment=$pincorrect;
11323: # Special case: numerical answer "0"
11324:                    if ($correct[$i] eq '0') {
11325:                       if ($answer[$i]=~/^[0\.]+$/) {
11326:                          $increment=$pcorrect;
11327:                       }
11328: # General numerical answer, both evaluate to something non-zero
11329:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
11330:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
11331:                          $increment=$pcorrect;
11332:                       }
11333: # Must be just alphanumeric
11334:                    } elsif ($answer[$i] eq $correct[$i]) {
11335:                       $increment=$pcorrect;
11336:                    }
11337:                    $sum+=$increment;
11338:                 }
11339:              }
11340:           }
11341:           my $ave=$sum/(100*$realnumber);
11342: # Store
11343:           my ($username,$domain)=split(/\:/,$user);
11344:           my %grades=();
11345:           $grades{"resource.$part.solved"}='correct_by_override';
11346:           $grades{"resource.$part.awarded"}=$ave;
11347:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
11348:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
11349:                                                  $env{'request.course.id'},
11350:                                                  $domain,$username);
11351:           if ($returncode ne 'ok') {
11352:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
11353:           } else {
11354:              $storecount++;
11355:           }
11356:        }
11357:     }
11358: # We are done
11359:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
11360:              '</td>'.
11361:              &Apache::loncommon::end_data_table_row().
11362:              &Apache::loncommon::end_data_table();
11363:     return $result;
11364: }
11365: 
11366: sub navmap_errormsg {
11367:     return '<div class="LC_error">'.
11368:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11369:            &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>').
11370:            '</div>';
11371: }
11372: 
11373: sub startpage {
11374:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11375:     my %args;
11376:     if ($onload) {
11377:          my %loaditems = (
11378:                         'onload' => $onload,
11379:                       );
11380:          $args{'add_entries'} = \%loaditems;
11381:     }
11382:     if ($nomenu) {
11383:         $args{'only_body'} = 1; 
11384:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11385:     } else {
11386:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11387:         $args{'bread_crumbs'} = $crumbs;
11388:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11389:         if ($env{'request.course.id'}) {
11390:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
11391:         }
11392:     }
11393:     unless ($nodisplayflag) {
11394:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11395:     }
11396: }
11397: 
11398: sub select_problem {
11399:     my ($r)=@_;
11400:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11401:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
11402:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11403:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11404: }
11405: 
11406: sub handler {
11407:     my $request=$_[0];
11408:     &reset_caches();
11409:     if ($request->header_only) {
11410:         &Apache::loncommon::content_type($request,'text/html');
11411:         $request->send_http_header;
11412:         return OK;
11413:     }
11414:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11415: 
11416: # see what command we need to execute
11417: 
11418:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11419:     my $command=$commands[0];
11420: 
11421:     &init_perm();
11422:     if (!$env{'request.course.id'}) {
11423:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11424:                 ($command =~ /^scantronupload/)) {
11425:             # Not in a course.
11426:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11427:             return HTTP_NOT_ACCEPTABLE;
11428:         }
11429:     } elsif (!%perm) {
11430:         $request->internal_redirect('/adm/quickgrades');
11431:         return OK;
11432:     }
11433:     &Apache::loncommon::content_type($request,'text/html');
11434:     $request->send_http_header;
11435: 
11436:     if ($#commands > 0) {
11437: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11438:     }
11439: 
11440: # see what the symb is
11441: 
11442:     my $symb=$env{'form.symb'};
11443:     unless ($symb) {
11444:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11445:        $symb=&Apache::lonnet::symbread($url);
11446:     }
11447:     &Apache::lonenc::check_decrypt(\$symb);
11448: 
11449:     $ssi_error = 0;
11450:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11451: #
11452: # Not called from a resource, but inside a course
11453: #    
11454:         &startpage($request,undef,[],1,1);
11455:         &select_problem($request);
11456:     } else {
11457: 	if ($command eq 'submission' && $perm{'vgr'}) {
11458:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11459:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11460:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11461:                     &choose_task_version_form($symb,$env{'form.student'},
11462:                                               $env{'form.userdom'});
11463:             }
11464:             my $divforres;
11465:             if ($env{'form.student'} eq '') {
11466:                 $js .= &part_selector_js();
11467:                 $onload = "toggleParts('gradesub');";
11468:             } else {
11469:                 $divforres = 1;
11470:             }
11471:             my $head_extra = $js;
11472:             unless ($env{'form.vProb'} eq 'no') {
11473:                 my $csslinks = &Apache::loncommon::css_links($symb);
11474:                 if ($csslinks) {
11475:                     $head_extra .= "\n$csslinks";
11476:                 }
11477:             }
11478:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11479:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11480:             if ($versionform) {
11481:                 if ($divforres) {
11482:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11483:                 }
11484:                 $request->print($versionform);
11485:             }
11486: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11487:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11488:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11489:                 &choose_task_version_form($symb,$env{'form.student'},
11490:                                           $env{'form.userdom'},
11491:                                           $env{'form.inhibitmenu'});
11492:             my $head_extra = $js;
11493:             unless ($env{'form.vProb'} eq 'no') {
11494:                 my $csslinks = &Apache::loncommon::css_links($symb);
11495:                 if ($csslinks) {
11496:                     $head_extra .= "\n$csslinks";
11497:                 }
11498:             }
11499:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11500:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11501:             if ($versionform) {
11502:                 $request->print($versionform);
11503:             }
11504:             $request->print('<br clear="all" />');
11505:             $request->print(&show_previous_task_version($request,$symb));
11506: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11507:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11508:                                        {href=>'',text=>'Select student'}],1,1);
11509: 	    &pickStudentPage($request,$symb);
11510: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11511:             my $csslinks;
11512:             unless ($env{'form.vProb'} eq 'no') {
11513:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11514:             }
11515:             &startpage($request,$symb,
11516:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11517:                                        {href=>'',text=>'Select student'},
11518:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11519: 	    &displayPage($request,$symb);
11520: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11521:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11522:                                        {href=>'',text=>'Select student'},
11523:                                        {href=>'',text=>'Grade student'},
11524:                                        {href=>'',text=>'Store grades'}],1,1);
11525: 	    &updateGradeByPage($request,$symb);
11526: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11527:             my $csslinks;
11528:             unless ($env{'form.vProb'} eq 'no') {
11529:                 $csslinks = &Apache::loncommon::css_links($symb);
11530:             }
11531:             &startpage($request,$symb,[{href=>'',text=>'...'},
11532:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11533: 	    &processGroup($request,$symb);
11534: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11535:             &startpage($request,$symb);
11536: 	    $request->print(&grading_menu($request,$symb));
11537: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
11538:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11539: 	    $request->print(&submit_options($request,$symb));
11540:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11541:             my $js = &part_selector_js();
11542:             my $onload = "toggleParts('gradesub');";
11543:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11544:                        undef,undef,undef,undef,undef,$js,$onload);
11545:             $request->print(&listStudents($request,$symb,'graded'));
11546:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11547:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11548:             $request->print(&submit_options_table($request,$symb));
11549:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11550:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11551:             $request->print(&submit_options_sequence($request,$symb));
11552: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11553:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11554: 	    $request->print(&viewgrades($request,$symb));
11555: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11556:             &startpage($request,$symb,[{href=>'',text=>'...'},
11557:                                        {href=>'',text=>'Store grades'}]);
11558: 	    $request->print(&processHandGrade($request,$symb));
11559: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11560:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11561:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11562:                                                                              text=>"Modify grades"},
11563:                                        {href=>'', text=>"Store grades"}]);
11564: 	    $request->print(&editgrades($request,$symb));
11565:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11566:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11567:             $request->print(&initialverifyreceipt($request,$symb));
11568: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
11569:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11570:                                        {href=>'',text=>'Verification Result'}]);
11571: 	    $request->print(&verifyreceipt($request,$symb));
11572:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11573:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11574:             $request->print(&process_clicker($request,$symb));
11575:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11576:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11577:                                        {href=>'', text=>'Process clicker file'}]);
11578:             $request->print(&process_clicker_file($request,$symb));
11579:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11580:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11581:                                        {href=>'', text=>'Process clicker file'},
11582:                                        {href=>'', text=>'Store grades'}]);
11583:             $request->print(&assign_clicker_grades($request,$symb));
11584: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
11585:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11586: 	    $request->print(&upcsvScores_form($request,$symb));
11587: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11588:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11589: 	    $request->print(&csvupload($request,$symb));
11590: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11591:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11592: 	    $request->print(&csvuploadmap($request,$symb));
11593: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11594: 	    if ($env{'form.associate'} ne 'Reverse Association') {
11595:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11596: 		$request->print(&csvuploadoptions($request,$symb));
11597: 	    } else {
11598: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11599: 		    $env{'form.upfile_associate'} = 'reverse';
11600: 		} else {
11601: 		    $env{'form.upfile_associate'} = 'forward';
11602: 		}
11603:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11604: 		$request->print(&csvuploadmap($request,$symb));
11605: 	    }
11606: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11607:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11608: 	    $request->print(&csvuploadassign($request,$symb));
11609: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11610:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11611:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11612: 	    $request->print(&scantron_selectphase($request,undef,$symb));
11613:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11614:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11615:  	    $request->print(&scantron_do_warning($request,$symb));
11616: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11617:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11618: 	    $request->print(&scantron_validate_file($request,$symb));
11619: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11620:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11621: 	    $request->print(&scantron_process_students($request,$symb));
11622:  	} elsif ($command eq 'scantronupload' && 
11623:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11624:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11625:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11626:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
11627:  	} elsif ($command eq 'scantronupload_save' &&
11628:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11629:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11630:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
11631:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
11632:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11633:  	    $request->print(&scantron_download_scantron_data($request,$symb));
11634:         } elsif ($command eq 'scantronupload_delete' &&
11635:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
11636:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11637:             &scantron_upload_delete($request,$symb);
11638:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11639:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11640:             $request->print(&checkscantron_results($request,$symb));
11641:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11642:             my $js = &part_selector_js();
11643:             my $onload = "toggleParts('gradingMenu');";
11644:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11645:                        undef,undef,undef,undef,undef,$js,$onload);
11646:             $request->print(&submit_options_download($request,$symb));
11647:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11648:             &startpage($request,$symb,
11649:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11650:     {href=>'', text=>'Download submitted files'}],
11651:                undef,undef,undef,undef,undef,undef,undef,1);
11652:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11653:             &submit_download_link($request,$symb);
11654: 	} elsif ($command) {
11655:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11656: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11657: 	}
11658:     }
11659:     if ($ssi_error) {
11660: 	&ssi_print_error($request);
11661:     }
11662:     if ($env{'form.inhibitmenu'}) {
11663:         $request->print(&Apache::loncommon::end_page());
11664:     } elsif ($env{'request.course.id'}) {
11665:         &Apache::lonquickgrades::endGradeScreen($request);
11666:     }
11667:     &reset_caches();
11668:     return OK;
11669: }
11670: 
11671: 1;
11672: 
11673: __END__;
11674: 
11675: 
11676: =head1 NAME
11677: 
11678: Apache::grades
11679: 
11680: =head1 SYNOPSIS
11681: 
11682: Handles the viewing of grades.
11683: 
11684: This is part of the LearningOnline Network with CAPA project
11685: described at http://www.lon-capa.org.
11686: 
11687: =head1 OVERVIEW
11688: 
11689: Do an ssi with retries:
11690: While I'd love to factor out this with the version in lonprintout,
11691: 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
11692: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11693: 
11694: At least the logic that drives this has been pulled out into loncommon.
11695: 
11696: 
11697: 
11698: ssi_with_retries - Does the server side include of a resource.
11699:                      if the ssi call returns an error we'll retry it up to
11700:                      the number of times requested by the caller.
11701:                      If we still have a problem, no text is appended to the
11702:                      output and we set some global variables.
11703:                      to indicate to the caller an SSI error occurred.  
11704:                      All of this is supposed to deal with the issues described
11705:                      in LON-CAPA BZ 5631 see:
11706:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11707:                      by informing the user that this happened.
11708: 
11709: Parameters:
11710:   resource   - The resource to include.  This is passed directly, without
11711:                interpretation to lonnet::ssi.
11712:   form       - The form hash parameters that guide the interpretation of the resource
11713:                
11714:   retries    - Number of retries allowed before giving up completely.
11715: Returns:
11716:   On success, returns the rendered resource identified by the resource parameter.
11717: Side Effects:
11718:   The following global variables can be set:
11719:    ssi_error                - If an unrecoverable error occurred this becomes true.
11720:                               It is up to the caller to initialize this to false
11721:                               if desired.
11722:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11723:                               of the resource that could not be rendered by the ssi
11724:                               call.
11725:    ssi_error_message   - The error string fetched from the ssi response
11726:                               in the event of an error.
11727: 
11728: 
11729: =head1 HANDLER SUBROUTINE
11730: 
11731: ssi_with_retries()
11732: 
11733: =head1 SUBROUTINES
11734: 
11735: =over
11736: 
11737: =head1 Routines to display previous version of a Task for a specific student
11738: 
11739: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11740: can receive another opportunity. Access to tasks is slot-based. If a slot
11741: requires a proctor to check-in the student, a new version of the Task will
11742: be created when the student is checked in to the new opportunity.
11743: 
11744: If a particular student has tried two or more versions of a particular task,
11745: the submission screen provides a user with vgr privileges (e.g., a Course
11746: Coordinator) the ability to display a previous version worked on by the
11747: student.  By default, the current version is displayed. If a previous version
11748: has been selected for display, submission data are only shown that pertain
11749: to that particular version, and the interface to submit grades is not shown.
11750: 
11751: =over 4
11752: 
11753: =item show_previous_task_version()
11754: 
11755: Displays a specified version of a student's Task, as the student sees it.
11756: 
11757: Inputs: 2
11758:         request - request object
11759:         symb    - unique symb for current instance of resource
11760: 
11761: Output: None.
11762: 
11763: Side Effects: calls &show_problem() to print version of Task, with
11764:               version contained in form item: $env{'form.previousversion'}
11765: 
11766: =item choose_task_version_form()
11767: 
11768: Displays a web form used to select which version of a student's view of a
11769: Task should be displayed.  Either launches a pop-up window, or replaces
11770: content in existing pop-up, or replaces page in main window.
11771: 
11772: Inputs: 4
11773:         symb    - unique symb for current instance of resource
11774:         uname   - username of student
11775:         udom    - domain of student
11776:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11777:                   breadcrumbs etc., are displayed
11778: 
11779: Output: 4
11780:         current   - student's current version
11781:         displayed - student's version being displayed
11782:         result    - scalar containing HTML for web form used to switch to
11783:                     a different version (or a link to close window, if pop-up).
11784:         js        - javascript for processing selection in versions web form
11785: 
11786: Side Effects: None.
11787: 
11788: =item previous_display_javascript()
11789: 
11790: Inputs: 2
11791:         nomenu  - 1 if display is in a pop-up window, and hence no menu
11792:                   breadcrumbs etc., are displayed.
11793:         current - student's current version number.
11794: 
11795: Output: 1
11796:         js      - javascript for processing selection in versions web form.
11797: 
11798: Side Effects: None.
11799: 
11800: =back
11801: 
11802: =head1 Routines to process bubblesheet data.
11803: 
11804: =over 4
11805: 
11806: =item scantron_get_correction() : 
11807: 
11808:    Builds the interface screen to interact with the operator to fix a
11809:    specific error condition in a specific scanline
11810: 
11811:  Arguments:
11812:     $r           - Apache request object
11813:     $i           - number of the current scanline
11814:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11815:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11816:     $line        - full contents of the current scanline
11817:     $error       - error condition, valid values are
11818:                    'incorrectCODE', 'duplicateCODE',
11819:                    'doublebubble', 'missingbubble',
11820:                    'duplicateID', 'incorrectID'
11821:     $arg         - extra information needed
11822:        For errors:
11823:          - duplicateID   - paper number that this studentID was seen before on
11824:          - duplicateCODE - array ref of the paper numbers this CODE was
11825:                            seen on before
11826:          - incorrectCODE - current incorrect CODE 
11827:          - doublebubble  - array ref of the bubble lines that have double
11828:                            bubble errors
11829:          - missingbubble - array ref of the bubble lines that have missing
11830:                            bubble errors
11831: 
11832:    $randomorder - True if exam folder has randomorder set
11833:    $randompick  - True if exam folder has randompick set
11834:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11835:                      for current line to question number used for same question
11836:                      in "Master Seqence" (as seen by Course Coordinator).
11837:    $startline   - Reference to hash where key is question number (0 is first)
11838:                   and value is number of first bubble line for current student
11839:                   or code-based randompick and/or randomorder.
11840: 
11841: 
11842: 
11843: =item  scantron_get_maxbubble() : 
11844: 
11845:    Arguments:
11846:        $nav_error  - Reference to scalar which is a flag to indicate a
11847:                       failure to retrieve a navmap object.
11848:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11849:        calling routine should trap the error condition and display the warning
11850:        found in &navmap_errormsg().
11851: 
11852:        $scantron_config - Reference to bubblesheet format configuration hash.
11853: 
11854:    Returns the maximum number of bubble lines that are expected to
11855:    occur. Does this by walking the selected sequence rendering the
11856:    resource and then checking &Apache::lonxml::get_problem_counter()
11857:    for what the current value of the problem counter is.
11858: 
11859:    Caches the results to $env{'form.scantron_maxbubble'},
11860:    $env{'form.scantron.bubble_lines.n'}, 
11861:    $env{'form.scantron.first_bubble_line.n'} and
11862:    $env{"form.scantron.sub_bubblelines.n"}
11863:    which are the total number of bubble lines, the number of bubble
11864:    lines for response n and number of the first bubble line for response n,
11865:    and a comma separated list of numbers of bubble lines for sub-questions
11866:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11867: 
11868: 
11869: =item  scantron_validate_missingbubbles() : 
11870: 
11871:    Validates all scanlines in the selected file to not have any
11872:     answers that don't have bubbles that have not been verified
11873:     to be bubble free.
11874: 
11875: =item  scantron_process_students() : 
11876: 
11877:    Routine that does the actual grading of the bubblesheet information.
11878: 
11879:    The parsed scanline hash is added to %env 
11880: 
11881:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11882:    foreach resource , with the form data of
11883: 
11884: 	'submitted'     =>'scantron' 
11885: 	'grade_target'  =>'grade',
11886: 	'grade_username'=> username of student
11887: 	'grade_domain'  => domain of student
11888: 	'grade_courseid'=> of course
11889: 	'grade_symb'    => symb of resource to grade
11890: 
11891:     This triggers a grading pass. The problem grading code takes care
11892:     of converting the bubbled letter information (now in %env) into a
11893:     valid submission.
11894: 
11895: =item  scantron_upload_scantron_data() :
11896: 
11897:     Creates the screen for adding a new bubblesheet data file to a course.
11898: 
11899: =item  scantron_upload_scantron_data_save() : 
11900: 
11901:    Adds a provided bubble information data file to the course if user
11902:    has the correct privileges to do so.
11903: 
11904: = item scantron_upload_delete() :
11905: 
11906:    Deletes a previously uploaded bubble information data file, if user
11907:    was the one who uploaded the file, and has the privileges to do so.
11908: 
11909: =item  valid_file() :
11910: 
11911:    Validates that the requested bubble data file exists in the course.
11912: 
11913: =item  scantron_download_scantron_data() : 
11914: 
11915:    Shows a list of the three internal files (original, corrected,
11916:    skipped) for a specific bubblesheet data file that exists in the
11917:    course.
11918: 
11919: =item  scantron_validate_ID() : 
11920: 
11921:    Validates all scanlines in the selected file to not have any
11922:    invalid or underspecified student/employee IDs
11923: 
11924: =item navmap_errormsg() :
11925: 
11926:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11927:    Should be called whenever the request to instantiate a navmap object fails.
11928: 
11929: =back
11930: 
11931: =back
11932: 
11933: =cut

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