File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.62: download - view: text, annotated - select for diffs
Wed Jul 3 13:12:44 2024 UTC (11 days, 11 hours ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_5
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  Backport 1.789, 1.790

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.62 2024/07/03 13:12:44 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::bridgetask();
   48: use Apache::lontexconvert();
   49: use HTML::Parser();
   50: use File::MMagic;
   51: use String::Similarity;
   52: use LONCAPA;
   53: 
   54: use POSIX qw(floor);
   55: 
   56: 
   57: 
   58: my %perm=();
   59: my %old_essays=();
   60: 
   61: #  These variables are used to recover from ssi errors
   62: 
   63: my $ssi_retries = 5;
   64: my $ssi_error;
   65: my $ssi_error_resource;
   66: my $ssi_error_message;
   67: 
   68: 
   69: sub ssi_with_retries {
   70:     my ($resource, $retries, %form) = @_;
   71:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   72:     if ($response->is_error) {
   73: 	$ssi_error          = 1;
   74: 	$ssi_error_resource = $resource;
   75: 	$ssi_error_message  = $response->code . " " . $response->message;
   76:     }
   77: 
   78:     return $content;
   79: 
   80: }
   81: #
   82: #  Prodcuces an ssi retry failure error message to the user:
   83: #
   84: 
   85: sub ssi_print_error {
   86:     my ($r) = @_;
   87:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   88:     $r->print('
   89: <br />
   90: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   91: <p>
   92: '.&mt('Unable to retrieve a resource from a server:').'<br />
   93: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   94: '.&mt('Error:').' '.$ssi_error_message.'
   95: </p>
   96: <p>'.
   97: &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 />'.
   98: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   99: '</p>');
  100:     return;
  101: }
  102: 
  103: #
  104: # --- Retrieve the parts from the metadata file.---
  105: # Returns an array of everything that the resources stores away
  106: #
  107: 
  108: sub getpartlist {
  109:     my ($symb,$errorref) = @_;
  110: 
  111:     my $navmap   = Apache::lonnavmaps::navmap->new();
  112:     unless (ref($navmap)) {
  113:         if (ref($errorref)) { 
  114:             $$errorref = 'navmap';
  115:             return;
  116:         }
  117:     }
  118:     my $res      = $navmap->getBySymb($symb);
  119:     my $partlist = $res->parts();
  120:     my $url      = $res->src();
  121:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  122: 
  123:     my @stores;
  124:     foreach my $part (@{ $partlist }) {
  125: 	foreach my $key (@metakeys) {
  126: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  127: 	}
  128:     }
  129:     return @stores;
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: #--- Count responseIDs, essayresponse items, and dropbox items ---
  147: #--- Sets response_error pointer to "1" if navmaps object broken ---
  148: sub response_type {
  149:     my ($symb,$response_error) = @_;
  150: 
  151:     my $navmap = Apache::lonnavmaps::navmap->new();
  152:     unless (ref($navmap)) {
  153:         if (ref($response_error)) {
  154:             $$response_error = 1;
  155:         }
  156:         return;
  157:     }
  158:     my $res = $navmap->getBySymb($symb);
  159:     unless (ref($res)) {
  160:         $$response_error = 1;
  161:         return;
  162:     }
  163:     my $partlist = $res->parts();
  164:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
  165:     my %vPart = 
  166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  167:     my (%response_types,%handgrade);
  168:     foreach my $part (@{ $partlist }) {
  169: 	next if (%vPart && !exists($vPart{$part}));
  170: 
  171: 	my @types = $res->responseType($part);
  172: 	my @ids = $res->responseIds($part);
  173: 	for (my $i=0; $i < scalar(@ids); $i++) {
  174:             $numresp ++;
  175: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  176:             if ($types[$i] eq 'essay') {
  177:                 $numessay ++;
  178:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
  179:                     $numdropbox ++;
  180:                 }
  181:             }
  182: 	    $handgrade{$part.'_'.$ids[$i]} = 
  183: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  184: 				     '.handgrade',$symb);
  185: 	}
  186:     }
  187:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
  188: }
  189: 
  190: sub flatten_responseType {
  191:     my ($responseType) = @_;
  192:     my @part_response_id =
  193: 	map { 
  194: 	    my $part = $_;
  195: 	    map {
  196: 		[$part,$_]
  197: 		} sort(keys(%{ $responseType->{$part} }));
  198: 	} sort(keys(%$responseType));
  199:     return @part_response_id;
  200: }
  201: 
  202: sub get_display_part {
  203:     my ($partID,$symb)=@_;
  204:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  205:     if (defined($display) and $display ne '') {
  206:         $display.= ' (<span class="LC_internal_info">'
  207:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  208:     } else {
  209: 	$display=$partID;
  210:     }
  211:     return $display;
  212: }
  213: 
  214: #--- Show parts and response type
  215: sub showResourceInfo {
  216:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
  217:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
  218:         return '<br clear="all">';
  219:     }
  220:     my $coltitle = &mt('Problem Part Shown');
  221:     if ($checkboxes) {
  222:         $coltitle = &mt('Problem Part');
  223:     } else {
  224:         my $checkedparts = 0;
  225:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
  226:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
  227:                 $checkedparts ++;
  228:             }
  229:         }
  230:         if ($checkedparts == scalar(@{$partlist})) {
  231:             return '<br clear="all">';
  232:         }
  233:         if ($uploads) {
  234:             $coltitle = &mt('Problem Part Selected');
  235:         }
  236:     }
  237:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
  238:     if ($checkboxes) {
  239:         my $legend = &mt('Parts to display');
  240:         if ($uploads) {
  241:             $legend = &mt('Part(s) with dropbox');
  242:         }
  243:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
  244:                    '<span class="LC_nobreak">'.
  245:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
  246:                    &mt('All parts').'</label>'.('&nbsp;'x2).
  247:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
  248:                    &mt('Selected parts').'</label></span>'.
  249:                    '<div id="LC_partselector" style="display:none">';
  250:     }
  251:     $result .= &Apache::loncommon::start_data_table()
  252:               .&Apache::loncommon::start_data_table_header_row();
  253:     if ($checkboxes) {
  254:         $result .= '<th>'.&mt('Display?').'</th>';
  255:     }
  256:     $result .= '<th>'.$coltitle.'</th>'
  257:               .'<th>'.&mt('Res. ID').'</th>'
  258:               .'<th>'.&mt('Type').'</th>'
  259:               .&Apache::loncommon::end_data_table_header_row();
  260:     my %partsseen;
  261:     foreach my $partID (sort(keys(%$responseType))) {
  262:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  263:             my $responsetype = $responseType->{$partID}->{$resID};
  264:             if ($uploads) {
  265:                 next unless ($responsetype eq 'essay');
  266:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
  267:             }
  268:             my $display_part=&get_display_part($partID,$symb);
  269:             if (exists($partsseen{$partID})) {
  270:                 $result.=&Apache::loncommon::continue_data_table_row();
  271:             } else {
  272:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
  273:                 $result.=&Apache::loncommon::start_data_table_row().
  274:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
  275:                 if ($checkboxes) {
  276:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
  277:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
  278:                 } else {
  279:                     $result.=$display_part.'</td>';
  280:                 }
  281:             }
  282:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  283:                     .'<td>'.&mt($responsetype).'</td>'
  284:                     .&Apache::loncommon::end_data_table_row();
  285:         }
  286:     }
  287:     $result.=&Apache::loncommon::end_data_table();
  288:     if ($checkboxes) {
  289:         $result .= '</div></fieldset>';
  290:     }
  291:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
  292:     if (!keys(%partsseen)) {
  293:         $result = '';
  294:         if ($uploads) {
  295:             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
  296:                    '<p class="LC_info">'.
  297:                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
  298:                    '</p>';
  299:         } else {
  300:             return '<br clear="all" />';
  301:         }
  302:     }  
  303:     return $result;
  304: }
  305: 
  306: sub part_selector_js {
  307:     my $js = <<"END";
  308: function toggleParts(formname) {
  309:     if (document.getElementById('LC_partselector')) {
  310:         var index = '';
  311:         if (document.forms.length) {
  312:             for (var i=0; i<document.forms.length; i++) {
  313:                 if (document.forms[i].name == formname) {
  314:                     index = i;
  315:                     break;
  316:                 }
  317:             }
  318:         }
  319:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
  320:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
  321:                 if (document.forms[index].elements['chooseparts'][i].checked) {
  322:                    var val = document.forms[index].elements['chooseparts'][i].value;
  323:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
  324:                         document.getElementById('LC_partselector').style.display = 'block';
  325:                     } else {
  326:                         document.getElementById('LC_partselector').style.display = 'none';
  327:                     }
  328:                 }
  329:             }
  330:         }
  331:     }
  332: }
  333: END
  334:     return &Apache::lonhtmlcommon::scripttag($js);
  335: }
  336: 
  337: sub reset_caches {
  338:     &reset_analyze_cache();
  339:     &reset_perm();
  340:     &reset_old_essays();
  341: }
  342: 
  343: {
  344:     my %analyze_cache;
  345:     my %analyze_cache_formkeys;
  346: 
  347:     sub reset_analyze_cache {
  348: 	undef(%analyze_cache);
  349:         undef(%analyze_cache_formkeys);
  350:     }
  351: 
  352:     sub get_analyze {
  353: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  354: 	my $key = "$symb\0$uname\0$udom";
  355:         if ($type eq 'randomizetry') {
  356:             if ($trial ne '') {
  357:                 $key .= "\0".$trial;
  358:             }
  359:         }
  360: 	if (exists($analyze_cache{$key})) {
  361:             my $getupdate = 0;
  362:             if (ref($add_to_hash) eq 'HASH') {
  363:                 foreach my $item (keys(%{$add_to_hash})) {
  364:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  365:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  366:                             $getupdate = 1;
  367:                             last;
  368:                         }
  369:                     } else {
  370:                         $getupdate = 1;
  371:                     }
  372:                 }
  373:             }
  374:             if (!$getupdate) {
  375:                 return $analyze_cache{$key};
  376:             }
  377:         }
  378: 
  379: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  380: 	$url=&Apache::lonnet::clutter($url);
  381:         my %form = ('grade_target'      => 'analyze',
  382:                     'grade_domain'      => $udom,
  383:                     'grade_symb'        => $symb,
  384:                     'grade_courseid'    =>  $env{'request.course.id'},
  385:                     'grade_username'    => $uname,
  386:                     'grade_noincrement' => $no_increment);
  387:         if ($bubbles_per_row ne '') {
  388:             $form{'bubbles_per_row'} = $bubbles_per_row;
  389:         }
  390:         if ($type eq 'randomizetry') {
  391:             $form{'grade_questiontype'} = $type;
  392:             if ($rndseed ne '') {
  393:                 $form{'grade_rndseed'} = $rndseed;
  394:             }
  395:         }
  396:         if (ref($add_to_hash)) {
  397:             %form = (%form,%{$add_to_hash});
  398:         }
  399: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  400: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  401: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  402:         if (ref($add_to_hash) eq 'HASH') {
  403:             $analyze_cache_formkeys{$key} = $add_to_hash;
  404:         } else {
  405:             $analyze_cache_formkeys{$key} = {};
  406:         }
  407: 	return $analyze_cache{$key} = \%analyze;
  408:     }
  409: 
  410:     sub get_order {
  411: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  412: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  413: 	return $analyze->{"$partid.$respid.shown"};
  414:     }
  415: 
  416:     sub get_radiobutton_correct_foil {
  417: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  418: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  419:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  420:         if (ref($foils) eq 'ARRAY') {
  421: 	    foreach my $foil (@{$foils}) {
  422: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  423: 		    return $foil;
  424: 	        }
  425: 	    }
  426: 	}
  427:     }
  428: 
  429:     sub scantron_partids_tograde {
  430:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  431:         my (%analysis,@parts);
  432:         if (ref($resource)) {
  433:             my $symb = $resource->symb();
  434:             my $add_to_form;
  435:             if ($check_for_randomlist) {
  436:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  437:             }
  438:             if ($scancode) {
  439:                 if (ref($add_to_form) eq 'HASH') {
  440:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  441:                 } else {
  442:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  443:                 }
  444:             }
  445:             my $analyze =
  446:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  447:                              undef,undef,undef,$bubbles_per_row);
  448:             if (ref($analyze) eq 'HASH') {
  449:                 %analysis = %{$analyze};
  450:             }
  451:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  452:                 foreach my $part (@{$analysis{'parts'}}) {
  453:                     my ($id,$respid) = split(/\./,$part);
  454:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  455:                         push(@parts,$part);
  456:                     }
  457:                 }
  458:             }
  459:         }
  460:         return (\%analysis,\@parts);
  461:     }
  462: 
  463: }
  464: 
  465: #--- Clean response type for display
  466: #--- Currently filters option/rank/radiobutton/match/essay/Task
  467: #        response types only.
  468: sub cleanRecord {
  469:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  470: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  471:     my $grayFont = '<span class="LC_internal_info">';
  472:     if ($response =~ /^(option|rank)$/) {
  473: 	my %answer=&Apache::lonnet::str2hash($answer);
  474:         my @answer = %answer;
  475:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  476: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  477: 	my ($toprow,$bottomrow);
  478: 	foreach my $foil (@$order) {
  479: 	    if ($grading{$foil} == 1) {
  480: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  481: 	    } else {
  482: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  483: 	    }
  484: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  485: 	}
  486: 	return '<blockquote><table border="1">'.
  487: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  488: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  489: 	    $bottomrow.'</tr></table></blockquote>';
  490:     } elsif ($response eq 'match') {
  491: 	my %answer=&Apache::lonnet::str2hash($answer);
  492:         my @answer = %answer;
  493:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
  494: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  495: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  496: 	my ($toprow,$middlerow,$bottomrow);
  497: 	foreach my $foil (@$order) {
  498: 	    my $item=shift(@items);
  499: 	    if ($grading{$foil} == 1) {
  500: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  501: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  502: 	    } else {
  503: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  504: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  505: 	    }
  506: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  507: 	}
  508: 	return '<blockquote><table border="1">'.
  509: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  510: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  511: 	    $middlerow.'</tr>'.
  512: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  513: 	    $bottomrow.'</tr></table></blockquote>';
  514:     } elsif ($response eq 'radiobutton') {
  515: 	my %answer=&Apache::lonnet::str2hash($answer);
  516:         my @answer = %answer;
  517:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  518: 	my ($toprow,$bottomrow);
  519: 	my $correct = 
  520: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  521: 	foreach my $foil (@$order) {
  522: 	    if (exists($answer{$foil})) {
  523: 		if ($foil eq $correct) {
  524: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  525: 		} else {
  526: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  527: 		}
  528: 	    } else {
  529: 		$toprow.='<td>'.&mt('false').'</td>';
  530: 	    }
  531: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  532: 	}
  533: 	return '<blockquote><table border="1">'.
  534: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  535: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  536: 	    $bottomrow.'</tr></table></blockquote>';
  537:     } elsif ($response eq 'essay') {
  538: 	if (! exists ($env{'form.'.$symb})) {
  539: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  540: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  541: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  542: 
  543: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  544: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  545: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  546: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  547: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  548: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  549: 	}
  550:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
  551: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  552:     } elsif ( $response eq 'organic') {
  553:         my $result=&mt('Smile representation: [_1]',
  554:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  555: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  556: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  557: 	return $result;
  558:     } elsif ( $response eq 'Task') {
  559: 	if ( $answer eq 'SUBMITTED') {
  560: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  561: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  562: 	    return $result;
  563: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  564: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  565: 			       keys(%{$record}));
  566: 	    return join('<br />',($version,@matches));
  567: 			       
  568: 			       
  569: 	} else {
  570: 	    my $result =
  571: 		'<p>'
  572: 		.&mt('Overall result: [_1]',
  573: 		     $record->{$version."resource.$respid.$partid.status"})
  574: 		.'</p>';
  575: 	    
  576: 	    $result .= '<ul>';
  577: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  578: 			     keys(%{$record}));
  579: 	    foreach my $grade (sort(@grade)) {
  580: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  581: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  582: 				     $dim, $record->{$grade}).
  583: 			  '</li>';
  584: 	    }
  585: 	    $result.='</ul>';
  586: 	    return $result;
  587: 	}
  588:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  589:         # Respect multiple input fields, see Bug #5409 
  590: 	$answer = 
  591: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  592: 							      $answer);
  593: 	return $answer;
  594:     }
  595:     return &HTML::Entities::encode($answer, '"<>&');
  596: }
  597: 
  598: #-- A couple of common js functions
  599: sub commonJSfunctions {
  600:     my $request = shift;
  601:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  602:     function radioSelection(radioButton) {
  603: 	var selection=null;
  604: 	if (radioButton.length > 1) {
  605: 	    for (var i=0; i<radioButton.length; i++) {
  606: 		if (radioButton[i].checked) {
  607: 		    return radioButton[i].value;
  608: 		}
  609: 	    }
  610: 	} else {
  611: 	    if (radioButton.checked) return radioButton.value;
  612: 	}
  613: 	return selection;
  614:     }
  615: 
  616:     function pullDownSelection(selectOne) {
  617: 	var selection="";
  618: 	if (selectOne.length > 1) {
  619: 	    for (var i=0; i<selectOne.length; i++) {
  620: 		if (selectOne[i].selected) {
  621: 		    return selectOne[i].value;
  622: 		}
  623: 	    }
  624: 	} else {
  625:             // only one value it must be the selected one
  626: 	    return selectOne.value;
  627: 	}
  628:     }
  629: COMMONJSFUNCTIONS
  630: }
  631: 
  632: #--- Dumps the class list with usernames,list of sections,
  633: #--- section, ids and fullnames for each user.
  634: sub getclasslist {
  635:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  636:     my @getsec;
  637:     my @getgroup;
  638:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  639:     if (!ref($getsec)) {
  640: 	if ($getsec ne '' && $getsec ne 'all') {
  641: 	    @getsec=($getsec);
  642: 	}
  643:     } else {
  644: 	@getsec=@{$getsec};
  645:     }
  646:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  647:     if (!ref($getgroup)) {
  648: 	if ($getgroup ne '' && $getgroup ne 'all') {
  649: 	    @getgroup=($getgroup);
  650: 	}
  651:     } else {
  652: 	@getgroup=@{$getgroup};
  653:     }
  654:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  655: 
  656:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  657:     # Bail out if we were unable to get the classlist
  658:     return if (! defined($classlist));
  659:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  660:     #
  661:     my %sections;
  662:     my %fullnames;
  663:     my ($cdom,$cnum,$partlist);
  664:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  665:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  666:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  667:         my $res_error;
  668:         ($partlist) = &response_type($symb,\$res_error);
  669:     }
  670:     foreach my $student (keys(%$classlist)) {
  671:         my $end      = 
  672:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  673:         my $start    = 
  674:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  675:         my $id       = 
  676:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  677:         my $section  = 
  678:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  679:         my $fullname = 
  680:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  681:         my $status   = 
  682:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  683:         my $group   = 
  684:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  685: 	# filter students according to status selected
  686: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  687: 	    if (!($stu_status =~ $status)) {
  688: 		delete($classlist->{$student});
  689: 		next;
  690: 	    }
  691: 	}
  692: 	# filter students according to groups selected
  693: 	my @stu_groups = split(/,/,$group);
  694: 	if (@getgroup) {
  695: 	    my $exclude = 1;
  696: 	    foreach my $grp (@getgroup) {
  697: 	        foreach my $stu_group (@stu_groups) {
  698: 	            if ($stu_group eq $grp) {
  699: 	                $exclude = 0;
  700:     	            } 
  701: 	        }
  702:     	        if (($grp eq 'none') && !$group) {
  703:         	    $exclude = 0;
  704:         	}
  705: 	    }
  706: 	    if ($exclude) {
  707: 	        delete($classlist->{$student});
  708: 		next;
  709: 	    }
  710: 	}
  711:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  712:             my $udom =
  713:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  714:             my $uname =
  715:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  716:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  717:                 if ($submitonly eq 'queued') {
  718:                     my %queue_status =
  719:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  720:                                                                 $udom,$uname);
  721:                     if (!defined($queue_status{'gradingqueue'})) {
  722:                         delete($classlist->{$student});
  723:                         next;
  724:                     }
  725:                 } else {
  726:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  727:                     my $submitted = 0;
  728:                     my $graded = 0;
  729:                     my $incorrect = 0;
  730:                     foreach (keys(%status)) {
  731:                         $submitted = 1 if ($status{$_} ne 'nothing');
  732:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  733:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  734: 
  735:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  736:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  737:                             $submitted = 0;
  738:                         }
  739:                     }
  740:                     if (!$submitted && ($submitonly eq 'yes' ||
  741:                                         $submitonly eq 'incorrect' ||
  742:                                         $submitonly eq 'graded')) {
  743:                         delete($classlist->{$student});
  744:                         next;
  745:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  746:                         delete($classlist->{$student});
  747:                         next;
  748:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  749:                         delete($classlist->{$student});
  750:                         next;
  751:                     }
  752:                 }
  753:             }
  754:         }
  755: 	$section = ($section ne '' ? $section : 'none');
  756: 	if (&canview($section)) {
  757: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  758: 		$sections{$section}++;
  759: 		if ($classlist->{$student}) {
  760: 		    $fullnames{$student}=$fullname;
  761: 		}
  762: 	    } else {
  763: 		delete($classlist->{$student});
  764: 	    }
  765: 	} else {
  766: 	    delete($classlist->{$student});
  767: 	}
  768:     }
  769:     my @sections = sort(keys(%sections));
  770:     return ($classlist,\@sections,\%fullnames);
  771: }
  772: 
  773: sub canmodify {
  774:     my ($sec)=@_;
  775:     if ($perm{'mgr'}) {
  776: 	if (!defined($perm{'mgr_section'})) {
  777: 	    # can modify whole class
  778: 	    return 1;
  779: 	} else {
  780: 	    if ($sec eq $perm{'mgr_section'}) {
  781: 		#can modify the requested section
  782: 		return 1;
  783: 	    } else {
  784: 		# can't modify the requested section
  785: 		return 0;
  786: 	    }
  787: 	}
  788:     }
  789:     #can't modify
  790:     return 0;
  791: }
  792: 
  793: sub canview {
  794:     my ($sec)=@_;
  795:     if ($perm{'vgr'}) {
  796: 	if (!defined($perm{'vgr_section'})) {
  797: 	    # can view whole class
  798: 	    return 1;
  799: 	} else {
  800: 	    if ($sec eq $perm{'vgr_section'}) {
  801: 		#can view the requested section
  802: 		return 1;
  803: 	    } else {
  804: 		# can't view the requested section
  805: 		return 0;
  806: 	    }
  807: 	}
  808:     }
  809:     #can't view
  810:     return 0;
  811: }
  812: 
  813: #--- Retrieve the grade status of a student for all the parts
  814: sub student_gradeStatus {
  815:     my ($symb,$udom,$uname,$partlist) = @_;
  816:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  817:     my %partstatus = ();
  818:     foreach (@$partlist) {
  819: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  820: 	$status              = 'nothing' if ($status eq '');
  821: 	$partstatus{$_}      = $status;
  822: 	my $subkey           = "resource.$_.submitted_by";
  823: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  824:     }
  825:     return %partstatus;
  826: }
  827: 
  828: # hidden form and javascript that calls the form
  829: # Use by verifyscript and viewgrades
  830: # Shows a student's view of problem and submission
  831: sub jscriptNform {
  832:     my ($symb) = @_;
  833:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  834:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  835: 	'    function viewOneStudent(user,domain) {'."\n".
  836: 	'	document.onestudent.student.value = user;'."\n".
  837: 	'	document.onestudent.userdom.value = domain;'."\n".
  838: 	'	document.onestudent.submit();'."\n".
  839: 	'    }'."\n".
  840: 	"\n");
  841:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  842: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  843: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  844: 	'<input type="hidden" name="command" value="submission" />'."\n".
  845: 	'<input type="hidden" name="student" value="" />'."\n".
  846: 	'<input type="hidden" name="userdom" value="" />'."\n".
  847: 	'</form>'."\n";
  848:     return $jscript;
  849: }
  850: 
  851: 
  852: 
  853: # Given the score (as a number [0-1] and the weight) what is the final
  854: # point value? This function will round to the nearest tenth, third,
  855: # or quarter if one of those is within the tolerance of .00001.
  856: sub compute_points {
  857:     my ($score, $weight) = @_;
  858:     
  859:     my $tolerance = .00001;
  860:     my $points = $score * $weight;
  861: 
  862:     # Check for nearness to 1/x.
  863:     my $check_for_nearness = sub {
  864:         my ($factor) = @_;
  865:         my $num = ($points * $factor) + $tolerance;
  866:         my $floored_num = floor($num);
  867:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  868:             return $floored_num / $factor;
  869:         }
  870:         return $points;
  871:     };
  872: 
  873:     $points = $check_for_nearness->(10);
  874:     $points = $check_for_nearness->(3);
  875:     $points = $check_for_nearness->(4);
  876:     
  877:     return $points;
  878: }
  879: 
  880: #------------------ End of general use routines --------------------
  881: 
  882: #
  883: # Find most similar essay
  884: #
  885: 
  886: sub most_similar {
  887:     my ($uname,$udom,$symb,$uessay)=@_;
  888: 
  889:     unless ($symb) { return ''; }
  890: 
  891:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  892: 
  893: # ignore spaces and punctuation
  894: 
  895:     $uessay=~s/\W+/ /gs;
  896: 
  897: # ignore empty submissions (occuring when only files are sent)
  898: 
  899:     unless ($uessay=~/\w+/s) { return ''; }
  900: 
  901: # these will be returned. Do not care if not at least 50 percent similar
  902:     my $limit=0.6;
  903:     my $sname='';
  904:     my $sdom='';
  905:     my $scrsid='';
  906:     my $sessay='';
  907: # go through all essays ...
  908:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  909: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  910: # ... except the same student
  911:         next if (($tname eq $uname) && ($tdom eq $udom));
  912: 	my $tessay=$old_essays{$symb}{$tkey};
  913: 	$tessay=~s/\W+/ /gs;
  914: # String similarity gives up if not even limit
  915: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  916: # Found one
  917: 	if ($tsimilar>$limit) {
  918: 	    $limit=$tsimilar;
  919: 	    $sname=$tname;
  920: 	    $sdom=$tdom;
  921: 	    $scrsid=$tcrsid;
  922: 	    $sessay=$old_essays{$symb}{$tkey};
  923: 	}
  924:     }
  925:     if ($limit>0.6) {
  926:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  927:     } else {
  928:        return ('','','','',0);
  929:     }
  930: }
  931: 
  932: #-------------------------------------------------------------------
  933: 
  934: #------------------------------------ Receipt Verification Routines
  935: #
  936: 
  937: sub initialverifyreceipt {
  938:    my ($request,$symb) = @_;
  939:    &commonJSfunctions($request);
  940:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  941:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  942:         '-<input type="text" name="receipt" size="4" />'.
  943:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  944:         '<input type="hidden" name="command" value="verify" />'.
  945:         "</form>\n";
  946: }
  947: 
  948: #--- Check whether a receipt number is valid.---
  949: sub verifyreceipt {
  950:     my ($request,$symb) = @_;
  951: 
  952:     my $courseid = $env{'request.course.id'};
  953:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  954: 	$env{'form.receipt'};
  955:     $receipt     =~ s/[^\-\d]//g;
  956: 
  957:     my $title =
  958: 	'<h3><span class="LC_info">'.
  959: 	&mt('Verifying Receipt Number [_1]',$receipt).
  960: 	'</span></h3>'."\n";
  961: 
  962:     my ($string,$contents,$matches) = ('','',0);
  963:     my (undef,undef,$fullname) = &getclasslist('all','0');
  964:     
  965:     my $receiptparts=0;
  966:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  967: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  968:     my $parts=['0'];
  969:     if ($receiptparts) {
  970:         my $res_error; 
  971:         ($parts)=&response_type($symb,\$res_error);
  972:         if ($res_error) {
  973:             return &navmap_errormsg();
  974:         } 
  975:     }
  976:     
  977:     my $header = 
  978: 	&Apache::loncommon::start_data_table().
  979: 	&Apache::loncommon::start_data_table_header_row().
  980: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  981: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  982: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  983:     if ($receiptparts) {
  984: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  985:     }
  986:     $header.=
  987: 	&Apache::loncommon::end_data_table_header_row();
  988: 
  989:     foreach (sort 
  990: 	     {
  991: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  992: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  993: 		 }
  994: 		 return $a cmp $b;
  995: 	     } (keys(%$fullname))) {
  996: 	my ($uname,$udom)=split(/\:/);
  997: 	foreach my $part (@$parts) {
  998: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  999: 		$contents.=
 1000: 		    &Apache::loncommon::start_data_table_row().
 1001: 		    '<td>&nbsp;'."\n".
 1002: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 1003: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
 1004: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
 1005: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
 1006: 		if ($receiptparts) {
 1007: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
 1008: 		}
 1009: 		$contents.= 
 1010: 		    &Apache::loncommon::end_data_table_row()."\n";
 1011: 		
 1012: 		$matches++;
 1013: 	    }
 1014: 	}
 1015:     }
 1016:     if ($matches == 0) {
 1017:         $string = $title
 1018:                  .'<p class="LC_warning">'
 1019:                  .&mt('No match found for the above receipt number.')
 1020:                  .'</p>';
 1021:     } else {
 1022: 	$string = &jscriptNform($symb).$title.
 1023: 	    '<p>'.
 1024: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
 1025: 	    '</p>'.
 1026: 	    $header.
 1027: 	    $contents.
 1028: 	    &Apache::loncommon::end_data_table()."\n";
 1029:     }
 1030:     return $string;
 1031: }
 1032: 
 1033: #--- This is called by a number of programs.
 1034: #--- Called from the Grading Menu - View/Grade an individual student
 1035: #--- Also called directly when one clicks on the subm button 
 1036: #    on the problem page.
 1037: sub listStudents {
 1038:     my ($request,$symb,$submitonly,$divforres) = @_;
 1039: 
 1040:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 1041:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 1042:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 1043:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 1044:     unless ($submitonly) {
 1045:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 1046:     }
 1047: 
 1048:     my $result='';
 1049:     my $res_error;
 1050:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 1051: 
 1052:     my $table;
 1053:     if (ref($partlist) eq 'ARRAY') {
 1054:         if (scalar(@$partlist) > 1 ) {
 1055:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
 1056:         } elsif ($divforres) {
 1057:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 1058:         } else {
 1059:             $table = '<br clear="all" />';
 1060:         }
 1061:     }
 1062: 
 1063:     my %js_lt = &Apache::lonlocal::texthash (
 1064: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
 1065: 		'single'   => 'Please select the student before clicking on the Next button.',
 1066: 	     );
 1067:     &js_escape(\%js_lt);
 1068:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 1069:     function checkSelect(checkBox) {
 1070: 	var ctr=0;
 1071: 	var sense="";
 1072: 	if (checkBox.length > 1) {
 1073: 	    for (var i=0; i<checkBox.length; i++) {
 1074: 		if (checkBox[i].checked) {
 1075: 		    ctr++;
 1076: 		}
 1077: 	    }
 1078: 	    sense = '$js_lt{'multiple'}';
 1079: 	} else {
 1080: 	    if (checkBox.checked) {
 1081: 		ctr = 1;
 1082: 	    }
 1083: 	    sense = '$js_lt{'single'}';
 1084: 	}
 1085: 	if (ctr == 0) {
 1086: 	    alert(sense);
 1087: 	    return false;
 1088: 	}
 1089: 	document.gradesub.submit();
 1090:     }
 1091: 
 1092:     function reLoadList(formname) {
 1093: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1094: 	formname.command.value = 'submission';
 1095: 	formname.submit();
 1096:     }
 1097: LISTJAVASCRIPT
 1098: 
 1099:     &commonJSfunctions($request);
 1100:     $request->print($result);
 1101: 
 1102:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1103: 	"\n".$table;
 1104: 
 1105:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
 1106:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 1107:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
 1108:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
 1109:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
 1110:                   .&Apache::lonhtmlcommon::row_closure();
 1111:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
 1112:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
 1113:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
 1114:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
 1115:                   .&Apache::lonhtmlcommon::row_closure();
 1116: 
 1117:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1118:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1119:     $env{'form.Status'} = $saveStatus;
 1120:     my %optiontext = &Apache::lonlocal::texthash (
 1121:                           lastonly => 'last submission',
 1122:                           last     => 'last submission with details',
 1123:                           datesub  => 'all submissions',
 1124:                           all      => 'all submissions with details',
 1125:                       );
 1126:     my $submission_options =
 1127:         '<span class="LC_nobreak">'.
 1128:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1129:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1130:         '<span class="LC_nobreak">'.
 1131:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1132:         $optiontext{'last'}.' </label></span>'."\n".
 1133:         '<span class="LC_nobreak">'.
 1134:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1135:         $optiontext{'datesub'}.'</label></span>'."\n".
 1136:         '<span class="LC_nobreak">'.
 1137:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1138:         $optiontext{'all'}.'</label></span>';
 1139:     my ($compmsg,$nocompmsg);
 1140:     $nocompmsg = ' checked="checked"';
 1141:     if ($numessay) {
 1142:         $compmsg = $nocompmsg;
 1143:         $nocompmsg = '';
 1144:     }
 1145:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
 1146:                   .$submission_options;
 1147: # Check if any gradable
 1148:     my $showmore;
 1149:     if ($perm{'mgr'}) {
 1150:         my @sections;
 1151:         if ($env{'request.course.sec'} ne '') {
 1152:             @sections = ($env{'request.course.sec'});
 1153:         } elsif ($env{'form.section'} eq '') {
 1154:             @sections = ('all');
 1155:         } else {
 1156:             @sections = &Apache::loncommon::get_env_multiple('form.section');
 1157:         }
 1158:         if (grep(/^all$/,@sections)) {
 1159:             $showmore = 1;
 1160:         } else {
 1161:             foreach my $sec (@sections) {
 1162:                 if (&canmodify($sec)) {
 1163:                     $showmore = 1;
 1164:                     last;
 1165:                 }
 1166:             }
 1167:         }
 1168:     }
 1169: 
 1170:     if ($showmore) {
 1171:         $gradeTable .=
 1172:                    &Apache::lonhtmlcommon::row_closure()
 1173:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
 1174:                   .'<span class="LC_nobreak">'
 1175:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
 1176:                   .&mt('No').('&nbsp;'x2).'</label>'
 1177:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
 1178:                   .&mt('Yes').('&nbsp;'x2).'</label>'
 1179:                   .&Apache::lonhtmlcommon::row_closure();
 1180: 
 1181:         $gradeTable .= 
 1182:                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1183:                   .'<select name="increment">'
 1184:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1185:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1186:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1187:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1188:                   .'</select>';
 1189:     }
 1190:     $gradeTable .= 
 1191:         &build_section_inputs().
 1192: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1193: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1194: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1195:     if (exists($env{'form.Status'})) {
 1196: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
 1197:     } else {
 1198:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1199:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1200:                       .&Apache::lonhtmlcommon::StatusOptions(
 1201:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
 1202:     }
 1203:     if ($numessay) {
 1204:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
 1205:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1206:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
 1207:     }
 1208:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
 1209:                   .&Apache::lonhtmlcommon::end_pick_box();
 1210: 
 1211:     $gradeTable .= '<p>'
 1212:                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
 1213:                   .'<input type="hidden" name="command" value="processGroup" />'
 1214:                   .'</p>';
 1215: 
 1216: # checkall buttons
 1217:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1218:     $gradeTable.='<input type="button" '."\n".
 1219:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1220:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1221:     $gradeTable.=&check_buttons();
 1222:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1223:     $gradeTable.= &Apache::loncommon::start_data_table().
 1224: 	&Apache::loncommon::start_data_table_header_row();
 1225:     my $loop = 0;
 1226:     while ($loop < 2) {
 1227: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1228: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1229: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1230: 	    foreach my $part (sort(@$partlist)) {
 1231: 		my $display_part=
 1232: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1233: 		$gradeTable.=
 1234: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1235: 	    }
 1236: 	} elsif ($submitonly eq 'queued') {
 1237: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1238: 	}
 1239: 	$loop++;
 1240: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1241:     }
 1242:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1243: 
 1244:     my $ctr = 0;
 1245:     foreach my $student (sort 
 1246: 			 {
 1247: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1248: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1249: 			     }
 1250: 			     return $a cmp $b;
 1251: 			 }
 1252: 			 (keys(%$fullname))) {
 1253: 	my ($uname,$udom) = split(/:/,$student);
 1254: 
 1255: 	my %status = ();
 1256: 
 1257: 	if ($submitonly eq 'queued') {
 1258: 	    my %queue_status = 
 1259: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1260: 							$udom,$uname);
 1261: 	    next if (!defined($queue_status{'gradingqueue'}));
 1262: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1263: 	}
 1264: 
 1265: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1266: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1267: 	    my $submitted = 0;
 1268: 	    my $graded = 0;
 1269: 	    my $incorrect = 0;
 1270: 	    foreach (keys(%status)) {
 1271: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1272: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1273: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1274: 		
 1275: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1276: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1277: 		    $submitted = 0;
 1278: 		    my ($part)=split(/\./,$partid);
 1279: 		    $gradeTable.='<input type="hidden" name="'.
 1280: 			$student.':'.$part.':submitted_by" value="'.
 1281: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1282: 		}
 1283: 	    }
 1284: 	    
 1285: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1286: 				     $submitonly eq 'incorrect' ||
 1287: 				     $submitonly eq 'graded'));
 1288: 	    next if (!$graded && ($submitonly eq 'graded'));
 1289: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1290: 	}
 1291: 
 1292: 	$ctr++;
 1293: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1294:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1295: 	if ( $perm{'vgr'} eq 'F' ) {
 1296: 	    if ($ctr%2 ==1) {
 1297: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1298: 	    }
 1299: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1300:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1301:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1302: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1303: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1304: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1305: 
 1306: 	    if ($submitonly ne 'all') {
 1307: 		foreach (sort(keys(%status))) {
 1308: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1309: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1310: 		}
 1311: 	    }
 1312: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1313: 	    if ($ctr%2 ==0) {
 1314: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1315: 	    }
 1316: 	}
 1317:     }
 1318:     if ($ctr%2 ==1) {
 1319: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1320: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1321: 		foreach (@$partlist) {
 1322: 		    $gradeTable.='<td>&nbsp;</td>';
 1323: 		}
 1324: 	    } elsif ($submitonly eq 'queued') {
 1325: 		$gradeTable.='<td>&nbsp;</td>';
 1326: 	    }
 1327: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1328:     }
 1329: 
 1330:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1331:         '<input type="button" '.
 1332:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1333:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1334:     if ($ctr == 0) {
 1335: 	my $num_students=(scalar(keys(%$fullname)));
 1336: 	if ($num_students eq 0) {
 1337: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1338: 	} else {
 1339: 	    my $submissions='submissions';
 1340: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1341: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1342: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1343: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1344: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1345: 		    $num_students).
 1346: 		'</span><br />';
 1347: 	}
 1348:     } elsif ($ctr == 1) {
 1349: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1350:     }
 1351:     $request->print($gradeTable);
 1352:     return '';
 1353: }
 1354: 
 1355: #---- Called from the listStudents routine
 1356: 
 1357: sub check_script {
 1358:     my ($form,$type) = @_;
 1359:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
 1360:     function checkall() {
 1361:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1362:             ele = document.forms.'.$form.'.elements[i];
 1363:             if (ele.name == "'.$type.'") {
 1364:             document.forms.'.$form.'.elements[i].checked=true;
 1365:                                        }
 1366:         }
 1367:     }
 1368: 
 1369:     function checksec() {
 1370:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1371:             ele = document.forms.'.$form.'.elements[i];
 1372:            string = document.forms.'.$form.'.chksec.value;
 1373:            if
 1374:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1375:               document.forms.'.$form.'.elements[i].checked=true;
 1376:             }
 1377:         }
 1378:     }
 1379: 
 1380: 
 1381:     function uncheckall() {
 1382:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1383:             ele = document.forms.'.$form.'.elements[i];
 1384:             if (ele.name == "'.$type.'") {
 1385:             document.forms.'.$form.'.elements[i].checked=false;
 1386:                                        }
 1387:         }
 1388:     }
 1389: 
 1390: '."\n");
 1391:     return $chkallscript;
 1392: }
 1393: 
 1394: sub check_buttons {
 1395:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1396:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1397:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1398:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1399:     return $buttons;
 1400: }
 1401: 
 1402: #     Displays the submissions for one student or a group of students
 1403: sub processGroup {
 1404:     my ($request,$symb) = @_;
 1405:     my $ctr        = 0;
 1406:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1407:     my $total      = scalar(@stuchecked)-1;
 1408: 
 1409:     foreach my $student (@stuchecked) {
 1410: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1411: 	$env{'form.student'}        = $uname;
 1412: 	$env{'form.userdom'}        = $udom;
 1413: 	$env{'form.fullname'}       = $fullname;
 1414: 	&submission($request,$ctr,$total,$symb);
 1415: 	$ctr++;
 1416:     }
 1417:     return '';
 1418: }
 1419: 
 1420: #------------------------------------------------------------------------------------
 1421: #
 1422: #-------------------------- Next few routines handles grading by student, essentially
 1423: #                           handles essay response type problem/part
 1424: #
 1425: #--- Javascript to handle the submission page functionality ---
 1426: sub sub_page_js {
 1427:     my $request = shift;
 1428:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1429:     &js_escape(\$alertmsg);
 1430:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1431:     function updateRadio(formname,id,weight) {
 1432: 	var gradeBox = formname["GD_BOX"+id];
 1433: 	var radioButton = formname["RADVAL"+id];
 1434: 	var oldpts = formname["oldpts"+id].value;
 1435: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1436: 	gradeBox.value = pts;
 1437: 	var resetbox = false;
 1438: 	if (isNaN(pts) || pts < 0) {
 1439: 	    alert("$alertmsg"+pts);
 1440: 	    for (var i=0; i<radioButton.length; i++) {
 1441: 		if (radioButton[i].checked) {
 1442: 		    gradeBox.value = i;
 1443: 		    resetbox = true;
 1444: 		}
 1445: 	    }
 1446: 	    if (!resetbox) {
 1447: 		formtextbox.value = "";
 1448: 	    }
 1449: 	    return;
 1450: 	}
 1451: 
 1452: 	if (pts > weight) {
 1453: 	    var resp = confirm("You entered a value ("+pts+
 1454: 			       ") greater than the weight for the part. Accept?");
 1455: 	    if (resp == false) {
 1456: 		gradeBox.value = oldpts;
 1457: 		return;
 1458: 	    }
 1459: 	}
 1460: 
 1461: 	for (var i=0; i<radioButton.length; i++) {
 1462: 	    radioButton[i].checked=false;
 1463: 	    if (pts == i && pts != "") {
 1464: 		radioButton[i].checked=true;
 1465: 	    }
 1466: 	}
 1467: 	updateSelect(formname,id);
 1468: 	formname["stores"+id].value = "0";
 1469:     }
 1470: 
 1471:     function writeBox(formname,id,pts) {
 1472: 	var gradeBox = formname["GD_BOX"+id];
 1473: 	if (checkSolved(formname,id) == 'update') {
 1474: 	    gradeBox.value = pts;
 1475: 	} else {
 1476: 	    var oldpts = formname["oldpts"+id].value;
 1477: 	    gradeBox.value = oldpts;
 1478: 	    var radioButton = formname["RADVAL"+id];
 1479: 	    for (var i=0; i<radioButton.length; i++) {
 1480: 		radioButton[i].checked=false;
 1481: 		if (i == oldpts) {
 1482: 		    radioButton[i].checked=true;
 1483: 		}
 1484: 	    }
 1485: 	}
 1486: 	formname["stores"+id].value = "0";
 1487: 	updateSelect(formname,id);
 1488: 	return;
 1489:     }
 1490: 
 1491:     function clearRadBox(formname,id) {
 1492: 	if (checkSolved(formname,id) == 'noupdate') {
 1493: 	    updateSelect(formname,id);
 1494: 	    return;
 1495: 	}
 1496: 	gradeSelect = formname["GD_SEL"+id];
 1497: 	for (var i=0; i<gradeSelect.length; i++) {
 1498: 	    if (gradeSelect[i].selected) {
 1499: 		var selectx=i;
 1500: 	    }
 1501: 	}
 1502: 	var stores = formname["stores"+id];
 1503: 	if (selectx == stores.value) { return };
 1504: 	var gradeBox = formname["GD_BOX"+id];
 1505: 	gradeBox.value = "";
 1506: 	var radioButton = formname["RADVAL"+id];
 1507: 	for (var i=0; i<radioButton.length; i++) {
 1508: 	    radioButton[i].checked=false;
 1509: 	}
 1510: 	stores.value = selectx;
 1511:     }
 1512: 
 1513:     function checkSolved(formname,id) {
 1514: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1515: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1516: 	    if (!reply) {return "noupdate";}
 1517: 	    formname.overRideScore.value = 'yes';
 1518: 	}
 1519: 	return "update";
 1520:     }
 1521: 
 1522:     function updateSelect(formname,id) {
 1523: 	formname["GD_SEL"+id][0].selected = true;
 1524: 	return;
 1525:     }
 1526: 
 1527: //=========== Check that a point is assigned for all the parts  ============
 1528:     function checksubmit(formname,val,total,parttot) {
 1529: 	formname.gradeOpt.value = val;
 1530: 	if (val == "Save & Next") {
 1531: 	    for (i=0;i<=total;i++) {
 1532: 		for (j=0;j<parttot;j++) {
 1533: 		    var partid = formname["partid"+i+"_"+j].value;
 1534: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1535: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1536: 			if (points == "") {
 1537: 			    var name = formname["name"+i].value;
 1538: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1539: 			    var resp = confirm("You did not assign a score for "+studentID+
 1540: 					       ", part "+partid+". Continue?");
 1541: 			    if (resp == false) {
 1542: 				formname["GD_BOX"+i+"_"+partid].focus();
 1543: 				return false;
 1544: 			    }
 1545: 			}
 1546: 		    }
 1547: 		}
 1548: 	    }
 1549: 	}
 1550: 	formname.submit();
 1551:     }
 1552: 
 1553: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1554:     function checkSubmitPage(formname,total) {
 1555: 	noscore = new Array(100);
 1556: 	var ptr = 0;
 1557: 	for (i=1;i<total;i++) {
 1558: 	    var partid = formname["q_"+i].value;
 1559: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1560: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1561: 		var status = formname["solved"+i+"_"+partid].value;
 1562: 		if (points == "" && status != "correct_by_student") {
 1563: 		    noscore[ptr] = i;
 1564: 		    ptr++;
 1565: 		}
 1566: 	    }
 1567: 	}
 1568: 	if (ptr != 0) {
 1569: 	    var sense = ptr == 1 ? ": " : "s: ";
 1570: 	    var prolist = "";
 1571: 	    if (ptr == 1) {
 1572: 		prolist = noscore[0];
 1573: 	    } else {
 1574: 		var i = 0;
 1575: 		while (i < ptr-1) {
 1576: 		    prolist += noscore[i]+", ";
 1577: 		    i++;
 1578: 		}
 1579: 		prolist += "and "+noscore[i];
 1580: 	    }
 1581: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1582: 	    if (resp == false) {
 1583: 		return false;
 1584: 	    }
 1585: 	}
 1586: 
 1587: 	formname.submit();
 1588:     }
 1589: SUBJAVASCRIPT
 1590: }
 1591: 
 1592: #--- javascript for grading message center
 1593: sub sub_grademessage_js {
 1594:     my $request = shift;
 1595:     my $iconpath = $request->dir_config('lonIconsURL');
 1596:     &commonJSfunctions($request);
 1597: 
 1598:     my $inner_js_msg_central= (<<INNERJS);
 1599: <script type="text/javascript">
 1600:     function checkInput() {
 1601:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1602:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1603:       var usrctr = document.msgcenter.usrctr.value;
 1604:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1605:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1606: 
 1607:       var msgchk = "";
 1608:       if (document.msgcenter.subchk.checked) {
 1609:          msgchk = "msgsub,";
 1610:       }
 1611:       var includemsg = 0;
 1612:       for (var i=1; i<=nmsg; i++) {
 1613:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1614:           var frmmsg = document.msgcenter["msg"+i];
 1615:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1616:           var showflg = opener.document.SCORE["shownOnce"+i];
 1617:           showflg.value = "1";
 1618:           var chkbox = document.msgcenter["msgn"+i];
 1619:           if (chkbox.checked) {
 1620:              msgchk += "savemsg"+i+",";
 1621:              includemsg = 1;
 1622:           }
 1623:       }
 1624:       if (document.msgcenter.newmsgchk.checked) {
 1625:          msgchk += "newmsg"+usrctr;
 1626:          includemsg = 1;
 1627:       }
 1628:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1629:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1630:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1631:       includemsg.value = msgchk;
 1632: 
 1633:       self.close()
 1634: 
 1635:     }
 1636: </script>
 1637: INNERJS
 1638: 
 1639:     my $start_page_msg_central =
 1640:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1641: 				       {'js_ready'  => 1,
 1642: 					'only_body' => 1,
 1643: 					'bgcolor'   =>'#FFFFFF',});
 1644:     my $end_page_msg_central =
 1645: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1646: 
 1647: 
 1648:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1649:     $docopen=~s/^document\.//;
 1650: 
 1651:     my %html_js_lt = &Apache::lonlocal::texthash(
 1652:                 comp => 'Compose Message for: ',
 1653:                 incl => 'Include',
 1654:                 type => 'Type',
 1655:                 subj => 'Subject',
 1656:                 mesa => 'Message',
 1657:                 new  => 'New',
 1658:                 save => 'Save',
 1659:                 canc => 'Cancel',
 1660:              );
 1661:     &html_escape(\%html_js_lt);
 1662:     &js_escape(\%html_js_lt);
 1663:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1664: 
 1665: //===================== Script to view submitted by ==================
 1666:   function viewSubmitter(submitter) {
 1667:     document.SCORE.refresh.value = "on";
 1668:     document.SCORE.NCT.value = "1";
 1669:     document.SCORE.unamedom0.value = submitter;
 1670:     document.SCORE.submit();
 1671:     return;
 1672:   }
 1673: 
 1674: //====================== Script for composing message ==============
 1675:    // preload images
 1676:    img1 = new Image();
 1677:    img1.src = "$iconpath/mailbkgrd.gif";
 1678:    img2 = new Image();
 1679:    img2.src = "$iconpath/mailto.gif";
 1680: 
 1681:   function msgCenter(msgform,usrctr,fullname) {
 1682:     var Nmsg  = msgform.savemsgN.value;
 1683:     savedMsgHeader(Nmsg,usrctr,fullname);
 1684:     var subject = msgform.msgsub.value;
 1685:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1686:     re = /msgsub/;
 1687:     var shwsel = "";
 1688:     if (re.test(msgchk)) { shwsel = "checked" }
 1689:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1690:     displaySubject(checkEntities(subject),shwsel);
 1691:     for (var i=1; i<=Nmsg; i++) {
 1692: 	var testmsg = "savemsg"+i+",";
 1693: 	re = new RegExp(testmsg,"g");
 1694: 	shwsel = "";
 1695: 	if (re.test(msgchk)) { shwsel = "checked" }
 1696: 	var message = document.SCORE["savemsg"+i].value;
 1697: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1698: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1699: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1700:     }
 1701:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1702:     shwsel = "";
 1703:     re = /newmsg/;
 1704:     if (re.test(msgchk)) { shwsel = "checked" }
 1705:     newMsg(newmsg,shwsel);
 1706:     msgTail(); 
 1707:     return;
 1708:   }
 1709: 
 1710:   function checkEntities(strx) {
 1711:     if (strx.length == 0) return strx;
 1712:     var orgStr = ["&", "<", ">", '"']; 
 1713:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1714:     var counter = 0;
 1715:     while (counter < 4) {
 1716: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1717: 	counter++;
 1718:     }
 1719:     return strx;
 1720:   }
 1721: 
 1722:   function strReplace(strx, orgStr, newStr) {
 1723:     return strx.split(orgStr).join(newStr);
 1724:   }
 1725: 
 1726:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1727:     var height = 70*Nmsg+250;
 1728:     if (height > 600) {
 1729: 	height = 600;
 1730:     }
 1731:     var xpos = (screen.width-600)/2;
 1732:     xpos = (xpos < 0) ? '0' : xpos;
 1733:     var ypos = (screen.height-height)/2-30;
 1734:     ypos = (ypos < 0) ? '0' : ypos;
 1735: 
 1736:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1737:     pWin.focus();
 1738:     pDoc = pWin.document;
 1739:     pDoc.$docopen;
 1740:     pDoc.write('$start_page_msg_central');
 1741: 
 1742:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1743:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1744:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1745: 
 1746:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1747:     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>");
 1748: }
 1749:     function displaySubject(msg,shwsel) {
 1750:     pDoc = pWin.document;
 1751:     pDoc.write("<tr>");
 1752:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1753:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1754:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1755: }
 1756: 
 1757:   function displaySavedMsg(ctr,msg,shwsel) {
 1758:     pDoc = pWin.document;
 1759:     pDoc.write("<tr>");
 1760:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1761:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1762:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1763: }
 1764: 
 1765:   function newMsg(newmsg,shwsel) {
 1766:     pDoc = pWin.document;
 1767:     pDoc.write("<tr>");
 1768:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1769:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1770:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1771: }
 1772: 
 1773:   function msgTail() {
 1774:     pDoc = pWin.document;
 1775:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1776:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1777:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1778:     pDoc.write("<\\/form>");
 1779:     pDoc.write('$end_page_msg_central');
 1780:     pDoc.close();
 1781: }
 1782: 
 1783: SUBJAVASCRIPT
 1784: }
 1785: 
 1786: #--- javascript for essay type problem --
 1787: sub sub_page_kw_js {
 1788:     my $request = shift;
 1789: 
 1790:     unless ($env{'form.compmsg'}) {
 1791:         &commonJSfunctions($request);
 1792:     }
 1793: 
 1794:     my $inner_js_highlight_central= (<<INNERJS);
 1795: <script type="text/javascript">
 1796:     function updateChoice(flag) {
 1797:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1798:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1799:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1800:       opener.document.SCORE.refresh.value = "on";
 1801:       if (opener.document.SCORE.keywords.value!=""){
 1802:          opener.document.SCORE.submit();
 1803:       }
 1804:       self.close()
 1805:     }
 1806: </script>
 1807: INNERJS
 1808: 
 1809:     my $start_page_highlight_central =
 1810:         &Apache::loncommon::start_page('Highlight Central',
 1811:                                        $inner_js_highlight_central,
 1812:                                        {'js_ready'  => 1,
 1813:                                         'only_body' => 1,
 1814:                                         'bgcolor'   =>'#FFFFFF',});
 1815:     my $end_page_highlight_central =
 1816:         &Apache::loncommon::end_page({'js_ready' => 1});
 1817: 
 1818:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1819:     $docopen=~s/^document\.//;
 1820: 
 1821:     my %js_lt = &Apache::lonlocal::texthash(
 1822:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1823:                 plse => 'Please select a word or group of words from document and then click this link.',
 1824:                 adds => 'Add selection to keyword list? Edit if desired.',
 1825:                 col1 => 'red',
 1826:                 col2 => 'green',
 1827:                 col3 => 'blue',
 1828:                 siz1 => 'normal',
 1829:                 siz2 => '+1',
 1830:                 siz3 => '+2',
 1831:                 sty1 => 'normal',
 1832:                 sty2 => 'italic',
 1833:                 sty3 => 'bold',
 1834:              );
 1835:     my %html_js_lt = &Apache::lonlocal::texthash(
 1836:                 save => 'Save',
 1837:                 canc => 'Cancel',
 1838:                 kehi => 'Keyword Highlight Options',
 1839:                 txtc => 'Text Color',
 1840:                 font => 'Font Size',
 1841:                 fnst => 'Font Style',
 1842:              );
 1843:     &js_escape(\%js_lt);
 1844:     &html_escape(\%html_js_lt);
 1845:     &js_escape(\%html_js_lt);
 1846:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1847: 
 1848: //===================== Show list of keywords ====================
 1849:   function keywords(formname) {
 1850:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1851:     if (nret==null) return;
 1852:     formname.keywords.value = nret;
 1853: 
 1854:     if (formname.keywords.value != "") {
 1855:         formname.refresh.value = "on";
 1856:         formname.submit();
 1857:     }
 1858:     return;
 1859:   }
 1860: 
 1861: //===================== Script to add keyword(s) ==================
 1862:   function getSel() {
 1863:     if (document.getSelection) txt = document.getSelection();
 1864:     else if (document.selection) txt = document.selection.createRange().text;
 1865:     else return;
 1866:     if (typeof(txt) != 'string') {
 1867:         txt = String(txt);
 1868:     }
 1869:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1870:     if (cleantxt=="") {
 1871:         alert("$js_lt{'plse'}");
 1872:         return;
 1873:     }
 1874:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1875:     if (nret==null) return;
 1876:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1877:     if (document.SCORE.keywords.value != "") {
 1878:         document.SCORE.refresh.value = "on";
 1879:         document.SCORE.submit();
 1880:     }
 1881:     return;
 1882:   }
 1883: 
 1884: //====================== Script for keyword highlight options ==============
 1885:   function kwhighlight() {
 1886:     var kwclr    = document.SCORE.kwclr.value;
 1887:     var kwsize   = document.SCORE.kwsize.value;
 1888:     var kwstyle  = document.SCORE.kwstyle.value;
 1889:     var redsel = "";
 1890:     var grnsel = "";
 1891:     var blusel = "";
 1892:     var txtcol1 = "$js_lt{'col1'}";
 1893:     var txtcol2 = "$js_lt{'col2'}";
 1894:     var txtcol3 = "$js_lt{'col3'}";
 1895:     var txtsiz1 = "$js_lt{'siz1'}";
 1896:     var txtsiz2 = "$js_lt{'siz2'}";
 1897:     var txtsiz3 = "$js_lt{'siz3'}";
 1898:     var txtsty1 = "$js_lt{'sty1'}";
 1899:     var txtsty2 = "$js_lt{'sty2'}";
 1900:     var txtsty3 = "$js_lt{'sty3'}";
 1901:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1902:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1903:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1904:     var sznsel = "";
 1905:     var sz1sel = "";
 1906:     var sz2sel = "";
 1907:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1908:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1909:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1910:     var synsel = "";
 1911:     var syisel = "";
 1912:     var sybsel = "";
 1913:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1914:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1915:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1916:     highlightCentral();
 1917:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1918:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1919:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1920:     highlightend();
 1921:     return;
 1922:   }
 1923: 
 1924:   function highlightCentral() {
 1925: //    if (window.hwdWin) window.hwdWin.close();
 1926:     var xpos = (screen.width-400)/2;
 1927:     xpos = (xpos < 0) ? '0' : xpos;
 1928:     var ypos = (screen.height-330)/2-30;
 1929:     ypos = (ypos < 0) ? '0' : ypos;
 1930: 
 1931:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1932:     hwdWin.focus();
 1933:     var hDoc = hwdWin.document;
 1934:     hDoc.$docopen;
 1935:     hDoc.write('$start_page_highlight_central');
 1936:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1937:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1938: 
 1939:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1940:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1941:   }
 1942: 
 1943:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1944:     var hDoc = hwdWin.document;
 1945:     hDoc.write("<tr>");
 1946:     hDoc.write("<td align=\\"left\\">");
 1947:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1948:     hDoc.write("<td align=\\"left\\">");
 1949:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1950:     hDoc.write("<td align=\\"left\\">");
 1951:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1952:     hDoc.write("<\\/tr>");
 1953:   }
 1954: 
 1955:   function highlightend() { 
 1956:     var hDoc = hwdWin.document;
 1957:     hDoc.write("<\\/table><br \\/>");
 1958:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1959:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1960:     hDoc.write("<\\/form>");
 1961:     hDoc.write('$end_page_highlight_central');
 1962:     hDoc.close();
 1963:   }
 1964: 
 1965: SUBJAVASCRIPT
 1966: }
 1967: 
 1968: sub get_increment {
 1969:     my $increment = $env{'form.increment'};
 1970:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1971:         $increment != .1) {
 1972:         $increment = 1;
 1973:     }
 1974:     return $increment;
 1975: }
 1976: 
 1977: sub gradeBox_start {
 1978:     return (
 1979:         &Apache::loncommon::start_data_table()
 1980:        .&Apache::loncommon::start_data_table_header_row()
 1981:        .'<th>'.&mt('Part').'</th>'
 1982:        .'<th>'.&mt('Points').'</th>'
 1983:        .'<th>&nbsp;</th>'
 1984:        .'<th>'.&mt('Assign Grade').'</th>'
 1985:        .'<th>'.&mt('Weight').'</th>'
 1986:        .'<th>'.&mt('Grade Status').'</th>'
 1987:        .&Apache::loncommon::end_data_table_header_row()
 1988:     );
 1989: }
 1990: 
 1991: sub gradeBox_end {
 1992:     return (
 1993:         &Apache::loncommon::end_data_table()
 1994:     );
 1995: }
 1996: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1997: sub gradeBox {
 1998:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1999:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2000: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 2001:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 2002:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 2003:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 2004:     $wgt       = ($wgt > 0 ? $wgt : '1');
 2005:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 2006: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 2007:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 2008:     my $display_part= &get_display_part($partid,$symb);
 2009:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2010: 				       [$partid]);
 2011:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 2012:     if ($last_resets{$partid}) {
 2013:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 2014:     }
 2015:     my $result=&Apache::loncommon::start_data_table_row();
 2016:     my $ctr = 0;
 2017:     my $thisweight = 0;
 2018:     my $increment = &get_increment();
 2019: 
 2020:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 2021:     while ($thisweight<=$wgt) {
 2022: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 2023:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 2024: 	    $thisweight.')" value="'.$thisweight.'" '.
 2025: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 2026: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2027:         $thisweight += $increment;
 2028: 	$ctr++;
 2029:     }
 2030:     $radio.='</tr></table>';
 2031: 
 2032:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 2033: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 2034: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 2035: 	$wgt.')" /></td>'."\n";
 2036:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 2037: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 2038: 	' </td>'."\n";
 2039:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 2040: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 2041:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 2042: 	$line.='<option></option>'.
 2043: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 2044:     } else {
 2045: 	$line.='<option selected="selected"></option>'.
 2046: 	    '<option value="excused" >'.&mt('excused').'</option>';
 2047:     }
 2048:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 2049: 
 2050: 
 2051:     $result .= 
 2052: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 2053:     $result.=&Apache::loncommon::end_data_table_row();
 2054:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 2055:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 2056: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 2057: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 2058: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 2059:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 2060:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 2061:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 2062:         $aggtries.'" />'."\n";
 2063:     my $res_error;
 2064:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 2065:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 2066:     if ($res_error) {
 2067:         return &navmap_errormsg();
 2068:     }
 2069:     return $result;
 2070: }
 2071: 
 2072: sub handback_box {
 2073:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 2074:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
 2075:     return unless ($numessay);
 2076:     my (@respids);
 2077:     my @part_response_id = &flatten_responseType($responseType);
 2078:     foreach my $part_response_id (@part_response_id) {
 2079:     	my ($part,$resp) = @{ $part_response_id };
 2080:         if ($part eq $partid) {
 2081:             push(@respids,$resp);
 2082:         }
 2083:     }
 2084:     my $result;
 2085:     foreach my $respid (@respids) {
 2086: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 2087: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 2088: 	next if (!@$files);
 2089: 	my $file_counter = 0;
 2090: 	foreach my $file (@$files) {
 2091: 	    if ($file =~ /\/portfolio\//) {
 2092:                 $file_counter++;
 2093:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 2094:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 2095:     	        $file_disp = "$name.$ext";
 2096:     	        $file = $file_path.$file_disp;
 2097:     	        $result.=&mt('Return commented version of [_1] to student.',
 2098:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 2099:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 2100:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 2101: 	    }
 2102: 	}
 2103:         if ($file_counter) {
 2104:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 2105:                        '<span class="LC_info">'.
 2106:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 2107:         }
 2108:     }
 2109:     return $result;    
 2110: }
 2111: 
 2112: sub show_problem {
 2113:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 2114:     my $rendered;
 2115:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 2116:     &Apache::lonxml::remember_problem_counter();
 2117:     if ($mode eq 'both' or $mode eq 'text') {
 2118: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 2119: 						       $env{'request.course.id'},
 2120: 						       undef,\%form);
 2121:     }
 2122:     if ($removeform) {
 2123: 	$rendered=~s|<form(.*?)>||g;
 2124: 	$rendered=~s|</form>||g;
 2125: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 2126:     }
 2127:     my $companswer;
 2128:     if ($mode eq 'both' or $mode eq 'answer') {
 2129: 	&Apache::lonxml::restore_problem_counter();
 2130: 	$companswer=
 2131: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 2132: 						    $env{'request.course.id'},
 2133: 						    %form);
 2134:     }
 2135:     if ($removeform) {
 2136: 	$companswer=~s|<form(.*?)>||g;
 2137: 	$companswer=~s|</form>||g;
 2138: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 2139:     }
 2140:     my $renderheading = &mt('View of the problem');
 2141:     my $answerheading = &mt('Correct answer');
 2142:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 2143:         my $stu_fullname = $env{'form.fullname'};
 2144:         if ($stu_fullname eq '') {
 2145:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 2146:         }
 2147:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 2148:         if ($forwhom ne '') {
 2149:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 2150:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 2151:         }
 2152:     }
 2153:     $rendered=
 2154:         '<div class="LC_Box">'
 2155:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 2156:        .$rendered
 2157:        .'</div>';
 2158:     $companswer=
 2159:         '<div class="LC_Box">'
 2160:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 2161:        .$companswer
 2162:        .'</div>';
 2163:     my $result;
 2164:     if ($mode eq 'both') {
 2165:         $result=$rendered.$companswer;
 2166:     } elsif ($mode eq 'text') {
 2167:         $result=$rendered;
 2168:     } elsif ($mode eq 'answer') {
 2169:         $result=$companswer;
 2170:     }
 2171:     return $result;
 2172: }
 2173: 
 2174: sub files_exist {
 2175:     my ($r, $symb) = @_;
 2176:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2177:     foreach my $student (@students) {
 2178:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2179:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2180: 					      $udom,$uname);
 2181:         my ($string)= &get_last_submission(\%record);
 2182:         foreach my $submission (@$string) {
 2183:             my ($partid,$respid) =
 2184: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2185:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2186: 					   \%record);
 2187:             return 1 if (@$files);
 2188:         }
 2189:     }
 2190:     return 0;
 2191: }
 2192: 
 2193: sub download_all_link {
 2194:     my ($r,$symb) = @_;
 2195:     unless (&files_exist($r, $symb)) {
 2196:         $r->print(&mt('There are currently no submitted documents.'));
 2197:         return;
 2198:     }
 2199:     my $all_students = 
 2200: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2201: 
 2202:     my $parts =
 2203: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2204: 
 2205:     my $identifier = &Apache::loncommon::get_cgi_id();
 2206:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2207:                              'cgi.'.$identifier.'.symb' => $symb,
 2208:                              'cgi.'.$identifier.'.parts' => $parts,});
 2209:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2210: 	      &mt('Download All Submitted Documents').'</a>');
 2211:     return;
 2212: }
 2213: 
 2214: sub submit_download_link {
 2215:     my ($request,$symb) = @_;
 2216:     if (!$symb) { return ''; }
 2217:     my $res_error;
 2218:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
 2219:         &response_type($symb,\$res_error);
 2220:     if ($res_error) {
 2221:         $request->print(&mt('An error occurred retrieving response types'));
 2222:         return;
 2223:     }
 2224:     unless ($numessay) {
 2225:         $request->print(&mt('No essayresponse items found'));
 2226:         return;
 2227:     }
 2228:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2229:     if (@chosenparts) {
 2230:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
 2231:                                           undef,undef,1));
 2232:     }
 2233:     if ($numessay) {
 2234:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2235:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2236:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2237:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2238:         if (ref($fullname) eq 'HASH') {
 2239:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2240:             if (@students) {
 2241:                 @{$env{'form.stuinfo'}} = @students;
 2242:                 if ($numdropbox) {
 2243:                     &download_all_link($request,$symb);
 2244:                 } else {
 2245:                     $request->print(&mt('No essayrespose items with dropbox found'));
 2246:                 }
 2247: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
 2248: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2249:             } else {
 2250:                 $request->print(&mt('No students match the criteria you selected'));
 2251:             }
 2252:         } else {
 2253:             $request->print(&mt('Could not retrieve student information'));
 2254:         }
 2255:     } else {
 2256:         $request->print(&mt('No essayresponse items found'));
 2257:     }
 2258:     return;
 2259: }
 2260: 
 2261: sub build_section_inputs {
 2262:     my $section_inputs;
 2263:     if ($env{'form.section'} eq '') {
 2264:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2265:     } else {
 2266:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2267:         foreach my $section (@sections) {
 2268:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2269:         }
 2270:     }
 2271:     return $section_inputs;
 2272: }
 2273: 
 2274: # --------------------------- show submissions of a student, option to grade 
 2275: sub submission {
 2276:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
 2277:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2278:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2279:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2280:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2281: 
 2282:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2283:     my $probtitle=&Apache::lonnet::gettitle($symb);
 2284:     my ($essayurl,%coursedesc_by_cid);
 2285: 
 2286:     if (!&canview($usec)) {
 2287:         $request->print(
 2288:             '<span class="LC_warning">'.
 2289:             &mt('Unable to view requested student.').
 2290:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2291:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2292:             '</span>');
 2293: 	return;
 2294:     }
 2295: 
 2296:     my $res_error;
 2297:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
 2298:         &response_type($symb,\$res_error);
 2299:     if ($res_error) {
 2300:         $request->print(&navmap_errormsg());
 2301:         return;
 2302:     }
 2303: 
 2304:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2305:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2306:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2307:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
 2308:         $env{'form.compmsg'} = 1;
 2309:     }
 2310:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2311:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2312: 	'" src="'.$request->dir_config('lonIconsURL').
 2313: 	'/check.gif" height="16" border="0" />';
 2314: 
 2315:     # header info
 2316:     if ($counter == 0) {
 2317:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
 2318:         if (@chosenparts) {
 2319:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
 2320:         } elsif ($divforres) {
 2321:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
 2322:         } else {
 2323:             $request->print('<br clear="all" />');
 2324:         }
 2325: 	&sub_page_js($request);
 2326:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
 2327: 	&sub_page_kw_js($request) if ($numessay);
 2328: 
 2329: 	# option to display problem, only once else it cause problems 
 2330:         # with the form later since the problem has a form.
 2331: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2332: 	    my $mode;
 2333: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2334: 		$mode='both';
 2335: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2336: 		$mode='text';
 2337: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2338: 		$mode='answer';
 2339: 	    }
 2340: 	    &Apache::lonxml::clear_problem_counter();
 2341: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2342: 	}
 2343: 
 2344: 	my %keyhash = ();
 2345: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
 2346: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2347: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2348: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2349: 	}
 2350: 	# kwclr is the only variable that is guaranteed not to be blank
 2351: 	# if this subroutine has been called once.
 2352: 	if ($env{'form.kwclr'} eq '' && $numessay) {
 2353: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2354: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2355: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2356: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2357: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2358: 	}
 2359: 	if ($env{'form.compmsg'}) {
 2360: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
 2361: 		$keyhash{$symb.'_subject'} : $probtitle;
 2362: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2363: 	}
 2364: 
 2365: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2366: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2367: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2368: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2369: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2370: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2371: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2372: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2373: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2374: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2375: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2376: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2377: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2378: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
 2379: 			&build_section_inputs().
 2380: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2381: 			'<input type="hidden" name="NCT"'.
 2382: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2383: 	if ($env{'form.compmsg'}) {
 2384: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2385: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2386: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2387: 	}
 2388: 	if ($numessay) {
 2389: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2390: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2391: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2392: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
 2393: 	}
 2394: 
 2395: 	my ($cts,$prnmsg) = (1,'');
 2396: 	while ($cts <= $env{'form.savemsgN'}) {
 2397: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2398: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2399: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2400: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2401: 		'" />'."\n".
 2402: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2403: 	    $cts++;
 2404: 	}
 2405: 	$request->print($prnmsg);
 2406: 
 2407: 	if ($numessay) {
 2408: 
 2409:             my %lt = &Apache::lonlocal::texthash(
 2410:                           keyh => 'Keyword Highlighting for Essays',
 2411:                           keyw => 'Keyword Options',
 2412:                           list => 'List',
 2413:                           past => 'Paste Selection to List',
 2414:                           high => 'Highlight Attribute',
 2415:                      );
 2416: #
 2417: # Print out the keyword options line
 2418: #
 2419: 	    $request->print(
 2420:                 '<div class="LC_columnSection">'
 2421:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2422:                .&Apache::lonhtmlcommon::funclist_from_array(
 2423:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2424:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2425:  class="page">'.$lt{'past'}.'</a>',
 2426:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2427:                     {legend => $lt{'keyw'}})
 2428:                .'</fieldset></div>'
 2429:             );
 2430: 
 2431: #
 2432: # Load the other essays for similarity check
 2433: #
 2434:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2435:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2436:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2437:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2438:                 if ($cdom ne '' && $cnum ne '') {
 2439:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
 2440:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
 2441:                         my $apath = $1.'_'.$id;
 2442:                         $apath=~s/\W/\_/gs;
 2443:                         &init_old_essays($symb,$apath,$cdom,$cnum);
 2444:                     }
 2445:                 }
 2446:             } else {
 2447: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2448: 	        $apath=&escape($apath);
 2449: 	        $apath=~s/\W/\_/gs;
 2450:                 &init_old_essays($symb,$apath,$adom,$aname);
 2451:             }
 2452:         }
 2453:     }
 2454: 
 2455: # This is where output for one specific student would start
 2456:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2457:     $request->print(
 2458:         "\n\n"
 2459:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2460:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2461:        ."\n"
 2462:     );
 2463: 
 2464:     # Show additional functions if allowed
 2465:     if ($perm{'vgr'}) {
 2466:         $request->print(
 2467:             &Apache::loncommon::track_student_link(
 2468:                 'View recent activity',
 2469:                 $uname,$udom,'check')
 2470:            .' '
 2471:         );
 2472:     }
 2473:     if ($perm{'opa'}) {
 2474:         $request->print(
 2475:             &Apache::loncommon::pprmlink(
 2476:                 &mt('Set/Change parameters'),
 2477:                 $uname,$udom,$symb,'check'));
 2478:     }
 2479: 
 2480:     # Show Problem
 2481:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2482: 	my $mode;
 2483: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2484: 	    $mode='both';
 2485: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2486: 	    $mode='text';
 2487: 	} elsif ($env{'form.vAns'} eq 'all') {
 2488: 	    $mode='answer';
 2489: 	}
 2490: 	&Apache::lonxml::clear_problem_counter();
 2491: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2492:     }
 2493: 
 2494:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2495: 
 2496:     # Display student info
 2497:     $request->print(($counter == 0 ? '' : '<br />'));
 2498: 
 2499:     my $result='<div class="LC_Box">'
 2500:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2501:     $result.='<input type="hidden" name="name'.$counter.
 2502:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2503:     if ($numresp > $numessay) {
 2504:         $result.='<p class="LC_info">'
 2505:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2506:                 ."</p>\n";
 2507:     }
 2508: 
 2509:     # If any part of the problem is an essayresponse, then check for collaborators
 2510:     my $fullname;
 2511:     my $col_fullnames = [];
 2512:     if ($numessay) {
 2513: 	(my $sub_result,$fullname,$col_fullnames)=
 2514: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2515: 				 $counter);
 2516: 	$result.=$sub_result;
 2517:     }
 2518:     $request->print($result."\n");
 2519: 
 2520:     # print student answer/submission
 2521:     # Options are (1) Last submission only
 2522:     #             (2) Last submission (with detailed information for that submission)
 2523:     #             (3) All transactions (by date)
 2524:     #             (4) The whole record (with detailed information for all transactions)
 2525: 
 2526:     my ($string,$timestamp,$lastgradetime,$lastsubmittime) =
 2527:         &get_last_submission(\%record);
 2528: 
 2529:     my $lastsubonly;
 2530: 
 2531:     if ($timestamp eq '') {
 2532:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>'; 
 2533:     } else {
 2534:         my ($shownsubmdate,$showngradedate);
 2535:         if ($lastsubmittime && $lastgradetime) {
 2536:             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
 2537:             if ($lastgradetime > $lastsubmittime) {
 2538:                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
 2539:              }
 2540:         } else {
 2541:             $shownsubmdate = $timestamp;
 2542:         }
 2543:         $lastsubonly =
 2544:             '<div class="LC_grade_submissions_body">'
 2545:            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
 2546:         if ($showngradedate) {
 2547:             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
 2548:         }
 2549: 
 2550: 	my %seenparts;
 2551: 	my @part_response_id = &flatten_responseType($responseType);
 2552: 	foreach my $part (@part_response_id) {
 2553: 	    my ($partid,$respid) = @{ $part };
 2554: 	    my $display_part=&get_display_part($partid,$symb);
 2555: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2556: 		if (exists($seenparts{$partid})) { next; }
 2557: 		$seenparts{$partid}=1;
 2558:                 $request->print(
 2559:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2560:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2561:                                '<a href="javascript:viewSubmitter(\''.
 2562:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2563:                                '\');" target="_self">'.
 2564:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2565:                     '<br />');
 2566: 		next;
 2567: 	    }
 2568: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2569: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2570:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2571:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2572:                     ' <span class="LC_internal_info">'.
 2573:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2574:                     '</span>&nbsp; &nbsp;'.
 2575: 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2576: 		next;
 2577: 	    }
 2578: 	    foreach my $submission (@$string) {
 2579: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2580: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2581: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2582: 		# Similarity check
 2583:                 my $similar='';
 2584:                 my ($type,$trial,$rndseed);
 2585:                 if ($hide eq 'rand') {
 2586:                     $type = 'randomizetry';
 2587:                     $trial = $record{"resource.$partid.tries"};
 2588:                     $rndseed = $record{"resource.$partid.rndseed"};
 2589:                 }
 2590: 		if ($env{'form.checkPlag'}) {
 2591: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2592: 		        &most_similar($uname,$udom,$symb,$subval);
 2593: 		    if ($osim) {
 2594: 		        $osim=int($osim*100.0);
 2595:                         if ($hide eq 'anon') {
 2596:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2597:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2598:                         } else {
 2599: 			    $similar='<hr />';
 2600:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
 2601:                                 $similar .= '<h3><span class="LC_warning">'.
 2602:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
 2603:                                                 $osim,
 2604:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2605:                                             '</span></h3>';
 2606:                             } elsif ($ocrsid ne '') {
 2607:                                 my %old_course_desc;
 2608:                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
 2609:                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
 2610:                                 } else {
 2611:                                     my $args;
 2612:                                     if ($ocrsid ne $env{'request.course.id'}) {
 2613:                                         $args = {'one_time' => 1};
 2614:                                     }
 2615:                                     %old_course_desc =
 2616:                                         &Apache::lonnet::coursedescription($ocrsid,$args);
 2617:                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
 2618:                                 }
 2619:                                 $similar .=
 2620:                                     '<h3><span class="LC_warning">'.
 2621: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2622: 				        $osim,
 2623: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2624: 				        $old_course_desc{'description'},
 2625: 				        $old_course_desc{'num'},
 2626: 				        $old_course_desc{'domain'}).
 2627: 				    '</span></h3>';
 2628:                             } else {
 2629:                                 $similar .=
 2630:                                     '<h3><span class="LC_warning">'.
 2631:                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
 2632:                                         $osim,
 2633:                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
 2634:                                     '</span></h3>';
 2635:                             }
 2636:                             $similar .= '<blockquote><i>'.
 2637:                                         &keywords_highlight($oessay).
 2638:                                         '</i></blockquote><hr />';
 2639: 		        }
 2640:                     }
 2641:                 }
 2642: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2643:                                      undef,$type,$trial,$rndseed);
 2644:                 if (($env{'form.lastSub'} eq 'lastonly') ||
 2645:                     ($env{'form.lastSub'} eq 'datesub')  ||
 2646:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
 2647: 		    my $display_part=&get_display_part($partid,$symb);
 2648:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2649:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2650:                         ' <span class="LC_internal_info">'.
 2651:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2652:                         '</span>&nbsp; &nbsp;';
 2653: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2654: 		    if (@$files) {
 2655:                         if ($hide eq 'anon') {
 2656:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2657:                         } else {
 2658:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2659:                                          .'<br /><span class="LC_warning">';
 2660:                             if(@$files == 1) {
 2661:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2662:                             } else {
 2663:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2664:                             }
 2665:                             $lastsubonly .= '</span>';
 2666:                             foreach my $file (@$files) {
 2667:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2668:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2669:                             }
 2670:                         }
 2671: 			$lastsubonly.='<br />';
 2672: 		    }
 2673:                     if ($hide eq 'anon') {
 2674:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2675:                     } else {
 2676:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2677:                         if ($draft) {
 2678:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2679:                         }
 2680:                         $subval =
 2681: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2682: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2683:                         if ($responsetype eq 'essay') {
 2684:                             $subval =~ s{\n}{<br />}g;
 2685:                         }
 2686:                         $lastsubonly.=$subval."\n";
 2687:                     }
 2688:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2689: 		    $lastsubonly.='</div>';
 2690: 		}
 2691: 	    }
 2692: 	}
 2693: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2694:     }
 2695:     $request->print($lastsubonly);
 2696:     if ($env{'form.lastSub'} eq 'datesub') {
 2697:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2698: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2699:     }
 2700:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2701:         my $identifier = (&canmodify($usec)? $counter : '');
 2702: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2703: 								 $env{'request.course.id'},
 2704: 								 $last,'.submission',
 2705: 								 'Apache::grades::keywords_highlight',
 2706:                                                                  $usec,$identifier));
 2707:     }
 2708:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2709: 	.$udom.'" />'."\n");
 2710:     # return if view submission with no grading option
 2711:     if (!&canmodify($usec)) {
 2712:         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2713:         return;
 2714:     } else {
 2715: 	$request->print('</div>'."\n");
 2716:     }
 2717: 
 2718:     # grading message center
 2719: 
 2720:     if ($env{'form.compmsg'}) {
 2721:         my $result='<div class="LC_Box">'.
 2722:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
 2723:                    '<div class="LC_grade_message_center_body">';
 2724:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2725:         my $msgfor = $givenn.' '.$lastname;
 2726:         if (scalar(@$col_fullnames) > 0) {
 2727:             my $lastone = pop(@$col_fullnames);
 2728:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2729:         }
 2730:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2731:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2732:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
 2733: 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2734:                  ',\''.$msgfor.'\');" target="_self">'.
 2735:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2736:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2737:                  ' <img src="'.$request->dir_config('lonIconsURL').
 2738:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2739:                  '<br />&nbsp;('.
 2740:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
 2741: 	         '</div></div>';
 2742:         $request->print($result);
 2743:     }
 2744: 
 2745:     my %seen = ();
 2746:     my @partlist;
 2747:     my @gradePartRespid;
 2748:     my @part_response_id = &flatten_responseType($responseType);
 2749:     $request->print(
 2750:         '<div class="LC_Box">'
 2751:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2752:     );
 2753:     $request->print(&gradeBox_start());
 2754:     foreach my $part_response_id (@part_response_id) {
 2755:     	my ($partid,$respid) = @{ $part_response_id };
 2756: 	my $part_resp = join('_',@{ $part_response_id });
 2757: 	next if ($seen{$partid} > 0);
 2758: 	$seen{$partid}++;
 2759: 	push(@partlist,$partid);
 2760: 	push(@gradePartRespid,$partid.'.'.$respid);
 2761: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2762:     }
 2763:     $request->print(&gradeBox_end()); # </div>
 2764:     $request->print('</div>');
 2765: 
 2766:     $request->print('<div class="LC_grade_info_links">');
 2767:     $request->print('</div>');
 2768: 
 2769:     $result='<input type="hidden" name="partlist'.$counter.
 2770: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2771:     $result.='<input type="hidden" name="gradePartRespid'.
 2772: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2773:     my $ctr = 0;
 2774:     while ($ctr < scalar(@partlist)) {
 2775: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2776: 	    $partlist[$ctr].'" />'."\n";
 2777: 	$ctr++;
 2778:     }
 2779:     $request->print($result.''."\n");
 2780: 
 2781: # Done with printing info for one student
 2782: 
 2783:     $request->print('</div>');#LC_grade_show_user
 2784: 
 2785: 
 2786:     # print end of form
 2787:     if ($counter == $total) {
 2788:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2789: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2790: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2791: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2792: 	my $ntstu ='<select name="NTSTU">'.
 2793: 	    '<option>1</option><option>2</option>'.
 2794: 	    '<option>3</option><option>5</option>'.
 2795: 	    '<option>7</option><option>10</option></select>'."\n";
 2796: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2797: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2798:         $endform.=&mt('[_1]student(s)',$ntstu);
 2799: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2800: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2801: 	    '<input type="button" value="'.&mt('Next').'" '.
 2802: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2803:         $endform.='<span class="LC_warning">'.
 2804:                   &mt('(Next and Previous (student) do not save the scores.)').
 2805:                   '</span>'."\n" ;
 2806:         $endform.="<input type='hidden' value='".&get_increment().
 2807:             "' name='increment' />";
 2808: 	$endform.='</td></tr></table></form>';
 2809: 	$request->print($endform);
 2810:     }
 2811:     return '';
 2812: }
 2813: 
 2814: sub check_collaborators {
 2815:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2816:     my ($result,@col_fullnames);
 2817:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2818:     foreach my $part (keys(%$handgrade)) {
 2819: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2820: 					'.maxcollaborators',
 2821: 					$symb,$udom,$uname);
 2822: 	next if ($ncol <= 0);
 2823: 	$part =~ s/\_/\./g;
 2824: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2825: 	my (@good_collaborators, @bad_collaborators);
 2826: 	foreach my $possible_collaborator
 2827: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2828: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2829: 	    next if ($possible_collaborator eq '');
 2830: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2831: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2832: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2833: 	    # Doing this grep allows 'fuzzy' specification
 2834: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2835: 			       keys(%$classlist));
 2836: 	    if (! scalar(@matches)) {
 2837: 		push(@bad_collaborators, $possible_collaborator);
 2838: 	    } else {
 2839: 		push(@good_collaborators, @matches);
 2840: 	    }
 2841: 	}
 2842: 	if (scalar(@good_collaborators) != 0) {
 2843: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2844: 	    foreach my $name (@good_collaborators) {
 2845: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2846: 		push(@col_fullnames, $givenn.' '.$lastname);
 2847: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2848: 	    }
 2849: 	    $result.='</ol><br />'."\n";
 2850: 	    my ($part)=split(/\./,$part);
 2851: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2852: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2853: 		"\n";
 2854: 	}
 2855: 	if (scalar(@bad_collaborators) > 0) {
 2856: 	    $result.='<div class="LC_warning">';
 2857: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2858: 	    $result .= '</div>';
 2859: 	}         
 2860: 	if (scalar(@bad_collaborators > $ncol)) {
 2861: 	    $result .= '<div class="LC_warning">';
 2862: 	    $result .= &mt('This student has submitted too many '.
 2863: 		'collaborators.  Maximum is [_1].',$ncol);
 2864: 	    $result .= '</div>';
 2865: 	}
 2866:     }
 2867:     return ($result,$fullname,\@col_fullnames);
 2868: }
 2869: 
 2870: #--- Retrieve the last submission for all the parts
 2871: sub get_last_submission {
 2872:     my ($returnhash)=@_;
 2873:     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
 2874:     if ($$returnhash{'version'}) {
 2875: 	my %lasthash=();
 2876:         my %prevsolved=();
 2877:         my %solved=();
 2878: 	my $version;
 2879: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2880:             my %handgraded = ();
 2881: 	    foreach my $key (sort(split(/\:/,
 2882: 					$$returnhash{$version.':keys'}))) {
 2883: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2884:                 if ($key =~ /\.([^.]+)\.regrader$/) {
 2885:                     $handgraded{$1} = 1;
 2886:                 } elsif ($key =~ /\.portfiles$/) {
 2887:                     if (($$returnhash{$version.':'.$key} ne '') &&
 2888:                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
 2889:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2890:                     }
 2891:                 } elsif ($key =~ /\.submission$/) {
 2892:                     if ($$returnhash{$version.':'.$key} ne '') {
 2893:                         $lastsubmittime = $$returnhash{$version.':timestamp'};
 2894:                     }
 2895:                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
 2896:                     $prevsolved{$1} = $solved{$1};
 2897:                     $solved{$1} = $lasthash{$key};
 2898:                 }
 2899: 	    }
 2900:             foreach my $partid (keys(%handgraded)) {
 2901:                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
 2902:                     (($solved{$partid} eq 'incorrect_by_override') ||
 2903:                      ($solved{$partid} eq 'correct_by_override'))) {
 2904:                     $lastgradetime = $$returnhash{$version.':timestamp'};
 2905:                 }
 2906:                 if ($solved{$partid} ne '') {
 2907:                     $prevsolved{$partid} = $solved{$partid};
 2908:                 }
 2909:             }
 2910: 	}
 2911: #
 2912: # Timestamp is for last transaction for this resource, which does not
 2913: # necessarily correspond to the time of last submission for problem (or part).
 2914: #
 2915:         if ($lasthash{'timestamp'} ne '') {
 2916:             $timestamp = &Apache::lonlocal::locallocaltime($lasthash{'timestamp'});
 2917:         }
 2918:         my (%typeparts,%randombytry);
 2919:         my $showsurv = 
 2920:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2921:         foreach my $key (sort(keys(%lasthash))) {
 2922:             if ($key =~ /\.type$/) {
 2923:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2924:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2925:                     ($lasthash{$key} eq 'randomizetry')) {
 2926:                     my ($ign,@parts) = split(/\./,$key);
 2927:                     pop(@parts);
 2928:                     my $id = join('.',@parts);
 2929:                     if ($lasthash{$key} eq 'randomizetry') {
 2930:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2931:                     } else {
 2932:                         unless ($showsurv) {
 2933:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2934:                         }
 2935:                     }
 2936:                     delete($lasthash{$key});
 2937:                 }
 2938:             }
 2939:         }
 2940:         my @hidden = keys(%typeparts);
 2941:         my @randomize = keys(%randombytry);
 2942: 	foreach my $key (keys(%lasthash)) {
 2943: 	    next if ($key !~ /\.submission$/);
 2944:             my $hide;
 2945:             if (@hidden) {
 2946:                 foreach my $id (@hidden) {
 2947:                     if ($key =~ /^\Q$id\E/) {
 2948:                         $hide = 'anon';
 2949:                         last;
 2950:                     }
 2951:                 }
 2952:             }
 2953:             unless ($hide) {
 2954:                 if (@randomize) {
 2955:                     foreach my $id (@randomize) {
 2956:                         if ($key =~ /^\Q$id\E/) {
 2957:                             $hide = 'rand';
 2958:                             last;
 2959:                         }
 2960:                     }
 2961:                 }
 2962:             }
 2963: 	    my ($partid,$foo) = split(/submission$/,$key);
 2964: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2965:             push(@string, join(':', $key, $hide, $draft, (
 2966:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2967:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2968: 	}
 2969:     }
 2970:     if (!@string) {
 2971: 	$string[0] =
 2972: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2973:     }
 2974:     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
 2975: }
 2976: 
 2977: #--- High light keywords, with style choosen by user.
 2978: sub keywords_highlight {
 2979:     my $string    = shift;
 2980:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2981:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2982:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2983:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2984:     foreach my $keyword (@keylist) {
 2985: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2986:     }
 2987:     return $string;
 2988: }
 2989: 
 2990: # For Tasks provide a mechanism to display previous version for one specific student
 2991: 
 2992: sub show_previous_task_version {
 2993:     my ($request,$symb) = @_;
 2994:     if ($symb eq '') {
 2995:         $request->print(
 2996:             '<span class="LC_error">'.
 2997:             &mt('Unable to handle ambiguous references.').
 2998:             '</span>');
 2999:         return '';
 3000:     }
 3001:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 3002:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 3003:     if (!&canview($usec)) {
 3004:         $request->print('<span class="LC_warning">'.
 3005:                         &mt('Unable to view previous version for requested student.').
 3006:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 3007:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 3008:                         '</span>');
 3009:         return;
 3010:     }
 3011:     my $mode = 'both';
 3012:     my $isTask = ($symb =~/\.task$/);
 3013:     if ($isTask) {
 3014:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 3015:             if ($env{'form.fullname'} eq '') {
 3016:                 $env{'form.fullname'} =
 3017:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 3018:             }
 3019:             my $probtitle=&Apache::lonnet::gettitle($symb);
 3020:             $request->print("\n\n".
 3021:                             '<div class="LC_grade_show_user">'.
 3022:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3023:                             '</h2>'."\n");
 3024:             &Apache::lonxml::clear_problem_counter();
 3025:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 3026:                             {'previousversion' => $env{'form.previousversion'} }));
 3027:             $request->print("\n</div>");
 3028:         }
 3029:     }
 3030:     return;
 3031: }
 3032: 
 3033: sub choose_task_version_form {
 3034:     my ($symb,$uname,$udom,$nomenu) = @_;
 3035:     my $isTask = ($symb =~/\.task$/);
 3036:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 3037:     if ($isTask) {
 3038:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3039:                                               $udom,$uname);
 3040:         if (($record{'resource.0.version'} eq '') ||
 3041:             ($record{'resource.0.version'} < 2)) {
 3042:             return ($record{'resource.0.version'},
 3043:                     $record{'resource.0.version'},$result,$js);
 3044:         } else {
 3045:             $current = $record{'resource.0.version'};
 3046:         }
 3047:         if ($env{'form.previousversion'}) {
 3048:             $displayed = $env{'form.previousversion'};
 3049:             $rowtitle = &mt('Choose another version:')
 3050:         } else {
 3051:             $displayed = $current;
 3052:             $rowtitle = &mt('Show earlier version:');
 3053:         }
 3054:         $result = '<div class="LC_left_float">';
 3055:         my $list;
 3056:         my $numversions = 0;
 3057:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 3058:             if ($i == $current) {
 3059:                 if (!$env{'form.previousversion'} || $nomenu) {
 3060:                     next;
 3061:                 } else {
 3062:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 3063:                     $numversions ++;
 3064:                 }
 3065:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 3066:                 unless ($i == $env{'form.previousversion'}) {
 3067:                     $numversions ++;
 3068:                 }
 3069:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 3070:             }
 3071:         }
 3072:         if ($numversions) {
 3073:             $symb = &HTML::Entities::encode($symb,'<>"&');
 3074:             $result .=
 3075:                 '<form name="getprev" method="post" action=""'.
 3076:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 3077:                 &Apache::loncommon::start_data_table().
 3078:                 &Apache::loncommon::start_data_table_row().
 3079:                 '<th align="left">'.$rowtitle.'</th>'.
 3080:                 '<td><select name="version">'.
 3081:                 '<option>'.&mt('Select').'</option>'.
 3082:                 $list.
 3083:                 '</select></td>'.
 3084:                 &Apache::loncommon::end_data_table_row();
 3085:             unless ($nomenu) {
 3086:                 $result .= &Apache::loncommon::start_data_table_row().
 3087:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 3088:                 '<td><span class="LC_nobreak">'.
 3089:                 '<label><input type="radio" name="prevwin" value="1" />'.
 3090:                 &mt('Yes').'</label>'.
 3091:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 3092:                 '</span></td>'.
 3093:                 &Apache::loncommon::end_data_table_row();
 3094:             }
 3095:             $result .=
 3096:                 &Apache::loncommon::start_data_table_row().
 3097:                 '<th align="left">&nbsp;</th>'.
 3098:                 '<td>'.
 3099:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 3100:                 '</td>'.
 3101:                 &Apache::loncommon::end_data_table_row().
 3102:                 &Apache::loncommon::end_data_table().
 3103:                 '</form>';
 3104:             $js = &previous_display_javascript($nomenu,$current);
 3105:         } elsif ($displayed && $nomenu) {
 3106:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 3107:         } else {
 3108:             $result .= &mt('No previous versions to show for this student');
 3109:         }
 3110:         $result .= '</div>';
 3111:     }
 3112:     return ($current,$displayed,$result,$js);
 3113: }
 3114: 
 3115: sub previous_display_javascript {
 3116:     my ($nomenu,$current) = @_;
 3117:     my $js = <<"JSONE";
 3118: <script type="text/javascript">
 3119: // <![CDATA[
 3120: function previousVersion(uname,udom,symb) {
 3121:     var current = '$current';
 3122:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 3123:     var prevstr = new RegExp("^\\\\d+\$");
 3124:     if (!prevstr.test(version)) {
 3125:         return false;
 3126:     }
 3127:     var url = '';
 3128:     if (version == current) {
 3129:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 3130:     } else {
 3131:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 3132:     }
 3133: JSONE
 3134:     if ($nomenu) {
 3135:         $js .= <<"JSTWO";
 3136:     document.location.href = url;
 3137: JSTWO
 3138:     } else {
 3139:         $js .= <<"JSTHREE";
 3140:     var newwin = 0;
 3141:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 3142:         if (document.getprev.prevwin[i].checked == true) {
 3143:             newwin = document.getprev.prevwin[i].value;
 3144:         }
 3145:     }
 3146:     if (newwin == 1) {
 3147:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 3148:         url = url+'&inhibitmenu=yes';
 3149:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 3150:             previousWin = window.open(url,'',options,1);
 3151:         } else {
 3152:             previousWin.location.href = url;
 3153:         }
 3154:         previousWin.focus();
 3155:         return false;
 3156:     } else {
 3157:         document.location.href = url;
 3158:         return false;
 3159:     }
 3160: JSTHREE
 3161:     }
 3162:     $js .= <<"ENDJS";
 3163:     return false;
 3164: }
 3165: // ]]>
 3166: </script>
 3167: ENDJS
 3168: 
 3169: }
 3170: 
 3171: #--- Called from submission routine
 3172: sub processHandGrade {
 3173:     my ($request,$symb) = @_;
 3174:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3175:     my $button = $env{'form.gradeOpt'};
 3176:     my $ngrade = $env{'form.NCT'};
 3177:     my $ntstu  = $env{'form.NTSTU'};
 3178:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3179:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 3180:     my ($res_error,%queueable);
 3181:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
 3182:     if ($res_error) {
 3183:         $request->print(&navmap_errormsg());
 3184:         return;
 3185:     } else {
 3186:         foreach my $part (@{$partlist}) {
 3187:             if (ref($responseType->{$part}) eq 'HASH') {
 3188:                 foreach my $id (keys(%{$responseType->{$part}})) {
 3189:                     if (($responseType->{$part}->{$id} eq 'essay') ||
 3190:                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
 3191:                         $queueable{$part} = 1;
 3192:                         last;
 3193:                     }
 3194:                 }
 3195:             }
 3196:         }
 3197:     }
 3198: 
 3199:     if ($button eq 'Save & Next') {
 3200: 	my $ctr = 0;
 3201: 	while ($ctr < $ngrade) {
 3202: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 3203: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 3204:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
 3205: 	    if ($errorflag eq 'no_score') {
 3206: 		$ctr++;
 3207: 		next;
 3208: 	    }
 3209: 	    if ($errorflag eq 'not_allowed') {
 3210:                 $request->print(
 3211:                     '<span class="LC_error">'
 3212:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 3213:                    .'</span>');
 3214: 		$ctr++;
 3215: 		next;
 3216: 	    }
 3217:             if ($numhidden) {
 3218:                 $request->print(
 3219:                     '<span class="LC_info">'
 3220:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 3221:                    .'</span><br />');
 3222:             }
 3223: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 3224: 	    my ($subject,$message,$msgstatus) = ('','','');
 3225: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 3226:             my ($feedurl,$showsymb) =
 3227: 		&get_feedurl_and_symb($symb,$uname,$udom);
 3228: 	    my $messagetail;
 3229: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 3230: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 3231: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 3232: 		$subject.=' ['.$restitle.']';
 3233: 		my (@msgnum) = split(/,/,$includemsg);
 3234: 		foreach (@msgnum) {
 3235: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 3236: 		}
 3237: 		$message =&Apache::lonfeedback::clear_out_html($message);
 3238: 		if ($env{'form.withgrades'.$ctr}) {
 3239: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 3240: 		    $messagetail = " for <a href=\"".
 3241: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 3242: 		}
 3243: 		$msgstatus = 
 3244:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 3245: 						     $message.$messagetail,
 3246:                                                      undef,$feedurl,undef,
 3247:                                                      undef,undef,$showsymb,
 3248:                                                      $restitle);
 3249: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3250: 				$msgstatus.'<br />');
 3251: 	    }
 3252: 	    if ($env{'form.collaborator'.$ctr}) {
 3253: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3254: 		foreach my $collabstr (@collabstrs) {
 3255: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3256: 		    foreach my $collaborator (@collaborators) {
 3257: 			my ($errorflag,$pts,$wgt) = 
 3258: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3259: 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
 3260: 			if ($errorflag eq 'not_allowed') {
 3261: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3262: 			    next;
 3263: 			} elsif ($message ne '') {
 3264: 			    my ($baseurl,$showsymb) = 
 3265: 				&get_feedurl_and_symb($symb,$collaborator,
 3266: 						      $udom);
 3267: 			    if ($env{'form.withgrades'.$ctr}) {
 3268: 				$messagetail = " for <a href=\"".
 3269:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3270: 			    }
 3271: 			    $msgstatus = 
 3272: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3273: 			}
 3274: 		    }
 3275: 		}
 3276: 	    }
 3277: 	    $ctr++;
 3278: 	}
 3279:     }
 3280: 
 3281:     my %keyhash = ();
 3282:     if ($numessay) {
 3283: 	# Keywords sorted in alphabatical order
 3284: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3285: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3286: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
 3287: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3288: 	$env{'form.keywords'} = join(' ',@keywords);
 3289: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3290: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3291: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3292: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3293: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3294:     }
 3295: 
 3296:     if ($env{'form.compmsg'}) {
 3297: 	# message center - Order of message gets changed. Blank line is eliminated.
 3298: 	# New messages are saved in env for the next student.
 3299: 	# All messages are saved in nohist_handgrade.db
 3300: 	my ($ctr,$idx) = (1,1);
 3301: 	while ($ctr <= $env{'form.savemsgN'}) {
 3302: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3303: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3304: 		$idx++;
 3305: 	    }
 3306: 	    $ctr++;
 3307: 	}
 3308: 	$ctr = 0;
 3309: 	while ($ctr < $ngrade) {
 3310: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3311: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3312: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3313: 		$idx++;
 3314: 	    }
 3315: 	    $ctr++;
 3316: 	}
 3317: 	$env{'form.savemsgN'} = --$idx;
 3318: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3319:     }
 3320:     if (($numessay) || ($env{'form.compmsg'})) {
 3321: 	my $putresult = &Apache::lonnet::put
 3322: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3323:     }
 3324: 
 3325:     # Called by Save & Refresh from Highlight Attribute Window
 3326:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3327:     if ($env{'form.refresh'} eq 'on') {
 3328: 	my ($ctr,$total) = (0,0);
 3329: 	while ($ctr < $ngrade) {
 3330: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3331: 	    $ctr++;
 3332: 	}
 3333: 	$env{'form.NTSTU'}=$ngrade;
 3334: 	$ctr = 0;
 3335: 	while ($ctr < $total) {
 3336: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3337: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3338: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3339: 	    &submission($request,$ctr,$total-1,$symb);
 3340: 	    $ctr++;
 3341: 	}
 3342: 	return '';
 3343:     }
 3344: 
 3345:     # Get the next/previous one or group of students
 3346:     my $firststu = $env{'form.unamedom0'};
 3347:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3348:     my $ctr = 2;
 3349:     while ($laststu eq '') {
 3350: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3351: 	$ctr++;
 3352: 	$laststu = $firststu if ($ctr > $ngrade);
 3353:     }
 3354: 
 3355:     my (@parsedlist,@nextlist);
 3356:     my ($nextflg) = 0;
 3357:     foreach my $item (sort 
 3358: 	     {
 3359: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3360: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3361: 		 }
 3362: 		 return $a cmp $b;
 3363: 	     } (keys(%$fullname))) {
 3364: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3365: 	    push(@parsedlist,$item);
 3366: 	}
 3367: 	$nextflg = 1 if ($item eq $laststu);
 3368: 	if ($button eq 'Previous') {
 3369: 	    last if ($item eq $firststu);
 3370: 	    push(@parsedlist,$item);
 3371: 	}
 3372:     }
 3373:     $ctr = 0;
 3374:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3375:     foreach my $student (@parsedlist) {
 3376: 	my $submitonly=$env{'form.submitonly'};
 3377: 	my ($uname,$udom) = split(/:/,$student);
 3378: 	
 3379: 	if ($submitonly eq 'queued') {
 3380: 	    my %queue_status = 
 3381: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3382: 							$udom,$uname);
 3383: 	    next if (!defined($queue_status{'gradingqueue'}));
 3384: 	}
 3385: 
 3386: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3387: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3388: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3389: 	    my $submitted = 0;
 3390: 	    my $ungraded = 0;
 3391: 	    my $incorrect = 0;
 3392: 	    foreach my $item (keys(%status)) {
 3393: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3394: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3395: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3396: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3397: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3398: 		    $submitted = 0;
 3399: 		}
 3400: 	    }
 3401: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3402: 				     $submitonly eq 'incorrect' ||
 3403: 				     $submitonly eq 'graded'));
 3404: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3405: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3406: 	}
 3407: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3408: 	last if ($ctr == $ntstu);
 3409: 	$ctr++;
 3410:     }
 3411: 
 3412:     $ctr = 0;
 3413:     my $total = scalar(@nextlist)-1;
 3414: 
 3415:     foreach (sort(@nextlist)) {
 3416: 	my ($uname,$udom,$submitter) = split(/:/);
 3417: 	$env{'form.student'}  = $uname;
 3418: 	$env{'form.userdom'}  = $udom;
 3419: 	$env{'form.fullname'} = $$fullname{$_};
 3420: 	&submission($request,$ctr,$total,$symb);
 3421: 	$ctr++;
 3422:     }
 3423:     if ($total < 0) {
 3424:         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3425: 	$request->print($the_end);
 3426:     }
 3427:     return '';
 3428: }
 3429: 
 3430: #---- Save the score and award for each student, if changed
 3431: sub saveHandGrade {
 3432:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
 3433:     my @version_parts;
 3434:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3435: 					   $env{'request.course.id'});
 3436:     if (!&canmodify($usec)) { return('not_allowed'); }
 3437:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3438:     my @parts_graded;
 3439:     my %newrecord  = ();
 3440:     my ($pts,$wgt,$totchg) = ('','',0);
 3441:     my %aggregate = ();
 3442:     my $aggregateflag = 0;
 3443:     if ($env{'form.HIDE'.$newflg}) {
 3444:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3445:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3446:         $totchg += $numchgs;
 3447:     }
 3448:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3449:     foreach my $new_part (@parts) {
 3450: 	#collaborator ($submi may vary for different parts
 3451: 	if ($submitter && $new_part ne $part) { next; }
 3452: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3453: 	if ($dropMenu eq 'excused') {
 3454: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3455: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3456: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3457: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3458: 		}
 3459: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3460: 	    }
 3461: 	} elsif ($dropMenu eq 'reset status'
 3462: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3463: 	    foreach my $key (keys(%record)) {
 3464: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3465: 	    }
 3466: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3467: 		"$env{'user.name'}:$env{'user.domain'}";
 3468:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3469: 
 3470:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3471: 					       [$new_part]);
 3472:             my $aggtries =$totaltries;
 3473:             if ($last_resets{$new_part}) {
 3474:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3475: 					   $new_part);
 3476:             }
 3477: 
 3478:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3479:             if ($aggtries > 0) {
 3480:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3481:                 $aggregateflag = 1;
 3482:             }
 3483: 	} elsif ($dropMenu eq '') {
 3484: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3485: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3486: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3487: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3488: 		next;
 3489: 	    }
 3490: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3491: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3492: 	    my $partial= $pts/$wgt;
 3493: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3494: 		#do not update score for part if not changed.
 3495:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3496: 		next;
 3497: 	    } else {
 3498: 	        push(@parts_graded,$new_part);
 3499: 	    }
 3500: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3501: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3502: 	    }
 3503: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3504: 	    if ($partial == 0) {
 3505: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3506: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3507: 		}
 3508: 	    } else {
 3509: 		if ($record{$reckey} ne 'correct_by_override') {
 3510: 		    $newrecord{$reckey} = 'correct_by_override';
 3511: 		}
 3512: 	    }	    
 3513: 	    if ($submitter && 
 3514: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3515: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3516: 	    }
 3517: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3518: 		"$env{'user.name'}:$env{'user.domain'}";
 3519: 	}
 3520: 	# unless problem has been graded, set flag to version the submitted files
 3521: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3522: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3523: 	        $dropMenu eq 'reset status')
 3524: 	   {
 3525: 	    push(@version_parts,$new_part);
 3526: 	}
 3527:     }
 3528:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3529:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3530: 
 3531:     if (%newrecord) {
 3532:         if (@version_parts) {
 3533:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3534:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3535: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3536: 	    foreach my $new_part (@version_parts) {
 3537: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3538: 				$new_part,\%newrecord);
 3539: 	    }
 3540:         }
 3541: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3542: 				$env{'request.course.id'},$domain,$stuname);
 3543: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3544: 				     $cdom,$cnum,$domain,$stuname,$queueable);
 3545:     }
 3546:     if ($aggregateflag) {
 3547:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3548: 			      $cdom,$cnum);
 3549:     }
 3550:     return ('',$pts,$wgt,$totchg);
 3551: }
 3552: 
 3553: sub makehidden {
 3554:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3555:     return unless (ref($record) eq 'HASH');
 3556:     my %modified;
 3557:     my $numchanged = 0;
 3558:     if (exists($record->{$version.':keys'})) {
 3559:         my $partsregexp = $parts;
 3560:         $partsregexp =~ s/,/|/g;
 3561:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3562:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3563:                  my $item = $1;
 3564:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3565:                      $modified{$key} = $record->{$version.':'.$key};
 3566:                  }
 3567:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3568:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3569:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3570:                 $modified{$key} = $record->{$version.':'.$key};
 3571:             }
 3572:         }
 3573:         if (keys(%modified)) {
 3574:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3575:                                           $domain,$stuname,$tolog) eq 'ok') {
 3576:                 $numchanged ++;
 3577:             }
 3578:         }
 3579:     }
 3580:     return $numchanged;
 3581: }
 3582: 
 3583: sub check_and_remove_from_queue {
 3584:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
 3585:     my @ungraded_parts;
 3586:     foreach my $part (@{$parts}) {
 3587: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3588: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3589: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3590: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3591: 		) {
 3592:             if ($queueable->{$part}) {
 3593: 	        push(@ungraded_parts, $part);
 3594:             }
 3595: 	}
 3596:     }
 3597:     if ( !@ungraded_parts ) {
 3598: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3599: 					       $cnum,$domain,$stuname);
 3600:     }
 3601: }
 3602: 
 3603: sub handback_files {
 3604:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3605:     my $portfolio_root = '/userfiles/portfolio';
 3606:     my $res_error;
 3607:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3608:     if ($res_error) {
 3609:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3610:         return;
 3611:     }
 3612:     my @handedback;
 3613:     my $file_msg;
 3614:     my @part_response_id = &flatten_responseType($responseType);
 3615:     foreach my $part_response_id (@part_response_id) {
 3616:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3617: 	my $part_resp = join('_',@{ $part_response_id });
 3618:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3619:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3620:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3621: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3622:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3623:                     my ($directory,$answer_file) = 
 3624:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3625:                     my ($answer_name,$answer_ver,$answer_ext) =
 3626: 		        &file_name_version_ext($answer_file);
 3627: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3628:                     my $getpropath = 1;
 3629:                     my ($dir_list,$listerror) =
 3630:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3631:                                                  $domain,$stuname,$getpropath);
 3632: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3633:                     # fix filename
 3634:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3635:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3636:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3637:             	                                $save_file_name);
 3638:                     if ($result !~ m|^/uploaded/|) {
 3639:                         $request->print('<br /><span class="LC_error">'.
 3640:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3641:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3642:                                         '</span>');
 3643:                     } else {
 3644:                         # mark the file as read only
 3645:                         push(@handedback,$save_file_name);
 3646: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3647: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3648: 			}
 3649:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3650: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3651: 
 3652:                     }
 3653:                     $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>'));
 3654:                 }
 3655:             }
 3656:         }
 3657:     }
 3658:     if (@handedback > 0) {
 3659:         $request->print('<br />');
 3660:         my @what = ($symb,$env{'request.course.id'},'handback');
 3661:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3662:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3663:         my ($subject,$message);
 3664:         if (scalar(@handedback) == 1) {
 3665:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3666:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3667:         } else {
 3668:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3669:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3670:         }
 3671:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3672:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3673:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3674:         my ($feedurl,$showsymb) =
 3675:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3676:         my $restitle = &Apache::lonnet::gettitle($symb);
 3677:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3678:         my $msgstatus =
 3679:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3680:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3681:                  $restitle);
 3682:         if ($msgstatus) {
 3683:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3684:         }
 3685:     }
 3686:     return;
 3687: }
 3688: 
 3689: sub get_feedurl_and_symb {
 3690:     my ($symb,$uname,$udom) = @_;
 3691:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3692:     $url = &Apache::lonnet::clutter($url);
 3693:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3694: 					$symb,$udom,$uname);
 3695:     if ($encrypturl =~ /^yes$/i) {
 3696: 	&Apache::lonenc::encrypted(\$url,1);
 3697: 	&Apache::lonenc::encrypted(\$symb,1);
 3698:     }
 3699:     return ($url,$symb);
 3700: }
 3701: 
 3702: sub get_submitted_files {
 3703:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3704:     my @files;
 3705:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3706:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3707:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3708:     	    push(@files,$file_url.$file);
 3709:         }
 3710:     }
 3711:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3712:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3713:     }
 3714:     return (\@files);
 3715: }
 3716: 
 3717: # ----------- Provides number of tries since last reset.
 3718: sub get_num_tries {
 3719:     my ($record,$last_reset,$part) = @_;
 3720:     my $timestamp = '';
 3721:     my $num_tries = 0;
 3722:     if ($$record{'version'}) {
 3723:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3724:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3725:                 $timestamp = $$record{$version.':timestamp'};
 3726:                 if ($timestamp > $last_reset) {
 3727:                     $num_tries ++;
 3728:                 } else {
 3729:                     last;
 3730:                 }
 3731:             }
 3732:         }
 3733:     }
 3734:     return $num_tries;
 3735: }
 3736: 
 3737: # ----------- Determine decrements required in aggregate totals 
 3738: sub decrement_aggs {
 3739:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3740:     my %decrement = (
 3741:                         attempts => 0,
 3742:                         users => 0,
 3743:                         correct => 0
 3744:                     );
 3745:     $decrement{'attempts'} = $aggtries;
 3746:     if ($solvedstatus =~ /^correct/) {
 3747:         $decrement{'correct'} = 1;
 3748:     }
 3749:     if ($aggtries == $totaltries) {
 3750:         $decrement{'users'} = 1;
 3751:     }
 3752:     foreach my $type (keys(%decrement)) {
 3753:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3754:     }
 3755:     return;
 3756: }
 3757: 
 3758: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3759: sub get_last_resets {
 3760:     my ($symb,$courseid,$partids) =@_;
 3761:     my %last_resets;
 3762:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3763:     my $cname = $env{'course.'.$courseid.'.num'};
 3764:     my @keys;
 3765:     foreach my $part (@{$partids}) {
 3766: 	push(@keys,"$symb\0$part\0resettime");
 3767:     }
 3768:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3769: 				     $cdom,$cname);
 3770:     foreach my $part (@{$partids}) {
 3771: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3772:     }
 3773:     return %last_resets;
 3774: }
 3775: 
 3776: # ----------- Handles creating versions for portfolio files as answers
 3777: sub version_portfiles {
 3778:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3779:     my $version_parts = join('|',@$v_flag);
 3780:     my @returned_keys;
 3781:     my $parts = join('|', @$parts_graded);
 3782:     my $portfolio_root = '/userfiles/portfolio';
 3783:     foreach my $key (keys(%$record)) {
 3784:         my $new_portfiles;
 3785:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3786:             my @versioned_portfiles;
 3787:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3788:             foreach my $file (@portfiles) {
 3789:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3790:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3791: 		my ($answer_name,$answer_ver,$answer_ext) =
 3792: 		    &file_name_version_ext($answer_file);
 3793:                 my $getpropath = 1;
 3794:                 my ($dir_list,$listerror) =
 3795:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3796:                                              $stu_name,$getpropath);
 3797:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3798:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3799:                 if ($new_answer ne 'problem getting file') {
 3800:                     push(@versioned_portfiles, $directory.$new_answer);
 3801:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3802:                         [$directory.$new_answer],
 3803:                         [$symb,$env{'request.course.id'},'graded']);
 3804:                 }
 3805:             }
 3806:             $$record{$key} = join(',',@versioned_portfiles);
 3807:             push(@returned_keys,$key);
 3808:         }
 3809:     }
 3810:     return (@returned_keys);
 3811: }
 3812: 
 3813: sub get_next_version {
 3814:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3815:     my $version;
 3816:     if (ref($dir_list) eq 'ARRAY') {
 3817:         foreach my $row (@{$dir_list}) {
 3818:             my ($file) = split(/\&/,$row,2);
 3819:             my ($file_name,$file_version,$file_ext) =
 3820: 	        &file_name_version_ext($file);
 3821:             if (($file_name eq $answer_name) && 
 3822: 	        ($file_ext eq $answer_ext)) {
 3823:                 # gets here if filename and extension match, 
 3824:                 # regardless of version
 3825:                 if ($file_version ne '') {
 3826:                     # a versioned file is found  so save it for later
 3827:                     if ($file_version > $version) {
 3828: 		        $version = $file_version;
 3829:                     }
 3830: 	        }
 3831:             }
 3832:         }
 3833:     }
 3834:     $version ++;
 3835:     return($version);
 3836: }
 3837: 
 3838: sub version_selected_portfile {
 3839:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3840:     my ($answer_name,$answer_ver,$answer_ext) =
 3841:         &file_name_version_ext($file_name);
 3842:     my $new_answer;
 3843:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3844:     if($env{'form.copy'} eq '-1') {
 3845:         $new_answer = 'problem getting file';
 3846:     } else {
 3847:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3848:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3849:                             $stu_name,$domain,'copy',
 3850: 		        '/portfolio'.$directory.$new_answer);
 3851:     }    
 3852:     return ($new_answer);
 3853: }
 3854: 
 3855: sub file_name_version_ext {
 3856:     my ($file)=@_;
 3857:     my @file_parts = split(/\./, $file);
 3858:     my ($name,$version,$ext);
 3859:     if (@file_parts > 1) {
 3860: 	$ext=pop(@file_parts);
 3861: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3862: 	    $version=pop(@file_parts);
 3863: 	}
 3864: 	$name=join('.',@file_parts);
 3865:     } else {
 3866: 	$name=join('.',@file_parts);
 3867:     }
 3868:     return($name,$version,$ext);
 3869: }
 3870: 
 3871: #--------------------------------------------------------------------------------------
 3872: #
 3873: #-------------------------- Next few routines handles grading by section or whole class
 3874: #
 3875: #--- Javascript to handle grading by section or whole class
 3876: sub viewgrades_js {
 3877:     my ($request) = shift;
 3878: 
 3879:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3880:     &js_escape(\$alertmsg);
 3881:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3882:    function writePoint(partid,weight,point) {
 3883: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3884: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3885: 	if (point == "textval") {
 3886: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3887: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3888: 		alert("$alertmsg"+parseFloat(point));
 3889: 		var resetbox = false;
 3890: 		for (var i=0; i<radioButton.length; i++) {
 3891: 		    if (radioButton[i].checked) {
 3892: 			textbox.value = i;
 3893: 			resetbox = true;
 3894: 		    }
 3895: 		}
 3896: 		if (!resetbox) {
 3897: 		    textbox.value = "";
 3898: 		}
 3899: 		return;
 3900: 	    }
 3901: 	    if (parseFloat(point) > parseFloat(weight)) {
 3902: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3903: 				   ") greater than the weight for the part. Accept?");
 3904: 		if (resp == false) {
 3905: 		    textbox.value = "";
 3906: 		    return;
 3907: 		}
 3908: 	    }
 3909: 	    for (var i=0; i<radioButton.length; i++) {
 3910: 		radioButton[i].checked=false;
 3911: 		if (parseFloat(point) == i) {
 3912: 		    radioButton[i].checked=true;
 3913: 		}
 3914: 	    }
 3915: 
 3916: 	} else {
 3917: 	    textbox.value = parseFloat(point);
 3918: 	}
 3919: 	for (i=0;i<document.classgrade.total.value;i++) {
 3920: 	    var user = document.classgrade["ctr"+i].value;
 3921: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3922: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3923: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3924: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3925: 	    if (saveval != "correct") {
 3926: 		scorename.value = point;
 3927: 		if (selname[0].selected != true) {
 3928: 		    selname[0].selected = true;
 3929: 		}
 3930: 	    }
 3931: 	}
 3932: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3933:     }
 3934: 
 3935:     function writeRadText(partid,weight) {
 3936: 	var selval   = document.classgrade["SELVAL_"+partid];
 3937: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3938:         var override = document.classgrade["FORCE_"+partid].checked;
 3939: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3940: 	if (selval[1].selected || selval[2].selected) {
 3941: 	    for (var i=0; i<radioButton.length; i++) {
 3942: 		radioButton[i].checked=false;
 3943: 
 3944: 	    }
 3945: 	    textbox.value = "";
 3946: 
 3947: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3948: 		var user = document.classgrade["ctr"+i].value;
 3949: 		user = user.replace(new RegExp(':', 'g'),"_");
 3950: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3951: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3952: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3953: 		if ((saveval != "correct") || override) {
 3954: 		    scorename.value = "";
 3955: 		    if (selval[1].selected) {
 3956: 			selname[1].selected = true;
 3957: 		    } else {
 3958: 			selname[2].selected = true;
 3959: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3960: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3961: 		    }
 3962: 		}
 3963: 	    }
 3964: 	} else {
 3965: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3966: 		var user = document.classgrade["ctr"+i].value;
 3967: 		user = user.replace(new RegExp(':', 'g'),"_");
 3968: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3969: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3970: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3971: 		if ((saveval != "correct") || override) {
 3972: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3973: 		    selname[0].selected = true;
 3974: 		}
 3975: 	    }
 3976: 	}	    
 3977:     }
 3978: 
 3979:     function changeSelect(partid,user) {
 3980: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3981: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3982: 	var point  = textbox.value;
 3983: 	var weight = document.classgrade["weight_"+partid].value;
 3984: 
 3985: 	if (isNaN(point) || parseFloat(point) < 0) {
 3986: 	    alert("$alertmsg"+parseFloat(point));
 3987: 	    textbox.value = "";
 3988: 	    return;
 3989: 	}
 3990: 	if (parseFloat(point) > parseFloat(weight)) {
 3991: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3992: 			       ") greater than the weight of the part. Accept?");
 3993: 	    if (resp == false) {
 3994: 		textbox.value = "";
 3995: 		return;
 3996: 	    }
 3997: 	}
 3998: 	selval[0].selected = true;
 3999:     }
 4000: 
 4001:     function changeOneScore(partid,user) {
 4002: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 4003: 	if (selval[1].selected || selval[2].selected) {
 4004: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 4005: 	    if (selval[2].selected) {
 4006: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 4007: 	    }
 4008:         }
 4009:     }
 4010: 
 4011:     function resetEntry(numpart) {
 4012: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 4013: 	    var partid = document.classgrade["partid_"+ctpart].value;
 4014: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 4015: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 4016: 	    var selval  = document.classgrade["SELVAL_"+partid];
 4017: 	    for (var i=0; i<radioButton.length; i++) {
 4018: 		radioButton[i].checked=false;
 4019: 
 4020: 	    }
 4021: 	    textbox.value = "";
 4022: 	    selval[0].selected = true;
 4023: 
 4024: 	    for (i=0;i<document.classgrade.total.value;i++) {
 4025: 		var user = document.classgrade["ctr"+i].value;
 4026: 		user = user.replace(new RegExp(':', 'g'),"_");
 4027: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 4028: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 4029: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 4030: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 4031: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 4032: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 4033: 		if (saveselval == "excused") {
 4034: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 4035: 		} else {
 4036: 		    if (selname[0].selected == false) {selname[0].selected = true};
 4037: 		}
 4038: 	    }
 4039: 	}
 4040:     }
 4041: 
 4042: VIEWJAVASCRIPT
 4043: }
 4044: 
 4045: #--- show scores for a section or whole class w/ option to change/update a score
 4046: sub viewgrades {
 4047:     my ($request,$symb) = @_;
 4048:     &viewgrades_js($request);
 4049: 
 4050:     #need to make sure we have the correct data for later EXT calls, 
 4051:     #thus invalidate the cache
 4052:     &Apache::lonnet::devalidatecourseresdata(
 4053:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4054:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4055:     &Apache::lonnet::clear_EXT_cache_status();
 4056: 
 4057:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 4058: 
 4059:     #view individual student submission form - called using Javascript viewOneStudent
 4060:     $result.=&jscriptNform($symb);
 4061: 
 4062:     #beginning of class grading form
 4063:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4064:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 4065: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4066: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 4067: 	&build_section_inputs().
 4068: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 4069: 
 4070:     #retrieve selected groups
 4071:     my (@groups,$group_display);
 4072:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 4073:     if (grep(/^all$/,@groups)) {
 4074:         @groups = ('all');
 4075:     } elsif (grep(/^none$/,@groups)) {
 4076:         @groups = ('none');
 4077:     } elsif (@groups > 0) {
 4078:         $group_display = join(', ',@groups);
 4079:     }
 4080: 
 4081:     my ($common_header,$specific_header,@sections,$section_display);
 4082:     if ($env{'request.course.sec'} ne '') {
 4083:         @sections = ($env{'request.course.sec'});
 4084:     } else {
 4085:         @sections = &Apache::loncommon::get_env_multiple('form.section');
 4086:     }
 4087: 
 4088: # Check if Save button should be usable
 4089:     my $disabled = ' disabled="disabled"';
 4090:     if ($perm{'mgr'}) {
 4091:         if (grep(/^all$/,@sections)) {
 4092:             undef($disabled);
 4093:         } else {
 4094:             foreach my $sec (@sections) {
 4095:                 if (&canmodify($sec)) {
 4096:                     undef($disabled);
 4097:                     last;
 4098:                 }
 4099:             }
 4100:         }
 4101:     }
 4102:     if (grep(/^all$/,@sections)) {
 4103:         @sections = ('all');
 4104:         if ($group_display) {
 4105:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 4106:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 4107:         } elsif (grep(/^none$/,@groups)) {
 4108:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 4109:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 4110:         } else {
 4111:             $common_header = &mt('Assign Common Grade to Class');
 4112:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 4113:         }
 4114:     } elsif (grep(/^none$/,@sections)) {
 4115:         @sections = ('none');
 4116:         if ($group_display) {
 4117:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 4118:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 4119:         } elsif (grep(/^none$/,@groups)) {
 4120:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 4121:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 4122:         } else {
 4123:             $common_header = &mt('Assign Common Grade to Students in no Section');
 4124:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 4125:         }
 4126:     } else {
 4127:         $section_display = join (", ",@sections);
 4128:         if ($group_display) {
 4129:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 4130:                                  $section_display,$group_display);
 4131:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 4132:                                    $section_display,$group_display);
 4133:         } elsif (grep(/^none$/,@groups)) {
 4134:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 4135:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 4136:         } else {
 4137:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 4138:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 4139:         }
 4140:     }
 4141:     my %submit_types = &substatus_options();
 4142:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 4143: 
 4144:     if ($env{'form.submitonly'} eq 'all') {
 4145:         $result.= '<h3>'.$common_header.'</h3>';
 4146:     } else {
 4147:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 4148:     }
 4149:     $result .= &Apache::loncommon::start_data_table();
 4150:     #radio buttons/text box for assigning points for a section or class.
 4151:     #handles different parts of a problem
 4152:     my $res_error;
 4153:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 4154:     if ($res_error) {
 4155:         return &navmap_errormsg();
 4156:     }
 4157:     my %weight = ();
 4158:     my $ctsparts = 0;
 4159:     my %seen = ();
 4160:     my @part_response_id = &flatten_responseType($responseType);
 4161:     foreach my $part_response_id (@part_response_id) {
 4162:     	my ($partid,$respid) = @{ $part_response_id };
 4163: 	my $part_resp = join('_',@{ $part_response_id });
 4164: 	next if $seen{$partid};
 4165: 	$seen{$partid}++;
 4166: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 4167: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 4168: 
 4169: 	my $display_part=&get_display_part($partid,$symb);
 4170: 	my $radio.='<table border="0"><tr>';  
 4171: 	my $ctr = 0;
 4172: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 4173: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 4174: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 4175: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 4176: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 4177: 	    $ctr++;
 4178: 	}
 4179: 	$radio.='</tr></table>';
 4180: 	my $line = '<input type="text" name="TEXTVAL_'.
 4181: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 4182: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 4183: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 4184: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 4185:                 '<select name="SELVAL_'.$partid.'" '.
 4186: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 4187: 		$weight{$partid}.')"> '.
 4188: 	    '<option selected="selected"> </option>'.
 4189: 	    '<option value="excused">'.&mt('excused').'</option>'.
 4190: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 4191: 	    '</select></td>'.
 4192:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 4193: 	$line.='<input type="hidden" name="partid_'.
 4194: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 4195: 	$line.='<input type="hidden" name="weight_'.
 4196: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 4197: 
 4198: 	$result.=
 4199: 	    &Apache::loncommon::start_data_table_row()."\n".
 4200: 	    '<td><b>'.&mt('Part:').'</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points:').'</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
 4201: 	    &Apache::loncommon::end_data_table_row()."\n";
 4202: 	$ctsparts++;
 4203:     }
 4204:     $result.=&Apache::loncommon::end_data_table()."\n".
 4205: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 4206:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 4207: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 4208: 
 4209:     #table listing all the students in a section/class
 4210:     #header of table
 4211:     if ($env{'form.submitonly'} eq 'all') { 
 4212:         $result.= '<h3>'.$specific_header.'</h3>';
 4213:     } else {
 4214:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 4215:     }
 4216:     $result.= &Apache::loncommon::start_data_table().
 4217: 	      &Apache::loncommon::start_data_table_header_row().
 4218: 	      '<th>'.&mt('No.').'</th>'.
 4219: 	      '<th>'.&nameUserString('header')."</th>\n";
 4220:     my $partserror;
 4221:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4222:     if ($partserror) {
 4223:         return &navmap_errormsg();
 4224:     }
 4225:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 4226:     my @partids = ();
 4227:     foreach my $part (@parts) {
 4228: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4229:         my $narrowtext = &mt('Tries');
 4230: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 4231: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 4232: 	my ($partid) = &split_part_type($part);
 4233:         push(@partids,$partid);
 4234: #
 4235: # FIXME: Looks like $display looks at English text
 4236: #
 4237: 	my $display_part=&get_display_part($partid,$symb);
 4238: 	if ($display =~ /^Partial Credit Factor/) {
 4239: 	    $result.='<th>'.
 4240:                 &mt('Score Part: [_1][_2](weight = [_3])',
 4241:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 4242: 	    next;
 4243: 	    
 4244: 	} else {
 4245: 	    if ($display =~ /Problem Status/) {
 4246: 		my $grade_status_mt = &mt('Grade Status');
 4247: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 4248: 	    }
 4249: 	    my $part_mt = &mt('Part:');
 4250: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 4251: 	}
 4252: 
 4253: 	$result.='<th>'.$display.'</th>'."\n";
 4254:     }
 4255:     $result.=&Apache::loncommon::end_data_table_header_row();
 4256: 
 4257:     my %last_resets = 
 4258: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 4259: 
 4260:     #get info for each student
 4261:     #list all the students - with points and grade status
 4262:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 4263:     my $ctr = 0;
 4264:     foreach (sort 
 4265: 	     {
 4266: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4267: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4268: 		 }
 4269: 		 return $a cmp $b;
 4270: 	     } (keys(%$fullname))) {
 4271: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 4272: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 4273:     }
 4274:     $result.=&Apache::loncommon::end_data_table();
 4275:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 4276:     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 4277: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 4278:     if ($ctr == 0) {
 4279:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 4280:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 4281:                 '<span class="LC_warning">';
 4282:         if ($env{'form.submitonly'} eq 'all') {
 4283:             if (grep(/^all$/,@sections)) {
 4284:                 if (grep(/^all$/,@groups)) {
 4285:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 4286:                                    $stu_status);
 4287:                 } elsif (grep(/^none$/,@groups)) {
 4288:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 4289:                                    $stu_status);
 4290:                 } else {
 4291:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4292:                                    $group_display,$stu_status);
 4293:                 }
 4294:             } elsif (grep(/^none$/,@sections)) {
 4295:                 if (grep(/^all$/,@groups)) {
 4296:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 4297:                                    $stu_status);
 4298:                 } elsif (grep(/^none$/,@groups)) {
 4299:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 4300:                                    $stu_status);
 4301:                 } else {
 4302:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 4303:                                    $group_display,$stu_status);
 4304:                 }
 4305:             } else {
 4306:                 if (grep(/^all$/,@groups)) {
 4307:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 4308:                                    $section_display,$stu_status);
 4309:                 } elsif (grep(/^none$/,@groups)) {
 4310:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 4311:                                    $section_display,$stu_status);
 4312:                 } else {
 4313:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 4314:                                    $section_display,$group_display,$stu_status);
 4315:                 }
 4316:             }
 4317:         } else {
 4318:             if (grep(/^all$/,@sections)) {
 4319:                 if (grep(/^all$/,@groups)) {
 4320:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4321:                                    $stu_status,$submission_status);
 4322:                 } elsif (grep(/^none$/,@groups)) {
 4323:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4324:                                    $stu_status,$submission_status);
 4325:                 } else {
 4326:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4327:                                    $group_display,$stu_status,$submission_status);
 4328:                 }
 4329:             } elsif (grep(/^none$/,@sections)) {
 4330:                 if (grep(/^all$/,@groups)) {
 4331:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4332:                                    $stu_status,$submission_status);
 4333:                 } elsif (grep(/^none$/,@groups)) {
 4334:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4335:                                    $stu_status,$submission_status);
 4336:                 } else {
 4337:                     $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.',
 4338:                                    $group_display,$stu_status,$submission_status);
 4339:                 }
 4340:             } else {
 4341:                 if (grep(/^all$/,@groups)) {
 4342:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4343:                                    $section_display,$stu_status,$submission_status);
 4344:                 } elsif (grep(/^none$/,@groups)) {
 4345:                     $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.',
 4346:                                    $section_display,$stu_status,$submission_status);
 4347:                 } else {
 4348:                     $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.',
 4349:                                    $section_display,$group_display,$stu_status,$submission_status);
 4350:                 }
 4351:             }
 4352: 	}
 4353: 	$result .= '</span><br />';
 4354:     }
 4355:     return $result;
 4356: }
 4357: 
 4358: #--- call by previous routine to display each student who satisfies submission filter.
 4359: sub viewstudentgrade {
 4360:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4361:     my ($uname,$udom) = split(/:/,$student);
 4362:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4363:     my $submitonly = $env{'form.submitonly'};
 4364:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4365:         my %partstatus = ();
 4366:         if (ref($parts) eq 'ARRAY') {
 4367:             foreach my $apart (@{$parts}) {
 4368:                 my ($part,$type) = &split_part_type($apart);
 4369:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4370:                 $status = 'nothing' if ($status eq '');
 4371:                 $partstatus{$part}      = $status;
 4372:                 my $subkey = "resource.$part.submitted_by";
 4373:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4374:             }
 4375:             my $submitted = 0;
 4376:             my $graded = 0;
 4377:             my $incorrect = 0;
 4378:             foreach my $key (keys(%partstatus)) {
 4379:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4380:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4381:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4382: 
 4383:                 my $partid = (split(/\./,$key))[1];
 4384:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4385:                     $submitted = 0;
 4386:                 }
 4387:             }
 4388:             return if (!$submitted && ($submitonly eq 'yes' ||
 4389:                                        $submitonly eq 'incorrect' ||
 4390:                                        $submitonly eq 'graded'));
 4391:             return if (!$graded && ($submitonly eq 'graded'));
 4392:             return if (!$incorrect && $submitonly eq 'incorrect');
 4393:         }
 4394:     }
 4395:     if ($submitonly eq 'queued') {
 4396:         my ($cdom,$cnum) = split(/_/,$courseid);
 4397:         my %queue_status =
 4398:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4399:                                                     $udom,$uname);
 4400:         return if (!defined($queue_status{'gradingqueue'}));
 4401:     }
 4402:     $$ctr++;
 4403:     my %aggregates = ();
 4404:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4405: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4406: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4407: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4408: 	'\');" target="_self">'.$fullname.'</a> '.
 4409: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4410:     $student=~s/:/_/; # colon doen't work in javascript for names
 4411:     foreach my $apart (@$parts) {
 4412: 	my ($part,$type) = &split_part_type($apart);
 4413: 	my $score=$record{"resource.$part.$type"};
 4414:         $result.='<td align="center">';
 4415:         my ($aggtries,$totaltries);
 4416:         unless (exists($aggregates{$part})) {
 4417: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4418: 
 4419: 	    $aggtries = $totaltries;
 4420:             if ($$last_resets{$part}) {  
 4421:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4422: 					   $part);
 4423:             }
 4424:             $result.='<input type="hidden" name="'.
 4425:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4426:             $result.='<input type="hidden" name="'.
 4427:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4428:             $aggregates{$part} = 1;
 4429:         }
 4430: 	if ($type eq 'awarded') {
 4431: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4432: 	    $result.='<input type="hidden" name="'.
 4433: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4434: 	    $result.='<input type="text" name="'.
 4435: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4436:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4437: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4438: 	} elsif ($type eq 'solved') {
 4439: 	    my ($status,$foo)=split(/_/,$score,2);
 4440: 	    $status = 'nothing' if ($status eq '');
 4441: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4442: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4443: 	    $result.='&nbsp;<select name="'.
 4444: 		'GD_'.$student.'_'.$part.'_solved" '.
 4445:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4446: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4447: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4448: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4449: 	    $result.="</select>&nbsp;</td>\n";
 4450: 	} else {
 4451: 	    $result.='<input type="hidden" name="'.
 4452: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4453: 		    "\n";
 4454: 	    $result.='<input type="text" name="'.
 4455: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4456: 		'value="'.$score.'" size="4" /></td>'."\n";
 4457: 	}
 4458:     }
 4459:     $result.=&Apache::loncommon::end_data_table_row();
 4460:     return $result;
 4461: }
 4462: 
 4463: #--- change scores for all the students in a section/class
 4464: #    record does not get update if unchanged
 4465: sub editgrades {
 4466:     my ($request,$symb) = @_;
 4467: 
 4468:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4469:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4470:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4471: 
 4472:     my $result= &Apache::loncommon::start_data_table().
 4473: 	&Apache::loncommon::start_data_table_header_row().
 4474: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4475: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4476:     my %scoreptr = (
 4477: 		    'correct'  =>'correct_by_override',
 4478: 		    'incorrect'=>'incorrect_by_override',
 4479: 		    'excused'  =>'excused',
 4480: 		    'ungraded' =>'ungraded_attempted',
 4481:                     'credited' =>'credit_attempted',
 4482: 		    'nothing'  => '',
 4483: 		    );
 4484:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4485: 
 4486:     my (@partid);
 4487:     my %weight = ();
 4488:     my %columns = ();
 4489:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4490: 
 4491:     my $partserror;
 4492:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4493:     if ($partserror) {
 4494:         return &navmap_errormsg();
 4495:     }
 4496:     my $header;
 4497:     while ($ctr < $env{'form.totalparts'}) {
 4498: 	my $partid = $env{'form.partid_'.$ctr};
 4499: 	push(@partid,$partid);
 4500: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4501: 	$ctr++;
 4502:     }
 4503:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4504:     my $totcolspan = 0;
 4505:     foreach my $partid (@partid) {
 4506: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4507: 	    '<th align="center">'.&mt('New Score').'</th>';
 4508: 	$columns{$partid}=2;
 4509: 	foreach my $stores (@parts) {
 4510: 	    my ($part,$type) = &split_part_type($stores);
 4511: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4512: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4513: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4514: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4515:             my $narrowtext = &mt('Tries');
 4516: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4517: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4518: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4519: 	    $columns{$partid}+=2;
 4520: 	}
 4521:         $totcolspan += $columns{$partid};
 4522:     }
 4523:     foreach my $partid (@partid) {
 4524: 	my $display_part=&get_display_part($partid,$symb);
 4525: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4526: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4527: 	    '</th>';
 4528: 
 4529:     }
 4530:     $result .= &Apache::loncommon::end_data_table_header_row().
 4531: 	&Apache::loncommon::start_data_table_header_row().
 4532: 	$header.
 4533: 	&Apache::loncommon::end_data_table_header_row();
 4534:     my @noupdate;
 4535:     my ($updateCtr,$noupdateCtr) = (1,1);
 4536:     my ($got_types,%queueable);
 4537:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4538: 	my $user = $env{'form.ctr'.$i};
 4539: 	my ($uname,$udom)=split(/:/,$user);
 4540: 	my %newrecord;
 4541: 	my $updateflag = 0;
 4542:         my $usec=$classlist->{"$uname:$udom"}[5];
 4543:         my $canmodify = &canmodify($usec);
 4544:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4545:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4546:         if (!$canmodify) {
 4547:             push(@noupdate,
 4548:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4549:                  &mt('Not allowed to modify student')."</span></td>");
 4550:             next;
 4551:         }
 4552:         my %aggregate = ();
 4553:         my $aggregateflag = 0;
 4554: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4555: 	foreach (@partid) {
 4556: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4557: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4558: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4559: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4560: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4561: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4562: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4563: 	    my $score;
 4564: 	    if ($partial eq '') {
 4565: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4566: 	    } elsif ($partial > 0) {
 4567: 		$score = 'correct_by_override';
 4568: 	    } elsif ($partial == 0) {
 4569: 		$score = 'incorrect_by_override';
 4570: 	    }
 4571: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4572: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4573: 
 4574: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4575: 		"$env{'user.name'}:$env{'user.domain'}";
 4576: 	    if ($dropMenu eq 'reset status' &&
 4577: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4578: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4579: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4580: 		$newrecord{'resource.'.$_.'.award'} = '';
 4581: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4582: 		$updateflag = 1;
 4583:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4584:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4585:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4586:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4587:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4588:                     $aggregateflag = 1;
 4589:                 }
 4590: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4591: 		$updateflag = 1;
 4592: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4593: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4594: 		$rec_update++;
 4595: 	    }
 4596: 
 4597: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4598: 		'<td align="center">'.$awarded.
 4599: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4600: 
 4601: 
 4602: 	    my $partid=$_;
 4603: 	    foreach my $stores (@parts) {
 4604: 		my ($part,$type) = &split_part_type($stores);
 4605: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4606: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4607: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4608: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4609: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4610: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4611: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4612: 		    $updateflag=1;
 4613: 		}
 4614: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4615: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4616: 	    }
 4617: 	}
 4618: 	$line.="\n";
 4619: 
 4620: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4621: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4622: 
 4623: 	if ($updateflag) {
 4624: 	    $count++;
 4625: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4626: 				    $udom,$uname);
 4627: 
 4628: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4629: 					      $cnum,$udom,$uname)) {
 4630: 		# need to figure out if should be in queue.
 4631: 		my %record =  
 4632: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4633: 					     $udom,$uname);
 4634: 		my $all_graded = 1;
 4635: 		my $none_graded = 1;
 4636:                 unless ($got_types) {
 4637:                     my $error;
 4638:                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
 4639:                     unless ($error) {
 4640:                         foreach my $part (@parts) {
 4641:                             if (ref($resptype->{$part}) eq 'HASH') {
 4642:                                 foreach my $id (keys(%{$resptype->{$part}})) {
 4643:                                     if (($resptype->{$part}->{$id} eq 'essay') ||
 4644:                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
 4645:                                         $queueable{$part} = 1;
 4646:                                         last;
 4647:                                     }
 4648:                                 }
 4649:                             }
 4650:                         }
 4651:                     }
 4652:                     $got_types = 1;
 4653:                 }
 4654: 		foreach my $part (@parts) {
 4655:                     if ($queueable{$part}) {
 4656: 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4657: 			    $all_graded = 0;
 4658: 		        } else {
 4659: 			    $none_graded = 0;
 4660: 		        }
 4661:                     }
 4662: 		}
 4663: 
 4664: 		if ($all_graded || $none_graded) {
 4665: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4666: 							   $symb,$cdom,$cnum,
 4667: 							   $udom,$uname);
 4668: 		}
 4669: 	    }
 4670: 
 4671: 	    $result.=&Apache::loncommon::start_data_table_row().
 4672: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4673: 		&Apache::loncommon::end_data_table_row();
 4674: 	    $updateCtr++;
 4675: 	} else {
 4676: 	    push(@noupdate,
 4677: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4678: 	    $noupdateCtr++;
 4679: 	}
 4680:         if ($aggregateflag) {
 4681:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4682: 				  $cdom,$cnum);
 4683:         }
 4684:     }
 4685:     if (@noupdate) {
 4686:         my $numcols=$totcolspan+2;
 4687: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4688: 	    '<td align="center" colspan="'.$numcols.'">'.
 4689: 	    &mt('No Changes Occurred For the Students Below').
 4690: 	    '</td>'.
 4691: 	    &Apache::loncommon::end_data_table_row();
 4692: 	foreach my $line (@noupdate) {
 4693: 	    $result.=
 4694: 		&Apache::loncommon::start_data_table_row().
 4695: 		$line.
 4696: 		&Apache::loncommon::end_data_table_row();
 4697: 	}
 4698:     }
 4699:     $result .= &Apache::loncommon::end_data_table();
 4700:     my $msg = '<p><b>'.
 4701: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4702: 	    $rec_update,$count).'</b><br />'.
 4703: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4704: 	'</b></p>';
 4705:     return $title.$msg.$result;
 4706: }
 4707: 
 4708: sub split_part_type {
 4709:     my ($partstr) = @_;
 4710:     my ($temp,@allparts)=split(/_/,$partstr);
 4711:     my $type=pop(@allparts);
 4712:     my $part=join('_',@allparts);
 4713:     return ($part,$type);
 4714: }
 4715: 
 4716: #------------- end of section for handling grading by section/class ---------
 4717: #
 4718: #----------------------------------------------------------------------------
 4719: 
 4720: 
 4721: #----------------------------------------------------------------------------
 4722: #
 4723: #-------------------------- Next few routines handles grading by csv upload
 4724: #
 4725: #--- Javascript to handle csv upload
 4726: sub csvupload_javascript_reverse_associate {
 4727:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4728:     my $error2=&mt('You need to specify at least one grading field');
 4729:   &js_escape(\$error1);
 4730:   &js_escape(\$error2);
 4731:   return(<<ENDPICK);
 4732:   function verify(vf) {
 4733:     var foundsomething=0;
 4734:     var founduname=0;
 4735:     var foundID=0;
 4736:     for (i=0;i<=vf.nfields.value;i++) {
 4737:       tw=eval('vf.f'+i+'.selectedIndex');
 4738:       if (i==0 && tw!=0) { foundID=1; }
 4739:       if (i==1 && tw!=0) { founduname=1; }
 4740:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4741:     }
 4742:     if (founduname==0 && foundID==0) {
 4743: 	alert('$error1');
 4744: 	return;
 4745:     }
 4746:     if (foundsomething==0) {
 4747: 	alert('$error2');
 4748: 	return;
 4749:     }
 4750:     vf.submit();
 4751:   }
 4752:   function flip(vf,tf) {
 4753:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4754:     var i;
 4755:     for (i=0;i<=vf.nfields.value;i++) {
 4756:       //can not pick the same destination field for both name and domain
 4757:       if (((i ==0)||(i ==1)) && 
 4758:           ((tf==0)||(tf==1)) && 
 4759:           (i!=tf) &&
 4760:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4761:         eval('vf.f'+i+'.selectedIndex=0;')
 4762:       }
 4763:     }
 4764:   }
 4765: ENDPICK
 4766: }
 4767: 
 4768: sub csvupload_javascript_forward_associate {
 4769:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4770:     my $error2=&mt('You need to specify at least one grading field');
 4771:   &js_escape(\$error1);
 4772:   &js_escape(\$error2);
 4773:   return(<<ENDPICK);
 4774:   function verify(vf) {
 4775:     var foundsomething=0;
 4776:     var founduname=0;
 4777:     var foundID=0;
 4778:     for (i=0;i<=vf.nfields.value;i++) {
 4779:       tw=eval('vf.f'+i+'.selectedIndex');
 4780:       if (tw==1) { foundID=1; }
 4781:       if (tw==2) { founduname=1; }
 4782:       if (tw>3) { foundsomething=1; }
 4783:     }
 4784:     if (founduname==0 && foundID==0) {
 4785: 	alert('$error1');
 4786: 	return;
 4787:     }
 4788:     if (foundsomething==0) {
 4789: 	alert('$error2');
 4790: 	return;
 4791:     }
 4792:     vf.submit();
 4793:   }
 4794:   function flip(vf,tf) {
 4795:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4796:     var i;
 4797:     //can not pick the same destination field twice
 4798:     for (i=0;i<=vf.nfields.value;i++) {
 4799:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4800:         eval('vf.f'+i+'.selectedIndex=0;')
 4801:       }
 4802:     }
 4803:   }
 4804: ENDPICK
 4805: }
 4806: 
 4807: sub csvuploadmap_header {
 4808:     my ($request,$symb,$datatoken,$distotal)= @_;
 4809:     my $javascript;
 4810:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4811: 	$javascript=&csvupload_javascript_reverse_associate();
 4812:     } else {
 4813: 	$javascript=&csvupload_javascript_forward_associate();
 4814:     }
 4815: 
 4816:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4817:     my $ignore=&mt('Ignore First Line');
 4818:     $symb = &Apache::lonenc::check_encrypt($symb);
 4819:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4820:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4821:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4822:     my $reverse=&mt("Reverse Association");
 4823:     $request->print(<<ENDPICK);
 4824: <br />
 4825: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4826: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4827: <input type="hidden" name="associate"  value="" />
 4828: <input type="hidden" name="phase"      value="three" />
 4829: <input type="hidden" name="datatoken"  value="$datatoken" />
 4830: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4831: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4832: <input type="hidden" name="upfile_associate" 
 4833:                                        value="$env{'form.upfile_associate'}" />
 4834: <input type="hidden" name="symb"       value="$symb" />
 4835: <input type="hidden" name="command"    value="csvuploadoptions" />
 4836: <hr />
 4837: ENDPICK
 4838:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4839:     return '';
 4840: 
 4841: }
 4842: 
 4843: sub csvupload_fields {
 4844:     my ($symb,$errorref) = @_;
 4845:     my (@parts) = &getpartlist($symb,$errorref);
 4846:     if (ref($errorref)) {
 4847:         if ($$errorref) {
 4848:             return;
 4849:         }
 4850:     }
 4851: 
 4852:     my @fields=(['ID','Student/Employee ID'],
 4853: 		['username','Student Username'],
 4854: 		['domain','Student Domain']);
 4855:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4856:     foreach my $part (sort(@parts)) {
 4857: 	my @datum;
 4858: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4859: 	my $name=$part;
 4860: 	if  (!$display) { $display = $name; }
 4861: 	@datum=($name,$display);
 4862: 	if ($name=~/^stores_(.*)_awarded/) {
 4863: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4864: 	}
 4865: 	push(@fields,\@datum);
 4866:     }
 4867:     return (@fields);
 4868: }
 4869: 
 4870: sub csvuploadmap_footer {
 4871:     my ($request,$i,$keyfields) =@_;
 4872:     my $buttontext = &mt('Assign Grades');
 4873:     $request->print(<<ENDPICK);
 4874: </table>
 4875: <input type="hidden" name="nfields" value="$i" />
 4876: <input type="hidden" name="keyfields" value="$keyfields" />
 4877: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4878: </form>
 4879: ENDPICK
 4880: }
 4881: 
 4882: sub checkforfile_js {
 4883:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4884:     &js_escape(\$alertmsg);
 4885:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4886:     function checkUpload(formname) {
 4887: 	if (formname.upfile.value == "") {
 4888: 	    alert("$alertmsg");
 4889: 	    return false;
 4890: 	}
 4891: 	formname.submit();
 4892:     }
 4893: CSVFORMJS
 4894:     return $result;
 4895: }
 4896: 
 4897: sub upcsvScores_form {
 4898:     my ($request,$symb) = @_;
 4899:     if (!$symb) {return '';}
 4900:     my $result=&checkforfile_js();
 4901:     $result.=&Apache::loncommon::start_data_table().
 4902:              &Apache::loncommon::start_data_table_header_row().
 4903:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4904:              &Apache::loncommon::end_data_table_header_row().
 4905:              &Apache::loncommon::start_data_table_row().'<td>';
 4906:     my $upload=&mt("Upload Scores");
 4907:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4908:     my $ignore=&mt('Ignore First Line');
 4909:     $symb = &Apache::lonenc::check_encrypt($symb);
 4910:     $result.=<<ENDUPFORM;
 4911: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4912: <input type="hidden" name="symb" value="$symb" />
 4913: <input type="hidden" name="command" value="csvuploadmap" />
 4914: $upfile_select
 4915: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4916: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4917: </form>
 4918: ENDUPFORM
 4919:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4920:                            &mt("How do I create a CSV file from a spreadsheet")).
 4921:             '</td>'.
 4922:             &Apache::loncommon::end_data_table_row().
 4923:             &Apache::loncommon::end_data_table();
 4924:     return $result;
 4925: }
 4926: 
 4927: 
 4928: sub csvuploadmap {
 4929:     my ($request,$symb) = @_;
 4930:     if (!$symb) {return '';}
 4931: 
 4932:     my $datatoken;
 4933:     if (!$env{'form.datatoken'}) {
 4934: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4935:     } else {
 4936:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4937:         if ($datatoken ne '') { 
 4938: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4939:         }
 4940:     }
 4941:     my @records=&Apache::loncommon::upfile_record_sep();
 4942:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4943:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4944:     my ($i,$keyfields);
 4945:     if (@records) {
 4946:         my $fieldserror;
 4947: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4948:         if ($fieldserror) {
 4949:             $request->print(&navmap_errormsg());
 4950:             return;
 4951:         }
 4952: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4953: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4954: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4955: 							  \@fields);
 4956: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4957: 	    chop($keyfields);
 4958: 	} else {
 4959: 	    unshift(@fields,['none','']);
 4960: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4961: 							    \@fields);
 4962:             foreach my $rec (@records) {
 4963:                 my %temp = &Apache::loncommon::record_sep($rec);
 4964:                 if (%temp) {
 4965:                     $keyfields=join(',',sort(keys(%temp)));
 4966:                     last;
 4967:                 }
 4968:             }
 4969: 	}
 4970:     }
 4971:     &csvuploadmap_footer($request,$i,$keyfields);
 4972: 
 4973:     return '';
 4974: }
 4975: 
 4976: sub csvuploadoptions {
 4977:     my ($request,$symb)= @_;
 4978:     my $overwrite=&mt('Overwrite any existing score');
 4979:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4980:     my $ignore=&mt('Ignore First Line');
 4981:     $request->print(<<ENDPICK);
 4982: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4983: <input type="hidden" name="command"    value="csvuploadassign" />
 4984: <p>
 4985: <label>
 4986:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4987:    $overwrite
 4988: </label>
 4989: </p>
 4990: ENDPICK
 4991:     my %fields=&get_fields();
 4992:     if (!defined($fields{'domain'})) {
 4993: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4994:         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4995:     }
 4996:     foreach my $key (sort(keys(%env))) {
 4997: 	if ($key !~ /^form\.(.*)$/) { next; }
 4998: 	my $cleankey=$1;
 4999: 	if ($cleankey eq 'command') { next; }
 5000: 	$request->print('<input type="hidden" name="'.$cleankey.
 5001: 			'"  value="'.$env{$key}.'" />'."\n");
 5002:     }
 5003:     # FIXME do a check for any duplicated user ids...
 5004:     # FIXME do a check for any invalid user ids?...
 5005:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 5006: <hr /></form>'."\n");
 5007:     return '';
 5008: }
 5009: 
 5010: sub get_fields {
 5011:     my %fields;
 5012:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 5013:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 5014: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 5015: 	    if ($env{'form.f'.$i} ne 'none') {
 5016: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 5017: 	    }
 5018: 	} else {
 5019: 	    if ($env{'form.f'.$i} ne 'none') {
 5020: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 5021: 	    }
 5022: 	}
 5023:     }
 5024:     return %fields;
 5025: }
 5026: 
 5027: sub csvuploadassign {
 5028:     my ($request,$symb) = @_;
 5029:     if (!$symb) {return '';}
 5030:     my $error_msg = '';
 5031:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 5032:     if ($datatoken ne '') {
 5033:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 5034:     }
 5035:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 5036:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 5037:     my %fields=&get_fields();
 5038:     my $courseid=$env{'request.course.id'};
 5039:     my ($classlist) = &getclasslist('all',0);
 5040:     my @notallowed;
 5041:     my @skipped;
 5042:     my @warnings;
 5043:     my $countdone=0;
 5044:     foreach my $grade (@gradedata) {
 5045: 	my %entries=&Apache::loncommon::record_sep($grade);
 5046: 	my $domain;
 5047: 	if ($entries{$fields{'domain'}}) {
 5048: 	    $domain=$entries{$fields{'domain'}};
 5049: 	} else {
 5050: 	    $domain=$env{'form.default_domain'};
 5051: 	}
 5052: 	$domain=~s/\s//g;
 5053: 	my $username=$entries{$fields{'username'}};
 5054: 	$username=~s/\s//g;
 5055: 	if (!$username) {
 5056: 	    my $id=$entries{$fields{'ID'}};
 5057: 	    $id=~s/\s//g;
 5058: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 5059: 	    $username=$ids{$id};
 5060: 	}
 5061: 	if (!exists($$classlist{"$username:$domain"})) {
 5062: 	    my $id=$entries{$fields{'ID'}};
 5063: 	    $id=~s/\s//g;
 5064: 	    if ($id) {
 5065: 		push(@skipped,"$id:$domain");
 5066: 	    } else {
 5067: 		push(@skipped,"$username:$domain");
 5068: 	    }
 5069: 	    next;
 5070: 	}
 5071: 	my $usec=$classlist->{"$username:$domain"}[5];
 5072: 	if (!&canmodify($usec)) {
 5073: 	    push(@notallowed,"$username:$domain");
 5074: 	    next;
 5075: 	}
 5076: 	my %points;
 5077: 	my %grades;
 5078: 	foreach my $dest (keys(%fields)) {
 5079: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 5080: 		$dest eq 'domain') { next; }
 5081: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 5082: 	    if ($dest=~/stores_(.*)_points/) {
 5083: 		my $part=$1;
 5084: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 5085: 					      $symb,$domain,$username);
 5086:                 if ($wgt) {
 5087:                     $entries{$fields{$dest}}=~s/\s//g;
 5088:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 5089:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 5090:                                           : 'correct_by_override';
 5091:                     if ($pcr>1) {
 5092:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 5093:                     }
 5094:                     $grades{"resource.$part.awarded"}=$pcr;
 5095:                     $grades{"resource.$part.solved"}=$award;
 5096:                     $points{$part}=1;
 5097:                 } else {
 5098:                     $error_msg = "<br />" .
 5099:                         &mt("Some point values were assigned"
 5100:                             ." for problems with a weight "
 5101:                             ."of zero. These values were "
 5102:                             ."ignored.");
 5103:                 }
 5104: 	    } else {
 5105: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 5106: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 5107: 		my $store_key=$dest;
 5108: 		$store_key=~s/^stores/resource/;
 5109: 		$store_key=~s/_/\./g;
 5110: 		$grades{$store_key}=$entries{$fields{$dest}};
 5111: 	    }
 5112: 	}
 5113: 	if (! %grades) {
 5114:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 5115:         } else {
 5116: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 5117: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 5118: 					   $env{'request.course.id'},
 5119: 					   $domain,$username);
 5120: 	   if ($result eq 'ok') {
 5121: # Successfully stored
 5122: 	      $request->print('.');
 5123: # Remove from grading queue
 5124:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 5125:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 5126:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 5127:                                              $domain,$username);
 5128: 	   } else {
 5129: 	      $request->print("<p><span class=\"LC_error\">".
 5130:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 5131:                                   "$username:$domain",$result)."</span></p>");
 5132: 	   }
 5133: 	   $request->rflush();
 5134: 	   $countdone++;
 5135:         }
 5136:     }
 5137:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 5138:     if (@warnings) {
 5139:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 5140:         $request->print(join(', ',@warnings));
 5141:     }
 5142:     if (@skipped) {
 5143: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 5144:         $request->print(join(', ',@skipped));
 5145:     }
 5146:     if (@notallowed) {
 5147: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 5148: 	$request->print(join(', ',@notallowed));
 5149:     }
 5150:     $request->print("<br />\n");
 5151:     return $error_msg;
 5152: }
 5153: #------------- end of section for handling csv file upload ---------
 5154: #
 5155: #-------------------------------------------------------------------
 5156: #
 5157: #-------------- Next few routines handle grading by page/sequence
 5158: #
 5159: #--- Select a page/sequence and a student to grade
 5160: sub pickStudentPage {
 5161:     my ($request,$symb) = @_;
 5162: 
 5163:     my $alertmsg = &mt('Please select the student you wish to grade.');
 5164:     &js_escape(\$alertmsg);
 5165:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 5166: 
 5167: function checkPickOne(formname) {
 5168:     if (radioSelection(formname.student) == null) {
 5169: 	alert("$alertmsg");
 5170: 	return;
 5171:     }
 5172:     ptr = pullDownSelection(formname.selectpage);
 5173:     formname.page.value = formname["page"+ptr].value;
 5174:     formname.title.value = formname["title"+ptr].value;
 5175:     formname.submit();
 5176: }
 5177: 
 5178: LISTJAVASCRIPT
 5179:     &commonJSfunctions($request);
 5180: 
 5181:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5182:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5183:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5184:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 5185: 
 5186:     my $result='<h3><span class="LC_info">&nbsp;'.
 5187: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 5188: 
 5189:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 5190:     my $map_error;
 5191:     my ($titles,$symbx) = &getSymbMap($map_error);
 5192:     if ($map_error) {
 5193:         $request->print(&navmap_errormsg());
 5194:         return; 
 5195:     }
 5196:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 5197: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 5198: #    my $type=($curpage =~ /\.(page|sequence)/);
 5199: 
 5200:     # Collection of hidden fields
 5201:     my $ctr=0;
 5202:     foreach (@$titles) {
 5203: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5204: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 5205: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 5206: 	$ctr++;
 5207:     }
 5208:     $result.='<input type="hidden" name="page" />'."\n".
 5209: 	'<input type="hidden" name="title" />'."\n";
 5210: 
 5211:     $result.=&build_section_inputs();
 5212:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 5213:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 5214:         '<input type="hidden" name="command" value="displayPage" />'."\n".
 5215:         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 5216: 
 5217:     # Show grading options
 5218:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 5219:     my $select = '<select name="selectpage">'."\n";
 5220:     $ctr=0;
 5221:     foreach (@$titles) {
 5222:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5223:         $select.='<option value="'.$ctr.'"'.
 5224:             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 5225:             '>'.$showtitle.'</option>'."\n";
 5226:         $ctr++;
 5227:     }
 5228:     $select.= '</select>';
 5229: 
 5230:     $result.=
 5231:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 5232:        .$select
 5233:        .&Apache::lonhtmlcommon::row_closure();
 5234: 
 5235:     $result.=
 5236:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 5237:        .'<label><input type="radio" name="vProb" value="no"'
 5238:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 5239:        .'<label><input type="radio" name="vProb" value="yes" />'
 5240:            .&mt('yes').'</label>'."\n"
 5241:        .&Apache::lonhtmlcommon::row_closure();
 5242: 
 5243:     $result.=
 5244:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 5245:        .'<label><input type="radio" name="lastSub" value="none" /> '
 5246:            .&mt('none').' </label>'."\n"
 5247:        .'<label><input type="radio" name="lastSub" value="datesub"'
 5248:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 5249:        .'<label><input type="radio" name="lastSub" value="all" /> '
 5250:            .&mt('all submissions with details').' </label>'
 5251:        .&Apache::lonhtmlcommon::row_closure();
 5252: 
 5253:     $result.=
 5254:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 5255:        .'<input type="text" name="CODE" value="" />'
 5256:        .&Apache::lonhtmlcommon::row_closure(1)
 5257:        .&Apache::lonhtmlcommon::end_pick_box();
 5258: 
 5259:     # Show list of students to select for grading
 5260:     $result.='<br /><input type="button" '.
 5261:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 5262: 
 5263:     $request->print($result);
 5264: 
 5265:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 5266: 	&Apache::loncommon::start_data_table().
 5267: 	&Apache::loncommon::start_data_table_header_row().
 5268: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5269: 	'<th>'.&nameUserString('header').'</th>'.
 5270: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 5271: 	'<th>'.&nameUserString('header').'</th>'.
 5272: 	&Apache::loncommon::end_data_table_header_row();
 5273:  
 5274:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
 5275:     my $ptr = 1;
 5276:     foreach my $student (sort 
 5277: 			 {
 5278: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 5279: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 5280: 			     }
 5281: 			     return $a cmp $b;
 5282: 			 } (keys(%$fullname))) {
 5283: 	my ($uname,$udom) = split(/:/,$student);
 5284: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 5285:                                   : '</td>');
 5286: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 5287: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 5288: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 5289: 	$studentTable.=
 5290: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 5291:                          : '');
 5292: 	$ptr++;
 5293:     }
 5294:     if ($ptr%2 == 0) {
 5295: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 5296: 	    &Apache::loncommon::end_data_table_row();
 5297:     }
 5298:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 5299:     $studentTable.='<input type="button" '.
 5300:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 5301: 
 5302:     $request->print($studentTable);
 5303: 
 5304:     return '';
 5305: }
 5306: 
 5307: sub getSymbMap {
 5308:     my ($map_error) = @_;
 5309:     my $navmap = Apache::lonnavmaps::navmap->new();
 5310:     unless (ref($navmap)) {
 5311:         if (ref($map_error)) {
 5312:             $$map_error = 'navmap';
 5313:         }
 5314:         return;
 5315:     }
 5316:     my %symbx = ();
 5317:     my @titles = ();
 5318:     my $minder = 0;
 5319: 
 5320:     # Gather every sequence that has problems.
 5321:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5322: 					       1,0,1);
 5323:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5324: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 5325: 	    my $title = $minder.'.'.
 5326: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5327: 	    push(@titles, $title); # minder in case two titles are identical
 5328: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5329: 	    $minder++;
 5330: 	}
 5331:     }
 5332:     return \@titles,\%symbx;
 5333: }
 5334: 
 5335: #
 5336: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5337: sub displayPage {
 5338:     my ($request,$symb) = @_;
 5339:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5340:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5341:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5342:     my $pageTitle = $env{'form.page'};
 5343:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5344:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5345:     my $usec=$classlist->{$env{'form.student'}}[5];
 5346: 
 5347:     #need to make sure we have the correct data for later EXT calls, 
 5348:     #thus invalidate the cache
 5349:     &Apache::lonnet::devalidatecourseresdata(
 5350:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5351:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5352:     &Apache::lonnet::clear_EXT_cache_status();
 5353: 
 5354:     if (!&canview($usec)) {
 5355: 	$request->print(
 5356:             '<span class="LC_warning">'.
 5357:             &mt('Unable to view requested student. ([_1])',
 5358:                 $env{'form.student'}).
 5359:             '</span>');
 5360:         return;
 5361:     }
 5362:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5363:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5364: 	'</h3>'."\n";
 5365:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5366:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5367: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5368:     } else {
 5369: 	delete($env{'form.CODE'});
 5370:     }
 5371:     &sub_page_js($request);
 5372:     $request->print($result);
 5373: 
 5374:     my $navmap = Apache::lonnavmaps::navmap->new();
 5375:     unless (ref($navmap)) {
 5376:         $request->print(&navmap_errormsg());
 5377:         return;
 5378:     }
 5379:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5380:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5381:     if (!$map) {
 5382: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5383: 	return; 
 5384:     }
 5385:     my $iterator = $navmap->getIterator($map->map_start(),
 5386: 					$map->map_finish());
 5387: 
 5388:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5389: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5390: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5391: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5392: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5393: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5394: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5395: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5396: 
 5397:     if (defined($env{'form.CODE'})) {
 5398: 	$studentTable.=
 5399: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5400:     }
 5401:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5402: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5403: 
 5404:     $studentTable.='&nbsp;<span class="LC_info">'.
 5405:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5406:         '</span>'."\n".
 5407: 	&Apache::loncommon::start_data_table().
 5408: 	&Apache::loncommon::start_data_table_header_row().
 5409: 	'<th>'.&mt('Prob.').'</th>'.
 5410: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5411: 	&Apache::loncommon::end_data_table_header_row();
 5412: 
 5413:     &Apache::lonxml::clear_problem_counter();
 5414:     my ($depth,$question,$prob) = (1,1,1);
 5415:     $iterator->next(); # skip the first BEGIN_MAP
 5416:     my $curRes = $iterator->next(); # for "current resource"
 5417:     while ($depth > 0) {
 5418:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5419:         if($curRes == $iterator->END_MAP) { $depth--; }
 5420: 
 5421:         if (ref($curRes) && $curRes->is_problem()) {
 5422: 	    my $parts = $curRes->parts();
 5423:             my $title = $curRes->compTitle();
 5424: 	    my $symbx = $curRes->symb();
 5425: 	    $studentTable.=
 5426: 		&Apache::loncommon::start_data_table_row().
 5427: 		'<td align="center" valign="top" >'.$prob.
 5428: 		(scalar(@{$parts}) == 1 ? '' 
 5429: 		                        : '<br />('.&mt('[_1]parts',
 5430: 							scalar(@{$parts}).'&nbsp;').')'
 5431: 		 ).
 5432: 		 '</td>';
 5433: 	    $studentTable.='<td valign="top">';
 5434: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5435: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5436: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5437: 					     undef,'both',\%form);
 5438: 	    } else {
 5439: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5440: 		$companswer =~ s|<form(.*?)>||g;
 5441: 		$companswer =~ s|</form>||g;
 5442: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5443: #		    $companswer =~ s/$1/ /ms;
 5444: #		    $request->print('match='.$1."<br />\n");
 5445: #		}
 5446: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5447: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5448: 	    }
 5449: 
 5450: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5451: 
 5452: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5453: 		if ($record{'version'} eq '') {
 5454: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5455: 		} else {
 5456: 		    my %responseType = ();
 5457: 		    foreach my $partid (@{$parts}) {
 5458: 			my @responseIds =$curRes->responseIds($partid);
 5459: 			my @responseType =$curRes->responseType($partid);
 5460: 			my %responseIds;
 5461: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5462: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5463: 			}
 5464: 			$responseType{$partid} = \%responseIds;
 5465: 		    }
 5466: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5467: 
 5468: 		}
 5469: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5470: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5471:                 my $identifier = (&canmodify($usec)? $prob : '');
 5472: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5473: 									$env{'request.course.id'},
 5474: 									'','.submission',undef,
 5475:                                                                         $usec,$identifier);
 5476:  
 5477: 	    }
 5478: 	    if (&canmodify($usec)) {
 5479:             $studentTable.=&gradeBox_start();
 5480: 		foreach my $partid (@{$parts}) {
 5481: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5482: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5483: 		    $question++;
 5484: 		}
 5485:             $studentTable.=&gradeBox_end();
 5486: 		$prob++;
 5487: 	    }
 5488: 	    $studentTable.='</td></tr>';
 5489: 
 5490: 	}
 5491:         $curRes = $iterator->next();
 5492:     }
 5493:     my $disabled;
 5494:     unless (&canmodify($usec)) {
 5495:         $disabled = ' disabled="disabled"';
 5496:     }
 5497: 
 5498:     $studentTable.=
 5499:         '</table>'."\n".
 5500:         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
 5501:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5502:         '</form>'."\n";
 5503:     $request->print($studentTable);
 5504: 
 5505:     return '';
 5506: }
 5507: 
 5508: sub displaySubByDates {
 5509:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5510:     my $isCODE=0;
 5511:     my $isTask = ($symb =~/\.task$/);
 5512:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5513:     my $studentTable=&Apache::loncommon::start_data_table().
 5514: 	&Apache::loncommon::start_data_table_header_row().
 5515: 	'<th>'.&mt('Date/Time').'</th>'.
 5516: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5517:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5518: 	'<th>'.&mt('Submission').'</th>'.
 5519: 	'<th>'.&mt('Status').'</th>'.
 5520: 	&Apache::loncommon::end_data_table_header_row();
 5521:     my ($version);
 5522:     my %mark;
 5523:     my %orders;
 5524:     $mark{'correct_by_student'} = $checkIcon;
 5525:     if (!exists($$record{'1:timestamp'})) {
 5526: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5527:     }
 5528: 
 5529:     my $interaction;
 5530:     my $no_increment = 1;
 5531:     my (%lastrndseed,%lasttype);
 5532:     for ($version=1;$version<=$$record{'version'};$version++) {
 5533: 	my $timestamp = 
 5534: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5535: 	if (exists($$record{$version.':resource.0.version'})) {
 5536: 	    $interaction = $$record{$version.':resource.0.version'};
 5537: 	}
 5538:         if ($isTask && $env{'form.previousversion'}) {
 5539:             next unless ($interaction == $env{'form.previousversion'});
 5540:         }
 5541: 	my $where = ($isTask ? "$version:resource.$interaction"
 5542: 		             : "$version:resource");
 5543: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5544: 	    '<td>'.$timestamp.'</td>';
 5545: 	if ($isCODE) {
 5546: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5547: 	}
 5548:         if ($isTask) {
 5549:             $studentTable.='<td>'.$interaction.'</td>';
 5550:         }
 5551: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5552: 	my @displaySub = ();
 5553: 	foreach my $partid (@{$parts}) {
 5554:             my ($hidden,$type);
 5555:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5556:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5557:                 $hidden = 1;
 5558:             }
 5559: 	    my @matchKey;
 5560:             if ($isTask) {
 5561:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
 5562:             } else {
 5563: 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5564:             }
 5565: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5566: 	    my $display_part=&get_display_part($partid,$symb);
 5567: 	    foreach my $matchKey (@matchKey) {
 5568: 		if (exists($$record{$version.':'.$matchKey}) &&
 5569: 		    $$record{$version.':'.$matchKey} ne '') {
 5570:                     
 5571: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5572: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5573:                     $displaySub[0].='<span class="LC_nobreak">';
 5574:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5575:                                    .' <span class="LC_internal_info">'
 5576:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5577:                                    .'</span>'
 5578:                                    .' <b>';
 5579:                     if ($hidden) {
 5580:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5581:                     } else {
 5582:                         my ($trial,$rndseed,$newvariation);
 5583:                         if ($type eq 'randomizetry') {
 5584:                             $trial = $$record{"$where.$partid.tries"};
 5585:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5586:                         }
 5587: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5588: 			    $displaySub[0].=&mt('Trial not counted');
 5589: 		        } else {
 5590: 			    $displaySub[0].=&mt('Trial: [_1]',
 5591: 					    $$record{"$where.$partid.tries"});
 5592:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5593:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5594:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5595:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5596:                                 }
 5597:                             }
 5598:                             $lastrndseed{$partid} = $rndseed;
 5599:                             $lasttype{$partid} = $type;
 5600: 		        }
 5601: 		        my $responseType=($isTask ? 'Task'
 5602:                                               : $responseType->{$partid}->{$responseId});
 5603: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5604: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5605: 			    $orders{$partid}->{$responseId}=
 5606: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5607:                                            $no_increment,$type,$trial,$rndseed);
 5608: 		        }
 5609: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5610: 		        $displaySub[0].='&nbsp; '.
 5611: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5612:                     }
 5613: 		}
 5614: 	    }
 5615: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5616: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5617: 				    $$record{"$where.$partid.checkedin"},
 5618: 				    $$record{"$where.$partid.checkedin.slot"}).
 5619: 					'<br />';
 5620: 	    }
 5621: 	    if (exists $$record{"$where.$partid.award"}) {
 5622: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5623: 		    lc($$record{"$where.$partid.award"}).' '.
 5624: 		    $mark{$$record{"$where.$partid.solved"}}.
 5625: 		    '<br />';
 5626: 	    }
 5627: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5628: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5629: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5630: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5631: 		$displaySub[2].=
 5632: 		    $$record{"$version:resource.$partid.regrader"}.
 5633: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5634: 	    }
 5635: 	}
 5636: 	# needed because old essay regrader has not parts info
 5637: 	if (exists $$record{"$version:resource.regrader"}) {
 5638: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5639: 	}
 5640: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5641: 	if ($displaySub[2]) {
 5642: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5643: 	}
 5644: 	$studentTable.='&nbsp;</td>'.
 5645: 	    &Apache::loncommon::end_data_table_row();
 5646:     }
 5647:     $studentTable.=&Apache::loncommon::end_data_table();
 5648:     return $studentTable;
 5649: }
 5650: 
 5651: sub updateGradeByPage {
 5652:     my ($request,$symb) = @_;
 5653: 
 5654:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5655:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5656:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5657:     my $pageTitle = $env{'form.page'};
 5658:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5659:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5660:     my $usec=$classlist->{$env{'form.student'}}[5];
 5661:     if (!&canmodify($usec)) {
 5662: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5663: 	return;
 5664:     }
 5665:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5666:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5667: 	'</h3>'."\n";
 5668: 
 5669:     $request->print($result);
 5670: 
 5671: 
 5672:     my $navmap = Apache::lonnavmaps::navmap->new();
 5673:     unless (ref($navmap)) {
 5674:         $request->print(&navmap_errormsg());
 5675:         return;
 5676:     }
 5677:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5678:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5679:     if (!$map) {
 5680: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5681: 	return; 
 5682:     }
 5683:     my $iterator = $navmap->getIterator($map->map_start(),
 5684: 					$map->map_finish());
 5685: 
 5686:     my $studentTable=
 5687: 	&Apache::loncommon::start_data_table().
 5688: 	&Apache::loncommon::start_data_table_header_row().
 5689: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5690: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5691: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5692: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5693: 	&Apache::loncommon::end_data_table_header_row();
 5694: 
 5695:     $iterator->next(); # skip the first BEGIN_MAP
 5696:     my $curRes = $iterator->next(); # for "current resource"
 5697:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5698:     while ($depth > 0) {
 5699:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5700:         if($curRes == $iterator->END_MAP) { $depth--; }
 5701: 
 5702:         if (ref($curRes) && $curRes->is_problem()) {
 5703: 	    my $parts = $curRes->parts();
 5704:             my $title = $curRes->compTitle();
 5705: 	    my $symbx = $curRes->symb();
 5706: 	    $studentTable.=
 5707: 		&Apache::loncommon::start_data_table_row().
 5708: 		'<td align="center" valign="top" >'.$prob.
 5709: 		(scalar(@{$parts}) == 1 ? '' 
 5710:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5711: 		.')').'</td>';
 5712: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5713: 
 5714: 	    my %newrecord=();
 5715: 	    my @displayPts=();
 5716:             my %aggregate = ();
 5717:             my $aggregateflag = 0;
 5718:             my %queueable;
 5719:             if ($env{'form.HIDE'.$prob}) {
 5720:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5721:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5722:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5723:                 $hideflag += $numchgs;
 5724:             }
 5725: 	    foreach my $partid (@{$parts}) {
 5726: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5727: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5728:                 my @types = $curRes->responseType($partid);
 5729:                 if (grep(/^essay$/,@types)) {
 5730:                     $queueable{$partid} = 1;
 5731:                 } else {
 5732:                     my @ids = $curRes->responseIds($partid);
 5733:                     for (my $i=0; $i < scalar(@ids); $i++) {
 5734:                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
 5735:                                                           '.handgrade',$symb);
 5736:                         if (lc($hndgrd) eq 'yes') {
 5737:                             $queueable{$partid} = 1;
 5738:                             last;
 5739:                         }
 5740:                     }
 5741:                 }
 5742: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5743: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5744: 		my $partial = $newpts/$wgt;
 5745: 		my $score;
 5746: 		if ($partial > 0) {
 5747: 		    $score = 'correct_by_override';
 5748: 		} elsif ($newpts ne '') { #empty is taken as 0
 5749: 		    $score = 'incorrect_by_override';
 5750: 		}
 5751: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5752: 		if ($dropMenu eq 'excused') {
 5753: 		    $partial = '';
 5754: 		    $score = 'excused';
 5755: 		} elsif ($dropMenu eq 'reset status'
 5756: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5757: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5758: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5759: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5760: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5761: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5762: 		    $changeflag++;
 5763: 		    $newpts = '';
 5764:                     
 5765:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5766:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5767:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5768:                     if ($aggtries > 0) {
 5769:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5770:                         $aggregateflag = 1;
 5771:                     }
 5772: 		}
 5773: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5774: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5775: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5776: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5777: 		    '&nbsp;<br />';
 5778: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5779: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5780: 		    '&nbsp;<br />';
 5781: 		$question++;
 5782: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5783: 
 5784: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5785: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5786: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5787: 		    if (scalar(keys(%newrecord)) > 0);
 5788: 
 5789: 		$changeflag++;
 5790: 	    }
 5791: 	    if (scalar(keys(%newrecord)) > 0) {
 5792: 		my %record = 
 5793: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5794: 					     $udom,$uname);
 5795: 
 5796: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5797: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5798: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5799: 		    $newrecord{'resource.CODE'} = '';
 5800: 		}
 5801: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5802: 					$udom,$uname);
 5803: 		%record = &Apache::lonnet::restore($symbx,
 5804: 						   $env{'request.course.id'},
 5805: 						   $udom,$uname);
 5806: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5807: 					     $cdom,$cnum,$udom,$uname,\%queueable);
 5808: 	    }
 5809: 	    
 5810:             if ($aggregateflag) {
 5811:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5812:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5813:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5814:             }
 5815: 
 5816: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5817: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5818: 		&Apache::loncommon::end_data_table_row();
 5819: 
 5820: 	    $prob++;
 5821: 	}
 5822:         $curRes = $iterator->next();
 5823:     }
 5824: 
 5825:     $studentTable.=&Apache::loncommon::end_data_table();
 5826:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5827: 		  &mt('The scores were changed for [quant,_1,problem].',
 5828: 		  $changeflag).'<br />');
 5829:     my $hidemsg=($hideflag == 0 ? '' :
 5830:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5831:                      $hideflag).'<br />');
 5832:     $request->print($hidemsg.$grademsg.$studentTable);
 5833: 
 5834:     return '';
 5835: }
 5836: 
 5837: #-------- end of section for handling grading by page/sequence ---------
 5838: #
 5839: #-------------------------------------------------------------------
 5840: 
 5841: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5842: #
 5843: #------ start of section for handling grading by page/sequence ---------
 5844: 
 5845: =pod
 5846: 
 5847: =head1 Bubble sheet grading routines
 5848: 
 5849:   For this documentation:
 5850: 
 5851:    'scanline' refers to the full line of characters
 5852:    from the file that we are parsing that represents one entire sheet
 5853: 
 5854:    'bubble line' refers to the data
 5855:    representing the line of bubbles that are on the physical bubblesheet
 5856: 
 5857: 
 5858: The overall process is that a scanned in bubblesheet data is uploaded
 5859: into a course. When a user wants to grade, they select a
 5860: sequence/folder of resources, a file of bubblesheet info, and pick
 5861: one of the predefined configurations for what each scanline looks
 5862: like.
 5863: 
 5864: Next each scanline is checked for any errors of either 'missing
 5865: bubbles' (it's an error because it may have been mis-scanned
 5866: because too light bubbling), 'double bubble' (each bubble line should
 5867: have no more than one letter picked), invalid or duplicated CODE,
 5868: invalid student/employee ID
 5869: 
 5870: If the CODE option is used that determines the randomization of the
 5871: homework problems, either way the student/employee ID is looked up into a
 5872: username:domain.
 5873: 
 5874: During the validation phase the instructor can choose to skip scanlines. 
 5875: 
 5876: After the validation phase, there are now 3 bubblesheet files
 5877: 
 5878:   scantron_original_filename (unmodified original file)
 5879:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5880:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5881: 
 5882: Also there is a separate hash nohist_scantrondata that contains extra
 5883: correction information that isn't representable in the bubblesheet
 5884: file (see &scantron_getfile() for more information)
 5885: 
 5886: After all scanlines are either valid, marked as valid or skipped, then
 5887: foreach line foreach problem in the picked sequence, an ssi request is
 5888: made that simulates a user submitting their selected letter(s) against
 5889: the homework problem.
 5890: 
 5891: =over 4
 5892: 
 5893: 
 5894: 
 5895: =item defaultFormData
 5896: 
 5897:   Returns html hidden inputs used to hold context/default values.
 5898: 
 5899:  Arguments:
 5900:   $symb - $symb of the current resource 
 5901: 
 5902: =cut
 5903: 
 5904: sub defaultFormData {
 5905:     my ($symb)=@_;
 5906:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5907: }
 5908: 
 5909: 
 5910: =pod 
 5911: 
 5912: =item getSequenceDropDown
 5913: 
 5914:    Return html dropdown of possible sequences to grade
 5915:  
 5916:  Arguments:
 5917:    $symb - $symb of the current resource
 5918:    $map_error - ref to scalar which will container error if
 5919:                 $navmap object is unavailable in &getSymbMap().
 5920: 
 5921: =cut
 5922: 
 5923: sub getSequenceDropDown {
 5924:     my ($symb,$map_error)=@_;
 5925:     my $result='<select name="selectpage">'."\n";
 5926:     my ($titles,$symbx) = &getSymbMap($map_error);
 5927:     if (ref($map_error)) {
 5928:         return if ($$map_error);
 5929:     }
 5930:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5931:     my $ctr=0;
 5932:     foreach (@$titles) {
 5933: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5934: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5935: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5936: 	    '>'.$showtitle.'</option>'."\n";
 5937: 	$ctr++;
 5938:     }
 5939:     $result.= '</select>';
 5940:     return $result;
 5941: }
 5942: 
 5943: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5944:                                    # key is zero-based index - 0, 1, 2 ...
 5945: 
 5946: my %first_bubble_line;             # First bubble line no. for each bubble.
 5947: 
 5948: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5949:                                    # matchresponse or rankresponse, where 
 5950:                                    # an individual response can have multiple 
 5951:                                    # lines
 5952: 
 5953: my %responsetype_per_response;     # responsetype for each response
 5954: 
 5955: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5956:                                    # numbered response. Needed when randomorder
 5957:                                    # or randompick are in use. Key is ID, value 
 5958:                                    # is response number.
 5959: 
 5960: # Save and restore the bubble lines array to the form env.
 5961: 
 5962: 
 5963: sub save_bubble_lines {
 5964:     foreach my $line (keys(%bubble_lines_per_response)) {
 5965: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5966: 	$env{"form.scantron.first_bubble_line.$line"} =
 5967: 	    $first_bubble_line{$line};
 5968:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5969:             $subdivided_bubble_lines{$line};
 5970:         $env{"form.scantron.responsetype.$line"} =
 5971:             $responsetype_per_response{$line};
 5972:     }
 5973:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5974:         my $line = $masterseq_id_responsenum{$resid};
 5975:         $env{"form.scantron.residpart.$line"} = $resid;
 5976:     }
 5977: }
 5978: 
 5979: 
 5980: sub restore_bubble_lines {
 5981:     my $line = 0;
 5982:     %bubble_lines_per_response = ();
 5983:     %masterseq_id_responsenum = ();
 5984:     while ($env{"form.scantron.bubblelines.$line"}) {
 5985: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5986: 	$bubble_lines_per_response{$line} = $value;
 5987: 	$first_bubble_line{$line}  =
 5988: 	    $env{"form.scantron.first_bubble_line.$line"};
 5989:         $subdivided_bubble_lines{$line} =
 5990:             $env{"form.scantron.sub_bubblelines.$line"};
 5991:         $responsetype_per_response{$line} =
 5992:             $env{"form.scantron.responsetype.$line"};
 5993:         my $id = $env{"form.scantron.residpart.$line"};
 5994:         $masterseq_id_responsenum{$id} = $line;
 5995: 	$line++;
 5996:     }
 5997: }
 5998: 
 5999: =pod 
 6000: 
 6001: =item scantron_filenames
 6002: 
 6003:    Returns a list of the scantron files in the current course 
 6004: 
 6005: =cut
 6006: 
 6007: sub scantron_filenames {
 6008:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6009:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6010:     my $getpropath = 1;
 6011:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 6012:                                                         $cname,$getpropath);
 6013:     my @possiblenames;
 6014:     if (ref($dirlist) eq 'ARRAY') {
 6015:         foreach my $filename (sort(@{$dirlist})) {
 6016: 	    ($filename)=split(/&/,$filename);
 6017: 	    if ($filename!~/^scantron_orig_/) { next ; }
 6018: 	    $filename=~s/^scantron_orig_//;
 6019: 	    push(@possiblenames,$filename);
 6020:         }
 6021:     }
 6022:     return @possiblenames;
 6023: }
 6024: 
 6025: =pod 
 6026: 
 6027: =item scantron_uploads
 6028: 
 6029:    Returns  html drop-down list of scantron files in current course.
 6030: 
 6031:  Arguments:
 6032:    $file2grade - filename to set as selected in the dropdown
 6033: 
 6034: =cut
 6035: 
 6036: sub scantron_uploads {
 6037:     my ($file2grade) = @_;
 6038:     my $result=	'<select name="scantron_selectfile">';
 6039:     $result.="<option></option>";
 6040:     foreach my $filename (sort(&scantron_filenames())) {
 6041: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 6042:     }
 6043:     $result.="</select>";
 6044:     return $result;
 6045: }
 6046: 
 6047: =pod 
 6048: 
 6049: =item scantron_scantab
 6050: 
 6051:   Returns html drop down of the scantron formats in the scantronformat.tab
 6052:   file.
 6053: 
 6054: =cut
 6055: 
 6056: sub scantron_scantab {
 6057:     my $result='<select name="scantron_format">'."\n";
 6058:     $result.='<option></option>'."\n";
 6059:     my @lines = &Apache::lonnet::get_scantronformat_file();
 6060:     if (@lines > 0) {
 6061:         foreach my $line (@lines) {
 6062:             next if (($line =~ /^\#/) || ($line eq ''));
 6063: 	    my ($name,$descrip)=split(/:/,$line);
 6064: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 6065:         }
 6066:     }
 6067:     $result.='</select>'."\n";
 6068:     return $result;
 6069: }
 6070: 
 6071: =pod 
 6072: 
 6073: =item scantron_CODElist
 6074: 
 6075:   Returns html drop down of the saved CODE lists from current course,
 6076:   generated from earlier printings.
 6077: 
 6078: =cut
 6079: 
 6080: sub scantron_CODElist {
 6081:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6082:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6083:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 6084:     my $namechoice='<option></option>';
 6085:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 6086: 	if ($name =~ /^error: 2 /) { next; }
 6087: 	if ($name =~ /^type\0/) { next; }
 6088: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 6089:     }
 6090:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 6091:     return $namechoice;
 6092: }
 6093: 
 6094: =pod 
 6095: 
 6096: =item scantron_CODEunique
 6097: 
 6098:   Returns the html for "Each CODE to be used once" radio.
 6099: 
 6100: =cut
 6101: 
 6102: sub scantron_CODEunique {
 6103:     my $result='<span class="LC_nobreak">
 6104:                  <label><input type="radio" name="scantron_CODEunique"
 6105:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 6106:                 </span>
 6107:                 <span class="LC_nobreak">
 6108:                  <label><input type="radio" name="scantron_CODEunique"
 6109:                         value="no" />'.&mt('No').' </label>
 6110:                 </span>';
 6111:     return $result;
 6112: }
 6113: 
 6114: =pod 
 6115: 
 6116: =item scantron_selectphase
 6117: 
 6118:   Generates the initial screen to start the bubblesheet process.
 6119:   Allows for - starting a grading run.
 6120:              - downloading existing scan data (original, corrected
 6121:                                                 or skipped info)
 6122: 
 6123:              - uploading new scan data
 6124: 
 6125:  Arguments:
 6126:   $r          - The Apache request object
 6127:   $file2grade - name of the file that contain the scanned data to score
 6128: 
 6129: =cut
 6130: 
 6131: sub scantron_selectphase {
 6132:     my ($r,$file2grade,$symb) = @_;
 6133:     if (!$symb) {return '';}
 6134:     my $map_error;
 6135:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 6136:     if ($map_error) {
 6137:         $r->print('<br />'.&navmap_errormsg().'<br />');
 6138:         return;
 6139:     }
 6140:     my $default_form_data=&defaultFormData($symb);
 6141:     my $file_selector=&scantron_uploads($file2grade);
 6142:     my $format_selector=&scantron_scantab();
 6143:     my $CODE_selector=&scantron_CODElist();
 6144:     my $CODE_unique=&scantron_CODEunique();
 6145:     my $result;
 6146: 
 6147:     $ssi_error = 0;
 6148: 
 6149:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 6150:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 6151: 
 6152:         # Chunk of form to prompt for a scantron file upload.
 6153: 
 6154:         $r->print('
 6155:     <br />');
 6156:         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 6157:         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 6158:         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 6159:         &js_escape(\$alertmsg);
 6160:         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
 6161:         $r->print(&Apache::lonhtmlcommon::scripttag('
 6162:     function checkUpload(formname) {
 6163:         if (formname.upfile.value == "") {
 6164:             alert("'.$alertmsg.'");
 6165:             return false;
 6166:         }
 6167:         formname.submit();
 6168:     }'."\n".$formatjs));
 6169:         $r->print('
 6170:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 6171:                 '.$default_form_data.'
 6172:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 6173:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 6174:                 <input name="command" value="scantronupload_save" type="hidden" />
 6175:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6176:               '.&Apache::loncommon::start_data_table_header_row().'
 6177:                 <th>
 6178:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 6179:                 </th>
 6180:               '.&Apache::loncommon::end_data_table_header_row().'
 6181:               '.&Apache::loncommon::start_data_table_row().'
 6182:             <td>
 6183:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
 6184:         if ($formatoptions) {
 6185:             $r->print('</td>
 6186:                  '.&Apache::loncommon::end_data_table_row().'
 6187:                  '.&Apache::loncommon::start_data_table_row().'
 6188:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
 6189:                  </td>
 6190:                  '.&Apache::loncommon::end_data_table_row().'
 6191:                  '.&Apache::loncommon::start_data_table_row().'
 6192:                  <td>'
 6193:             );
 6194:         } else {
 6195:             $r->print(' <br />');
 6196:         }
 6197:         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 6198:               </td>
 6199:              '.&Apache::loncommon::end_data_table_row().'
 6200:              '.&Apache::loncommon::end_data_table().'
 6201:              </form>'
 6202:         );
 6203: 
 6204:     }
 6205: 
 6206:     # Chunk of form to prompt for a file to grade and how:
 6207: 
 6208:     $result.= '
 6209:     <br />
 6210:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 6211:     <input type="hidden" name="command" value="scantron_warning" />
 6212:     '.$default_form_data.'
 6213:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6214:        '.&Apache::loncommon::start_data_table_header_row().'
 6215:             <th colspan="2">
 6216:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 6217:             </th>
 6218:        '.&Apache::loncommon::end_data_table_header_row().'
 6219:        '.&Apache::loncommon::start_data_table_row().'
 6220:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 6221:        '.&Apache::loncommon::end_data_table_row().'
 6222:        '.&Apache::loncommon::start_data_table_row().'
 6223:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 6224:        '.&Apache::loncommon::end_data_table_row().'
 6225:        '.&Apache::loncommon::start_data_table_row().'
 6226:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 6227:        '.&Apache::loncommon::end_data_table_row().'
 6228:        '.&Apache::loncommon::start_data_table_row().'
 6229:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 6230:        '.&Apache::loncommon::end_data_table_row().'
 6231:        '.&Apache::loncommon::start_data_table_row().'
 6232:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 6233:        '.&Apache::loncommon::end_data_table_row().'
 6234:        '.&Apache::loncommon::start_data_table_row().'
 6235: 	    <td> '.&mt('Options:').' </td>
 6236:             <td>
 6237: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 6238:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 6239:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 6240: 	    </td>
 6241:        '.&Apache::loncommon::end_data_table_row().'
 6242:        '.&Apache::loncommon::start_data_table_row().'
 6243:             <td colspan="2">
 6244:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 6245:             </td>
 6246:        '.&Apache::loncommon::end_data_table_row().'
 6247:     '.&Apache::loncommon::end_data_table().'
 6248:     </form>
 6249: ';
 6250:    
 6251:     $r->print($result);
 6252: 
 6253:     # Chunk of the form that prompts to view a scoring office file,
 6254:     # corrected file, skipped records in a file.
 6255: 
 6256:     $r->print('
 6257:    <br />
 6258:    <form action="/adm/grades" name="scantron_download">
 6259:      '.$default_form_data.'
 6260:      <input type="hidden" name="command" value="scantron_download" />
 6261:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6262:        '.&Apache::loncommon::start_data_table_header_row().'
 6263:               <th>
 6264:                 &nbsp;'.&mt('Download a scoring office file').'
 6265:               </th>
 6266:        '.&Apache::loncommon::end_data_table_header_row().'
 6267:        '.&Apache::loncommon::start_data_table_row().'
 6268:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6269:                 <br />
 6270:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6271:        '.&Apache::loncommon::end_data_table_row().'
 6272:      '.&Apache::loncommon::end_data_table().'
 6273:    </form>
 6274:    <br />
 6275: ');
 6276: 
 6277:     &Apache::lonpickcode::code_list($r,2);
 6278: 
 6279:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6280:              $default_form_data."\n".
 6281:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6282:              &Apache::loncommon::start_data_table_header_row()."\n".
 6283:              '<th colspan="2">
 6284:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6285:              '</th>'."\n".
 6286:               &Apache::loncommon::end_data_table_header_row()."\n".
 6287:               &Apache::loncommon::start_data_table_row()."\n".
 6288:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6289:               '<td> '.$sequence_selector.' </td>'.
 6290:               &Apache::loncommon::end_data_table_row()."\n".
 6291:               &Apache::loncommon::start_data_table_row()."\n".
 6292:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6293:               '<td> '.$file_selector.' </td>'."\n".
 6294:               &Apache::loncommon::end_data_table_row()."\n".
 6295:               &Apache::loncommon::start_data_table_row()."\n".
 6296:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6297:               '<td> '.$format_selector.' </td>'."\n".
 6298:               &Apache::loncommon::end_data_table_row()."\n".
 6299:               &Apache::loncommon::start_data_table_row()."\n".
 6300:               '<td> '.&mt('Options').' </td>'."\n".
 6301:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6302:               &Apache::loncommon::end_data_table_row()."\n".
 6303:               &Apache::loncommon::start_data_table_row()."\n".
 6304:               '<td colspan="2">'."\n".
 6305:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6306:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6307:               '</td>'."\n".
 6308:               &Apache::loncommon::end_data_table_row()."\n".
 6309:               &Apache::loncommon::end_data_table()."\n".
 6310:               '</form><br />');
 6311:     return;
 6312: }
 6313: 
 6314: =pod 
 6315: 
 6316: =item username_to_idmap
 6317: 
 6318:     creates a hash keyed by student/employee ID with values of the corresponding
 6319:     student username:domain.
 6320: 
 6321:   Arguments:
 6322: 
 6323:     $classlist - reference to the class list hash. This is a hash
 6324:                  keyed by student name:domain  whose elements are references
 6325:                  to arrays containing various chunks of information
 6326:                  about the student. (See loncoursedata for more info).
 6327: 
 6328:   Returns
 6329:     %idmap - the constructed hash
 6330: 
 6331: =cut
 6332: 
 6333: sub username_to_idmap {
 6334:     my ($classlist)= @_;
 6335:     my %idmap;
 6336:     foreach my $student (keys(%$classlist)) {
 6337:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6338:         unless ($id eq '') {
 6339:             if (!exists($idmap{$id})) {
 6340:                 $idmap{$id} = $student;
 6341:             } else {
 6342:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6343:                 if ($status eq 'Active') {
 6344:                     $idmap{$id} = $student;
 6345:                 }
 6346:             }
 6347:         }
 6348:     }
 6349:     return %idmap;
 6350: }
 6351: 
 6352: =pod
 6353: 
 6354: =item scantron_fixup_scanline
 6355: 
 6356:    Process a requested correction to a scanline.
 6357: 
 6358:   Arguments:
 6359:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
 6360:     $scan_data         - hash of correction information 
 6361:                           (see &scantron_getfile())
 6362:     $line              - existing scanline
 6363:     $whichline         - line number of the passed in scanline
 6364:     $field             - type of change to process 
 6365:                          (either 
 6366:                           'ID'     -> correct the student/employee ID
 6367:                           'CODE'   -> correct the CODE
 6368:                           'answer' -> fixup the submitted answers)
 6369:     
 6370:    $args               - hash of additional info,
 6371:                           - 'ID' 
 6372:                                'newid' -> studentID to use in replacement
 6373:                                           of existing one
 6374:                           - 'CODE' 
 6375:                                'CODE_ignore_dup' - set to true if duplicates
 6376:                                                    should be ignored.
 6377: 	                       'CODE' - is new code or 'use_unfound'
 6378:                                         if the existing unfound code should
 6379:                                         be used as is
 6380:                           - 'answer'
 6381:                                'response' - new answer or 'none' if blank
 6382:                                'question' - the bubble line to change
 6383:                                'questionnum' - the question identifier,
 6384:                                                may include subquestion. 
 6385: 
 6386:   Returns:
 6387:     $line - the modified scanline
 6388: 
 6389:   Side effects: 
 6390:     $scan_data - may be updated
 6391: 
 6392: =cut
 6393: 
 6394: 
 6395: sub scantron_fixup_scanline {
 6396:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6397:     if ($field eq 'ID') {
 6398: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6399: 	    return ($line,1,'New value too large');
 6400: 	}
 6401: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6402: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6403: 				     $args->{'newid'});
 6404: 	}
 6405: 	substr($line,$$scantron_config{'IDstart'}-1,
 6406: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6407: 	if ($args->{'newid'}=~/^\s*$/) {
 6408: 	    &scan_data($scan_data,"$whichline.user",
 6409: 		       $args->{'username'}.':'.$args->{'domain'});
 6410: 	}
 6411:     } elsif ($field eq 'CODE') {
 6412: 	if ($args->{'CODE_ignore_dup'}) {
 6413: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6414: 	}
 6415: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6416: 	if ($args->{'CODE'} ne 'use_unfound') {
 6417: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6418: 		return ($line,1,'New CODE value too large');
 6419: 	    }
 6420: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6421: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6422: 	    }
 6423: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6424: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6425: 	}
 6426:     } elsif ($field eq 'answer') {
 6427: 	my $length=$scantron_config->{'Qlength'};
 6428: 	my $off=$scantron_config->{'Qoff'};
 6429: 	my $on=$scantron_config->{'Qon'};
 6430: 	my $answer=${off}x$length;
 6431: 	if ($args->{'response'} eq 'none') {
 6432: 	    &scan_data($scan_data,
 6433: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6434: 	} else {
 6435: 	    if ($on eq 'letter') {
 6436: 		my @alphabet=('A'..'Z');
 6437: 		$answer=$alphabet[$args->{'response'}];
 6438: 	    } elsif ($on eq 'number') {
 6439: 		$answer=$args->{'response'}+1;
 6440: 		if ($answer == 10) { $answer = '0'; }
 6441: 	    } else {
 6442: 		substr($answer,$args->{'response'},1)=$on;
 6443: 	    }
 6444: 	    &scan_data($scan_data,
 6445: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6446: 	}
 6447: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6448: 	substr($line,$where-1,$length)=$answer;
 6449:     }
 6450:     return $line;
 6451: }
 6452: 
 6453: =pod
 6454: 
 6455: =item scan_data
 6456: 
 6457:     Edit or look up  an item in the scan_data hash.
 6458: 
 6459:   Arguments:
 6460:     $scan_data  - The hash (see scantron_getfile)
 6461:     $key        - shorthand of the key to edit (actual key is
 6462:                   scantronfilename_key).
 6463:     $data        - New value of the hash entry.
 6464:     $delete      - If true, the entry is removed from the hash.
 6465: 
 6466:   Returns:
 6467:     The new value of the hash table field (undefined if deleted).
 6468: 
 6469: =cut
 6470: 
 6471: 
 6472: sub scan_data {
 6473:     my ($scan_data,$key,$value,$delete)=@_;
 6474:     my $filename=$env{'form.scantron_selectfile'};
 6475:     if (defined($value)) {
 6476: 	$scan_data->{$filename.'_'.$key} = $value;
 6477:     }
 6478:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6479:     return $scan_data->{$filename.'_'.$key};
 6480: }
 6481: 
 6482: # ----- These first few routines are general use routines.----
 6483: 
 6484: # Return the number of occurences of a pattern in a string.
 6485: 
 6486: sub occurence_count {
 6487:     my ($string, $pattern) = @_;
 6488: 
 6489:     my @matches = ($string =~ /$pattern/g);
 6490: 
 6491:     return scalar(@matches);
 6492: }
 6493: 
 6494: 
 6495: # Take a string known to have digits and convert all the
 6496: # digits into letters in the range J,A..I.
 6497: 
 6498: sub digits_to_letters {
 6499:     my ($input) = @_;
 6500: 
 6501:     my @alphabet = ('J', 'A'..'I');
 6502: 
 6503:     my @input    = split(//, $input);
 6504:     my $output ='';
 6505:     for (my $i = 0; $i < scalar(@input); $i++) {
 6506: 	if ($input[$i] =~ /\d/) {
 6507: 	    $output .= $alphabet[$input[$i]];
 6508: 	} else {
 6509: 	    $output .= $input[$i];
 6510: 	}
 6511:     }
 6512:     return $output;
 6513: }
 6514: 
 6515: =pod 
 6516: 
 6517: =item scantron_parse_scanline
 6518: 
 6519:   Decodes a scanline from the selected scantron file
 6520: 
 6521:  Arguments:
 6522:     line             - The text of the scantron file line to process
 6523:     whichline        - Line number
 6524:     scantron_config  - Hash describing the format of the scantron lines.
 6525:     scan_data        - Hash of extra information about the scanline
 6526:                        (see scantron_getfile for more information)
 6527:     just_header      - True if should not process question answers but only
 6528:                        the stuff to the left of the answers.
 6529:     randomorder      - True if randomorder in use
 6530:     randompick       - True if randompick in use
 6531:     sequence         - Exam folder URL
 6532:     master_seq       - Ref to array containing symbs in exam folder
 6533:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6534:                        (corresponding values are resource objects)
 6535:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6536:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6537:                        are refs to an array of resource objects, ordered
 6538:                        according to order used for CODE, when randomorder
 6539:                        and or randompick are in use.
 6540:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6541:                        for current line to question number used for same question
 6542:                         in "Master Sequence" (as seen by Course Coordinator).
 6543:     startline        - Ref to hash where key is question number (0 is first)
 6544:                        and value is number of first bubble line for current 
 6545:                        student or code-based randompick and/or randomorder.
 6546:     totalref         - Ref of scalar used to score total number of bubble
 6547:                        lines needed for responses in a scan line (used when
 6548:                        randompick in use. 
 6549: 
 6550:  Returns:
 6551:    Hash containing the result of parsing the scanline
 6552: 
 6553:    Keys are all proceeded by the string 'scantron.'
 6554: 
 6555:        CODE    - the CODE in use for this scanline
 6556:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6557:                  by the operator
 6558:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6559:                             CODEs were selected, but the usage has been
 6560:                             forced by the operator
 6561:        ID  - student/employee ID
 6562:        PaperID - if used, the ID number printed on the sheet when the 
 6563:                  paper was scanned
 6564:        FirstName - first name from the sheet
 6565:        LastName  - last name from the sheet
 6566: 
 6567:      if just_header was not true these key may also exist
 6568: 
 6569:        missingerror - a list of bubble ranges that are considered to be answers
 6570:                       to a single question that don't have any bubbles filled in.
 6571:                       Of the form questionnumber:firstbubblenumber:count.
 6572:        doubleerror  - a list of bubble ranges that are considered to be answers
 6573:                       to a single question that have more than one bubble filled in.
 6574:                       Of the form questionnumber::firstbubblenumber:count
 6575:    
 6576:                 In the above, count is the number of bubble responses in the
 6577:                 input line needed to represent the possible answers to the question.
 6578:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6579:                 per line would have count = 2.
 6580: 
 6581:        maxquest     - the number of the last bubble line that was parsed
 6582: 
 6583:        (<number> starts at 1)
 6584:        <number>.answer - zero or more letters representing the selected
 6585:                          letters from the scanline for the bubble line 
 6586:                          <number>.
 6587:                          if blank there was either no bubble or there where
 6588:                          multiple bubbles, (consult the keys missingerror and
 6589:                          doubleerror if this is an error condition)
 6590: 
 6591: =cut
 6592: 
 6593: sub scantron_parse_scanline {
 6594:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6595:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6596:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6597: 
 6598:     my %record;
 6599:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6600:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6601: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6602: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6603: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6604: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6605: 	    $record{'scantron.CODE'}=substr($data,
 6606: 					    $$scantron_config{'CODEstart'}-1,
 6607: 					    $$scantron_config{'CODElength'});
 6608: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6609: 		$record{'scantron.useCODE'}=1;
 6610: 	    }
 6611: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6612: 		$record{'scantron.CODE_ignore_dup'}=1;
 6613: 	    }
 6614: 	} else {
 6615: 	    #FIXME interpret first N questions
 6616: 	}
 6617:     }
 6618:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6619: 				  $$scantron_config{'IDlength'});
 6620:     $record{'scantron.PaperID'}=
 6621: 	substr($data,$$scantron_config{'PaperID'}-1,
 6622: 	       $$scantron_config{'PaperIDlength'});
 6623:     $record{'scantron.FirstName'}=
 6624: 	substr($data,$$scantron_config{'FirstName'}-1,
 6625: 	       $$scantron_config{'FirstNamelength'});
 6626:     $record{'scantron.LastName'}=
 6627: 	substr($data,$$scantron_config{'LastName'}-1,
 6628: 	       $$scantron_config{'LastNamelength'});
 6629:     if ($just_header) { return \%record; }
 6630: 
 6631:     my @alphabet=('A'..'Z');
 6632:     my $questnum=0;
 6633:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6634: 
 6635:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6636:     if ($randompick || $randomorder) {
 6637:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6638:                                          $master_seq,$symb_to_resource,
 6639:                                          $partids_by_symb,$orderedforcode,
 6640:                                          $respnumlookup,$startline);
 6641:         if ($total) {
 6642:             $lastpos = $total*$$scantron_config{'Qlength'};
 6643:         }
 6644:         if (ref($totalref)) {
 6645:             $$totalref = $total;
 6646:         }
 6647:     }
 6648:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6649:     chomp($questions);		# Get rid of any trailing \n.
 6650:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6651:     while (length($questions)) {
 6652:         my $answers_needed;
 6653:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6654:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6655:         } else {
 6656:             $answers_needed = $bubble_lines_per_response{$questnum};
 6657:         }
 6658:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6659:                              || 1;
 6660:         $questnum++;
 6661:         my $quest_id = $questnum;
 6662:         my $currentquest = substr($questions,0,$answer_length);
 6663:         $questions       = substr($questions,$answer_length);
 6664:         if (length($currentquest) < $answer_length) { next; }
 6665: 
 6666:         my $subdivided;
 6667:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6668:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6669:         } else {
 6670:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6671:         }
 6672:         if ($subdivided =~ /,/) {
 6673:             my $subquestnum = 1;
 6674:             my $subquestions = $currentquest;
 6675:             my @subanswers_needed = split(/,/,$subdivided);
 6676:             foreach my $subans (@subanswers_needed) {
 6677:                 my $subans_length =
 6678:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6679:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6680:                 $subquestions   = substr($subquestions,$subans_length);
 6681:                 $quest_id = "$questnum.$subquestnum";
 6682:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6683:                     ($$scantron_config{'Qon'} eq 'number')) {
 6684:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6685:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6686:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6687:                         $randomorder,$randompick,$respnumlookup);
 6688:                 } else {
 6689:                     $ansnum = &scantron_validator_positional($ansnum,
 6690:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6691:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6692:                         $randomorder,$randompick,$respnumlookup);
 6693:                 }
 6694:                 $subquestnum ++;
 6695:             }
 6696:         } else {
 6697:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6698:                 ($$scantron_config{'Qon'} eq 'number')) {
 6699:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6700:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6701:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6702:                     $randomorder,$randompick,$respnumlookup);
 6703:             } else {
 6704:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6705:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6706:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6707:                     $randomorder,$randompick,$respnumlookup);
 6708:             }
 6709:         }
 6710:     }
 6711:     $record{'scantron.maxquest'}=$questnum;
 6712:     return \%record;
 6713: }
 6714: 
 6715: sub get_master_seq {
 6716:     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
 6717:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6718:                    (ref($symb_to_resource) eq 'HASH'));
 6719:     if ($need_symb_in_map) {
 6720:         return unless (ref($symb_for_examcode) eq 'HASH');
 6721:     }
 6722:     my $resource_error;
 6723:     foreach my $resource (@{$resources}) {
 6724:         my $ressymb;
 6725:         if (ref($resource)) {
 6726:             $ressymb = $resource->symb();
 6727:             push(@{$master_seq},$ressymb);
 6728:             $symb_to_resource->{$ressymb} = $resource;
 6729:             if ($need_symb_in_map) {
 6730:                 unless ($resource->is_map()) {
 6731:                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
 6732:                     unless (exists($symb_for_examcode->{$map})) {
 6733:                         $symb_for_examcode->{$map} = $ressymb;
 6734:                     }
 6735:                 }
 6736:             }
 6737:         } else {
 6738:             $resource_error = 1;
 6739:             last;
 6740:         }
 6741:     }
 6742:     return $resource_error;
 6743: }
 6744: 
 6745: sub get_respnum_lookups {
 6746:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6747:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6748:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6749:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6750:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6751:                    (ref($startline) eq 'HASH'));
 6752:     my ($user,$scancode);
 6753:     if ((exists($record->{'scantron.CODE'})) &&
 6754:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6755:         $scancode = $record->{'scantron.CODE'};
 6756:     } else {
 6757:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6758:     }
 6759:     my @mapresources =
 6760:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6761:                      $orderedforcode);
 6762:     my $total = 0;
 6763:     my $count = 0;
 6764:     foreach my $resource (@mapresources) {
 6765:         my $id = $resource->id();
 6766:         my $symb = $resource->symb();
 6767:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6768:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6769:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6770:                 if ($respnum ne '') {
 6771:                     $respnumlookup->{$count} = $respnum;
 6772:                     $startline->{$count} = $total;
 6773:                     $total += $bubble_lines_per_response{$respnum};
 6774:                     $count ++;
 6775:                 }
 6776:             }
 6777:         }
 6778:     }
 6779:     return $total;
 6780: }
 6781: 
 6782: sub scantron_validator_lettnum {
 6783:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6784:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6785:         $randompick,$respnumlookup) = @_;
 6786: 
 6787:     # Qon 'letter' implies for each slot in currquest we have:
 6788:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6789:     #    about anything else (esp. a value of Qoff) for missing
 6790:     #    bubbles.
 6791:     #
 6792:     # Qon 'number' implies each slot gives a digit that indexes the
 6793:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6794:     #    and * or ? for double bubbles on a single line.
 6795:     #
 6796: 
 6797:     my $matchon;
 6798:     if ($$scantron_config{'Qon'} eq 'letter') {
 6799:         $matchon = '[A-Z]';
 6800:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6801:         $matchon = '\d';
 6802:     }
 6803:     my $occurrences = 0;
 6804:     my $responsenum = $questnum-1;
 6805:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6806:        $responsenum = $respnumlookup->{$questnum-1}
 6807:     }
 6808:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6809:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6810:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6811:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6812:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6813:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6814:         my @singlelines = split('',$currquest);
 6815:         foreach my $entry (@singlelines) {
 6816:             $occurrences = &occurence_count($entry,$matchon);
 6817:             if ($occurrences > 1) {
 6818:                 last;
 6819:             }
 6820:         }
 6821:     } else {
 6822:         $occurrences = &occurence_count($currquest,$matchon); 
 6823:     }
 6824:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6825:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6826:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6827:             my $bubble = substr($currquest,$ans,1);
 6828:             if ($bubble =~ /$matchon/ ) {
 6829:                 if ($$scantron_config{'Qon'} eq 'number') {
 6830:                     if ($bubble == 0) {
 6831:                         $bubble = 10; 
 6832:                     }
 6833:                     $record->{"scantron.$ansnum.answer"} = 
 6834:                         $alphabet->[$bubble-1];
 6835:                 } else {
 6836:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6837:                 }
 6838:             } else {
 6839:                 $record->{"scantron.$ansnum.answer"}='';
 6840:             }
 6841:             $ansnum++;
 6842:         }
 6843:     } elsif (!defined($currquest)
 6844:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6845:             || (&occurence_count($currquest,$matchon) == 0)) {
 6846:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6847:             $record->{"scantron.$ansnum.answer"}='';
 6848:             $ansnum++;
 6849:         }
 6850:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6851:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6852:         }
 6853:     } else {
 6854:         if ($$scantron_config{'Qon'} eq 'number') {
 6855:             $currquest = &digits_to_letters($currquest);            
 6856:         }
 6857:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6858:             my $bubble = substr($currquest,$ans,1);
 6859:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6860:             $ansnum++;
 6861:         }
 6862:     }
 6863:     return $ansnum;
 6864: }
 6865: 
 6866: sub scantron_validator_positional {
 6867:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6868:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6869:         $randomorder,$randompick,$respnumlookup) = @_;
 6870: 
 6871:     # Otherwise there's a positional notation;
 6872:     # each bubble line requires Qlength items, and there are filled in
 6873:     # bubbles for each case where there 'Qon' characters.
 6874:     #
 6875: 
 6876:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6877: 
 6878:     # If the split only gives us one element.. the full length of the
 6879:     # answer string, no bubbles are filled in:
 6880: 
 6881:     if ($answers_needed eq '') {
 6882:         return;
 6883:     }
 6884: 
 6885:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6886:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6887:             $record->{"scantron.$ansnum.answer"}='';
 6888:             $ansnum++;
 6889:         }
 6890:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6891:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6892:         }
 6893:     } elsif (scalar(@array) == 2) {
 6894:         my $location = length($array[0]);
 6895:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6896:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6897:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6898:             if ($ans eq $line_num) {
 6899:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6900:             } else {
 6901:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6902:             }
 6903:             $ansnum++;
 6904:          }
 6905:     } else {
 6906:         #  If there's more than one instance of a bubble character
 6907:         #  That's a double bubble; with positional notation we can
 6908:         #  record all the bubbles filled in as well as the
 6909:         #  fact this response consists of multiple bubbles.
 6910:         #
 6911:         my $responsenum = $questnum-1;
 6912:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6913:             $responsenum = $respnumlookup->{$questnum-1}
 6914:         }
 6915:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6916:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6917:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6918:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6919:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6920:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6921:             my $doubleerror = 0;
 6922:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6923:                    (!$doubleerror)) {
 6924:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6925:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6926:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6927:                if (length(@currarray) > 2) {
 6928:                    $doubleerror = 1;
 6929:                } 
 6930:             }
 6931:             if ($doubleerror) {
 6932:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6933:             }
 6934:         } else {
 6935:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6936:         }
 6937:         my $item = $ansnum;
 6938:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6939:             $record->{"scantron.$item.answer"} = '';
 6940:             $item ++;
 6941:         }
 6942: 
 6943:         my @ans=@array;
 6944:         my $i=0;
 6945:         my $increment = 0;
 6946:         while ($#ans) {
 6947:             $i+=length($ans[0]) + $increment;
 6948:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6949:             my $bubble = $i%$$scantron_config{'Qlength'};
 6950:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6951:             shift(@ans);
 6952:             $increment = 1;
 6953:         }
 6954:         $ansnum += $answers_needed;
 6955:     }
 6956:     return $ansnum;
 6957: }
 6958: 
 6959: =pod
 6960: 
 6961: =item scantron_add_delay
 6962: 
 6963:    Adds an error message that occurred during the grading phase to a
 6964:    queue of messages to be shown after grading pass is complete
 6965: 
 6966:  Arguments:
 6967:    $delayqueue  - arrary ref of hash ref of error messages
 6968:    $scanline    - the scanline that caused the error
 6969:    $errormesage - the error message
 6970:    $errorcode   - a numeric code for the error
 6971: 
 6972:  Side Effects:
 6973:    updates the $delayqueue to have a new hash ref of the error
 6974: 
 6975: =cut
 6976: 
 6977: sub scantron_add_delay {
 6978:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6979:     push(@$delayqueue,
 6980: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6981: 	  'ecode' => $errorcode }
 6982: 	 );
 6983: }
 6984: 
 6985: =pod
 6986: 
 6987: =item scantron_find_student
 6988: 
 6989:    Finds the username for the current scanline
 6990: 
 6991:   Arguments:
 6992:    $scantron_record - hash result from scantron_parse_scanline
 6993:    $scan_data       - hash of correction information 
 6994:                       (see &scantron_getfile() form more information)
 6995:    $idmap           - hash from &username_to_idmap()
 6996:    $line            - number of current scanline
 6997:  
 6998:   Returns:
 6999:    Either 'username:domain' or undef if unknown
 7000: 
 7001: =cut
 7002: 
 7003: sub scantron_find_student {
 7004:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 7005:     my $scanID=$$scantron_record{'scantron.ID'};
 7006:     if ($scanID =~ /^\s*$/) {
 7007:  	return &scan_data($scan_data,"$line.user");
 7008:     }
 7009:     foreach my $id (keys(%$idmap)) {
 7010:  	if (lc($id) eq lc($scanID)) {
 7011:  	    return $$idmap{$id};
 7012:  	}
 7013:     }
 7014:     return undef;
 7015: }
 7016: 
 7017: =pod
 7018: 
 7019: =item scantron_filter
 7020: 
 7021:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 7022:    hidden resources was selected
 7023: 
 7024: =cut
 7025: 
 7026: sub scantron_filter {
 7027:     my ($curres)=@_;
 7028: 
 7029:     if (ref($curres) && $curres->is_problem()) {
 7030: 	# if the user has asked to not have either hidden
 7031: 	# or 'randomout' controlled resources to be graded
 7032: 	# don't include them
 7033: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7034: 	    && $curres->randomout) {
 7035: 	    return 0;
 7036: 	}
 7037: 	return 1;
 7038:     }
 7039:     return 0;
 7040: }
 7041: 
 7042: =pod
 7043: 
 7044: =item scantron_process_corrections
 7045: 
 7046:    Gets correction information out of submitted form data and corrects
 7047:    the scanline
 7048: 
 7049: =cut
 7050: 
 7051: sub scantron_process_corrections {
 7052:     my ($r) = @_;
 7053:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7054:     my ($scanlines,$scan_data)=&scantron_getfile();
 7055:     my $classlist=&Apache::loncoursedata::get_classlist();
 7056:     my $which=$env{'form.scantron_line'};
 7057:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 7058:     my ($skip,$err,$errmsg);
 7059:     if ($env{'form.scantron_skip_record'}) {
 7060: 	$skip=1;
 7061:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 7062: 	my $newstudent=$env{'form.scantron_username'}.':'.
 7063: 	    $env{'form.scantron_domain'};
 7064: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 7065: 	($line,$err,$errmsg)=
 7066: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7067: 				     'ID',{'newid'=>$newid,
 7068: 				    'username'=>$env{'form.scantron_username'},
 7069: 				    'domain'=>$env{'form.scantron_domain'}});
 7070:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 7071: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 7072: 	my $newCODE;
 7073: 	my %args;
 7074: 	if      ($resolution eq 'use_unfound') {
 7075: 	    $newCODE='use_unfound';
 7076: 	} elsif ($resolution eq 'use_found') {
 7077: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 7078: 	} elsif ($resolution eq 'use_typed') {
 7079: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 7080: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 7081: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 7082: 	}
 7083: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 7084: 	    $args{'CODE_ignore_dup'}=1;
 7085: 	}
 7086: 	$args{'CODE'}=$newCODE;
 7087: 	($line,$err,$errmsg)=
 7088: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 7089: 				     'CODE',\%args);
 7090:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 7091: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 7092: 	    ($line,$err,$errmsg)=
 7093: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 7094: 					 $which,'answer',
 7095: 					 { 'question'=>$question,
 7096: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 7097:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 7098: 	    if ($err) { last; }
 7099: 	}
 7100:     }
 7101:     if ($err) {
 7102: 	$r->print(
 7103:             '<p class="LC_error">'
 7104:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 7105:                 $errmsg)
 7106:            .'</p>');
 7107:     } else {
 7108: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 7109: 	&scantron_putfile($scanlines,$scan_data);
 7110:     }
 7111: }
 7112: 
 7113: =pod
 7114: 
 7115: =item reset_skipping_status
 7116: 
 7117:    Forgets the current set of remember skipped scanlines (and thus
 7118:    reverts back to considering all lines in the
 7119:    scantron_skipped_<filename> file)
 7120: 
 7121: =cut
 7122: 
 7123: sub reset_skipping_status {
 7124:     my ($scanlines,$scan_data)=&scantron_getfile();
 7125:     &scan_data($scan_data,'remember_skipping',undef,1);
 7126:     &scantron_putfile(undef,$scan_data);
 7127: }
 7128: 
 7129: =pod
 7130: 
 7131: =item start_skipping
 7132: 
 7133:    Marks a scanline to be skipped. 
 7134: 
 7135: =cut
 7136: 
 7137: sub start_skipping {
 7138:     my ($scan_data,$i)=@_;
 7139:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7140:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 7141: 	$remembered{$i}=2;
 7142:     } else {
 7143: 	$remembered{$i}=1;
 7144:     }
 7145:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 7146: }
 7147: 
 7148: =pod
 7149: 
 7150: =item should_be_skipped
 7151: 
 7152:    Checks whether a scanline should be skipped.
 7153: 
 7154: =cut
 7155: 
 7156: sub should_be_skipped {
 7157:     my ($scanlines,$scan_data,$i)=@_;
 7158:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 7159: 	# not redoing old skips
 7160: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 7161: 	return 0;
 7162:     }
 7163:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7164: 
 7165:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7166: 	return 0;
 7167:     }
 7168:     return 1;
 7169: }
 7170: 
 7171: =pod
 7172: 
 7173: =item remember_current_skipped
 7174: 
 7175:    Discovers what scanlines are in the scantron_skipped_<filename>
 7176:    file and remembers them into scan_data for later use.
 7177: 
 7178: =cut
 7179: 
 7180: sub remember_current_skipped {
 7181:     my ($scanlines,$scan_data)=&scantron_getfile();
 7182:     my %to_remember;
 7183:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7184: 	if ($scanlines->{'skipped'}[$i]) {
 7185: 	    $to_remember{$i}=1;
 7186: 	}
 7187:     }
 7188: 
 7189:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7190:     &scantron_putfile(undef,$scan_data);
 7191: }
 7192: 
 7193: =pod
 7194: 
 7195: =item check_for_error
 7196: 
 7197:     Checks if there was an error when attempting to remove a specific
 7198:     scantron_.. bubblesheet data file. Prints out an error if
 7199:     something went wrong.
 7200: 
 7201: =cut
 7202: 
 7203: sub check_for_error {
 7204:     my ($r,$result)=@_;
 7205:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7206: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7207:     }
 7208: }
 7209: 
 7210: =pod
 7211: 
 7212: =item scantron_warning_screen
 7213: 
 7214:    Interstitial screen to make sure the operator has selected the
 7215:    correct options before we start the validation phase.
 7216: 
 7217: =cut
 7218: 
 7219: sub scantron_warning_screen {
 7220:     my ($button_text,$symb)=@_;
 7221:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7222:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7223:     my $CODElist;
 7224:     if ($scantron_config{'CODElocation'} &&
 7225: 	$scantron_config{'CODEstart'} &&
 7226: 	$scantron_config{'CODElength'}) {
 7227: 	$CODElist=$env{'form.scantron_CODElist'};
 7228: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7229: 	$CODElist=
 7230: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7231: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7232:     }
 7233:     my $lastbubblepoints;
 7234:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7235:         $lastbubblepoints =
 7236:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7237:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7238:     }
 7239:     return ('
 7240: <p>
 7241: <span class="LC_warning">
 7242: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7243: </p>
 7244: <table>
 7245: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7246: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7247: '.$CODElist.$lastbubblepoints.'
 7248: </table>
 7249: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7250: '.&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>
 7251: 
 7252: <br />
 7253: ');
 7254: }
 7255: 
 7256: =pod
 7257: 
 7258: =item scantron_do_warning
 7259: 
 7260:    Check if the operator has picked something for all required
 7261:    fields. Error out if something is missing.
 7262: 
 7263: =cut
 7264: 
 7265: sub scantron_do_warning {
 7266:     my ($r,$symb)=@_;
 7267:     if (!$symb) {return '';}
 7268:     my $default_form_data=&defaultFormData($symb);
 7269:     $r->print(&scantron_form_start().$default_form_data);
 7270:     if ( $env{'form.selectpage'} eq '' ||
 7271: 	 $env{'form.scantron_selectfile'} eq '' ||
 7272: 	 $env{'form.scantron_format'} eq '' ) {
 7273: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7274: 	if ( $env{'form.selectpage'} eq '') {
 7275: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7276: 	} 
 7277: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7278: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7279: 	} 
 7280: 	if ( $env{'form.scantron_format'} eq '') {
 7281: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7282: 	} 
 7283:     } else {
 7284: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7285:         my $bubbledbyhand=&hand_bubble_option();
 7286: 	$r->print('
 7287: '.$warning.$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:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7375:     #get the student pick code ready
 7376:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7377:     my $nav_error;
 7378:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7379:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7380:     if ($nav_error) {
 7381:         $r->print(&navmap_errormsg());
 7382:         return '';
 7383:     }
 7384:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7385:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7386:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7387:     }
 7388:     $r->print($result);
 7389:     
 7390:     my @validate_phases=( 'sequence',
 7391: 			  'ID',
 7392: 			  'CODE',
 7393: 			  'doublebubble',
 7394: 			  'missingbubbles');
 7395:     if (!$env{'form.validatepass'}) {
 7396: 	$env{'form.validatepass'} = 0;
 7397:     }
 7398:     my $currentphase=$env{'form.validatepass'};
 7399: 
 7400: 
 7401:     my $stop=0;
 7402:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7403: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7404: 	$r->rflush();
 7405: 
 7406: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7407: 	{
 7408: 	    no strict 'refs';
 7409: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7410: 	}
 7411:     }
 7412:     if (!$stop) {
 7413: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7414: 	$r->print(&mt('Validation process complete.').'<br />'.
 7415:                   $warning.
 7416:                   &mt('Perform verification for each student after storage of submissions?').
 7417:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7418:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7419:                   ('&nbsp;'x3).'<label>'.
 7420:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7421:                   '</label></span><br />'.
 7422:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7423:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7424:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7425:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7426:     } else {
 7427: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7428: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7429:     }
 7430:     if ($stop) {
 7431: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7432: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7433: 	    $r->print(' '.&mt('this error').' <br />');
 7434: 
 7435:             $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>');
 7436: 	} else {
 7437:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7438: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7439:             } else {
 7440:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7441:             }
 7442: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7443: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7444: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7445: 	}
 7446:     }
 7447:     $r->print(" </form><br />");
 7448:     return '';
 7449: }
 7450: 
 7451: 
 7452: =pod
 7453: 
 7454: =item scantron_remove_file
 7455: 
 7456:    Removes the requested bubblesheet data file, makes sure that
 7457:    scantron_original_<filename> is never removed
 7458: 
 7459: 
 7460: =cut
 7461: 
 7462: sub scantron_remove_file {
 7463:     my ($which)=@_;
 7464:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7465:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7466:     my $file='scantron_';
 7467:     if ($which eq 'corrected' || $which eq 'skipped') {
 7468: 	$file.=$which.'_';
 7469:     } else {
 7470: 	return 'refused';
 7471:     }
 7472:     $file.=$env{'form.scantron_selectfile'};
 7473:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7474: }
 7475: 
 7476: 
 7477: =pod
 7478: 
 7479: =item scantron_remove_scan_data
 7480: 
 7481:    Removes all scan_data correction for the requested bubblesheet
 7482:    data file.  (In the case that both the are doing skipped records we need
 7483:    to remember the old skipped lines for the time being so that element
 7484:    persists for a while.)
 7485: 
 7486: =cut
 7487: 
 7488: sub scantron_remove_scan_data {
 7489:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7490:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7491:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7492:     my @todelete;
 7493:     my $filename=$env{'form.scantron_selectfile'};
 7494:     foreach my $key (@keys) {
 7495: 	if ($key=~/^\Q$filename\E_/) {
 7496: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7497: 		$key=~/remember_skipping/) {
 7498: 		next;
 7499: 	    }
 7500: 	    push(@todelete,$key);
 7501: 	}
 7502:     }
 7503:     my $result;
 7504:     if (@todelete) {
 7505: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7506: 				       \@todelete,$cdom,$cname);
 7507:     } else {
 7508: 	$result = 'ok';
 7509:     }
 7510:     return $result;
 7511: }
 7512: 
 7513: 
 7514: =pod
 7515: 
 7516: =item scantron_getfile
 7517: 
 7518:     Fetches the requested bubblesheet data file (all 3 versions), and
 7519:     the scan_data hash
 7520:   
 7521:   Arguments:
 7522:     None
 7523: 
 7524:   Returns:
 7525:     2 hash references
 7526: 
 7527:      - first one has 
 7528:          orig      -
 7529:          corrected -
 7530:          skipped   -  each of which points to an array ref of the specified
 7531:                       file broken up into individual lines
 7532:          count     - number of scanlines
 7533:  
 7534:      - second is the scan_data hash possible keys are
 7535:        ($number refers to scanline numbered $number and thus the key affects
 7536:         only that scanline
 7537:         $bubline refers to the specific bubble line element and the aspects
 7538:         refers to that specific bubble line element)
 7539: 
 7540:        $number.user - username:domain to use
 7541:        $number.CODE_ignore_dup 
 7542:                     - ignore the duplicate CODE error 
 7543:        $number.useCODE
 7544:                     - use the CODE in the scanline as is
 7545:        $number.no_bubble.$bubline
 7546:                     - it is valid that there is no bubbled in bubble
 7547:                       at $number $bubline
 7548:        remember_skipping
 7549:                     - a frozen hash containing keys of $number and values
 7550:                       of either 
 7551:                         1 - we are on a 'do skipped records pass' and plan
 7552:                             on processing this line
 7553:                         2 - we are on a 'do skipped records pass' and this
 7554:                             scanline has been marked to skip yet again
 7555: 
 7556: =cut
 7557: 
 7558: sub scantron_getfile {
 7559:     #FIXME really would prefer a scantron directory
 7560:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7561:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7562:     my $lines;
 7563:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7564: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7565:     my %scanlines;
 7566:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7567:     my $temp=$scanlines{'orig'};
 7568:     $scanlines{'count'}=$#$temp;
 7569: 
 7570:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7571: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7572:     if ($lines eq '-1') {
 7573: 	$scanlines{'corrected'}=[];
 7574:     } else {
 7575: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7576:     }
 7577:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7578: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7579:     if ($lines eq '-1') {
 7580: 	$scanlines{'skipped'}=[];
 7581:     } else {
 7582: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7583:     }
 7584:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7585:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7586:     my %scan_data = @tmp;
 7587:     return (\%scanlines,\%scan_data);
 7588: }
 7589: 
 7590: =pod
 7591: 
 7592: =item lonnet_putfile
 7593: 
 7594:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7595: 
 7596:  Arguments:
 7597:    $contents - data to store
 7598:    $filename - filename to store $contents into
 7599: 
 7600:  Returns:
 7601:    result value from &Apache::lonnet::finishuserfileupload
 7602: 
 7603: =cut
 7604: 
 7605: sub lonnet_putfile {
 7606:     my ($contents,$filename)=@_;
 7607:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7608:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7609:     $env{'form.sillywaytopassafilearound'}=$contents;
 7610:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7611: 
 7612: }
 7613: 
 7614: =pod
 7615: 
 7616: =item scantron_putfile
 7617: 
 7618:     Stores the current version of the bubblesheet data files, and the
 7619:     scan_data hash. (Does not modify the original version only the
 7620:     corrected and skipped versions.
 7621: 
 7622:  Arguments:
 7623:     $scanlines - hash ref that looks like the first return value from
 7624:                  &scantron_getfile()
 7625:     $scan_data - hash ref that looks like the second return value from
 7626:                  &scantron_getfile()
 7627: 
 7628: =cut
 7629: 
 7630: sub scantron_putfile {
 7631:     my ($scanlines,$scan_data) = @_;
 7632:     #FIXME really would prefer a scantron directory
 7633:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7634:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7635:     if ($scanlines) {
 7636: 	my $prefix='scantron_';
 7637: # no need to update orig, shouldn't change
 7638: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7639: #		    $env{'form.scantron_selectfile'});
 7640: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7641: 			$prefix.'corrected_'.
 7642: 			$env{'form.scantron_selectfile'});
 7643: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7644: 			$prefix.'skipped_'.
 7645: 			$env{'form.scantron_selectfile'});
 7646:     }
 7647:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7648: }
 7649: 
 7650: =pod
 7651: 
 7652: =item scantron_get_line
 7653: 
 7654:    Returns the correct version of the scanline
 7655: 
 7656:  Arguments:
 7657:     $scanlines - hash ref that looks like the first return value from
 7658:                  &scantron_getfile()
 7659:     $scan_data - hash ref that looks like the second return value from
 7660:                  &scantron_getfile()
 7661:     $i         - number of the requested line (starts at 0)
 7662: 
 7663:  Returns:
 7664:    A scanline, (either the original or the corrected one if it
 7665:    exists), or undef if the requested scanline should be
 7666:    skipped. (Either because it's an skipped scanline, or it's an
 7667:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7668:    pass.
 7669: 
 7670: =cut
 7671: 
 7672: sub scantron_get_line {
 7673:     my ($scanlines,$scan_data,$i)=@_;
 7674:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7675:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7676:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7677:     return $scanlines->{'orig'}[$i]; 
 7678: }
 7679: 
 7680: =pod
 7681: 
 7682: =item scantron_todo_count
 7683: 
 7684:     Counts the number of scanlines that need processing.
 7685: 
 7686:  Arguments:
 7687:     $scanlines - hash ref that looks like the first return value from
 7688:                  &scantron_getfile()
 7689:     $scan_data - hash ref that looks like the second return value from
 7690:                  &scantron_getfile()
 7691: 
 7692:  Returns:
 7693:     $count - number of scanlines to process
 7694: 
 7695: =cut
 7696: 
 7697: sub get_todo_count {
 7698:     my ($scanlines,$scan_data)=@_;
 7699:     my $count=0;
 7700:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7701: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7702: 	if ($line=~/^[\s\cz]*$/) { next; }
 7703: 	$count++;
 7704:     }
 7705:     return $count;
 7706: }
 7707: 
 7708: =pod
 7709: 
 7710: =item scantron_put_line
 7711: 
 7712:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7713:     data file.
 7714: 
 7715:  Arguments:
 7716:     $scanlines - hash ref that looks like the first return value from
 7717:                  &scantron_getfile()
 7718:     $scan_data - hash ref that looks like the second return value from
 7719:                  &scantron_getfile()
 7720:     $i         - line number to update
 7721:     $newline   - contents of the updated scanline
 7722:     $skip      - if true make the line for skipping and update the
 7723:                  'skipped' file
 7724: 
 7725: =cut
 7726: 
 7727: sub scantron_put_line {
 7728:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7729:     if ($skip) {
 7730: 	$scanlines->{'skipped'}[$i]=$newline;
 7731: 	&start_skipping($scan_data,$i);
 7732: 	return;
 7733:     }
 7734:     $scanlines->{'corrected'}[$i]=$newline;
 7735: }
 7736: 
 7737: =pod
 7738: 
 7739: =item scantron_clear_skip
 7740: 
 7741:    Remove a line from the 'skipped' file
 7742: 
 7743:  Arguments:
 7744:     $scanlines - hash ref that looks like the first return value from
 7745:                  &scantron_getfile()
 7746:     $scan_data - hash ref that looks like the second return value from
 7747:                  &scantron_getfile()
 7748:     $i         - line number to update
 7749: 
 7750: =cut
 7751: 
 7752: sub scantron_clear_skip {
 7753:     my ($scanlines,$scan_data,$i)=@_;
 7754:     if (exists($scanlines->{'skipped'}[$i])) {
 7755: 	undef($scanlines->{'skipped'}[$i]);
 7756: 	return 1;
 7757:     }
 7758:     return 0;
 7759: }
 7760: 
 7761: =pod
 7762: 
 7763: =item scantron_filter_not_exam
 7764: 
 7765:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7766:    filter out resources that are not marked as 'exam' mode
 7767: 
 7768: =cut
 7769: 
 7770: sub scantron_filter_not_exam {
 7771:     my ($curres)=@_;
 7772:     
 7773:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7774: 	# if the user has asked to not have either hidden
 7775: 	# or 'randomout' controlled resources to be graded
 7776: 	# don't include them
 7777: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7778: 	    && $curres->randomout) {
 7779: 	    return 0;
 7780: 	}
 7781: 	return 1;
 7782:     }
 7783:     return 0;
 7784: }
 7785: 
 7786: =pod
 7787: 
 7788: =item scantron_validate_sequence
 7789: 
 7790:     Validates the selected sequence, checking for resource that are
 7791:     not set to exam mode.
 7792: 
 7793: =cut
 7794: 
 7795: sub scantron_validate_sequence {
 7796:     my ($r,$currentphase) = @_;
 7797: 
 7798:     my $navmap=Apache::lonnavmaps::navmap->new();
 7799:     unless (ref($navmap)) {
 7800:         $r->print(&navmap_errormsg());
 7801:         return (1,$currentphase);
 7802:     }
 7803:     my (undef,undef,$sequence)=
 7804: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7805: 
 7806:     my $map=$navmap->getResourceByUrl($sequence);
 7807: 
 7808:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7809:                                     value="ignore" />');
 7810:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7811: 	my @resources=
 7812: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7813: 	if (@resources) {
 7814: 	    $r->print('<p class="LC_warning">'
 7815:                .&mt('Some resources in the sequence currently are not set to'
 7816:                    .' exam mode. Grading these resources currently may not'
 7817:                    .' work correctly.')
 7818:                .'</p>'
 7819:             );
 7820: 	    return (1,$currentphase);
 7821: 	}
 7822:     }
 7823: 
 7824:     return (0,$currentphase+1);
 7825: }
 7826: 
 7827: 
 7828: 
 7829: sub scantron_validate_ID {
 7830:     my ($r,$currentphase) = @_;
 7831:     
 7832:     #get student info
 7833:     my $classlist=&Apache::loncoursedata::get_classlist();
 7834:     my %idmap=&username_to_idmap($classlist);
 7835: 
 7836:     #get scantron line setup
 7837:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 7838:     my ($scanlines,$scan_data)=&scantron_getfile();
 7839: 
 7840:     my $nav_error;
 7841:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7842:     if ($nav_error) {
 7843:         $r->print(&navmap_errormsg());
 7844:         return(1,$currentphase);
 7845:     }
 7846: 
 7847:     my %found=('ids'=>{},'usernames'=>{});
 7848:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7849: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7850: 	if ($line=~/^[\s\cz]*$/) { next; }
 7851: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7852: 						 $scan_data);
 7853: 	my $id=$$scan_record{'scantron.ID'};
 7854: 	my $found;
 7855: 	foreach my $checkid (keys(%idmap)) {
 7856: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7857: 	}
 7858: 	if ($found) {
 7859: 	    my $username=$idmap{$found};
 7860: 	    if ($found{'ids'}{$found}) {
 7861: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7862: 					 $line,'duplicateID',$found);
 7863: 		return(1,$currentphase);
 7864: 	    } elsif ($found{'usernames'}{$username}) {
 7865: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7866: 					 $line,'duplicateID',$username);
 7867: 		return(1,$currentphase);
 7868: 	    }
 7869: 	    #FIXME store away line we previously saw the ID on to use above
 7870: 	    $found{'ids'}{$found}++;
 7871: 	    $found{'usernames'}{$username}++;
 7872: 	} else {
 7873: 	    if ($id =~ /^\s*$/) {
 7874: 		my $username=&scan_data($scan_data,"$i.user");
 7875: 		if (defined($username) && $found{'usernames'}{$username}) {
 7876: 		    &scantron_get_correction($r,$i,$scan_record,
 7877: 					     \%scantron_config,
 7878: 					     $line,'duplicateID',$username);
 7879: 		    return(1,$currentphase);
 7880: 		} elsif (!defined($username)) {
 7881: 		    &scantron_get_correction($r,$i,$scan_record,
 7882: 					     \%scantron_config,
 7883: 					     $line,'incorrectID');
 7884: 		    return(1,$currentphase);
 7885: 		}
 7886: 		$found{'usernames'}{$username}++;
 7887: 	    } else {
 7888: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7889: 					 $line,'incorrectID');
 7890: 		return(1,$currentphase);
 7891: 	    }
 7892: 	}
 7893:     }
 7894: 
 7895:     return (0,$currentphase+1);
 7896: }
 7897: 
 7898: 
 7899: sub scantron_get_correction {
 7900:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7901:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7902: #FIXME in the case of a duplicated ID the previous line, probably need
 7903: #to show both the current line and the previous one and allow skipping
 7904: #the previous one or the current one
 7905: 
 7906:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7907:         $r->print(
 7908:             '<p class="LC_warning">'
 7909:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7910:                 "<b>$error</b>",
 7911:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7912:            ."</p> \n");
 7913:     } else {
 7914:         $r->print(
 7915:             '<p class="LC_warning">'
 7916:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7917:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7918:            ."</p> \n");
 7919:     }
 7920:     my $message =
 7921:         '<p>'
 7922:        .&mt('The ID on the form is [_1]',
 7923:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7924:        .'<br />'
 7925:        .&mt('The name on the paper is [_1], [_2]',
 7926:             $$scan_record{'scantron.LastName'},
 7927:             $$scan_record{'scantron.FirstName'})
 7928:        .'</p>';
 7929: 
 7930:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7931:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7932:                            # Array populated for doublebubble or
 7933:     my @lines_to_correct;  # missingbubble errors to build javascript
 7934:                            # to validate radio button checking   
 7935: 
 7936:     if ($error =~ /ID$/) {
 7937: 	if ($error eq 'incorrectID') {
 7938: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7939: 		      "</p>\n");
 7940: 	} elsif ($error eq 'duplicateID') {
 7941: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7942: 	}
 7943: 	$r->print($message);
 7944: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7945: 	$r->print("\n<ul><li> ");
 7946: 	#FIXME it would be nice if this sent back the user ID and
 7947: 	#could do partial userID matches
 7948: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7949: 				       'scantron_username','scantron_domain'));
 7950: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7951: 	$r->print("\n:\n".
 7952: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7953: 
 7954: 	$r->print('</li>');
 7955:     } elsif ($error =~ /CODE$/) {
 7956: 	if ($error eq 'incorrectCODE') {
 7957: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7958: 	} elsif ($error eq 'duplicateCODE') {
 7959: 	    $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");
 7960: 	}
 7961:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7962:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7963:                  ."</p>\n");
 7964: 	$r->print($message);
 7965: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7966: 	$r->print("\n<br /> ");
 7967: 	my $i=0;
 7968: 	if ($error eq 'incorrectCODE' 
 7969: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7970: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7971: 	    if ($closest > 0) {
 7972: 		foreach my $testcode (@{$closest}) {
 7973: 		    my $checked='';
 7974: 		    if (!$i) { $checked=' checked="checked"'; }
 7975: 		    $r->print("
 7976:    <label>
 7977:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7978:        ".&mt("Use the similar CODE [_1] instead.",
 7979: 	    "<b><tt>".$testcode."</tt></b>")."
 7980:     </label>
 7981:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7982: 		    $r->print("\n<br />");
 7983: 		    $i++;
 7984: 		}
 7985: 	    }
 7986: 	}
 7987: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7988: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7989: 	    $r->print("
 7990:     <label>
 7991:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7992:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7993: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7994:     </label>");
 7995: 	    $r->print("\n<br />");
 7996: 	}
 7997: 
 7998: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7999: function change_radio(field) {
 8000:     var slct=document.scantronupload.scantron_CODE_resolution;
 8001:     var i;
 8002:     for (i=0;i<slct.length;i++) {
 8003:         if (slct[i].value==field) { slct[i].checked=true; }
 8004:     }
 8005: }
 8006: ENDSCRIPT
 8007: 	my $href="/adm/pickcode?".
 8008: 	   "form=".&escape("scantronupload").
 8009: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 8010: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 8011: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 8012: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 8013: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 8014: 	    $r->print("
 8015:     <label>
 8016:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 8017:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 8018: 	     "<a target='_blank' href='$href'>","</a>")."
 8019:     </label> 
 8020:     ".&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\')" />'));
 8021: 	    $r->print("\n<br />");
 8022: 	}
 8023: 	$r->print("
 8024:     <label>
 8025:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 8026:        ".&mt("Use [_1] as the CODE.",
 8027: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 8028: 	$r->print("\n<br /><br />");
 8029:     } elsif ($error eq 'doublebubble') {
 8030: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 8031: 
 8032: 	# The form field scantron_questions is acutally a list of line numbers.
 8033: 	# represented by this form so:
 8034: 
 8035: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8036:                                                 $respnumlookup,$startline);
 8037: 
 8038: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8039: 		  $line_list.'" />');
 8040: 	$r->print($message);
 8041: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 8042: 	foreach my $question (@{$arg}) {
 8043: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8044:                                                    $scan_record, $error,
 8045:                                                    $randomorder,$randompick,
 8046:                                                    $respnumlookup,$startline);
 8047:             push(@lines_to_correct,@linenums);
 8048: 	}
 8049:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8050:     } elsif ($error eq 'missingbubble') {
 8051: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 8052: 	$r->print($message);
 8053: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 8054: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 8055: 
 8056: 	# The form field scantron_questions is actually a list of line numbers not
 8057: 	# a list of question numbers. Therefore:
 8058: 	#
 8059: 	
 8060: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 8061:                                                 $respnumlookup,$startline);
 8062: 
 8063: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 8064: 		  $line_list.'" />');
 8065: 	foreach my $question (@{$arg}) {
 8066: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 8067:                                                    $scan_record, $error,
 8068:                                                    $randomorder,$randompick,
 8069:                                                    $respnumlookup,$startline);
 8070:             push(@lines_to_correct,@linenums);
 8071: 	}
 8072:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 8073:     } else {
 8074: 	$r->print("\n<ul>");
 8075:     }
 8076:     $r->print("\n</li></ul>");
 8077: }
 8078: 
 8079: sub verify_bubbles_checked {
 8080:     my (@ansnums) = @_;
 8081:     my $ansnumstr = join('","',@ansnums);
 8082:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 8083:     &js_escape(\$warning);
 8084:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
 8085: function verify_bubble_radio(form) {
 8086:     var ansnumArray = new Array ("$ansnumstr");
 8087:     var need_bubble_count = 0;
 8088:     for (var i=0; i<ansnumArray.length; i++) {
 8089:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 8090:             var bubble_picked = 0; 
 8091:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 8092:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 8093:                     bubble_picked = 1;
 8094:                 }
 8095:             }
 8096:             if (bubble_picked == 0) {
 8097:                 need_bubble_count ++;
 8098:             }
 8099:         }
 8100:     }
 8101:     if (need_bubble_count) {
 8102:         alert("$warning");
 8103:         return;
 8104:     }
 8105:     form.submit(); 
 8106: }
 8107: ENDSCRIPT
 8108:     return $output;
 8109: }
 8110: 
 8111: =pod
 8112: 
 8113: =item  questions_to_line_list
 8114: 
 8115: Converts a list of questions into a string of comma separated
 8116: line numbers in the answer sheet used by the questions.  This is
 8117: used to fill in the scantron_questions form field.
 8118: 
 8119:   Arguments:
 8120:      questions    - Reference to an array of questions.
 8121:      randomorder  - True if randomorder in use.
 8122:      randompick   - True if randompick in use.
 8123:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8124:                      for current line to question number used for same question
 8125:                      in "Master Seqence" (as seen by Course Coordinator).
 8126:      startline    - Reference to hash where key is question number (0 is first)
 8127:                     and key is number of first bubble line for current student
 8128:                     or code-based randompick and/or randomorder.
 8129: 
 8130: =cut
 8131: 
 8132: 
 8133: sub questions_to_line_list {
 8134:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 8135:     my @lines;
 8136: 
 8137:     foreach my $item (@{$questions}) {
 8138:         my $question = $item;
 8139:         my ($first,$count,$last);
 8140:         if ($item =~ /^(\d+)\.(\d+)$/) {
 8141:             $question = $1;
 8142:             my $subquestion = $2;
 8143:             my $responsenum = $question-1;
 8144:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8145:                 $responsenum = $respnumlookup->{$question-1};
 8146:                 if (ref($startline) eq 'HASH') {
 8147:                     $first = $startline->{$question-1} + 1;
 8148:                 }
 8149:             } else {
 8150:                 $first = $first_bubble_line{$responsenum} + 1;
 8151:             }
 8152:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8153:             my $subcount = 1;
 8154:             while ($subcount<$subquestion) {
 8155:                 $first += $subans[$subcount-1];
 8156:                 $subcount ++;
 8157:             }
 8158:             $count = $subans[$subquestion-1];
 8159:         } else {
 8160:             my $responsenum = $question-1;
 8161:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8162:                 $responsenum = $respnumlookup->{$question-1};
 8163:                 if (ref($startline) eq 'HASH') {
 8164:                     $first = $startline->{$question-1} + 1;
 8165:                 }
 8166:             } else {
 8167:                 $first = $first_bubble_line{$responsenum} + 1;
 8168:             }
 8169:             $count   = $bubble_lines_per_response{$responsenum};
 8170:         }
 8171:         $last = $first+$count-1;
 8172:         push(@lines, ($first..$last));
 8173:     }
 8174:     return join(',', @lines);
 8175: }
 8176: 
 8177: =pod 
 8178: 
 8179: =item prompt_for_corrections
 8180: 
 8181: Prompts for a potentially multiline correction to the
 8182: user's bubbling (factors out common code from scantron_get_correction
 8183: for multi and missing bubble cases).
 8184: 
 8185:  Arguments:
 8186:    $r           - Apache request object.
 8187:    $question    - The question number to prompt for.
 8188:    $scan_config - The scantron file configuration hash.
 8189:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8190:    $error       - Type of error
 8191:    $randomorder - True if randomorder in use.
 8192:    $randompick  - True if randompick in use.
 8193:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8194:                     for current line to question number used for same question
 8195:                     in "Master Seqence" (as seen by Course Coordinator).
 8196:    $startline   - Reference to hash where key is question number (0 is first)
 8197:                   and value is number of first bubble line for current student
 8198:                   or code-based randompick and/or randomorder.
 8199: 
 8200:  Implicit inputs:
 8201:    %bubble_lines_per_response   - Starting line numbers for each question.
 8202:                                   Numbered from 0 (but question numbers are from
 8203:                                   1.
 8204:    %first_bubble_line           - Starting bubble line for each question.
 8205:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8206:                                   type problems render as separate sub-questions, 
 8207:                                   in exam mode. This hash contains a 
 8208:                                   comma-separated list of the lines per 
 8209:                                   sub-question.
 8210:    %responsetype_per_response   - essayresponse, formularesponse,
 8211:                                   stringresponse, imageresponse, reactionresponse,
 8212:                                   and organicresponse type problem parts can have
 8213:                                   multiple lines per response if the weight
 8214:                                   assigned exceeds 10.  In this case, only
 8215:                                   one bubble per line is permitted, but more 
 8216:                                   than one line might contain bubbles, e.g.
 8217:                                   bubbling of: line 1 - J, line 2 - J, 
 8218:                                   line 3 - B would assign 22 points.  
 8219: 
 8220: =cut
 8221: 
 8222: sub prompt_for_corrections {
 8223:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8224:         $randompick, $respnumlookup, $startline) = @_;
 8225:     my ($current_line,$lines);
 8226:     my @linenums;
 8227:     my $questionnum = $question;
 8228:     my ($first,$responsenum);
 8229:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8230:         $question = $1;
 8231:         my $subquestion = $2;
 8232:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8233:             $responsenum = $respnumlookup->{$question-1};
 8234:             if (ref($startline) eq 'HASH') {
 8235:                 $first = $startline->{$question-1};
 8236:             }
 8237:         } else {
 8238:             $responsenum = $question-1;
 8239:             $first = $first_bubble_line{$responsenum};
 8240:         }
 8241:         $current_line = $first + 1 ;
 8242:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8243:         my $subcount = 1;
 8244:         while ($subcount<$subquestion) {
 8245:             $current_line += $subans[$subcount-1];
 8246:             $subcount ++;
 8247:         }
 8248:         $lines = $subans[$subquestion-1];
 8249:     } else {
 8250:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8251:             $responsenum = $respnumlookup->{$question-1};
 8252:             if (ref($startline) eq 'HASH') {
 8253:                 $first = $startline->{$question-1};
 8254:             }
 8255:         } else {
 8256:             $responsenum = $question-1;
 8257:             $first = $first_bubble_line{$responsenum};
 8258:         }
 8259:         $current_line = $first + 1;
 8260:         $lines        = $bubble_lines_per_response{$responsenum};
 8261:     }
 8262:     if ($lines > 1) {
 8263:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8264:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8265:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8266:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8267:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8268:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8269:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8270:             $r->print(&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).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 8271:         } else {
 8272:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8273:         }
 8274:     }
 8275:     for (my $i =0; $i < $lines; $i++) {
 8276:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8277: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8278: 	        		  $questionnum,$error,split('', $selected));
 8279:         push(@linenums,$current_line);
 8280: 	$current_line++;
 8281:     }
 8282:     if ($lines > 1) {
 8283: 	$r->print("<hr /><br />");
 8284:     }
 8285:     return @linenums;
 8286: }
 8287: 
 8288: =pod
 8289: 
 8290: =item scantron_bubble_selector
 8291:   
 8292:    Generates the html radiobuttons to correct a single bubble line
 8293:    possibly showing the existing the selected bubbles if known
 8294: 
 8295:  Arguments:
 8296:     $r           - Apache request object
 8297:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
 8298:     $line        - Number of the line being displayed.
 8299:     $questionnum - Question number (may include subquestion)
 8300:     $error       - Type of error.
 8301:     @selected    - Array of bubbles picked on this line.
 8302: 
 8303: =cut
 8304: 
 8305: sub scantron_bubble_selector {
 8306:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8307:     my $max=$$scan_config{'Qlength'};
 8308: 
 8309:     my $scmode=$$scan_config{'Qon'};
 8310:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8311:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8312:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8313:             $max=$$scan_config{'BubblesPerRow'};
 8314:             if (($scmode eq 'number') && ($max > 10)) {
 8315:                 $max = 10;
 8316:             } elsif (($scmode eq 'letter') && $max > 26) {
 8317:                 $max = 26;
 8318:             }
 8319:         } else {
 8320:             $max = 10;
 8321:         }
 8322:     }
 8323: 
 8324:     my @alphabet=('A'..'Z');
 8325:     $r->print(&Apache::loncommon::start_data_table().
 8326:               &Apache::loncommon::start_data_table_row());
 8327:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8328:     for (my $i=0;$i<$max+1;$i++) {
 8329: 	$r->print("\n".'<td align="center">');
 8330: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8331: 	else { $r->print('&nbsp;'); }
 8332: 	$r->print('</td>');
 8333:     }
 8334:     $r->print(&Apache::loncommon::end_data_table_row().
 8335:               &Apache::loncommon::start_data_table_row());
 8336:     for (my $i=0;$i<$max;$i++) {
 8337: 	$r->print("\n".
 8338: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8339: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8340:     }
 8341:     my $nobub_checked = ' ';
 8342:     if ($error eq 'missingbubble') {
 8343:         $nobub_checked = ' checked = "checked" ';
 8344:     }
 8345:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8346: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8347:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8348:               $line.'" value="'.$questionnum.'" /></td>');
 8349:     $r->print(&Apache::loncommon::end_data_table_row().
 8350:               &Apache::loncommon::end_data_table());
 8351: }
 8352: 
 8353: =pod
 8354: 
 8355: =item num_matches
 8356: 
 8357:    Counts the number of characters that are the same between the two arguments.
 8358: 
 8359:  Arguments:
 8360:    $orig - CODE from the scanline
 8361:    $code - CODE to match against
 8362: 
 8363:  Returns:
 8364:    $count - integer count of the number of same characters between the
 8365:             two arguments
 8366: 
 8367: =cut
 8368: 
 8369: sub num_matches {
 8370:     my ($orig,$code) = @_;
 8371:     my @code=split(//,$code);
 8372:     my @orig=split(//,$orig);
 8373:     my $same=0;
 8374:     for (my $i=0;$i<scalar(@code);$i++) {
 8375: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8376:     }
 8377:     return $same;
 8378: }
 8379: 
 8380: =pod
 8381: 
 8382: =item scantron_get_closely_matching_CODEs
 8383: 
 8384:    Cycles through all CODEs and finds the set that has the greatest
 8385:    number of same characters as the provided CODE
 8386: 
 8387:  Arguments:
 8388:    $allcodes - hash ref returned by &get_codes()
 8389:    $CODE     - CODE from the current scanline
 8390: 
 8391:  Returns:
 8392:    2 element list
 8393:     - first elements is number of how closely matching the best fit is 
 8394:       (5 means best set has 5 matching characters)
 8395:     - second element is an arrary ref containing the set of valid CODEs
 8396:       that best fit the passed in CODE
 8397: 
 8398: =cut
 8399: 
 8400: sub scantron_get_closely_matching_CODEs {
 8401:     my ($allcodes,$CODE)=@_;
 8402:     my @CODEs;
 8403:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8404: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8405:     }
 8406: 
 8407:     return ($#CODEs,$CODEs[-1]);
 8408: }
 8409: 
 8410: =pod
 8411: 
 8412: =item get_codes
 8413: 
 8414:    Builds a hash which has keys of all of the valid CODEs from the selected
 8415:    set of remembered CODEs.
 8416: 
 8417:  Arguments:
 8418:   $old_name - name of the set of remembered CODEs
 8419:   $cdom     - domain of the course
 8420:   $cnum     - internal course name
 8421: 
 8422:  Returns:
 8423:   %allcodes - keys are the valid CODEs, values are all 1
 8424: 
 8425: =cut
 8426: 
 8427: sub get_codes {
 8428:     my ($old_name, $cdom, $cnum) = @_;
 8429:     if (!$old_name) {
 8430: 	$old_name=$env{'form.scantron_CODElist'};
 8431:     }
 8432:     if (!$cdom) {
 8433: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8434:     }
 8435:     if (!$cnum) {
 8436: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8437:     }
 8438:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8439: 				    $cdom,$cnum);
 8440:     my %allcodes;
 8441:     if ($result{"type\0$old_name"} eq 'number') {
 8442: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8443:     } else {
 8444: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8445:     }
 8446:     return %allcodes;
 8447: }
 8448: 
 8449: =pod
 8450: 
 8451: =item scantron_validate_CODE
 8452: 
 8453:    Validates all scanlines in the selected file to not have any
 8454:    invalid or underspecified CODEs and that none of the codes are
 8455:    duplicated if this was requested.
 8456: 
 8457: =cut
 8458: 
 8459: sub scantron_validate_CODE {
 8460:     my ($r,$currentphase) = @_;
 8461:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8462:     if ($scantron_config{'CODElocation'} &&
 8463: 	$scantron_config{'CODEstart'} &&
 8464: 	$scantron_config{'CODElength'}) {
 8465: 	if (!defined($env{'form.scantron_CODElist'})) {
 8466: 	    &FIXME_blow_up()
 8467: 	}
 8468:     } else {
 8469: 	return (0,$currentphase+1);
 8470:     }
 8471:     
 8472:     my %usedCODEs;
 8473: 
 8474:     my %allcodes=&get_codes();
 8475: 
 8476:     my $nav_error;
 8477:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8478:     if ($nav_error) {
 8479:         $r->print(&navmap_errormsg());
 8480:         return(1,$currentphase);
 8481:     }
 8482: 
 8483:     my ($scanlines,$scan_data)=&scantron_getfile();
 8484:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8485: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8486: 	if ($line=~/^[\s\cz]*$/) { next; }
 8487: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8488: 						 $scan_data);
 8489: 	my $CODE=$$scan_record{'scantron.CODE'};
 8490: 	my $error=0;
 8491: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8492: 	    &scantron_get_correction($r,$i,$scan_record,
 8493: 				     \%scantron_config,
 8494: 				     $line,'incorrectCODE',\%allcodes);
 8495: 	    return(1,$currentphase);
 8496: 	}
 8497: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8498: 	    && !$$scan_record{'scantron.useCODE'}) {
 8499: 	    &scantron_get_correction($r,$i,$scan_record,
 8500: 				     \%scantron_config,
 8501: 				     $line,'incorrectCODE',\%allcodes);
 8502: 	    return(1,$currentphase);
 8503: 	}
 8504: 	if (exists($usedCODEs{$CODE}) 
 8505: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8506: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8507: 	    &scantron_get_correction($r,$i,$scan_record,
 8508: 				     \%scantron_config,
 8509: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8510: 	    return(1,$currentphase);
 8511: 	}
 8512: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8513:     }
 8514:     return (0,$currentphase+1);
 8515: }
 8516: 
 8517: =pod
 8518: 
 8519: =item scantron_validate_doublebubble
 8520: 
 8521:    Validates all scanlines in the selected file to not have any
 8522:    bubble lines with multiple bubbles marked.
 8523: 
 8524: =cut
 8525: 
 8526: sub scantron_validate_doublebubble {
 8527:     my ($r,$currentphase) = @_;
 8528:     #get student info
 8529:     my $classlist=&Apache::loncoursedata::get_classlist();
 8530:     my %idmap=&username_to_idmap($classlist);
 8531:     my (undef,undef,$sequence)=
 8532:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8533: 
 8534:     #get scantron line setup
 8535:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8536:     my ($scanlines,$scan_data)=&scantron_getfile();
 8537: 
 8538:     my $navmap = Apache::lonnavmaps::navmap->new();
 8539:     unless (ref($navmap)) {
 8540:         $r->print(&navmap_errormsg());
 8541:         return(1,$currentphase);
 8542:     }
 8543:     my $map=$navmap->getResourceByUrl($sequence);
 8544:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8545:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8546:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8547:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8548: 
 8549:     my $nav_error;
 8550:     if (ref($map)) {
 8551:         $randomorder = $map->randomorder();
 8552:         $randompick = $map->randompick();
 8553:         unless ($randomorder || $randompick) {
 8554:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8555:                 if ($res->randomorder()) {
 8556:                     $randomorder = 1;
 8557:                 }
 8558:                 if ($res->randompick()) {
 8559:                     $randompick = 1;
 8560:                 }
 8561:                 last if ($randomorder || $randompick);
 8562:             }
 8563:         }
 8564:         if ($randomorder || $randompick) {
 8565:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8566:             if ($nav_error) {
 8567:                 $r->print(&navmap_errormsg());
 8568:                 return(1,$currentphase);
 8569:             }
 8570:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8571:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8572:         }
 8573:     } else {
 8574:         $r->print(&navmap_errormsg());
 8575:         return(1,$currentphase);
 8576:     }
 8577: 
 8578:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8579:     if ($nav_error) {
 8580:         $r->print(&navmap_errormsg());
 8581:         return(1,$currentphase);
 8582:     }
 8583: 
 8584:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8585: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8586: 	if ($line=~/^[\s\cz]*$/) { next; }
 8587: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8588: 						 $scan_data,undef,\%idmap,$randomorder,
 8589:                                                  $randompick,$sequence,\@master_seq,
 8590:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8591:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8592: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8593: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8594: 				 'doublebubble',
 8595: 				 $$scan_record{'scantron.doubleerror'},
 8596:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8597:     	return (1,$currentphase);
 8598:     }
 8599:     return (0,$currentphase+1);
 8600: }
 8601: 
 8602: 
 8603: sub scantron_get_maxbubble {
 8604:     my ($nav_error,$scantron_config) = @_;
 8605:     if (defined($env{'form.scantron_maxbubble'}) &&
 8606: 	$env{'form.scantron_maxbubble'}) {
 8607: 	&restore_bubble_lines();
 8608: 	return $env{'form.scantron_maxbubble'};
 8609:     }
 8610: 
 8611:     my (undef, undef, $sequence) =
 8612: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8613: 
 8614:     my $navmap=Apache::lonnavmaps::navmap->new();
 8615:     unless (ref($navmap)) {
 8616:         if (ref($nav_error)) {
 8617:             $$nav_error = 1;
 8618:         }
 8619:         return;
 8620:     }
 8621:     my $map=$navmap->getResourceByUrl($sequence);
 8622:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8623:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8624: 
 8625:     &Apache::lonxml::clear_problem_counter();
 8626: 
 8627:     my $uname       = $env{'user.name'};
 8628:     my $udom        = $env{'user.domain'};
 8629:     my $cid         = $env{'request.course.id'};
 8630:     my $total_lines = 0;
 8631:     %bubble_lines_per_response = ();
 8632:     %first_bubble_line         = ();
 8633:     %subdivided_bubble_lines   = ();
 8634:     %responsetype_per_response = ();
 8635:     %masterseq_id_responsenum  = ();
 8636: 
 8637:     my $response_number = 0;
 8638:     my $bubble_line     = 0;
 8639:     foreach my $resource (@resources) {
 8640:         my $resid = $resource->id();
 8641:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8642:                                                           $udom,undef,$bubbles_per_row);
 8643:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8644: 	    foreach my $part_id (@{$parts}) {
 8645:                 my $lines;
 8646: 
 8647: 	        # TODO - make this a persistent hash not an array.
 8648: 
 8649:                 # optionresponse, matchresponse and rankresponse type items 
 8650:                 # render as separate sub-questions in exam mode.
 8651:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8652:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8653:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8654:                     my ($numbub,$numshown);
 8655:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8656:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8657:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8658:                         }
 8659:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8660:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8661:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8662:                         }
 8663:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8664:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8665:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8666:                         }
 8667:                     }
 8668:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8669:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8670:                     }
 8671:                     my $bubbles_per_row =
 8672:                         &bubblesheet_bubbles_per_row($scantron_config);
 8673:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8674:                     if (($numbub % $bubbles_per_row) != 0) {
 8675:                         $inner_bubble_lines++;
 8676:                     }
 8677:                     for (my $i=0; $i<$numshown; $i++) {
 8678:                         $subdivided_bubble_lines{$response_number} .= 
 8679:                             $inner_bubble_lines.',';
 8680:                     }
 8681:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8682:                     $lines = $numshown * $inner_bubble_lines;
 8683:                 } else {
 8684:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8685:                 }
 8686: 
 8687:                 $first_bubble_line{$response_number} = $bubble_line;
 8688: 	        $bubble_lines_per_response{$response_number} = $lines;
 8689:                 $responsetype_per_response{$response_number} = 
 8690:                     $analysis->{$part_id.'.type'};
 8691:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8692: 	        $response_number++;
 8693: 
 8694: 	        $bubble_line +=  $lines;
 8695: 	        $total_lines +=  $lines;
 8696: 	    }
 8697:         }
 8698:     }
 8699:     &Apache::lonnet::delenv('scantron.');
 8700: 
 8701:     &save_bubble_lines();
 8702:     $env{'form.scantron_maxbubble'} =
 8703: 	$total_lines;
 8704:     return $env{'form.scantron_maxbubble'};
 8705: }
 8706: 
 8707: sub bubblesheet_bubbles_per_row {
 8708:     my ($scantron_config) = @_;
 8709:     my $bubbles_per_row;
 8710:     if (ref($scantron_config) eq 'HASH') {
 8711:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8712:     }
 8713:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8714:         $bubbles_per_row = 10;
 8715:     }
 8716:     return $bubbles_per_row;
 8717: }
 8718: 
 8719: sub scantron_validate_missingbubbles {
 8720:     my ($r,$currentphase) = @_;
 8721:     #get student info
 8722:     my $classlist=&Apache::loncoursedata::get_classlist();
 8723:     my %idmap=&username_to_idmap($classlist);
 8724:     my (undef,undef,$sequence)=
 8725:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8726: 
 8727:     #get scantron line setup
 8728:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8729:     my ($scanlines,$scan_data)=&scantron_getfile();
 8730: 
 8731:     my $navmap = Apache::lonnavmaps::navmap->new();
 8732:     unless (ref($navmap)) {
 8733:         $r->print(&navmap_errormsg());
 8734:         return(1,$currentphase);
 8735:     }
 8736: 
 8737:     my $map=$navmap->getResourceByUrl($sequence);
 8738:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8739:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8740:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8741:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8742: 
 8743:     my $nav_error;
 8744:     if (ref($map)) {
 8745:         $randomorder = $map->randomorder();
 8746:         $randompick = $map->randompick();
 8747:         unless ($randomorder || $randompick) {
 8748:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8749:                 if ($res->randomorder()) {
 8750:                     $randomorder = 1;
 8751:                 }
 8752:                 if ($res->randompick()) {
 8753:                     $randompick = 1;
 8754:                 }
 8755:                 last if ($randomorder || $randompick);
 8756:             }
 8757:         }
 8758:         if ($randomorder || $randompick) {
 8759:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8760:             if ($nav_error) {
 8761:                 $r->print(&navmap_errormsg());
 8762:                 return(1,$currentphase);
 8763:             }
 8764:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8765:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8766:         }
 8767:     } else {
 8768:         $r->print(&navmap_errormsg());
 8769:         return(1,$currentphase);
 8770:     }
 8771: 
 8772: 
 8773:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8774:     if ($nav_error) {
 8775:         $r->print(&navmap_errormsg());
 8776:         return(1,$currentphase);
 8777:     }
 8778: 
 8779:     if (!$max_bubble) { $max_bubble=2**31; }
 8780:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8781: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8782: 	if ($line=~/^[\s\cz]*$/) { next; }
 8783:         my $scan_record =
 8784:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8785:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8786:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8787:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8788: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8789: 	my @to_correct;
 8790: 	
 8791: 	# Probably here's where the error is...
 8792: 
 8793: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8794:             my $lastbubble;
 8795:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8796:                 my $question = $1;
 8797:                 my $subquestion = $2;
 8798:                 my ($first,$responsenum);
 8799:                 if ($randomorder || $randompick) {
 8800:                     $responsenum = $respnumlookup{$question-1};
 8801:                     $first = $startline{$question-1};
 8802:                 } else {
 8803:                     $responsenum = $question-1;
 8804:                     $first = $first_bubble_line{$responsenum};
 8805:                 }
 8806:                 if (!defined($first)) { next; }
 8807:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8808:                 my $subcount = 1;
 8809:                 while ($subcount<$subquestion) {
 8810:                     $first += $subans[$subcount-1];
 8811:                     $subcount ++;
 8812:                 }
 8813:                 my $count = $subans[$subquestion-1];
 8814:                 $lastbubble = $first + $count;
 8815:             } else {
 8816:                 my ($first,$responsenum);
 8817:                 if ($randomorder || $randompick) {
 8818:                     $responsenum = $respnumlookup{$missing-1};
 8819:                     $first = $startline{$missing-1};
 8820:                 } else {
 8821:                     $responsenum = $missing-1;
 8822:                     $first = $first_bubble_line{$responsenum};
 8823:                 }
 8824:                 if (!defined($first)) { next; }
 8825:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8826:             }
 8827:             if ($lastbubble > $max_bubble) { next; }
 8828: 	    push(@to_correct,$missing);
 8829: 	}
 8830: 	if (@to_correct) {
 8831: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8832: 				     $line,'missingbubble',\@to_correct,
 8833:                                      $randomorder,$randompick,\%respnumlookup,
 8834:                                      \%startline);
 8835: 	    return (1,$currentphase);
 8836: 	}
 8837: 
 8838:     }
 8839:     return (0,$currentphase+1);
 8840: }
 8841: 
 8842: sub hand_bubble_option {
 8843:     my (undef, undef, $sequence) =
 8844:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8845:     return if ($sequence eq '');
 8846:     my $navmap = Apache::lonnavmaps::navmap->new();
 8847:     unless (ref($navmap)) {
 8848:         return;
 8849:     }
 8850:     my $needs_hand_bubbles;
 8851:     my $map=$navmap->getResourceByUrl($sequence);
 8852:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8853:     foreach my $res (@resources) {
 8854:         if (ref($res)) {
 8855:             if ($res->is_problem()) {
 8856:                 my $partlist = $res->parts();
 8857:                 foreach my $part (@{ $partlist }) {
 8858:                     my @types = $res->responseType($part);
 8859:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8860:                         $needs_hand_bubbles = 1;
 8861:                         last;
 8862:                     }
 8863:                 }
 8864:             }
 8865:         }
 8866:     }
 8867:     if ($needs_hand_bubbles) {
 8868:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8869:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8870:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8871:                &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 />').
 8872:                '<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;'.
 8873:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8874:     }
 8875:     return;
 8876: }
 8877: 
 8878: sub scantron_process_students {
 8879:     my ($r,$symb) = @_;
 8880: 
 8881:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8882:     if (!$symb) {
 8883: 	return '';
 8884:     }
 8885:     my $default_form_data=&defaultFormData($symb);
 8886: 
 8887:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 8888:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8889:     my ($scanlines,$scan_data)=&scantron_getfile();
 8890:     my $classlist=&Apache::loncoursedata::get_classlist();
 8891:     my %idmap=&username_to_idmap($classlist);
 8892:     my $navmap=Apache::lonnavmaps::navmap->new();
 8893:     unless (ref($navmap)) {
 8894:         $r->print(&navmap_errormsg());
 8895:         return '';
 8896:     }
 8897:     my $map=$navmap->getResourceByUrl($sequence);
 8898:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8899:         %grader_randomlists_by_symb,%symb_for_examcode);
 8900:     if (ref($map)) {
 8901:         $randomorder = $map->randomorder();
 8902:         $randompick = $map->randompick();
 8903:         unless ($randomorder || $randompick) {
 8904:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 8905:                 if ($res->randomorder()) {
 8906:                     $randomorder = 1;
 8907:                 }
 8908:                 if ($res->randompick()) {
 8909:                     $randompick = 1;
 8910:                 }
 8911:                 last if ($randomorder || $randompick);
 8912:             }
 8913:         }
 8914:     } else {
 8915:         $r->print(&navmap_errormsg());
 8916:         return '';
 8917:     }
 8918:     my $nav_error;
 8919:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8920:     if ($randomorder || $randompick) {
 8921:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
 8922:         if ($nav_error) {
 8923:             $r->print(&navmap_errormsg());
 8924:             return '';
 8925:         }
 8926:     }
 8927:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8928:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8929: 
 8930:     my ($uname,$udom);
 8931:     my $result= <<SCANTRONFORM;
 8932: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8933:   <input type="hidden" name="command" value="scantron_configphase" />
 8934:   $default_form_data
 8935: SCANTRONFORM
 8936:     $r->print($result);
 8937: 
 8938:     my @delayqueue;
 8939:     my (%completedstudents,%scandata);
 8940:     
 8941:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8942:     my $count=&get_todo_count($scanlines,$scan_data);
 8943:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8944:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8945:     $r->print('<br />');
 8946:     my $start=&Time::HiRes::time();
 8947:     my $i=-1;
 8948:     my $started;
 8949: 
 8950:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8951:     if ($nav_error) {
 8952:         $r->print(&navmap_errormsg());
 8953:         return '';
 8954:     }
 8955: 
 8956:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8957:     # the user and return.
 8958: 
 8959:     if ($ssi_error) {
 8960: 	$r->print("</form>");
 8961: 	&ssi_print_error($r);
 8962:         &Apache::lonnet::remove_lock($lock);
 8963: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8964:     }
 8965: 
 8966:     my %lettdig = &Apache::lonnet::letter_to_digits();
 8967:     my $numletts = scalar(keys(%lettdig));
 8968:     my %orderedforcode;
 8969: 
 8970:     while ($i<$scanlines->{'count'}) {
 8971:  	($uname,$udom)=('','');
 8972:  	$i++;
 8973:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8974:  	if ($line=~/^[\s\cz]*$/) { next; }
 8975: 	if ($started) {
 8976: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8977: 	}
 8978: 	$started=1;
 8979:         my %respnumlookup = ();
 8980:         my %startline = ();
 8981:         my $total;
 8982:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8983:  						 $scan_data,undef,\%idmap,$randomorder,
 8984:                                                  $randompick,$sequence,\@master_seq,
 8985:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8986:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8987:                                                  \$total);
 8988:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8989:  					      \%idmap,$i)) {
 8990:   	    &scantron_add_delay(\@delayqueue,$line,
 8991:  				'Unable to find a student that matches',1);
 8992:  	    next;
 8993:   	}
 8994:  	if (exists $completedstudents{$uname}) {
 8995:  	    &scantron_add_delay(\@delayqueue,$line,
 8996:  				'Student '.$uname.' has multiple sheets',2);
 8997:  	    next;
 8998:  	}
 8999:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9000:         my $user = $uname.':'.$usec;
 9001:   	($uname,$udom)=split(/:/,$uname);
 9002: 
 9003:         my $scancode;
 9004:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9005:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9006:             $scancode = $scan_record->{'scantron.CODE'};
 9007:         } else {
 9008:             $scancode = '';
 9009:         }
 9010: 
 9011:         my @mapresources = @resources;
 9012:         if ($randomorder || $randompick) {
 9013:             @mapresources =
 9014:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9015:                              \%orderedforcode);
 9016:         }
 9017:         my (%partids_by_symb,$res_error);
 9018:         foreach my $resource (@mapresources) {
 9019:             my $ressymb;
 9020:             if (ref($resource)) {
 9021:                 $ressymb = $resource->symb();
 9022:             } else {
 9023:                 $res_error = 1;
 9024:                 last;
 9025:             }
 9026:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9027:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9028:                 my $currcode;
 9029:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9030:                     $currcode = $scancode;
 9031:                 }
 9032:                 my ($analysis,$parts) =
 9033:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9034:                                               $uname,$udom,undef,$bubbles_per_row,
 9035:                                               $currcode);
 9036:                 $partids_by_symb{$ressymb} = $parts;
 9037:             } else {
 9038:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 9039:             }
 9040:         }
 9041: 
 9042:         if ($res_error) {
 9043:             &scantron_add_delay(\@delayqueue,$line,
 9044:                                 'An error occurred while grading student '.$uname,2);
 9045:             next;
 9046:         }
 9047: 
 9048: 	&Apache::lonxml::clear_problem_counter();
 9049:   	&Apache::lonnet::appenv($scan_record);
 9050: 
 9051: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 9052: 	    &scantron_putfile($scanlines,$scan_data);
 9053: 	}
 9054: 	
 9055:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9056:                                    \@mapresources,\%partids_by_symb,
 9057:                                    $bubbles_per_row,$randomorder,$randompick,
 9058:                                    \%respnumlookup,\%startline) 
 9059:             eq 'ssi_error') {
 9060:             $ssi_error = 0; # So end of handler error message does not trigger.
 9061:             $r->print("</form>");
 9062:             &ssi_print_error($r);
 9063:             &Apache::lonnet::remove_lock($lock);
 9064:             return '';      # Why return ''?  Beats me.
 9065:         }
 9066: 
 9067:         if (($scancode) && ($randomorder || $randompick)) {
 9068:             foreach my $key (keys(%symb_for_examcode)) {
 9069:                 my $symb_in_map = $symb_for_examcode{$key};
 9070:                 if ($symb_in_map ne '') {
 9071:                     my $parmresult =
 9072:                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
 9073:                                                                '0_examcode',2,$scancode,
 9074:                                                                'string_examcode',$uname,
 9075:                                                                $udom);
 9076:                 }
 9077:             }
 9078:         }
 9079: 	$completedstudents{$uname}={'line'=>$line};
 9080:         if ($env{'form.verifyrecord'}) {
 9081:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9082:             if ($randompick) {
 9083:                 if ($total) {
 9084:                     $lastpos = $total*$scantron_config{'Qlength'};
 9085:                 }
 9086:             }
 9087: 
 9088:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9089:             chomp($studentdata);
 9090:             $studentdata =~ s/\r$//;
 9091:             my $studentrecord = '';
 9092:             my $counter = -1;
 9093:             foreach my $resource (@mapresources) {
 9094:                 my $ressymb = $resource->symb();
 9095:                 ($counter,my $recording) =
 9096:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9097:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 9098:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 9099:                                              $randompick,\%respnumlookup,\%startline);
 9100:                 $studentrecord .= $recording;
 9101:             }
 9102:             if ($studentrecord ne $studentdata) {
 9103:                 &Apache::lonxml::clear_problem_counter();
 9104:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 9105:                                            \@mapresources,\%partids_by_symb,
 9106:                                            $bubbles_per_row,$randomorder,$randompick,
 9107:                                            \%respnumlookup,\%startline)
 9108:                     eq 'ssi_error') {
 9109:                     $ssi_error = 0; # So end of handler error message does not trigger.
 9110:                     $r->print("</form>");
 9111:                     &ssi_print_error($r);
 9112:                     &Apache::lonnet::remove_lock($lock);
 9113:                     delete($completedstudents{$uname});
 9114:                     return '';
 9115:                 }
 9116:                 $counter = -1;
 9117:                 $studentrecord = '';
 9118:                 foreach my $resource (@mapresources) {
 9119:                     my $ressymb = $resource->symb();
 9120:                     ($counter,my $recording) =
 9121:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 9122:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 9123:                                                  \%scantron_config,\%lettdig,$numletts,
 9124:                                                  $randomorder,$randompick,\%respnumlookup,
 9125:                                                  \%startline);
 9126:                     $studentrecord .= $recording;
 9127:                 }
 9128:                 if ($studentrecord ne $studentdata) {
 9129:                     $r->print('<p><span class="LC_warning">');
 9130:                     if ($scancode eq '') {
 9131:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 9132:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 9133:                     } else {
 9134:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 9135:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 9136:                     }
 9137:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 9138:                               &Apache::loncommon::start_data_table_header_row()."\n".
 9139:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 9140:                               &Apache::loncommon::end_data_table_header_row()."\n".
 9141:                               &Apache::loncommon::start_data_table_row().
 9142:                               '<td>'.&mt('Bubblesheet').'</td>'.
 9143:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 9144:                               &Apache::loncommon::end_data_table_row().
 9145:                               &Apache::loncommon::start_data_table_row().
 9146:                               '<td>'.&mt('Stored submissions').'</td>'.
 9147:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 9148:                               &Apache::loncommon::end_data_table_row().
 9149:                               &Apache::loncommon::end_data_table().'</p>');
 9150:                 } else {
 9151:                     $r->print('<br /><span class="LC_warning">'.
 9152:                              &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 />'.
 9153:                              &mt("As a consequence, this user's submission history records two tries.").
 9154:                                  '</span><br />');
 9155:                 }
 9156:             }
 9157:         }
 9158:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 9159:     } continue {
 9160: 	&Apache::lonxml::clear_problem_counter();
 9161: 	&Apache::lonnet::delenv('scantron.');
 9162:     }
 9163:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9164:     &Apache::lonnet::remove_lock($lock);
 9165: #    my $lasttime = &Time::HiRes::time()-$start;
 9166: #    $r->print("<p>took $lasttime</p>");
 9167: 
 9168:     $r->print("</form>");
 9169:     return '';
 9170: }
 9171: 
 9172: sub graders_resources_pass {
 9173:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 9174:         $bubbles_per_row) = @_;
 9175:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 9176:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 9177:         foreach my $resource (@{$resources}) {
 9178:             my $ressymb = $resource->symb();
 9179:             my ($analysis,$parts) =
 9180:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 9181:                                           $env{'user.name'},$env{'user.domain'},
 9182:                                           1,$bubbles_per_row);
 9183:             $grader_partids_by_symb->{$ressymb} = $parts;
 9184:             if (ref($analysis) eq 'HASH') {
 9185:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 9186:                     $grader_randomlists_by_symb->{$ressymb} =
 9187:                         $analysis->{'parts_withrandomlist'};
 9188:                 }
 9189:             }
 9190:         }
 9191:     }
 9192:     return;
 9193: }
 9194: 
 9195: =pod
 9196: 
 9197: =item users_order
 9198: 
 9199:   Returns array of resources in current map, ordered based on either CODE,
 9200:   if this is a CODEd exam, or based on student's identity if this is a
 9201:   "NAMEd" exam.
 9202: 
 9203:   Should be used when randomorder and/or randompick applied when the 
 9204:   corresponding exam was printed, prior to students completing bubblesheets 
 9205:   for the version of the exam the student received.
 9206: 
 9207: =cut
 9208: 
 9209: sub users_order  {
 9210:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9211:     my @mapresources;
 9212:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9213:         return @mapresources;
 9214:     }
 9215:     if ($scancode) {
 9216:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9217:             @mapresources = @{$orderedforcode->{$scancode}};
 9218:         } else {
 9219:             $env{'form.CODE'} = $scancode;
 9220:             my $actual_seq =
 9221:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9222:                                                                $master_seq,
 9223:                                                                $user,$scancode,1);
 9224:             if (ref($actual_seq) eq 'ARRAY') {
 9225:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9226:                 if (ref($orderedforcode) eq 'HASH') {
 9227:                     if (@mapresources > 0) {
 9228:                         $orderedforcode->{$scancode} = \@mapresources;
 9229:                     }
 9230:                 }
 9231:             }
 9232:             delete($env{'form.CODE'});
 9233:         }
 9234:     } else {
 9235:         my $actual_seq =
 9236:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9237:                                                            $master_seq,
 9238:                                                            $user,undef,1);
 9239:         if (ref($actual_seq) eq 'ARRAY') {
 9240:             @mapresources =
 9241:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9242:         }
 9243:     }
 9244:     return @mapresources;
 9245: }
 9246: 
 9247: sub grade_student_bubbles {
 9248:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9249:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9250:     my $uselookup = 0;
 9251:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9252:         (ref($startline) eq 'HASH')) {
 9253:         $uselookup = 1;
 9254:     }
 9255: 
 9256:     if (ref($resources) eq 'ARRAY') {
 9257:         my $count = 0;
 9258:         foreach my $resource (@{$resources}) {
 9259:             my $ressymb = $resource->symb();
 9260:             my %form = ('submitted'      => 'scantron',
 9261:                         'grade_target'   => 'grade',
 9262:                         'grade_username' => $uname,
 9263:                         'grade_domain'   => $udom,
 9264:                         'grade_courseid' => $env{'request.course.id'},
 9265:                         'grade_symb'     => $ressymb,
 9266:                         'CODE'           => $scancode
 9267:                        );
 9268:             if ($bubbles_per_row ne '') {
 9269:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9270:             }
 9271:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9272:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9273:             }
 9274:             if (ref($parts) eq 'HASH') {
 9275:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9276:                     foreach my $part (@{$parts->{$ressymb}}) {
 9277:                         if ($uselookup) {
 9278:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9279:                         } else {
 9280:                             $form{'scantron_questnum_start.'.$part} =
 9281:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9282:                         }
 9283:                         $count++;
 9284:                     }
 9285:                 }
 9286:             }
 9287:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9288:             return 'ssi_error' if ($ssi_error);
 9289:             last if (&Apache::loncommon::connection_aborted($r));
 9290:         }
 9291:     }
 9292:     return;
 9293: }
 9294: 
 9295: sub scantron_upload_scantron_data {
 9296:     my ($r,$symb) = @_;
 9297:     my $dom = $env{'request.role.domain'};
 9298:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
 9299:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9300:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9301:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9302: 							  'domainid',
 9303: 							  'coursename',$dom);
 9304:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9305:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9306:     my $default_form_data=&defaultFormData($symb);
 9307:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9308:     &js_escape(\$nofile_alert);
 9309:     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.");
 9310:     &js_escape(\$nocourseid_alert);
 9311:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9312:     function checkUpload(formname) {
 9313: 	if (formname.upfile.value == "") {
 9314: 	    alert("'.$nofile_alert.'");
 9315: 	    return false;
 9316: 	}
 9317:         if (formname.courseid.value == "") {
 9318:             alert("'.$nocourseid_alert.'");
 9319:             return false;
 9320:         }
 9321: 	formname.submit();
 9322:     }
 9323: 
 9324:     function ToSyllabus() {
 9325:         var cdom = '."'$dom'".';
 9326:         var cnum = document.rules.courseid.value;
 9327:         if (cdom == "" || cdom == null) {
 9328:             return;
 9329:         }
 9330:         if (cnum == "" || cnum == null) {
 9331:            return;
 9332:         }
 9333:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9334:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9335:         return;
 9336:     }
 9337: 
 9338:     '.$formatjs.'
 9339: '));
 9340:     $r->print('
 9341: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9342: 
 9343: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9344: '.$default_form_data.
 9345:   &Apache::lonhtmlcommon::start_pick_box().
 9346:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9347:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9348:   &Apache::lonhtmlcommon::row_closure().
 9349:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9350:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9351:   &Apache::lonhtmlcommon::row_closure().
 9352:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9353:   '<input name="domainid" type="hidden" />'.$domdesc.
 9354:   &Apache::lonhtmlcommon::row_closure());
 9355:     if ($formatoptions) {
 9356:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
 9357:                   &Apache::lonhtmlcommon::row_closure());
 9358:     }
 9359:     $r->print(
 9360:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9361:   '<input type="file" name="upfile" size="50" />'.
 9362:   &Apache::lonhtmlcommon::row_closure(1).
 9363:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9364: 
 9365: <input name="command" value="scantronupload_save" type="hidden" />
 9366: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9367: </form>
 9368: ');
 9369:     return '';
 9370: }
 9371: 
 9372: sub scantron_upload_dataformat {
 9373:     my ($dom) = @_;
 9374:     my ($formatoptions,$formattitle,$formatjs);
 9375:     $formatjs = <<'END';
 9376: function toggleScantab(form) {
 9377:    return;
 9378: }
 9379: END
 9380:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
 9381:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 9382:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9383:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
 9384:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
 9385:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
 9386:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9387:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9388:                             my ($onclick,$formatextra,$singleline);
 9389:                             my @lines = &Apache::lonnet::get_scantronformat_file();
 9390:                             my $count = 0;
 9391:                             foreach my $line (@lines) {
 9392:                                 next if (($line =~ /^\#/) || ($line eq ''));
 9393:                                 $singleline = $line;
 9394:                                 $count ++;
 9395:                             }
 9396:                             if ($count > 1) {
 9397:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
 9398:                                                '<span class="LC_nobreak">'.
 9399:                                                &mt('Bubblesheet type').':&nbsp;'.
 9400:                                                &scantron_scantab().'</span></div>';
 9401:                                 $onclick = ' onclick="toggleScantab(this.form);"';
 9402:                                 $formatjs = <<"END";
 9403: function toggleScantab(form) {
 9404:     var divid = 'bubbletype';
 9405:     if (document.getElementById(divid)) {
 9406:         var radioname = 'fileformat';
 9407:         var num = form.elements[radioname].length;
 9408:         if (num) {
 9409:             for (var i=0; i<num; i++) {
 9410:                 if (form.elements[radioname][i].checked) {
 9411:                     var chosen = form.elements[radioname][i].value;
 9412:                     if (chosen == 'dat') {
 9413:                         document.getElementById(divid).style.display = 'none';
 9414:                     } else if (chosen == 'csv') {
 9415:                         document.getElementById(divid).style.display = 'block';
 9416:                     }
 9417:                 }
 9418:             }
 9419:         }
 9420:     }
 9421:     return;
 9422: }
 9423: 
 9424: END
 9425:                             } elsif ($count == 1) {
 9426:                                 my $formatname = (split(/:/,$singleline,2))[0];
 9427:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
 9428:                             }
 9429:                             $formattitle = &mt('File format');
 9430:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
 9431:                                              &mt('Plain Text (no delimiters)').
 9432:                                              '</label>'.('&nbsp;'x2).
 9433:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
 9434:                                              &mt('Comma separated values').'</label>'.$formatextra;
 9435:                         }
 9436:                     }
 9437:                 }
 9438:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
 9439:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9440:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
 9441:                         $formattitle = &mt('Bubblesheet type');
 9442:                         $formatoptions = &scantron_scantab();
 9443:                     }
 9444:                 }
 9445:             }
 9446:         }
 9447:     }
 9448:     return ($formatoptions,$formattitle,$formatjs);
 9449: }
 9450: 
 9451: sub scantron_upload_scantron_data_save {
 9452:     my ($r,$symb) = @_;
 9453:     my $doanotherupload=
 9454: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9455: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9456: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9457: 	'</form>'."\n";
 9458:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9459: 	!&Apache::lonnet::allowed('usc',
 9460: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9461: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9462:         unless ($symb) {
 9463: 	    $r->print($doanotherupload);
 9464: 	}
 9465: 	return '';
 9466:     }
 9467:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9468:     my $uploadedfile;
 9469:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9470:     if (length($env{'form.upfile'}) < 2) {
 9471:         $r->print(
 9472:             &Apache::lonhtmlcommon::confirm_success(
 9473:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9474:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9475:     } else {
 9476:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
 9477:         my $parser;
 9478:         if (ref($domconfig{'scantron'}) eq 'HASH') {
 9479:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
 9480:                 my $is_csv;
 9481:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
 9482:                 if (@possibles > 1) {
 9483:                     if ($env{'form.fileformat'} eq 'csv') {
 9484:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9485:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9486:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9487:                                     $is_csv = 1;
 9488:                                 }
 9489:                             }
 9490:                         }
 9491:                     }
 9492:                 } elsif (@possibles == 1) {
 9493:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
 9494:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
 9495:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
 9496:                                 $is_csv = 1;
 9497:                             }
 9498:                         }
 9499:                     }
 9500:                 }
 9501:                 if ($is_csv) {
 9502:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
 9503:                 }
 9504:             }
 9505:         }
 9506:         my $result =
 9507:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
 9508:                                             $env{'form.courseid'},$env{'form.domainid'});
 9509: 	if ($result =~ m{^/uploaded/}) {
 9510:             $r->print(
 9511:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9512:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9513:                         (length($env{'form.upfile'})-1),
 9514:                         '<span class="LC_filename">'.$result.'</span>'));
 9515:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9516:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9517:                                                        $env{'form.courseid'},$uploadedfile));
 9518: 	} else {
 9519:             $r->print(
 9520:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9521:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9522:                           $result,
 9523: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9524: 	}
 9525:     }
 9526:     if ($symb) {
 9527: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9528:     } else {
 9529: 	$r->print($doanotherupload);
 9530:     }
 9531:     return '';
 9532: }
 9533: 
 9534: sub validate_uploaded_scantron_file {
 9535:     my ($cdom,$cname,$fname) = @_;
 9536:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9537:     my @lines;
 9538:     if ($scanlines ne '-1') {
 9539:         @lines=split("\n",$scanlines,-1);
 9540:     }
 9541:     my $output;
 9542:     if (@lines) {
 9543:         my (%counts,$max_match_format);
 9544:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9545:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9546:         my %idmap = &username_to_idmap($classlist);
 9547:         foreach my $key (keys(%idmap)) {
 9548:             my $lckey = lc($key);
 9549:             $idmap{$lckey} = $idmap{$key};
 9550:         }
 9551:         my %unique_formats;
 9552:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
 9553:         foreach my $line (@formatlines) {
 9554:             next if (($line =~ /^\#/) || ($line eq ''));
 9555:             my @config = split(/:/,$line);
 9556:             my $idstart = $config[5];
 9557:             my $idlength = $config[6];
 9558:             if (($idstart ne '') && ($idlength > 0)) {
 9559:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9560:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9561:                 } else {
 9562:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9563:                 }
 9564:             }
 9565:         }
 9566:         foreach my $key (keys(%unique_formats)) {
 9567:             my ($idstart,$idlength) = split(':',$key);
 9568:             %{$counts{$key}} = (
 9569:                                'found'   => 0,
 9570:                                'total'   => 0,
 9571:                               );
 9572:             foreach my $line (@lines) {
 9573:                 next if ($line =~ /^#/);
 9574:                 next if ($line =~ /^[\s\cz]*$/);
 9575:                 my $id = substr($line,$idstart-1,$idlength);
 9576:                 $id = lc($id);
 9577:                 if (exists($idmap{$id})) {
 9578:                     $counts{$key}{'found'} ++;
 9579:                 }
 9580:                 $counts{$key}{'total'} ++;
 9581:             }
 9582:             if ($counts{$key}{'total'}) {
 9583:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9584:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9585:                     $max_match_pct = $percent_match;
 9586:                     $max_match_format = $key;
 9587:                     $found_match_count = $counts{$key}{'found'};
 9588:                     $max_match_count = $counts{$key}{'total'};
 9589:                 }
 9590:             }
 9591:         }
 9592:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9593:             my $format_descs;
 9594:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9595:             for (my $i=0; $i<$numwithformat; $i++) {
 9596:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9597:                 if ($i<$numwithformat-2) {
 9598:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9599:                 } elsif ($i==$numwithformat-2) {
 9600:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9601:                 } elsif ($i==$numwithformat-1) {
 9602:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9603:                 }
 9604:             }
 9605:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9606:             $output .= '<br />';
 9607:             if ($found_match_count == $max_match_count) {
 9608:                 # 100% matching entries
 9609:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9610:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9611:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9612:                 &mt('Comparison of student IDs in the uploaded file with'.
 9613:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9614:                     ' in the file (for the format defined for [_3]).',
 9615:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9616:             } else {
 9617:                 # Not all entries matching? -> Show warning and additional info
 9618:                 $output .=
 9619:                     &Apache::lonhtmlcommon::confirm_success(
 9620:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9621:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9622:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9623:                     &mt('Comparison of student IDs in the uploaded file with'.
 9624:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9625:                         ' in the file (for the format defined for [_3]).',
 9626:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9627:                     '<p class="LC_info">'.
 9628:                     &mt('A low percentage of matches results from one of the following:').
 9629:                     '</p><ul>'.
 9630:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9631:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9632:                                '<i>'.$cdom.'</i>').'</li>'.
 9633:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9634:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9635:                     '</ul>';
 9636:             }
 9637:         }
 9638:     } else {
 9639:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9640:     }
 9641:     return $output;
 9642: }
 9643: 
 9644: sub valid_file {
 9645:     my ($requested_file)=@_;
 9646:     foreach my $filename (sort(&scantron_filenames())) {
 9647: 	if ($requested_file eq $filename) { return 1; }
 9648:     }
 9649:     return 0;
 9650: }
 9651: 
 9652: sub scantron_download_scantron_data {
 9653:     my ($r,$symb) = @_;
 9654:     my $default_form_data=&defaultFormData($symb);
 9655:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9656:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9657:     my $file=$env{'form.scantron_selectfile'};
 9658:     if (! &valid_file($file)) {
 9659: 	$r->print('
 9660: 	<p>
 9661: 	    '.&mt('The requested filename was invalid.').'
 9662:         </p>
 9663: ');
 9664: 	return;
 9665:     }
 9666:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9667:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9668:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9669:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9670:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9671:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9672:     $r->print('
 9673:     <p>
 9674: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9675: 	      '<a href="'.$orig.'">','</a>').'
 9676:     </p>
 9677:     <p>
 9678: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9679: 	      '<a href="'.$corrected.'">','</a>').'
 9680:     </p>
 9681:     <p>
 9682: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9683: 	      '<a href="'.$skipped.'">','</a>').'
 9684:     </p>
 9685: ');
 9686:     return '';
 9687: }
 9688: 
 9689: sub checkscantron_results {
 9690:     my ($r,$symb) = @_;
 9691:     if (!$symb) {return '';}
 9692:     my $cid = $env{'request.course.id'};
 9693:     my %lettdig = &Apache::lonnet::letter_to_digits();
 9694:     my $numletts = scalar(keys(%lettdig));
 9695:     my $cnum = $env{'course.'.$cid.'.num'};
 9696:     my $cdom = $env{'course.'.$cid.'.domain'};
 9697:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9698:     my %record;
 9699:     my %scantron_config =
 9700:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
 9701:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9702:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9703:     my $classlist=&Apache::loncoursedata::get_classlist();
 9704:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9705:     my $navmap=Apache::lonnavmaps::navmap->new();
 9706:     unless (ref($navmap)) {
 9707:         $r->print(&navmap_errormsg());
 9708:         return '';
 9709:     }
 9710:     my $map=$navmap->getResourceByUrl($sequence);
 9711:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9712:         %grader_randomlists_by_symb,%orderedforcode);
 9713:     if (ref($map)) {
 9714:         $randomorder=$map->randomorder();
 9715:         $randompick=$map->randompick();
 9716:         unless ($randomorder || $randompick) {
 9717:             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
 9718:                 if ($res->randomorder()) {
 9719:                     $randomorder = 1;
 9720:                 }
 9721:                 if ($res->randompick()) {
 9722:                     $randompick = 1;
 9723:                 }
 9724:                 last if ($randomorder || $randompick);
 9725:             }
 9726:         }
 9727:     }
 9728:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9729:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9730:     if ($nav_error) {
 9731:         $r->print(&navmap_errormsg());
 9732:         return '';
 9733:     }
 9734:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9735:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9736:     my ($uname,$udom);
 9737:     my (%scandata,%lastname,%bylast);
 9738:     $r->print('
 9739: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9740: 
 9741:     my @delayqueue;
 9742:     my %completedstudents;
 9743: 
 9744:     my $count=&get_todo_count($scanlines,$scan_data);
 9745:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9746:     my ($username,$domain,$started);
 9747:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9748:     if ($nav_error) {
 9749:         $r->print(&navmap_errormsg());
 9750:         return '';
 9751:     }
 9752: 
 9753:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9754:                                           'Processing first student');
 9755:     my $start=&Time::HiRes::time();
 9756:     my $i=-1;
 9757: 
 9758:     while ($i<$scanlines->{'count'}) {
 9759:         ($username,$domain,$uname)=('','','');
 9760:         $i++;
 9761:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9762:         if ($line=~/^[\s\cz]*$/) { next; }
 9763:         if ($started) {
 9764:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9765:                                                      'last student');
 9766:         }
 9767:         $started=1;
 9768:         my $scan_record=
 9769:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9770:                                                      $scan_data);
 9771:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9772:                                               \%idmap,$i)) {
 9773:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9774:                                 'Unable to find a student that matches',1);
 9775:             next;
 9776:         }
 9777:         if (exists $completedstudents{$uname}) {
 9778:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9779:                                 'Student '.$uname.' has multiple sheets',2);
 9780:             next;
 9781:         }
 9782:         my $pid = $scan_record->{'scantron.ID'};
 9783:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9784:         push(@{$bylast{$lastname{$pid}}},$pid);
 9785:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9786:         my $user = $uname.':'.$usec;
 9787:         ($username,$domain)=split(/:/,$uname);
 9788: 
 9789:         my $scancode;
 9790:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9791:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9792:             $scancode = $scan_record->{'scantron.CODE'};
 9793:         } else {
 9794:             $scancode = '';
 9795:         }
 9796: 
 9797:         my @mapresources = @resources;
 9798:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9799:         my %respnumlookup=();
 9800:         my %startline=();
 9801:         if ($randomorder || $randompick) {
 9802:             @mapresources =
 9803:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9804:                              \%orderedforcode);
 9805:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9806:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9807:                                              \%grader_partids_by_symb,\%orderedforcode,
 9808:                                              \%respnumlookup,\%startline);
 9809:             if ($randompick && $total) {
 9810:                 $lastpos = $total*$scantron_config{'Qlength'};
 9811:             }
 9812:         }
 9813:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9814:         chomp($scandata{$pid});
 9815:         $scandata{$pid} =~ s/\r$//;
 9816: 
 9817:         my $counter = -1;
 9818:         foreach my $resource (@mapresources) {
 9819:             my $parts;
 9820:             my $ressymb = $resource->symb();
 9821:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9822:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9823:                 my $currcode;
 9824:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9825:                     $currcode = $scancode;
 9826:                 }
 9827:                 (my $analysis,$parts) =
 9828:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9829:                                               $username,$domain,undef,
 9830:                                               $bubbles_per_row,$currcode);
 9831:             } else {
 9832:                 $parts = $grader_partids_by_symb{$ressymb};
 9833:             }
 9834:             ($counter,my $recording) =
 9835:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9836:                                          $scandata{$pid},$parts,
 9837:                                          \%scantron_config,\%lettdig,$numletts,
 9838:                                          $randomorder,$randompick,
 9839:                                          \%respnumlookup,\%startline);
 9840:             $record{$pid} .= $recording;
 9841:         }
 9842:     }
 9843:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9844:     $r->print('<br />');
 9845:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9846:     $passed = 0;
 9847:     $failed = 0;
 9848:     $numstudents = 0;
 9849:     foreach my $last (sort(keys(%bylast))) {
 9850:         if (ref($bylast{$last}) eq 'ARRAY') {
 9851:             foreach my $pid (sort(@{$bylast{$last}})) {
 9852:                 my $showscandata = $scandata{$pid};
 9853:                 my $showrecord = $record{$pid};
 9854:                 $showscandata =~ s/\s/&nbsp;/g;
 9855:                 $showrecord =~ s/\s/&nbsp;/g;
 9856:                 if ($scandata{$pid} eq $record{$pid}) {
 9857:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9858:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9859: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9860: '</tr>'."\n".
 9861: '<tr class="'.$css_class.'">'."\n".
 9862: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9863:                     $passed ++;
 9864:                 } else {
 9865:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9866:                     $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".
 9867: '</tr>'."\n".
 9868: '<tr class="'.$css_class.'">'."\n".
 9869: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9870: '</tr>'."\n";
 9871:                     $failed ++;
 9872:                 }
 9873:                 $numstudents ++;
 9874:             }
 9875:         }
 9876:     }
 9877:     $r->print('<p>'.
 9878:               &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).',
 9879:                   '<b>',
 9880:                   $numstudents,
 9881:                   '</b>',
 9882:                   $env{'form.scantron_maxbubble'}).
 9883:               '</p>'
 9884:     );
 9885:     $r->print('<p>'
 9886:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9887:              .'<br />'
 9888:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9889:              .'</p>');
 9890:     if ($passed) {
 9891:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9892:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9893:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9894:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9895:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9896:                  $okstudents."\n".
 9897:                  &Apache::loncommon::end_data_table().'<br />');
 9898:     }
 9899:     if ($failed) {
 9900:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9901:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9902:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9903:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9904:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9905:                  $badstudents."\n".
 9906:                  &Apache::loncommon::end_data_table()).'<br />'.
 9907:                  &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.');  
 9908:     }
 9909:     $r->print('</form><br />');
 9910:     return;
 9911: }
 9912: 
 9913: sub verify_scantron_grading {
 9914:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9915:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9916:         $respnumlookup,$startline) = @_;
 9917:     my ($record,%expected,%startpos);
 9918:     return ($counter,$record) if (!ref($resource));
 9919:     return ($counter,$record) if (!$resource->is_problem());
 9920:     my $symb = $resource->symb();
 9921:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9922:     foreach my $part_id (@{$partids}) {
 9923:         $counter ++;
 9924:         $expected{$part_id} = 0;
 9925:         my $respnum = $counter;
 9926:         if ($randomorder || $randompick) {
 9927:             $respnum = $respnumlookup->{$counter};
 9928:             $startpos{$part_id} = $startline->{$counter} + 1;
 9929:         } else {
 9930:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9931:         }
 9932:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9933:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9934:             foreach my $item (@sub_lines) {
 9935:                 $expected{$part_id} += $item;
 9936:             }
 9937:         } else {
 9938:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9939:         }
 9940:     }
 9941:     if ($symb) {
 9942:         my %recorded;
 9943:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9944:         if ($returnhash{'version'}) {
 9945:             my %lasthash=();
 9946:             my $version;
 9947:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9948:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9949:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9950:                 }
 9951:             }
 9952:             foreach my $key (keys(%lasthash)) {
 9953:                 if ($key =~ /\.scantron$/) {
 9954:                     my $value = &unescape($lasthash{$key});
 9955:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9956:                     if ($value eq '') {
 9957:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9958:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9959:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9960:                             }
 9961:                         }
 9962:                     } else {
 9963:                         my @tocheck;
 9964:                         my @items = split(//,$value);
 9965:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9966:                             ($scantron_config->{'Qon'} eq 'number')) {
 9967:                             if (@items < $expected{$part_id}) {
 9968:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9969:                                 my @singles = split(//,$fragment);
 9970:                                 foreach my $pos (@singles) {
 9971:                                     if ($pos eq ' ') {
 9972:                                         push(@tocheck,$pos);
 9973:                                     } else {
 9974:                                         my $next = shift(@items);
 9975:                                         push(@tocheck,$next);
 9976:                                     }
 9977:                                 }
 9978:                             } else {
 9979:                                 @tocheck = @items;
 9980:                             }
 9981:                             foreach my $letter (@tocheck) {
 9982:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9983:                                     if ($letter !~ /^[A-J]$/) {
 9984:                                         $letter = $scantron_config->{'Qoff'};
 9985:                                     }
 9986:                                     $recorded{$part_id} .= $letter;
 9987:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9988:                                     my $digit;
 9989:                                     if ($letter !~ /^[A-J]$/) {
 9990:                                         $digit = $scantron_config->{'Qoff'};
 9991:                                     } else {
 9992:                                         $digit = $lettdig->{$letter};
 9993:                                     }
 9994:                                     $recorded{$part_id} .= $digit;
 9995:                                 }
 9996:                             }
 9997:                         } else {
 9998:                             @tocheck = @items;
 9999:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
10000:                                 my $curr_sub = shift(@tocheck);
10001:                                 my $digit;
10002:                                 if ($curr_sub =~ /^[A-J]$/) {
10003:                                     $digit = $lettdig->{$curr_sub}-1;
10004:                                 }
10005:                                 if ($curr_sub eq 'J') {
10006:                                     $digit += scalar($numletts);
10007:                                 }
10008:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10009:                                     if ($j == $digit) {
10010:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
10011:                                     } else {
10012:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10013:                                     }
10014:                                 }
10015:                             }
10016:                         }
10017:                     }
10018:                 }
10019:             }
10020:         }
10021:         foreach my $part_id (@{$partids}) {
10022:             if ($recorded{$part_id} eq '') {
10023:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
10024:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
10025:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
10026:                     }
10027:                 }
10028:             }
10029:             $record .= $recorded{$part_id};
10030:         }
10031:     }
10032:     return ($counter,$record);
10033: }
10034: 
10035: #-------- end of section for handling grading scantron forms -------
10036: #
10037: #-------------------------------------------------------------------
10038: 
10039: #-------------------------- Menu interface -------------------------
10040: #
10041: #--- Href with symb and command ---
10042: 
10043: sub href_symb_cmd {
10044:     my ($symb,$cmd)=@_;
10045:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
10046: }
10047: 
10048: sub grading_menu {
10049:     my ($request,$symb) = @_;
10050:     if (!$symb) {return '';}
10051: 
10052:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
10053:                   'command'=>'individual');
10054: 
10055:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10056: 
10057:     $fields{'command'}='ungraded';
10058:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10059: 
10060:     $fields{'command'}='table';
10061:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10062: 
10063:     $fields{'command'}='all_for_one';
10064:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10065: 
10066:     $fields{'command'}='downloadfilesselect';
10067:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
10068:     
10069:     $fields{'command'} = 'csvform';
10070:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10071:     
10072:     $fields{'command'} = 'processclicker';
10073:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10074:     
10075:     $fields{'command'} = 'scantron_selectphase';
10076:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10077: 
10078:     $fields{'command'} = 'initialverifyreceipt';
10079:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
10080: 
10081:     my %permissions;
10082:     if ($perm{'mgr'}) {
10083:         $permissions{'either'} = 'F';
10084:         $permissions{'mgr'} = 'F';
10085:     }
10086:     if ($perm{'vgr'}) {
10087:         $permissions{'either'} = 'F';
10088:         $permissions{'vgr'} = 'F';
10089:     }
10090: 
10091:     my @menu = ({	categorytitle=>'Hand Grading',
10092:             items =>[
10093:                         {       linktext => 'Select individual students to grade',
10094:                                 url => $url1a,
10095:                                 permission => $permissions{'either'},
10096:                                 icon => 'grade_students.png',
10097:                                 linktitle => 'Grade current resource for a selection of students.'
10098:                         },
10099:                         {       linktext => 'Grade ungraded submissions',
10100:                                 url => $url1b,
10101:                                 permission => $permissions{'either'},
10102:                                 icon => 'ungrade_sub.png',
10103:                                 linktitle => 'Grade all submissions that have not been graded yet.'
10104:                         },
10105: 
10106:                         {       linktext => 'Grading table',
10107:                                 url => $url1c,
10108:                                 permission => $permissions{'either'},
10109:                                 icon => 'grading_table.png',
10110:                                 linktitle => 'Grade current resource for all students.'
10111:                         },
10112:                         {       linktext => 'Grade page/folder for one student',
10113:                                 url => $url1d,
10114:                                 permission => $permissions{'either'},
10115:                                 icon => 'grade_PageFolder.png',
10116:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
10117:                         },
10118:                         {       linktext => 'Download submitted files',
10119:                                 url => $url1e,
10120:                                 permission => $permissions{'either'},
10121:                                 icon => 'download_sub.png',
10122:                                 linktitle => 'Download all files submitted by students.'
10123:                         }]},
10124:                          { categorytitle=>'Automated Grading',
10125:                items =>[
10126: 
10127:                 	    {	linktext => 'Upload Scores',
10128:                     		url => $url2,
10129:                     		permission => $permissions{'mgr'},
10130:                     		icon => 'uploadscores.png',
10131:                     		linktitle => 'Specify a file containing the class scores for current resource.'
10132:                 	    },
10133:                 	    {	linktext => 'Process Clicker',
10134:                     		url => $url3,
10135:                     		permission => $permissions{'mgr'},
10136:                     		icon => 'addClickerInfoFile.png',
10137:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
10138:                 	    },
10139:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
10140:                     		url => $url4,
10141:                     		permission => $permissions{'mgr'},
10142:                     		icon => 'bubblesheet.png',
10143:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
10144:                 	    },
10145:                             {   linktext => 'Verify Receipt Number',
10146:                                 url => $url5,
10147:                                 permission => $permissions{'either'},
10148:                                 icon => 'receipt_number.png',
10149:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
10150:                             }
10151: 
10152:                     ]
10153:             });
10154: 
10155:     # Create the menu
10156:     my $Str;
10157:     $Str .= '<form method="post" action="" name="gradingMenu">';
10158:     $Str .= '<input type="hidden" name="command" value="" />'.
10159:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10160: 
10161:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
10162:     return $Str;    
10163: }
10164: 
10165: sub ungraded {
10166:     my ($request)=@_;
10167:     &submit_options($request);
10168: }
10169: 
10170: sub submit_options_sequence {
10171:     my ($request,$symb) = @_;
10172:     if (!$symb) {return '';}
10173:     &commonJSfunctions($request);
10174:     my $result;
10175: 
10176:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10177:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10178:     $result.=&selectfield(0).
10179:             '<input type="hidden" name="command" value="pickStudentPage" />
10180:             <div>
10181:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10182:             </div>
10183:         </div>
10184:   </form>';
10185:     return $result;
10186: }
10187: 
10188: sub submit_options_table {
10189:     my ($request,$symb) = @_;
10190:     if (!$symb) {return '';}
10191:     &commonJSfunctions($request);
10192:     my $result;
10193: 
10194:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10195:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10196: 
10197:     $result.=&selectfield(1).
10198:             '<input type="hidden" name="command" value="viewgrades" />
10199:             <div>
10200:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10201:             </div>
10202:         </div>
10203:   </form>';
10204:     return $result;
10205: }
10206: 
10207: sub submit_options_download {
10208:     my ($request,$symb) = @_;
10209:     if (!$symb) {return '';}
10210: 
10211:     my $res_error;
10212:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
10213:         &response_type($symb,\$res_error);
10214:     if ($res_error) {
10215:         $request->print(&mt('An error occurred retrieving response types'));
10216:         return;
10217:     }
10218:     unless ($numessay) {
10219:         $request->print(&mt('No essayresponse items found'));
10220:         return;
10221:     }
10222:     my $table;
10223:     if (ref($partlist) eq 'ARRAY') {
10224:         if (scalar(@$partlist) > 1 ) {
10225:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
10226:         }
10227:     }
10228: 
10229:     &commonJSfunctions($request);
10230: 
10231:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10232:         $table."\n".
10233:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10234:     $result.='
10235: <h2>
10236:   '.&mt('Select Students for whom to Download Submitted Files').'
10237: </h2>'.&selectfield(1).'
10238:                 <input type="hidden" name="command" value="downloadfileslink" />
10239:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10240:             </div>
10241:           </div>
10242: 
10243: 
10244:   </form>';
10245:     return $result;
10246: }
10247: 
10248: #--- Displays the submissions first page -------
10249: sub submit_options {
10250:     my ($request,$symb) = @_;
10251:     if (!$symb) {return '';}
10252: 
10253:     &commonJSfunctions($request);
10254:     my $result;
10255: 
10256:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
10257: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
10258:     $result.=&selectfield(1).'
10259:                 <input type="hidden" name="command" value="submission" />
10260:               <input type="submit" value="'.&mt('Next').' &rarr;" />
10261:             </div>
10262:           </div>
10263:   </form>';
10264:     return $result;
10265: }
10266: 
10267: sub selectfield {
10268:    my ($full)=@_;
10269:    my %options =
10270:        (&substatus_options,
10271:         'select_form_order' => ['yes','queued','graded','incorrect','all']);
10272: 
10273:   #
10274:   # PrepareClasslist() needs to be called to avoid getting a sections list
10275:   # for a different course from the @Sections global in lonstatistics.pm,
10276:   # populated by an earlier request.
10277:   #
10278:    &Apache::lonstatistics::PrepareClasslist();
10279: 
10280:    my $result='<div class="LC_columnSection">
10281: 
10282:     <fieldset>
10283:       <legend>
10284:        '.&mt('Sections').'
10285:       </legend>
10286:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
10287:     </fieldset>
10288: 
10289:     <fieldset>
10290:       <legend>
10291:         '.&mt('Groups').'
10292:       </legend>
10293:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
10294:     </fieldset>
10295:  
10296:     <fieldset>
10297:       <legend>
10298:         '.&mt('Access Status').'
10299:       </legend>
10300:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
10301:     </fieldset>';
10302:     if ($full) {
10303:         $result.='
10304:     <fieldset>
10305:       <legend>
10306:         '.&mt('Submission Status').'
10307:       </legend>'.
10308:        &Apache::loncommon::select_form('all','submitonly',\%options).
10309:    '</fieldset>';
10310:     }
10311:     $result.='</div><br />';
10312:     return $result;
10313: }
10314: 
10315: sub substatus_options {
10316:     return &Apache::lonlocal::texthash(
10317:                                       'yes'       => 'with submissions',
10318:                                       'queued'    => 'in grading queue',
10319:                                       'graded'    => 'with ungraded submissions',
10320:                                       'incorrect' => 'with incorrect submissions',
10321:                                       'all'       => 'with any status',
10322:                                       );
10323: }
10324: 
10325: sub transtatus_options {
10326:     return &Apache::lonlocal::texthash(
10327:                                        'yes'       => 'with score transactions',
10328:                                        'incorrect' => 'with less than full credit',
10329:                                        'all'       => 'with any status',
10330:                                       );
10331: }
10332: 
10333: sub reset_perm {
10334:     undef(%perm);
10335: }
10336: 
10337: sub init_perm {
10338:     &reset_perm();
10339:     foreach my $test_perm ('vgr','mgr','opa') {
10340: 
10341: 	my $scope = $env{'request.course.id'};
10342: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10343: 
10344: 	    $scope .= '/'.$env{'request.course.sec'};
10345: 	    if ( $perm{$test_perm}=
10346: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10347: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10348: 	    } else {
10349: 		delete($perm{$test_perm});
10350: 	    }
10351: 	}
10352:     }
10353: }
10354: 
10355: sub init_old_essays {
10356:     my ($symb,$apath,$adom,$aname) = @_;
10357:     if ($symb ne '') {
10358:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10359:         if (keys(%essays) > 0) {
10360:             $old_essays{$symb} = \%essays;
10361:         }
10362:     }
10363:     return;
10364: }
10365: 
10366: sub reset_old_essays {
10367:     undef(%old_essays);
10368: }
10369: 
10370: sub gather_clicker_ids {
10371:     my %clicker_ids;
10372: 
10373:     my $classlist = &Apache::loncoursedata::get_classlist();
10374: 
10375:     # Set up a couple variables.
10376:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10377:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10378:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10379: 
10380:     foreach my $student (keys(%$classlist)) {
10381:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10382:         my $username = $classlist->{$student}->[$username_idx];
10383:         my $domain   = $classlist->{$student}->[$domain_idx];
10384:         my $clickers =
10385: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10386:         foreach my $id (split(/\,/,$clickers)) {
10387:             $id=~s/^[\#0]+//;
10388:             $id=~s/[\-\:]//g;
10389:             if (exists($clicker_ids{$id})) {
10390: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10391:             } else {
10392: 		$clicker_ids{$id}=$username.':'.$domain;
10393:             }
10394:         }
10395:     }
10396:     return %clicker_ids;
10397: }
10398: 
10399: sub gather_adv_clicker_ids {
10400:     my %clicker_ids;
10401:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10402:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10403:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10404:     foreach my $element (sort(keys(%coursepersonnel))) {
10405:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10406:             my ($puname,$pudom)=split(/\:/,$person);
10407:             my $clickers =
10408: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10409:             foreach my $id (split(/\,/,$clickers)) {
10410: 		$id=~s/^[\#0]+//;
10411:                 $id=~s/[\-\:]//g;
10412: 		if (exists($clicker_ids{$id})) {
10413: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10414: 		} else {
10415: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10416: 		}
10417:             }
10418:         }
10419:     }
10420:     return %clicker_ids;
10421: }
10422: 
10423: sub clicker_grading_parameters {
10424:     return ('gradingmechanism' => 'scalar',
10425:             'upfiletype' => 'scalar',
10426:             'specificid' => 'scalar',
10427:             'pcorrect' => 'scalar',
10428:             'pincorrect' => 'scalar');
10429: }
10430: 
10431: sub process_clicker {
10432:     my ($r,$symb)=@_;
10433:     if (!$symb) {return '';}
10434:     my $result=&checkforfile_js();
10435:     $result.=&Apache::loncommon::start_data_table().
10436:              &Apache::loncommon::start_data_table_header_row().
10437:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10438:              &Apache::loncommon::end_data_table_header_row().
10439:              &Apache::loncommon::start_data_table_row()."<td>\n";
10440: # Attempt to restore parameters from last session, set defaults if not present
10441:     my %Saveable_Parameters=&clicker_grading_parameters();
10442:     &Apache::loncommon::restore_course_settings('grades_clicker',
10443:                                                  \%Saveable_Parameters);
10444:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10445:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10446:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10447:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10448: 
10449:     my %checked;
10450:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10451:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10452:           $checked{$gradingmechanism}=' checked="checked"';
10453:        }
10454:     }
10455: 
10456:     my $upload=&mt("Evaluate File");
10457:     my $type=&mt("Type");
10458:     my $attendance=&mt("Award points just for participation");
10459:     my $personnel=&mt("Correctness determined from response by course personnel");
10460:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10461:     my $given=&mt("Correctness determined from given list of answers").' '.
10462:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10463:     my $pcorrect=&mt("Percentage points for correct solution");
10464:     my $pincorrect=&mt("Percentage points for incorrect solution");
10465:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10466:                                                    {'iclicker' => 'i>clicker',
10467:                                                     'interwrite' => 'interwrite PRS',
10468:                                                     'turning' => 'Turning Technologies'});
10469:     $symb = &Apache::lonenc::check_encrypt($symb);
10470:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10471: function sanitycheck() {
10472: // Accept only integer percentages
10473:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10474:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10475: // Find out grading choice
10476:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10477:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10478:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10479:       }
10480:    }
10481: // By default, new choice equals user selection
10482:    newgradingchoice=gradingchoice;
10483: // Not good to give more points for false answers than correct ones
10484:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10485:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10486:    }
10487: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10488:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10489:       document.forms.gradesupload.pcorrect.value=100;
10490:       document.forms.gradesupload.pincorrect.value=100;
10491:    }
10492: // If the values are different, cannot be attendance only
10493:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10494:        (gradingchoice=='attendance')) {
10495:        newgradingchoice='personnel';
10496:    }
10497: // Change grading choice to new one
10498:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10499:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10500:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10501:       } else {
10502:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10503:       }
10504:    }
10505: // Remember the old state
10506:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10507: }
10508: ENDUPFORM
10509:     $result.= <<ENDUPFORM;
10510: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10511: <input type="hidden" name="symb" value="$symb" />
10512: <input type="hidden" name="command" value="processclickerfile" />
10513: <input type="file" name="upfile" size="50" />
10514: <br /><label>$type: $selectform</label>
10515: ENDUPFORM
10516:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10517:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10518:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10519: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10520: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10521: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10522: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10523: <br />&nbsp;&nbsp;&nbsp;
10524: <input type="text" name="givenanswer" size="50" />
10525: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10526: ENDGRADINGFORM
10527:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10528:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10529:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10530: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10531: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10532: </form>
10533: ENDPERCFORM
10534:     $result.='</td>'.
10535:              &Apache::loncommon::end_data_table_row().
10536:              &Apache::loncommon::end_data_table();
10537:     return $result;
10538: }
10539: 
10540: sub process_clicker_file {
10541:     my ($r,$symb) = @_;
10542:     if (!$symb) {return '';}
10543: 
10544:     my %Saveable_Parameters=&clicker_grading_parameters();
10545:     &Apache::loncommon::store_course_settings('grades_clicker',
10546:                                               \%Saveable_Parameters);
10547:     my $result='';
10548:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10549: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10550: 	return $result;
10551:     }
10552:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10553:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10554:         return $result;
10555:     }
10556:     my $foundgiven=0;
10557:     if ($env{'form.gradingmechanism'} eq 'given') {
10558:         $env{'form.givenanswer'}=~s/^\s*//gs;
10559:         $env{'form.givenanswer'}=~s/\s*$//gs;
10560:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10561:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10562:         my @answers=split(/\,/,$env{'form.givenanswer'});
10563:         $foundgiven=$#answers+1;
10564:     }
10565:     my %clicker_ids=&gather_clicker_ids();
10566:     my %correct_ids;
10567:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10568: 	%correct_ids=&gather_adv_clicker_ids();
10569:     }
10570:     if ($env{'form.gradingmechanism'} eq 'specific') {
10571: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10572: 	   $correct_id=~tr/a-z/A-Z/;
10573: 	   $correct_id=~s/\s//gs;
10574: 	   $correct_id=~s/^[\#0]+//;
10575:            $correct_id=~s/[\-\:]//g;
10576:            if ($correct_id) {
10577: 	      $correct_ids{$correct_id}='specified';
10578:            }
10579:         }
10580:     }
10581:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10582: 	$result.=&mt('Score based on attendance only');
10583:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10584:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10585:     } else {
10586: 	my $number=0;
10587: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10588: 	foreach my $id (sort(keys(%correct_ids))) {
10589: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10590: 	    if ($correct_ids{$id} eq 'specified') {
10591: 		$result.=&mt('specified');
10592: 	    } else {
10593: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10594: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10595: 	    }
10596: 	    $number++;
10597: 	}
10598:         $result.="</p>\n";
10599:         if ($number==0) {
10600:             $result .=
10601:                  &Apache::lonhtmlcommon::confirm_success(
10602:                      &mt('No IDs found to determine correct answer'),1);
10603:             return $result;
10604:         }
10605:     }
10606:     if (length($env{'form.upfile'}) < 2) {
10607:         $result .=
10608:             &Apache::lonhtmlcommon::confirm_success(
10609:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10610:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10611:         return $result;
10612:     }
10613:     my $mimetype;
10614:     if ($env{'form.upfiletype'} eq 'iclicker') {
10615:         my $mm = new File::MMagic;
10616:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
10617:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10618:             $result.= '<p>'.
10619:                 &Apache::lonhtmlcommon::confirm_success(
10620:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10621:             return $result;
10622:         }
10623:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10624:         $result .= '<p>'.
10625:             &Apache::lonhtmlcommon::confirm_success(
10626:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10627:         return $result;
10628:     }
10629: 
10630: # Were able to get all the info needed, now analyze the file
10631: 
10632:     $result.=&Apache::loncommon::studentbrowser_javascript();
10633:     $symb = &Apache::lonenc::check_encrypt($symb);
10634:     $result.=&Apache::loncommon::start_data_table().
10635:              &Apache::loncommon::start_data_table_header_row().
10636:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10637:              &Apache::loncommon::end_data_table_header_row().
10638:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10639: <td>
10640: <form method="post" action="/adm/grades" name="clickeranalysis">
10641: <input type="hidden" name="symb" value="$symb" />
10642: <input type="hidden" name="command" value="assignclickergrades" />
10643: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10644: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10645: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10646: ENDHEADER
10647:     if ($env{'form.gradingmechanism'} eq 'given') {
10648:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10649:     } 
10650:     my %responses;
10651:     my @questiontitles;
10652:     my $errormsg='';
10653:     my $number=0;
10654:     if ($env{'form.upfiletype'} eq 'iclicker') {
10655:         if ($mimetype eq 'text/plain') {
10656:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10657:         } elsif ($mimetype eq 'text/html') {
10658:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10659:         }
10660:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10661:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10662:     } elsif ($env{'form.upfiletype'} eq 'turning') {
10663:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10664:     }
10665:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10666:              '<input type="hidden" name="number" value="'.$number.'" />'.
10667:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10668:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10669:              '<br />';
10670:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10671:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10672:        return $result;
10673:     } 
10674: # Remember Question Titles
10675: # FIXME: Possibly need delimiter other than ":"
10676:     for (my $i=0;$i<$number;$i++) {
10677:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10678:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10679:     }
10680:     my $correct_count=0;
10681:     my $student_count=0;
10682:     my $unknown_count=0;
10683: # Match answers with usernames
10684: # FIXME: Possibly need delimiter other than ":"
10685:     foreach my $id (keys(%responses)) {
10686:        if ($correct_ids{$id}) {
10687:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10688:           $correct_count++;
10689:        } elsif ($clicker_ids{$id}) {
10690:           if ($clicker_ids{$id}=~/\,/) {
10691: # More than one user with the same clicker!
10692:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10693:                            &Apache::loncommon::start_data_table_row()."<td>".
10694:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10695:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10696:                            "<select name='multi".$id."'>";
10697:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10698:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10699:              }
10700:              $result.='</select>';
10701:              $unknown_count++;
10702:           } else {
10703: # Good: found one and only one user with the right clicker
10704:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10705:              $student_count++;
10706:           }
10707:        } else {
10708:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10709:                            &Apache::loncommon::start_data_table_row()."<td>".
10710:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10711:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10712:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10713:                    "\n".&mt("Domain").": ".
10714:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10715:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10716:           $unknown_count++;
10717:        }
10718:     }
10719:     $result.='<hr />'.
10720:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10721:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10722:        if ($correct_count==0) {
10723:           $errormsg.="Found no correct answers for grading!";
10724:        } elsif ($correct_count>1) {
10725:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10726:        }
10727:     }
10728:     if ($number<1) {
10729:        $errormsg.="Found no questions.";
10730:     }
10731:     if ($errormsg) {
10732:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10733:     } else {
10734:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10735:     }
10736:     $result.='</form></td>'.
10737:              &Apache::loncommon::end_data_table_row().
10738:              &Apache::loncommon::end_data_table();
10739:     return $result;
10740: }
10741: 
10742: sub iclicker_eval {
10743:     my ($questiontitles,$responses)=@_;
10744:     my $number=0;
10745:     my $errormsg='';
10746:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10747:         my %components=&Apache::loncommon::record_sep($line);
10748:         my @entries=map {$components{$_}} (sort(keys(%components)));
10749: 	if ($entries[0] eq 'Question') {
10750: 	    for (my $i=3;$i<$#entries;$i+=6) {
10751: 		$$questiontitles[$number]=$entries[$i];
10752: 		$number++;
10753: 	    }
10754: 	}
10755: 	if ($entries[0]=~/^\#/) {
10756: 	    my $id=$entries[0];
10757: 	    my @idresponses;
10758: 	    $id=~s/^[\#0]+//;
10759: 	    for (my $i=0;$i<$number;$i++) {
10760: 		my $idx=3+$i*6;
10761:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10762: 		push(@idresponses,$entries[$idx]);
10763: 	    }
10764: 	    $$responses{$id}=join(',',@idresponses);
10765: 	}
10766:     }
10767:     return ($errormsg,$number);
10768: }
10769: 
10770: sub iclickerxml_eval {
10771:     my ($questiontitles,$responses)=@_;
10772:     my $number=0;
10773:     my $errormsg='';
10774:     my @state;
10775:     my %respbyid;
10776:     my $p = HTML::Parser->new
10777:     (
10778:         xml_mode => 1,
10779:         start_h =>
10780:             [sub {
10781:                  my ($tagname,$attr) = @_;
10782:                  push(@state,$tagname);
10783:                  if ("@state" eq "ssn p") {
10784:                      my $title = $attr->{qn};
10785:                      $title =~ s/(^\s+|\s+$)//g;
10786:                      $questiontitles->[$number]=$title;
10787:                  } elsif ("@state" eq "ssn p v") {
10788:                      my $id = $attr->{id};
10789:                      my $entry = $attr->{ans};
10790:                      $id=~s/^[\#0]+//;
10791:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10792:                      $respbyid{$id}[$number] = $entry;
10793:                  }
10794:             }, "tagname, attr"],
10795:          end_h =>
10796:                [sub {
10797:                    my ($tagname) = @_;
10798:                    if ("@state" eq "ssn p") {
10799:                        $number++;
10800:                    }
10801:                    pop(@state);
10802:                 }, "tagname"],
10803:     );
10804: 
10805:     $p->parse($env{'form.upfile'});
10806:     $p->eof;
10807:     foreach my $id (keys(%respbyid)) {
10808:         $responses->{$id}=join(',',@{$respbyid{$id}});
10809:     }
10810:     return ($errormsg,$number);
10811: }
10812: 
10813: sub interwrite_eval {
10814:     my ($questiontitles,$responses)=@_;
10815:     my $number=0;
10816:     my $errormsg='';
10817:     my $skipline=1;
10818:     my $questionnumber=0;
10819:     my %idresponses=();
10820:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10821:         my %components=&Apache::loncommon::record_sep($line);
10822:         my @entries=map {$components{$_}} (sort(keys(%components)));
10823:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10824:         if ($entries[1] eq 'Response') { $skipline=1; }
10825:         next if $skipline;
10826:         if ($entries[0]!=$questionnumber) {
10827:            $questionnumber=$entries[0];
10828:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10829:            $number++;
10830:         }
10831:         my $id=$entries[4];
10832:         $id=~s/^[\#0]+//;
10833:         $id=~s/^v\d*\://i;
10834:         $id=~s/[\-\:]//g;
10835:         $idresponses{$id}[$number]=$entries[6];
10836:     }
10837:     foreach my $id (keys(%idresponses)) {
10838:        $$responses{$id}=join(',',@{$idresponses{$id}});
10839:        $$responses{$id}=~s/^\s*\,//;
10840:     }
10841:     return ($errormsg,$number);
10842: }
10843: 
10844: sub turning_eval {
10845:     my ($questiontitles,$responses)=@_;
10846:     my $number=0;
10847:     my $errormsg='';
10848:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10849:         my %components=&Apache::loncommon::record_sep($line);
10850:         my @entries=map {$components{$_}} (sort(keys(%components)));
10851:         if ($#entries>$number) { $number=$#entries; }
10852:         my $id=$entries[0];
10853:         my @idresponses;
10854:         $id=~s/^[\#0]+//;
10855:         unless ($id) { next; }
10856:         for (my $idx=1;$idx<=$#entries;$idx++) {
10857:             $entries[$idx]=~s/\,/\;/g;
10858:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10859:             push(@idresponses,$entries[$idx]);
10860:         }
10861:         $$responses{$id}=join(',',@idresponses);
10862:     }
10863:     for (my $i=1; $i<=$number; $i++) {
10864:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10865:     }
10866:     return ($errormsg,$number);
10867: }
10868: 
10869: sub assign_clicker_grades {
10870:     my ($r,$symb) = @_;
10871:     if (!$symb) {return '';}
10872: # See which part we are saving to
10873:     my $res_error;
10874:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10875:     if ($res_error) {
10876:         return &navmap_errormsg();
10877:     }
10878: # FIXME: This should probably look for the first handgradeable part
10879:     my $part=$$partlist[0];
10880: # Start screen output
10881:     my $result = &Apache::loncommon::start_data_table(). 
10882:                  &Apache::loncommon::start_data_table_header_row().
10883:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10884:                  &Apache::loncommon::end_data_table_header_row().
10885:                  &Apache::loncommon::start_data_table_row().'<td>';
10886: # Get correct result
10887: # FIXME: Possibly need delimiter other than ":"
10888:     my @correct=();
10889:     my $gradingmechanism=$env{'form.gradingmechanism'};
10890:     my $number=$env{'form.number'};
10891:     if ($gradingmechanism ne 'attendance') {
10892:        foreach my $key (keys(%env)) {
10893:           if ($key=~/^form\.correct\:/) {
10894:              my @input=split(/\,/,$env{$key});
10895:              for (my $i=0;$i<=$#input;$i++) {
10896:                  if (($correct[$i]) && ($input[$i]) &&
10897:                      ($correct[$i] ne $input[$i])) {
10898:                     $result.='<br /><span class="LC_warning">'.
10899:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10900:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10901:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10902:                     $correct[$i]=$input[$i];
10903:                  }
10904:              }
10905:           }
10906:        }
10907:        for (my $i=0;$i<$number;$i++) {
10908:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10909:              $result.='<br /><span class="LC_error">'.
10910:                       &mt('No correct result given for question "[_1]"!',
10911:                           $env{'form.question:'.$i}).'</span>';
10912:           }
10913:        }
10914:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10915:     }
10916: # Start grading
10917:     my $pcorrect=$env{'form.pcorrect'};
10918:     my $pincorrect=$env{'form.pincorrect'};
10919:     my $storecount=0;
10920:     my %users=();
10921:     foreach my $key (keys(%env)) {
10922:        my $user='';
10923:        if ($key=~/^form\.student\:(.*)$/) {
10924:           $user=$1;
10925:        }
10926:        if ($key=~/^form\.unknown\:(.*)$/) {
10927:           my $id=$1;
10928:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10929:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10930:           } elsif ($env{'form.multi'.$id}) {
10931:              $user=$env{'form.multi'.$id};
10932:           }
10933:        }
10934:        if ($user) {
10935:           if ($users{$user}) {
10936:              $result.='<br /><span class="LC_warning">'.
10937:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10938:                       '</span><br />';
10939:           }
10940:           $users{$user}=1;
10941:           my @answer=split(/\,/,$env{$key});
10942:           my $sum=0;
10943:           my $realnumber=$number;
10944:           for (my $i=0;$i<$number;$i++) {
10945:              if  ($correct[$i] eq '-') {
10946:                 $realnumber--;
10947:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10948:                 if ($gradingmechanism eq 'attendance') {
10949:                    $sum+=$pcorrect;
10950:                 } elsif ($correct[$i] eq '*') {
10951:                    $sum+=$pcorrect;
10952:                 } else {
10953: # We actually grade if correct or not
10954:                    my $increment=$pincorrect;
10955: # Special case: numerical answer "0"
10956:                    if ($correct[$i] eq '0') {
10957:                       if ($answer[$i]=~/^[0\.]+$/) {
10958:                          $increment=$pcorrect;
10959:                       }
10960: # General numerical answer, both evaluate to something non-zero
10961:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10962:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10963:                          $increment=$pcorrect;
10964:                       }
10965: # Must be just alphanumeric
10966:                    } elsif ($answer[$i] eq $correct[$i]) {
10967:                       $increment=$pcorrect;
10968:                    }
10969:                    $sum+=$increment;
10970:                 }
10971:              }
10972:           }
10973:           my $ave=$sum/(100*$realnumber);
10974: # Store
10975:           my ($username,$domain)=split(/\:/,$user);
10976:           my %grades=();
10977:           $grades{"resource.$part.solved"}='correct_by_override';
10978:           $grades{"resource.$part.awarded"}=$ave;
10979:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10980:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10981:                                                  $env{'request.course.id'},
10982:                                                  $domain,$username);
10983:           if ($returncode ne 'ok') {
10984:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10985:           } else {
10986:              $storecount++;
10987:           }
10988:        }
10989:     }
10990: # We are done
10991:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10992:              '</td>'.
10993:              &Apache::loncommon::end_data_table_row().
10994:              &Apache::loncommon::end_data_table();
10995:     return $result;
10996: }
10997: 
10998: sub navmap_errormsg {
10999:     return '<div class="LC_error">'.
11000:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
11001:            &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>').
11002:            '</div>';
11003: }
11004: 
11005: sub startpage {
11006:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
11007:     my %args;
11008:     if ($onload) {
11009:          my %loaditems = (
11010:                         'onload' => $onload,
11011:                       );
11012:          $args{'add_entries'} = \%loaditems;
11013:     }
11014:     if ($nomenu) {
11015:         $args{'only_body'} = 1;
11016:         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
11017:     } else {
11018:         if ($env{'request.course.id'}) {
11019:             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
11020:         }
11021:         $args{'bread_crumbs'} = $crumbs;
11022:         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
11023:     }
11024:     unless ($nodisplayflag) {
11025:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
11026:     }
11027: }
11028: 
11029: sub select_problem {
11030:     my ($r)=@_;
11031:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
11032:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
11033:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
11034:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
11035: }
11036: 
11037: sub handler {
11038:     my $request=$_[0];
11039:     &reset_caches();
11040:     if ($request->header_only) {
11041:         &Apache::loncommon::content_type($request,'text/html');
11042:         $request->send_http_header;
11043:         return OK;
11044:     }
11045:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
11046: 
11047: # see what command we need to execute
11048:  
11049:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
11050:     my $command=$commands[0];
11051: 
11052:     &init_perm();
11053:     if (!$env{'request.course.id'}) {
11054:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
11055:                 ($command =~ /^scantronupload/)) {
11056:             # Not in a course.
11057:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
11058:             return HTTP_NOT_ACCEPTABLE;
11059:         }
11060:     } elsif (!%perm) {
11061:         $request->internal_redirect('/adm/quickgrades');
11062:         return OK;
11063:     }
11064:     &Apache::loncommon::content_type($request,'text/html');
11065:     $request->send_http_header;
11066: 
11067:     if ($#commands > 0) {
11068: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
11069:     }
11070: 
11071: # see what the symb is
11072: 
11073:     my $symb=$env{'form.symb'};
11074:     unless ($symb) {
11075:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11076:        $symb=&Apache::lonnet::symbread($url);
11077:     }
11078:     &Apache::lonenc::check_decrypt(\$symb);
11079: 
11080:     $ssi_error = 0;
11081:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
11082: #
11083: # Not called from a resource, but inside a course
11084: #
11085:         &startpage($request,undef,[],1,1);
11086:         &select_problem($request);
11087:     } else {
11088:         if ($command eq 'submission' && $perm{'vgr'}) {
11089:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
11090:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
11091:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
11092:                     &choose_task_version_form($symb,$env{'form.student'},
11093:                                               $env{'form.userdom'});
11094:             }
11095:             my $divforres;
11096:             if ($env{'form.student'} eq '') {
11097:                 $js .= &part_selector_js();
11098:                 $onload = "toggleParts('gradesub');";
11099:             } else {
11100:                 $divforres = 1;
11101:             }
11102:             my $head_extra = $js;
11103:             unless ($env{'form.vProb'} eq 'no') {
11104:                 my $csslinks = &Apache::loncommon::css_links($symb);
11105:                 if ($csslinks) {
11106:                     $head_extra .= "\n$csslinks";
11107:                 }
11108:             }
11109:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
11110:                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
11111:             if ($versionform) {
11112:                 if ($divforres) {
11113:                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11114:                 }
11115:                 $request->print($versionform);
11116:             }
11117:             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
11118:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
11119:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
11120:                 &choose_task_version_form($symb,$env{'form.student'},
11121:                                           $env{'form.userdom'},
11122:                                           $env{'form.inhibitmenu'});
11123:             my $head_extra = $js;
11124:             unless ($env{'form.vProb'} eq 'no') {
11125:                 my $csslinks = &Apache::loncommon::css_links($symb);
11126:                 if ($csslinks) {
11127:                     $head_extra .= "\n$csslinks";
11128:                 }
11129:             }
11130:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
11131:                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
11132:             if ($versionform) {
11133:                 $request->print($versionform);
11134:             }
11135:             $request->print('<br clear="all" />');
11136:             $request->print(&show_previous_task_version($request,$symb));
11137:         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
11138:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11139:                                        {href=>'',text=>'Select student'}],1,1);
11140:             &pickStudentPage($request,$symb);
11141:         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
11142:             my $csslinks;
11143:             unless ($env{'form.vProb'} eq 'no') {
11144:                 $csslinks = &Apache::loncommon::css_links($symb,'map');
11145:             }
11146:             &startpage($request,$symb,
11147:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11148:                                        {href=>'',text=>'Select student'},
11149:                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
11150:             &displayPage($request,$symb);
11151:         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
11152:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
11153:                                        {href=>'',text=>'Select student'},
11154:                                        {href=>'',text=>'Grade student'},
11155:                                        {href=>'',text=>'Store grades'}],1,1);
11156:             &updateGradeByPage($request,$symb);
11157:         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
11158:             my $csslinks;
11159:             unless ($env{'form.vProb'} eq 'no') {
11160:                 $csslinks = &Apache::loncommon::css_links($symb);
11161:             }
11162:             &startpage($request,$symb,[{href=>'',text=>'...'},
11163:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
11164:             &processGroup($request,$symb);
11165:         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
11166:             &startpage($request,$symb);
11167:             $request->print(&grading_menu($request,$symb));
11168:         } elsif ($command eq 'individual' && $perm{'vgr'}) {
11169:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
11170:             $request->print(&submit_options($request,$symb));
11171:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
11172:             my $js = &part_selector_js();
11173:             my $onload = "toggleParts('gradesub');";
11174:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
11175:                        undef,undef,undef,undef,undef,$js,$onload);
11176:             $request->print(&listStudents($request,$symb,'graded'));
11177:         } elsif ($command eq 'table' && $perm{'vgr'}) {
11178:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
11179:             $request->print(&submit_options_table($request,$symb));
11180:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
11181:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
11182:             $request->print(&submit_options_sequence($request,$symb));
11183:         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
11184:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
11185:             $request->print(&viewgrades($request,$symb));
11186:         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
11187:             &startpage($request,$symb,[{href=>'',text=>'...'},
11188:                                        {href=>'',text=>'Store grades'}]);
11189:             $request->print(&processHandGrade($request,$symb));
11190:         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
11191:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
11192:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
11193:                                                                              text=>"Modify grades"},
11194:                                        {href=>'', text=>"Store grades"}]);
11195:             $request->print(&editgrades($request,$symb));
11196:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
11197:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
11198:             $request->print(&initialverifyreceipt($request,$symb));
11199:         } elsif ($command eq 'verify' && $perm{'vgr'}) {
11200:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
11201:                                        {href=>'',text=>'Verification Result'}]);
11202:             $request->print(&verifyreceipt($request,$symb));
11203:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
11204:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
11205:             $request->print(&process_clicker($request,$symb));
11206:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
11207:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11208:                                        {href=>'', text=>'Process clicker file'}]);
11209:             $request->print(&process_clicker_file($request,$symb));
11210:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
11211:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
11212:                                        {href=>'', text=>'Process clicker file'},
11213:                                        {href=>'', text=>'Store grades'}]);
11214:             $request->print(&assign_clicker_grades($request,$symb));
11215:         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
11216:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11217:             $request->print(&upcsvScores_form($request,$symb));
11218:         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
11219:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11220:             $request->print(&csvupload($request,$symb));
11221:         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
11222:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11223:             $request->print(&csvuploadmap($request,$symb));
11224:         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
11225:             if ($env{'form.associate'} ne 'Reverse Association') {
11226:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11227:                 $request->print(&csvuploadoptions($request,$symb));
11228:             } else {
11229:                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
11230:                     $env{'form.upfile_associate'} = 'reverse';
11231:                 } else {
11232:                     $env{'form.upfile_associate'} = 'forward';
11233:                 }
11234:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11235:                 $request->print(&csvuploadmap($request,$symb));
11236:             }
11237:         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
11238:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
11239:             $request->print(&csvuploadassign($request,$symb));
11240:         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
11241:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11242:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11243:             $request->print(&scantron_selectphase($request,undef,$symb));
11244:         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
11245:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11246:             $request->print(&scantron_do_warning($request,$symb));
11247:         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
11248:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11249:             $request->print(&scantron_validate_file($request,$symb));
11250:         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
11251:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11252:             $request->print(&scantron_process_students($request,$symb));
11253:         } elsif ($command eq 'scantronupload' &&
11254:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11255:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11256:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
11257:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
11258:             $request->print(&scantron_upload_scantron_data($request,$symb));
11259:         } elsif ($command eq 'scantronupload_save' &&
11260:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
11261:                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
11262:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11263:             $request->print(&scantron_upload_scantron_data_save($request,$symb));
11264:         } elsif ($command eq 'scantron_download' &&
11265:                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
11266:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11267:             $request->print(&scantron_download_scantron_data($request,$symb));
11268:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
11269:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
11270:             $request->print(&checkscantron_results($request,$symb));
11271:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
11272:             my $js = &part_selector_js();
11273:             my $onload = "toggleParts('gradingMenu');";
11274:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
11275:                        undef,undef,undef,undef,undef,$js,$onload);
11276:             $request->print(&submit_options_download($request,$symb));
11277:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
11278:             &startpage($request,$symb,
11279:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
11280:     {href=>'', text=>'Download submitted files'}],
11281:                undef,undef,undef,undef,undef,undef,undef,1);
11282:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
11283:             &submit_download_link($request,$symb);
11284:         } elsif ($command) {
11285:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
11286:             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
11287:         }
11288:     }
11289:     if ($ssi_error) {
11290: 	&ssi_print_error($request);
11291:     }
11292:     $request->print(&Apache::loncommon::end_page());
11293:     &reset_caches();
11294:     return OK;
11295: }
11296: 
11297: 1;
11298: 
11299: __END__;
11300: 
11301: 
11302: =head1 NAME
11303: 
11304: Apache::grades
11305: 
11306: =head1 SYNOPSIS
11307: 
11308: Handles the viewing of grades.
11309: 
11310: This is part of the LearningOnline Network with CAPA project
11311: described at http://www.lon-capa.org.
11312: 
11313: =head1 OVERVIEW
11314: 
11315: Do an ssi with retries:
11316: While I'd love to factor out this with the vesrion in lonprintout,
11317: 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
11318: I'm not quite ready to invent (e.g. an ssi_with_retry object).
11319: 
11320: At least the logic that drives this has been pulled out into loncommon.
11321: 
11322: 
11323: 
11324: ssi_with_retries - Does the server side include of a resource.
11325:                      if the ssi call returns an error we'll retry it up to
11326:                      the number of times requested by the caller.
11327:                      If we still have a problem, no text is appended to the
11328:                      output and we set some global variables.
11329:                      to indicate to the caller an SSI error occurred.  
11330:                      All of this is supposed to deal with the issues described
11331:                      in LON-CAPA BZ 5631 see:
11332:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
11333:                      by informing the user that this happened.
11334: 
11335: Parameters:
11336:   resource   - The resource to include.  This is passed directly, without
11337:                interpretation to lonnet::ssi.
11338:   form       - The form hash parameters that guide the interpretation of the resource
11339:                
11340:   retries    - Number of retries allowed before giving up completely.
11341: Returns:
11342:   On success, returns the rendered resource identified by the resource parameter.
11343: Side Effects:
11344:   The following global variables can be set:
11345:    ssi_error                - If an unrecoverable error occurred this becomes true.
11346:                               It is up to the caller to initialize this to false
11347:                               if desired.
11348:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
11349:                               of the resource that could not be rendered by the ssi
11350:                               call.
11351:    ssi_error_message   - The error string fetched from the ssi response
11352:                               in the event of an error.
11353: 
11354: 
11355: =head1 HANDLER SUBROUTINE
11356: 
11357: ssi_with_retries()
11358: 
11359: =head1 SUBROUTINES
11360: 
11361: =over
11362: 
11363: =item scantron_get_correction() : 
11364: 
11365:    Builds the interface screen to interact with the operator to fix a
11366:    specific error condition in a specific scanline
11367: 
11368:  Arguments:
11369:     $r           - Apache request object
11370:     $i           - number of the current scanline
11371:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11372:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11373:     $line        - full contents of the current scanline
11374:     $error       - error condition, valid values are
11375:                    'incorrectCODE', 'duplicateCODE',
11376:                    'doublebubble', 'missingbubble',
11377:                    'duplicateID', 'incorrectID'
11378:     $arg         - extra information needed
11379:        For errors:
11380:          - duplicateID   - paper number that this studentID was seen before on
11381:          - duplicateCODE - array ref of the paper numbers this CODE was
11382:                            seen on before
11383:          - incorrectCODE - current incorrect CODE 
11384:          - doublebubble  - array ref of the bubble lines that have double
11385:                            bubble errors
11386:          - missingbubble - array ref of the bubble lines that have missing
11387:                            bubble errors
11388: 
11389:    $randomorder - True if exam folder (or a sub-folder) has randomorder set
11390:    $randompick  - True if exam folder (or a sub-folder) has randompick set
11391:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11392:                      for current line to question number used for same question
11393:                      in "Master Seqence" (as seen by Course Coordinator).
11394:    $startline   - Reference to hash where key is question number (0 is first)
11395:                   and value is number of first bubble line for current student
11396:                   or code-based randompick and/or randomorder.
11397: 
11398: 
11399: =item  scantron_get_maxbubble() : 
11400: 
11401:    Arguments:
11402:        $nav_error  - Reference to scalar which is a flag to indicate a
11403:                       failure to retrieve a navmap object.
11404:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11405:        calling routine should trap the error condition and display the warning
11406:        found in &navmap_errormsg().
11407: 
11408:        $scantron_config - Reference to bubblesheet format configuration hash.
11409: 
11410:    Returns the maximum number of bubble lines that are expected to
11411:    occur. Does this by walking the selected sequence rendering the
11412:    resource and then checking &Apache::lonxml::get_problem_counter()
11413:    for what the current value of the problem counter is.
11414: 
11415:    Caches the results to $env{'form.scantron_maxbubble'},
11416:    $env{'form.scantron.bubble_lines.n'}, 
11417:    $env{'form.scantron.first_bubble_line.n'} and
11418:    $env{"form.scantron.sub_bubblelines.n"}
11419:    which are the total number of bubble lines, the number of bubble
11420:    lines for response n and number of the first bubble line for response n,
11421:    and a comma separated list of numbers of bubble lines for sub-questions
11422:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11423: 
11424: 
11425: =item  scantron_validate_missingbubbles() : 
11426: 
11427:    Validates all scanlines in the selected file to not have any
11428:     answers that don't have bubbles that have not been verified
11429:     to be bubble free.
11430: 
11431: =item  scantron_process_students() : 
11432: 
11433:    Routine that does the actual grading of the bubblesheet information.
11434: 
11435:    The parsed scanline hash is added to %env 
11436: 
11437:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11438:    foreach resource , with the form data of
11439: 
11440: 	'submitted'     =>'scantron' 
11441: 	'grade_target'  =>'grade',
11442: 	'grade_username'=> username of student
11443: 	'grade_domain'  => domain of student
11444: 	'grade_courseid'=> of course
11445: 	'grade_symb'    => symb of resource to grade
11446: 
11447:     This triggers a grading pass. The problem grading code takes care
11448:     of converting the bubbled letter information (now in %env) into a
11449:     valid submission.
11450: 
11451: =item  scantron_upload_scantron_data() :
11452: 
11453:     Creates the screen for adding a new bubblesheet data file to a course.
11454: 
11455: =item  scantron_upload_scantron_data_save() : 
11456: 
11457:    Adds a provided bubble information data file to the course if user
11458:    has the correct privileges to do so. 
11459: 
11460: =item  valid_file() :
11461: 
11462:    Validates that the requested bubble data file exists in the course.
11463: 
11464: =item  scantron_download_scantron_data() : 
11465: 
11466:    Shows a list of the three internal files (original, corrected,
11467:    skipped) for a specific bubblesheet data file that exists in the
11468:    course.
11469: 
11470: =item  scantron_validate_ID() : 
11471: 
11472:    Validates all scanlines in the selected file to not have any
11473:    invalid or underspecified student/employee IDs
11474: 
11475: =item navmap_errormsg() :
11476: 
11477:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11478:    Should be called whenever the request to instantiate a navmap object fails.  
11479: 
11480: =back
11481: 
11482: =cut

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